@contextmanager
时间: 2023-10-14 11:04:52 浏览: 48
The @contextmanager decorator in Python allows you to create a context manager using a generator function. A context manager is a class or function that is used to manage resources, such as opening and closing a file or acquiring and releasing a lock. The @contextmanager decorator provides a simple and concise way to create a context manager without having to define a class.
The decorator takes a generator function as input and returns a context manager. The generator function must yield exactly once to indicate the beginning of the context and again at the end to indicate the end of the context. Any code inside the with statement will be executed within the context.
Here is an example of a context manager created using the @contextmanager decorator:
```python
from contextlib import contextmanager
@contextmanager
def open_file(file_path):
file = open(file_path, 'w')
try:
yield file
finally:
file.close()
with open_file('test.txt') as f:
f.write('Hello, world!')
```
In this example, the open_file() function is decorated with @contextmanager. The function opens a file for writing and yields the file object. The try-finally block ensures that the file is closed properly when the context is exited.
The with statement is used to create a context in which the file is opened and used to write a string to the file. When the with block is exited, the file is closed automatically.
The @contextmanager decorator is a useful tool for creating context managers in a concise and readable manner.