Source From Here
PrefaceThe 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:
- with open('hello.txt', 'w') as f:
- f.write('hello, world!')
- f = open('hello.txt', 'w')
- try:
- f.write('hello, world')
- finally:
- f.close()
- f = open('hello.txt', 'w')
- f.write('hello, world')
- f.close()
Another good example where the with statement is used effectively in the Python standard library is the threading.Lock class:
- some_lock = threading.Lock()
- # Harmful:
- some_lock.acquire()
- try:
- # Do something...
- finally:
- some_lock.release()
- # Better:
- with some_lock:
- # Do something...
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:
- class ManagedFile:
- def __init__(self, name):
- self.name = name
- def __enter__(self):
- self.file = open(self.name, 'w')
- return self.file
- def __exit__(self, exc_type, exc_val, exc_tb):
- if self.file:
- self.file.close()
- with ManagedFile('hello.txt') as f:
- f.write('hello, world!')
- f.write('bye now')
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
- @contextmanager
- def managed_file(name):
- try:
- f = open(name, 'w')
- yield f
- finally:
- f.close()
- with managed_file('hello.txt') as f:
- f.write('hello, world!')
- f.write('bye now')
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:
- with Indenter() as indent:
- indent.print('hi!')
- with indent:
- indent.print('hello')
- with indent:
- indent.print('bonjour')
- indent.print('hey')
- hi!
- hello
- bonjour
- hey
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:
- class Indenter:
- def __init__(self):
- self.level = 0
- def __enter__(self):
- self.level += 1
- return self
- def __exit__(self, exc_type, exc_val, exc_tb):
- self.level -= 1
- def print(self, text):
- print(' ' * self.level + text)
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.
沒有留言:
張貼留言