using conte x t managers
play

Using conte x t managers W R ITIN G FU N C TION S IN P YTH ON Sha - PowerPoint PPT Presentation

Using conte x t managers W R ITIN G FU N C TION S IN P YTH ON Sha y ne Miel Director of So w are Engineering @ American E cient What is a conte x t manager ? A conte x t manager : Sets u p a conte x t R u ns y o u r code Remo v es the


  1. Using conte x t managers W R ITIN G FU N C TION S IN P YTH ON Sha y ne Miel Director of So �w are Engineering @ American E � cient

  2. What is a conte x t manager ? A conte x t manager : Sets u p a conte x t R u ns y o u r code Remo v es the conte x t WRITING FUNCTIONS IN PYTHON

  3. A catered part y WRITING FUNCTIONS IN PYTHON

  4. A catered part y WRITING FUNCTIONS IN PYTHON

  5. A catered part y WRITING FUNCTIONS IN PYTHON

  6. A catered part y WRITING FUNCTIONS IN PYTHON

  7. A catered part y WRITING FUNCTIONS IN PYTHON

  8. Catered part y as conte x t Conte x t managers : Caterers : Set u p a conte x t Set u p the tables w ith food and drink R u n y o u r code Let y o u and y o u r friends ha v e a part y Remo v e the conte x t Cleaned u p and remo v ed the tables WRITING FUNCTIONS IN PYTHON

  9. A real -w orld e x ample with open('my_file.txt') as my_file: text = my_file.read() length = len(text) print('The file is {} characters long'.format(length)) open() does three things : Sets u p a conte x t b y opening a � le Lets y o u r u n an y code y o u w ant on that � le Remo v es the conte x t b y closing the � le WRITING FUNCTIONS IN PYTHON

  10. Using a conte x t manager with WRITING FUNCTIONS IN PYTHON

  11. Using a conte x t manager with <context-manager>() WRITING FUNCTIONS IN PYTHON

  12. Using a conte x t manager with <context-manager>(<args>) WRITING FUNCTIONS IN PYTHON

  13. Using a conte x t manager with <context-manager>(<args>): WRITING FUNCTIONS IN PYTHON

  14. Using a conte x t manager with <context-manager>(<args>): # Run your code here # This code is running "inside the context" WRITING FUNCTIONS IN PYTHON

  15. Using a conte x t manager with <context-manager>(<args>): # Run your code here # This code is running "inside the context" # This code runs after the context is removed WRITING FUNCTIONS IN PYTHON

  16. Using a conte x t manager with <context-manager>(<args>) as <variable-name>: # Run your code here # This code is running "inside the context" # This code runs after the context is removed with open('my_file.txt') as my_file: text = my_file.read() length = len(text) print('The file is {} characters long'.format(length)) WRITING FUNCTIONS IN PYTHON

  17. Let ' s practice ! W R ITIN G FU N C TION S IN P YTH ON

  18. Writing conte x t managers W R ITIN G FU N C TION S IN P YTH ON Sha y ne Miel Director of So �w are Engineering @ American E � cient

  19. T w o w a y s to define a conte x t manager Class - based F u nction - based WRITING FUNCTIONS IN PYTHON

  20. T w o w a y s to define a conte x t manager Class - based F u nction - based * WRITING FUNCTIONS IN PYTHON

  21. Ho w to create a conte x t manager def my_context(): # Add any set up code you need yield # Add any teardown code you need 1. De � ne a f u nction . 2. ( optional ) Add an y set u p code y o u r conte x t needs . 3. Use the "y ield " ke yw ord . 4. ( optional ) Add an y teardo w n code y o u r conte x t needs . WRITING FUNCTIONS IN PYTHON

  22. Ho w to create a conte x t manager @contextlib.contextmanager def my_context(): # Add any set up code you need yield # Add any teardown code you need 1. De � ne a f u nction . 2. ( optional ) Add an y set u p code y o u r conte x t needs . 3. Use the "y ield " ke yw ord . 4. ( optional ) Add an y teardo w n code y o u r conte x t needs . 5. Add the `@ conte x tlib . conte x tmanager ` decorator . WRITING FUNCTIONS IN PYTHON

  23. The "y ield " ke yw ord @contextlib.contextmanager def my_context(): print('hello') yield 42 print('goodbye') with my_context() as foo: print('foo is {}'.format(foo)) hello foo is 42 goodbye WRITING FUNCTIONS IN PYTHON

  24. Set u p and teardo w n @contextlib.contextmanager def database(url): # set up database connection db = postgres.connect(url) yield db # tear down database connection db.disconnect() url = 'http://datacamp.com/data' with database(url) as my_db: course_list = my_db.execute( 'SELECT * FROM courses' ) WRITING FUNCTIONS IN PYTHON

  25. Set u p and teardo w n @contextlib.contextmanager def database(url): # set up database connection db = postgres.connect(url) yield db # tear down database connection db.disconnect() url = 'http://datacamp.com/data' with database(url) as my_db: course_list = my_db.execute( 'SELECT * FROM courses' ) WRITING FUNCTIONS IN PYTHON

  26. Set u p and teardo w n @contextlib.contextmanager def database(url): # set up database connection db = postgres.connect(url) yield db # tear down database connection db.disconnect() url = 'http://datacamp.com/data' with database(url) as my_db: course_list = my_db.execute( 'SELECT * FROM courses' ) WRITING FUNCTIONS IN PYTHON

  27. Yielding a v al u e or None @contextlib.contextmanager @contextlib.contextmanager def database(url): def in_dir(path): # set up database connection # save current working directory db = postgres.connect(url) old_dir = os.getcwd() yield db # switch to new working directory os.chdir(path) # tear down database connection db.disconnect() yield # change back to previous url = 'http://datacamp.com/data' # working directory with database(url) as my_db: os.chdir(old_dir) course_list = my_db.execute( 'SELECT * FROM courses' ) with in_dir('/data/project_1/'): project_files = os.listdir() WRITING FUNCTIONS IN PYTHON

  28. Let ' s practice ! W R ITIN G FU N C TION S IN P YTH ON

  29. Ad v anced topics W R ITIN G FU N C TION S IN P YTH ON Sha y ne Miel Director of So �w are Engineering @ American E � cient

  30. Nested conte x ts def copy(src, dst): """Copy the contents of one file to another. Args: src (str): File name of the file to be copied. dst (str): Where to write the new file. """ # Open the source file and read in the contents with open(src) as f_src: contents = f_src.read() # Open the destination file and write out the contents with open(dst, 'w') as f_dst: f_dst.write(contents) WRITING FUNCTIONS IN PYTHON

  31. Nested conte x ts with open('my_file.txt') as my_file: for line in my_file: # do something WRITING FUNCTIONS IN PYTHON

  32. Nested conte x ts def copy(src, dst): """Copy the contents of one file to another. Args: src (str): File name of the file to be copied. dst (str): Where to write the new file. """ # Open both files with open(src) as f_src: with open(dst, 'w') as f_dst: # Read and write each line, one at a time for line in f_src: f_dst.write(line) WRITING FUNCTIONS IN PYTHON

  33. Handling errors Traceback (most recent call last): def get_printer(ip): File "<stdin>", line 1, in <module> p = connect_to_printer(ip) printer.print_page(doc['txt']) KeyError: 'txt' yield # This MUST be called or no one else will # be able to connect to the printer p.disconnect() print('disconnected from printer') doc = {'text': 'This is my text.'} with get_printer('10.0.34.111') as printer: printer.print_page(doc['txt']) WRITING FUNCTIONS IN PYTHON

  34. Handling errors try: # code that might raise an error except: # do something about the error finally: # this code runs no matter what WRITING FUNCTIONS IN PYTHON

  35. Handling errors disconnected from printer def get_printer(ip): Traceback (most recent call last): p = connect_to_printer(ip) File "<stdin>", line 1, in <module> printer.print_page(doc['txt']) try: KeyError: 'txt' yield finally: p.disconnect() print('disconnected from printer') doc = {'text': 'This is my text.'} with get_printer('10.0.34.111') as printer: printer.print_page(doc['txt']) WRITING FUNCTIONS IN PYTHON

  36. Conte x t manager patterns Open Close Lock Release Change Reset Enter E x it Start Stop Set u p Teardo w n Connect Disconnect 1 Adapted from Da v e Brondsema ' s talk at P y Con 2012: h � ps ://y o u t u. be / cSbD 5 SK w ak 0? t =795 WRITING FUNCTIONS IN PYTHON

  37. Let ' s practice ! W R ITIN G FU N C TION S IN P YTH ON

Recommend


More recommend