cells: - markdown: | # Advanced Python: `with` statements ### Prabhu Ramachandran ### The FOSSEE Python group & ### Department of Aerospace Engineering ### IIT Bombay metadata: slideshow: slide_type: slide - markdown: | ## Introduction - `with` statement is used as follows metadata: slideshow: slide_type: slide - code: | with open('data/test.txt') as f: for line in f: print(line, end='') - code: | f.closed metadata: slideshow: slide_type: fragment - markdown: | ## Observations - Creates a context - `f` is automatically closed - Works even if there was an exception! metadata: slideshow: slide_type: slide - markdown: | ## Use cases - Use it with locks (for threaded computing) - Database connections - File objects metadata: slideshow: slide_type: slide - markdown: | ## Creating your own - Relatively easy to do metadata: slideshow: slide_type: slide - code: | from contextlib import contextmanager @contextmanager def context(): print("setup") try: yield finally: print("done") - code: | with context(): print("do something") - markdown: | ## A more complex example metadata: slideshow: slide_type: slide - code: | import os from contextlib import contextmanager @contextmanager def tempfile(filename): f = open(filename, 'w') try: yield f finally: f.close() os.remove(filename) - code: | %ls junk.txt - code: | with tempfile('junk.txt') as f: f.write('hello world\n') f.flush() metadata: slideshow: slide_type: slide - markdown: | ## Summary - Useful feature - Can define an object supporting this - Overload, `__enter__` and `__exit__` - Not covered here metadata: slideshow: slide_type: slide - markdown: | ## More information - https://www.python.org/dev/peps/pep-0343 - [With statement](https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers) - [Context manager types](https://docs.python.org/3/library/stdtypes.html#typecontextmanager) metadata: slideshow: slide_type: slide # The lines below here may be deleted if you do not need them. # --------------------------------------------------------------------------- metadata: kernelspec: display_name: Python 3 language: python name: python3 language_info: codemirror_mode: name: ipython version: 3 file_extension: .py mimetype: text/x-python name: python nbconvert_exporter: python pygments_lexer: ipython3 version: 3.5.2 rise: scroll: true transition: none nbformat: 4 nbformat_minor: 2