@@ -85,3 +85,70 @@ def my_context():
8585 # goodbye
8686 ++
8787********************************************************************************************************************************************"""
88+ ## The timer() context manager
89+
90+ # Add a decorator that will make timer() a context manager
91+ @contextlib .contextmanager
92+ def timer ():
93+ """Time the execution of a context block.
94+
95+ Yields:
96+ None
97+ """
98+ start = time .time ()
99+ # Send control back to the context block
100+ yield None
101+ end = time .time ()
102+ print ('Elapsed: {:.2f}s' .format (end - start ))
103+
104+ with timer ():
105+ print ('This should take approximately 0.25 seconds' )
106+ time .sleep (0.25 )
107+ #``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````
108+ ## A read-only open() context manager
109+
110+ @contextlib .contextmanager
111+ def open_read_only (filename ):
112+ """Open a file in read-only mode.
113+
114+ Args:
115+ filename (str): The location of the file to read
116+
117+ Yields:
118+ file object
119+ """
120+ read_only_file = open (filename , mode = 'r' )
121+ # Yield read_only_file so it can be assigned to my_file
122+ yield read_only_file
123+ # Close read_only_file
124+ read_only_file .close ()
125+
126+ with open_read_only ('my_file.txt' ) as my_file :
127+ print (my_file .read ())
128+ """********************************************************************************************************************************************
129+ Advanced topics
130+ ===============
131+ ********************************************************************************************************************************************"""
132+ ## Context manager use cases
133+ """---Which of the following would NOT be a good opportunity to use a context manager?"""
134+
135+ # A function that prints all of the prime numbers between 2 and some value n.
136+ #``````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````````
137+ ## Scraping the NASDAQ
138+
139+ # Use the "stock('NVDA')" context manager
140+ # and assign the result to the variable "nvda"
141+ with stock ('NVDA' ) as nvda :
142+ # Open "NVDA.txt" for writing as f_out
143+ with open ('NVDA.txt' , 'w' ) as f_out :
144+ for _ in range (10 ):
145+ value = nvda .price ()
146+ print ('Logging ${:.2f} for NVDA' .format (value ))
147+ f_out .write ('{:.2f}\n ' .format (value ))
148+ """Opening stock ticker for NVDA
149+ Logging $139.50 for NVDA
150+ Logging $139.54 for NVDA
151+ Logging $139.61 for NVDA....."""
152+ """!!!
153+ Nesting context managers like this allows you to connect to the stock market """
154+
0 commit comments