Get the App
SLTechnology News&Howtos  ›  Development  › 

How python uses ContextLib

Shulou Source: shulou.com Published: 2022-06-01 04:23:17 09月22日 Update

Editor to share with you how to use python ContextLib, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Context Management Library (ContextLib)

The contextlib module contains tools related to the context manager and with declarations. Usually if you want to write a context manager, you need to define a class that contains enter methods as well as exit methods, such as:

Import timeclass demo: def _ init__ (self, label): self.label = label def _ enter__ (self): self.start = time.time () def _ exit__ (self, exc_ty, exc_val, exc_tb): end = time.time () print ('{}: {} '.format (self.label, end-self.start))

A complete example is here:

Import timeclass demo: def _ init__ (self, label): self.label = label def _ enter__ (self): self.start = time.time () def _ exit__ (self, exc_ty, exc_val, exc_tb): end = time.time () print ('{}: {} '.format (self.label, end-self.start) with demo (' counting'): n = 10000000 while n > 0: n-= counting: 1.36000013351

The context manager is activated by the with declaration, and this API involves two methods. The enter method, which executes when the execution flow enters the with code block. And it returns an object that can be used by the context.

When the execution flow leaves the with code block, the exit method is called, which cleans up the resources being used.

Rewrite the above example with the @ contextmanager decorator:

From contextlib import contextmanagerimport time@contextmanagerdef demo (label): start = time.time () try: yield finally: end = time.time () print ('{}: {} '.format (label, end-start)) with demo (' counting'): n = 10000000 while n > 0: n-= blank counting: 1.32399988174

Looking at the example above, all the code before yield in the function is similar to the content of the enter method in the context manager. All the code after yield is like the content of the exit method. If an exception occurs during execution, it is triggered in the yield statement.

The above is all the content of the article "how python uses ContextLib". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Methods up and down context management code content examples articles not much two functions most objects tools more modules activation knowledge industry statements Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Huawei Microsoft MariaDB MySQL