import contextlib
@contextlib.contextmanagerdef managed_resource(): print("enter") try: yield "resource" except ValueError: print("value_error handled") finally: print("exit")with managed_resource() as res: print(f"using {res}") raise ValueError("Something went wrong")print("done")__enter__ 用 return 把值交给 as 变量;