Simplifying context managers in python

Lets start with an example of a context manager.

This is code without a context manager:

                f = open("test_file", "w")
f.write("Test")
f.close()
            

Converting it to context manager in python,

                with open("test_file", "a") as f:
   f.write("test_write_from_context_manager\n")
            

Lets create a custom context manager.

Using the 4 step process in the diagram above above, any code can be converted in context manager.

Context managers can be used in situations when the code has the below structure:

  1. Open/Setup/Enter
  2. Execute/Implement
  3. Close/Teardown/Exit

Examples of context managers:

  1. Open, read, close file
  2. Open connection of database, execute query, close connection of database
  3. Login, get data, logout


Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies and get more readers

Join other developers and claim your FAUN account now!

Stats
10

Influence

293

Total Hits

1

Posts