[Python]手动实现上下文管理器

发布时间 2023-03-26 22:30:21作者: LeoShi2020

1. 手动实现

'''
- 进入with语句块时,就会执行文件类的`__enter__`返回一个文件对象,并赋值给变量 `f`
- 从with语句块出来时,机会执行文件类的`__exit__`,在其内部实现 f.close(),所以使用者就不需要在手动关闭文件对象了。
'''

class MyFile():
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print("进入with...")
        return self		# 返回的数据赋值给p

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("退出with")


with MyFile('jack') as p:
    print(p.name)

进入with...
jack
退出with

2. 使用contextlib库

'''
- 使用装饰器 contextmanager
- get_file函数内部,yield语句前的代码在进入with语句时执行,yield的值赋值给 as后面的变量,
- yield后面的代码在退出with语句时执行
'''
import contextlib


@contextlib.contextmanager
def get_file(filename: str):
    file = open(filename, "r", encoding="utf-8")
    yield file
    file.close()


with get_file('oauth2.py') as f:
    print(f.read())