2021年7月24日 星期六

[Py Tricks] 2.3 Context Managers and the with Statement

Source From Here
Preface
The with statement in Python is regarded as an obscure feature by some. But when you peek behind the scenes, you’ll see that there’s no magic involved, and it’s actually a highly useful feature that can help you write cleaner and more readable Python code.

So what’s the with statement good for? It helps simplify some common resource management patterns by abstracting their functionality and allowing them to be factored out and reused. A good way to see this feature used effectively is by looking at examples in the Python standard library. The built-in open() function provides us with an excellent use case:
  1. with open('hello.txt''w') as f:  
  2.   f.write('hello, world!')  
Opening files using the with statement is generally recommended because it ensures that open file descriptors are closed automatically after program execution leaves the context of the with statement. Internally, the above code sample translates to something like this:
  1. f = open('hello.txt''w')  
  2. try:  
  3.   f.write('hello, world')  
  4. finally:  
  5.   f.close()  
You can already tell that this is quite a bit more verbose. Note that the try...finally statement is significant. It wouldn’t be enough to just write something like this:
  1. f = open('hello.txt''w')  
  2. f.write('hello, world')  
  3. f.close()  
This implementation won’t guarantee the file is closed if there’s an exception during the f.write() call—and therefore our program might leak a file descriptor. That’s why the with statement is so useful. It makes properly acquiring and releasing resources a breeze.

Another good example where the with statement is used effectively in the Python standard library is the threading.Lock class:
  1. some_lock = threading.Lock()  
  2. # Harmful:  
  3. some_lock.acquire()  
  4. try:  
  5.   # Do something...  
  6. finally:  
  7.   some_lock.release()  
  8.   
  9. # Better:  
  10. with some_lock:  
  11.   # Do something...  
In both cases, using a with statement allows you to abstract away most of the resource handling logic. Instead of having to write an explicit try...finally statement each time, using the with statement takes care of that for us.

The with statement can make code that deals with system resources more readable. It also helps you avoid bugs or leaks by making it practically impossible to forget to clean up or release a resource when it’s no longer needed.

Supporting with in Your Own Objects
Now, there’s nothing special or magical about the open() function or the threading.Lock class and the fact that they can be used with a with statement. You can provide the same functionality in your own classes and functions by implementing so-called context managers.

What’s a context manager? It’s a simple “protocol” (or interface) that your object needs to follow in order to support the with statement. Basically, all you need to do is add __enter__ and __exit__ methods to an object if you want it to function as a context manager. Python will call these two methods at the appropriate times in the resource management cycle.

Let’s take a look at what this would look like in practical terms. Here’s what a simple implementation of the open() context manager might look like:
  1. class ManagedFile:  
  2.   def __init__(self, name):  
  3.     self.name = name  
  4.   
  5.   def __enter__(self):  
  6.     self.file = open(self.name, 'w')  
  7.     return self.file  
  8.   
  9.   def __exit__(self, exc_type, exc_val, exc_tb):  
  10.     if self.file:  
  11.       self.file.close()  
Our ManagedFile class follows the context manager protocol and now supports the with statement, just like the original open() example did:
  1. with ManagedFile('hello.txt') as f:  
  2.   f.write('hello, world!')  
  3.   f.write('bye now')  
Python calls __enter__ when execution enters the context of the with statement and it’s time to acquire the resource. When execution leaves the context again, Python calls __exit__ to free up the resource.

Writing a class-based context manager isn’t the only way to support the with statement in Python. The contextlib utility module in the standard library provides a few more abstractions built on top of the basic context manager protocol. This can make your life a little easier if your use cases match what’s offered by contextlib.

For example, you can use the contextlib.contextmanager decorator to define a generator-based factory function for a resource that will then automatically support the with statement. Here’s what rewriting our ManagedFile context manager example with this technique looks like:
from contextlib import contextmanager
  1. @contextmanager  
  2. def managed_file(name):  
  3. try:  
  4.   f = open(name, 'w')  
  5.   yield f  
  6. finally:  
  7.   f.close()  
Example usage:
  1. with managed_file('hello.txt') as f:  
  2.   f.write('hello, world!')  
  3.   f.write('bye now')  
In this case, managed_file() is a generator that first acquires the resource. After that, it temporarily suspends its own execution and yields the resource so it can be used by the caller. When the caller leaves the with context, the generator continues to execute so that any remaining clean-up steps can occur and the resource can get released back to the system.

The class-based implementation and the generator-based one are essentially equivalent. You might prefer one over the other, depending on which approach you find more readable.

A downside of the @contextmanager-based implementation might be that it requires some understanding of advanced Python concepts like decorators and generators. If you need to get up to speed with those, feel free to take a detour to the relevant chapters here in this book.

Once again, making the right implementation choice here comes down to what you and your team are comfortable using and what you find the most readable.

Writing Pretty APIs With Context Managers
Context managers are quite flexible, and if you use the with statement creatively, you can define convenient APIs for your modules and classes.

For example, what if the “resource” we wanted to manage was text indentation levels in some kind of report generator program? What if we could write code like this to do it:
  1. with Indenter() as indent:  
  2.   indent.print('hi!')  
  3.   with indent:  
  4.     indent.print('hello')  
  5.     with indent:  
  6.       indent.print('bonjour')  
  7.   indent.print('hey')  
This almost reads like a domain-specific language (DSL) for indenting text. Also, notice how this code enters and leaves the same context manager multiple times to change indentation levels. Running this code snippet should lead to the following output and print neatly formatted text to the console:
  1. hi!  
  2.     hello  
  3.         bonjour  
  4. hey  
So, how would you implement a context manager to support this functionality?

By the way, this could be a great exercise for you to understand exactly how context managers work. So before you check out my implementation below, you might want to take some time and try to implement this yourself as a learning exercise.

If you’re ready to check out my implementation, here’s how you might implement this functionality using a class-based context manager:
  1. class Indenter:  
  2.   def __init__(self):  
  3.     self.level = 0  
  4.   def __enter__(self):  
  5.     self.level += 1  
  6.     return self  
  7.   def __exit__(self, exc_type, exc_val, exc_tb):  
  8.     self.level -= 1  
  9.   
  10.   def print(self, text):  
  11.     print(' ' * self.level + text)  
That wasn’t so bad, was it? I hope that by now you’re already feeling more comfortable using context managers and the with statement in your own Python programs. They’re an excellent feature that will allow you to deal with resource management in a much more Pythonic and maintainable way.

Key Takeaways
• The with statement simplifies exception handling by encapsulating standard uses of try/finally statements in so-called context managers.
• Most commonly it is used to manage the safe acquisition and release of system resources. Resources are acquired by the with statement and released automatically when execution leaves the with context.
• Using with effectively can help you avoid resource leaks and make your code easier to read.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...