@contextmanager作用,举例
时间: 2023-08-12 13:05:45 浏览: 56
@contextmanager是一个Python标准库中的装饰器,它用于定义一个上下文管理器。上下文管理器是在执行代码块前后执行特定操作的对象,通常用于资源分配和释放,如打开和关闭文件、数据库连接等。
下面是一个使用@contextmanager定义上下文管理器的例子,它用于在代码块执行期间打开和关闭一个文件:
```python
from contextlib import contextmanager
@contextmanager
def file_manager(file_path):
file = open(file_path, 'w')
try:
yield file
finally:
file.close()
with file_manager('example.txt') as f:
f.write('Hello, world!')
```
在这个例子中,@contextmanager装饰器将file_manager函数转换为一个上下文管理器。当with语句执行时,它将调用file_manager函数,并将其返回值绑定到f变量上。代码块执行期间,文件example.txt被打开,并可以通过f变量进行写入操作。当代码块执行完毕后,@contextmanager装饰器会自动调用file_manager函数中的finally块,关闭文件并释放相关资源。
相关问题
@contextmanager
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.
@contextlib.contextmanager
'@contextlib.contextmanager' 是一个装饰器,用于创建上下文管理器。使用 with 语句来管理代码块,这样可以确保代码块在执行完后会被自动清理。@contextlib.contextmanager 装饰器可以让我们更轻松地创建自定义的上下文管理器。