Session 11 - Context Managers

Today we will work with Context Managers.

Context managers can in short be described as something that takes care of the related tasks of a specific task. An example of this could be when opening a file, the context manager takes care of automaticly closing the file when we are finished using it.

You will make your own context managers and use already created ones.

Learning goals

  • Being able to use a Context Manager

  • Creating your own Context Managers

  • Using a context manager in relation to Working with JSON, Pickles and CSV files.

  • Using a context manager in relation to working with a SQlite database.

Materials

Exercises

1. Coroutine to Compute a Running Average Change the function below into a coroutine (generator) that calculates a running avarage. So instead of returning an avarage based on the parameter it should calculate an avarage based on the values inserted into the coroutine with the .send() method.

1
2
3
4
5
def averager(*args):
     sum = 0
     for i in args:
            sum += i
     return sum/len(args)

2. Context manager class Create a class “Makeparagraph” that “decorates” a text with an html <p> tag.

3. contextlib In the code example below we can se that the connect() function is a context manager. It has an __enter__ and an __exit__ method, and therefore works together with the “with” keyword.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
     from sqlite3 import connect

     with connect('testfiles/school.db') as conn:
         cur = conn.cursor()
         cur.execute('CREATE TABLE students(id int PRIMARY KEY, name text, cpr text)')
         cur.execute('INSERT INTO students(id, name, cpr) VALUES (1, "Claus", "223344-5566")')
         cur.execute('INSERT INTO students(id, name, cpr) VALUES (2, "Julie", "111111-1111")')
         cur.execute('INSERT INTO students(id, name, cpr) VALUES (3, "Hannah", "222222-2222")')

         for i in cur.execute('SELECT * FROM students'):
             print(i)

         cur.execute('DROP TABLE students')

The “CREATE TABLE” and the “DROP TABLE” has also some __enter__ / __exit__ logic behind it. Put this logic into its own contextmanager and use it. This should be done by using the contextmanager decorator from the contextlib library.