[161]python__enter__与__exit__的作用,以及与with语句的关系

32 阅读5分钟

@[toc]

With语句

With语句是什么?

有一些任务,可能事先需要设置,事后做清理工作。对于这种场景,Python的with语句提供了一种非常方便的处理方式。一个很好的例子是文件处理,你需要获取一个文件句柄,从文件中读取数据,然后关闭文件句柄。

如果不用with语句,代码如下:

file = open("/tmp/foo.txt")
data = file.read()
file.close()

这里有两个问题。一是可能忘记关闭文件句柄;二是文件读取数据发生异常,没有进行任何处理。下面是处理异常的加强版本:

file = open("/tmp/foo.txt")
try:
    data = file.read()
finally:
    file.close()

虽然这段代码运行良好,但是太冗长了。这时候就是with一展身手的时候了。除了有更优雅的语法,with还可以很好的处理上下文环境产生的异常。下面是with版本的代码:

with open("/tmp /foo.txt") as file:
    data = file.read()

with如何工作?

这看起来充满魔法,但不仅仅是魔法,Python对with的处理还很聪明。基本思想是with所求值的对象必须有一个__enter__()方法,一个__exit__()方法。

紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。

下面例子可以具体说明with如何工作:

#!/usr/bin/env python
# with_example01.py

class Sample:
    def __enter__(self):
        print "In __enter__()"
        return "Foo"

    def __exit__(self, type, value, trace):
        print "In __exit__()"


def get_sample():
    return Sample()


with get_sample() as sample:
    print "sample:", sample

输出如下

bash-3.2$ ./with_example01.py
In __enter__()
sample: Foo
In __exit__()

正如你看到的,

__enter__()方法被执行 __enter__()方法返回的值 - 这个例子中是"Foo",赋值给变量'sample' 执行代码块,打印变量"sample"的值为 "Foo" __exit__()方法被调用

with真正强大之处是它可以处理异常。可能你已经注意到Sample类的__exit__方法有三个参数val,type 和 trace。 这些参数在异常处理中相当有用。我们来改一下代码,看看具体如何工作的。

#!/usr/bin/env python
# with_example02.py


class Sample:
    def __enter__(self):
        return self

    def __exit__(self, type, value, trace):
        print "type:", type
        print "value:", value
        print "trace:", trace

    def do_something(self):
        bar = 1/0
        return bar + 10

with Sample() as sample:
    sample.do_something()

这个例子中,with后面的get_sample()变成了Sample()。这没有任何关系,只要紧跟with后面的语句所返回的对象有 __enter__()__exit__()方法即可。此例中,Sample()的__enter__()方法返回新创建的Sample对象,并赋值给变量sample。

代码执行后:

bash-3.2$ ./with_example02.py
type: <type 'exceptions.ZeroDivisionError'>
value: integer division or modulo by zero
trace: <traceback object at 0x1004a8128>
Traceback (most recent call last):
  File "./with_example02.py", line 19, in <module>
    sample.do_somet hing()
  File "./with_example02.py", line 15, in do_something
    bar = 1/0
ZeroDivisionError: integer division or modulo by zero

实际上,在with后面的代码块抛出任何异常时,__exit__()方法被执行。正如例子所示,异常抛出时,与之关联的type,value和stack trace传给__exit__()方法,因此抛出的ZeroDivisionError异常被打印出来了。开发库时,清理资源,关闭文件等等操作,都可以放在__exit__方法当中。

因此,Python的with语句是提供一个有效的机制,让代码更简练,同时在异常产生时,清理工作更简单。


__enter__ 方法是 Python 上下文管理器协议的一部分,与 __exit__ 方法配合使用,用于实现 with 语句。

基本作用

__enter__ 方法定义了在进入 with 代码块时要执行的操作。

基本语法

class MyContextManager:
    def __enter__(self):
        # 进入 with 块时执行
        print("进入上下文")
        return self  # 通常返回自身或其他对象
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        # 退出 with 块时执行
        print("退出上下文")
        return False  # 如果返回 True,会抑制异常

