Python小姿势 - Python Tips: How to Use Context Managers

简介: Python小姿势 - Python Tips: How to Use Context Managers

Python Tips: How to Use Context Managers

Python's with statement is extremely useful for managing resources, such as files or network connections. With it, you can ensure that resources are properly cleaned up even in the face of exceptions. But did you know that you can also use with to manage your own resources?

In this article, we'll take a look at how to create and use your own context managers. We'll also see how the contextlib module can help you write more robust and reusable context managers.

Creating Context Managers

To create a context manager, you need to define two methods on an object: enter and exit .

enter is invoked when the with statement is entered. It's responsible for acquiring the resource. In most cases, this will be a no-op, but it can also return an object that will be bound to the name given in the as clause of the with statement.

exit is invoked when the with statement is exited, regardless of whether it completed successfully, was interrupted by an exception, or was exited early with a return or break statement. It's responsible for releasing the resource. In most cases, this will be a no-op, but it can also handle exceptions that occur within the with block.

Here's a simple example of a context manager that manages a database connection:

class Database: def init(self, host, port, user, password): self.host = host self.port = port self.user = user self.password = password def enter(self): self.conn = psycopg2.connect( host=self.host, port=self.port, user=self.user, password=self.password ) return self.conn def exit(self, *args): self.conn.close()

This context manager can be used like this:

with Database('localhost', 5432, 'postgres', 'password') as conn: cur = conn.cursor() cur.execute('SELECT * FROM my_table') for row in cur: print(row)

In this example, enter establishes the database connection and exit closes it. Note that exit takes an arbitrary number of arguments. These arguments will be the exception type, exception value, and traceback, respectively, if an exception occurred. Otherwise, they will be None .

If you want your context manager to handle exceptions, you can do so like this:

def exit(self, *args): if any(args): An exception occurred print('An error occurred:', args) else: The with block completed successfully self.conn.commit() self.conn.close()

In this example, exit commits the database transaction if the with block completed successfully and closes the connection regardless of whether an error occurred.

You can also use the with statement to write your own context managers that don't use the enter and exit methods. For example, you could use a with statement to automatically acquire and release a lock:

lock = Lock() with lock: Do something that needs to be synchronized...

In this example, the with statement acquires the lock when it's entered and releases it when it's exited.

Context Managers and the with Statement

In addition to the enter and exit methods, context managers must also be implemented as either a class or a generator function. This is necessary because the with statement uses the context manager's enter and exit methods internally.

When using a class, the with statement creates an instance of the class and then calls the enter method on the instance. When using a generator function, the with statement calls the function and passes the result to the enter method.

In both cases, the with statement then calls the exit method on the result of the enter method when the with block is exited.

This means that you can't use a non-generator function as a context manager. For example, this won't work:

@contextmanager def my_context_manager(): Do something... yield Do something else...

If you try to use this context manager, you'll get an AttributeError because the with statement expects enter to be a generator function.

To fix this, you need to make my_context_manager a generator function:

@contextmanager def my_context_manager(): Do something... yield Do something else...

Now, my_context_manager can be used as a context manager.

If you're not sure whether a context manager is a class or a generator function, you can use the inspect module to find out:

import inspect @contextmanager def my_context_manager(): Do


相关文章
|
SQL 关系型数据库 数据库连接
|
Python
Python tricks Context Managers and the with Statement
Python tricks Context Managers and the with Statement
287 1
|
自然语言处理 Python
【Python】已解决:Resource punkt not found. Please use the NLTK Downloader to obtain the resource:
【Python】已解决:Resource punkt not found. Please use the NLTK Downloader to obtain the resource:
1710 1
跟着Tips案例学Seaborn之Catplot
跟着Tips案例学Seaborn之Catplot
557 0
|
计算机视觉 Python
ERROR: Could not build wheels for opencv-python which use PEP 517 and cannot be installed directly
ERROR: Could not build wheels for opencv-python which use PEP 517 and cannot be installed directly
914 2
|
自然语言处理 Java 开发工具
【Python】已解决Resource averaged_perceptron_tagger not found. Please use the NLTK Downloader to obtain t
【Python】已解决Resource averaged_perceptron_tagger not found. Please use the NLTK Downloader to obtain t
843 0
|
自然语言处理 Python
【Python】已解决:Resource stopwords not found. Please use the NLTK Downloader to obtain the resource:
【Python】已解决:Resource stopwords not found. Please use the NLTK Downloader to obtain the resource:
1187 0
|
监控 开发者 Python
【Python】已解决:WARNING: This is a development server. Do not use it in a production deployment. Use a p
【Python】已解决:WARNING: This is a development server. Do not use it in a production deployment. Use a p
2625 0
|
数据可视化 数据挖掘 API
seaborn从入门到精通01-seaborn介绍与load_dataset(“tips“)出现超时解决方案
seaborn从入门到精通01-seaborn介绍与load_dataset(“tips“)出现超时解决方案
seaborn从入门到精通01-seaborn介绍与load_dataset(“tips“)出现超时解决方案

推荐镜像

更多