# 使用
with MyContextManager() as cm:
    print("在上下文中执行操作")

实际应用示例

示例1:自定义文件操作上下文管理器

class FileHandler:
    def __init__(self, filename, mode):
        self.filename = filename
        self.mode = mode
        self.file = None
    
    def __enter__(self):
        self.file = open(self.filename, self.mode)
        print(f"打开文件: {self.filename}")
        return self.file
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.file:
            self.file.close()
            print(f"关闭文件: {self.filename}")
        # 如果发生异常,返回 False 会让异常继续传播
        return False

# 使用
with FileHandler('test.txt', 'w') as f:
    f.write('Hello, World!')
# 文件会自动关闭,即使发生异常也会关闭

示例2:计时上下文管理器

import time

class Timer:
    def __enter__(self):
        self.start_time = time.time()
        print("开始计时...")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end_time = time.time()
        self.duration = self.end_time - self.start_time
        print(f"执行时间: {self.duration:.2f} 秒")
        return False
    
    def get_duration(self):
        return self.duration

# 使用
with Timer() as timer:
    time.sleep(2)
    # 执行一些操作

print(f"总耗时: {timer.get_duration():.2f} 秒")

示例3:数据库连接上下文管理器

class DatabaseConnection:
    def __init__(self, connection_string):
        self.connection_string = connection_string
        self.connection = None
    
    def __enter__(self):
        # 模拟数据库连接
        self.connection = f"连接到: {self.connection_string}"
        print(self.connection)
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        # 关闭连接
        print(f"关闭数据库连接: {self.connection_string}")
        # 如果发生异常,可以在这里处理
        if exc_type is not None:
            print(f"发生异常: {exc_val}")
        return False  # 不抑制异常
    
    def execute(self, query):
        print(f"执行查询: {query}")
        return "查询结果"

# 使用
with DatabaseConnection("mysql://localhost:3306/mydb") as db:
    result = db.execute("SELECT * FROM users")
    print(result)
# 连接会自动关闭

示例4:临时目录上下文管理器

import tempfile
import shutil
import os

class TemporaryDirectory:
    def __enter__(self):
        self.temp_dir = tempfile.mkdtemp()
        print(f"创建临时目录: {self.temp_dir}")
        return self.temp_dir
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        if os.path.exists(self.temp_dir):
            shutil.rmtree(self.temp_dir)
            print(f"删除临时目录: {self.temp_dir}")
        return False

# 使用
with TemporaryDirectory() as temp_dir:
    # 在临时目录中工作
    temp_file = os.path.join(temp_dir, "test.txt")
    with open(temp_file, 'w') as f:
        f.write("临时文件内容")
    print(f"在 {temp_dir} 中创建了文件")
# 临时目录会自动删除

在标准库中的应用

很多 Python 标准库都使用了上下文管理器:

# 文件操作
with open('file.txt', 'r') as f:
    content = f.read()

# 锁操作
import threading
lock = threading.Lock()
with lock:
    # 线程安全的代码块
    pass

# 数据库事务
import sqlite3
with sqlite3.connect('test.db') as conn:
    cursor = conn.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS test (id INTEGER)")

# 十进制精度上下文
import decimal
with decimal.localcontext() as ctx:
    ctx.prec = 2
    result = decimal.Decimal('1.123') + decimal.Decimal('2.456')
    print(result)  # 3.58

__enter__ 方法的返回值

__enter__ 方法的返回值会被 as 关键字接收:

class Resource:
    def __enter__(self):
        print("分配资源")
        return "资源对象"
    
    def __exit__(self, *args):
        print("释放资源")

with Resource() as res:
    print(f"获取到的资源: {res}")  # 输出: 获取到的资源: 资源对象

总结

__enter__ 方法的主要作用:

  1. 资源分配:在进入上下文时分配资源
  2. 初始化设置:进行必要的初始化操作
  3. 返回对象:返回要在 with 块中使用的对象
  4. 异常安全:确保资源能被正确释放,即使发生异常

使用上下文管理器可以让代码更简洁、更安全,避免了手动管理资源的麻烦。