首页 > 解决方案 > 有没有办法让在 with 语句中调用的函数隐式获取 with 对象而不将其传递给另一个函数?

问题描述

想知道是否可以将 with 语句对象隐式传递给其他函数。

假设以下代码:

with get_something() as something:
    # do some things with it
    # then call another function for more things to happen
    do_other_things()

在另一个模块/类中:

def do_other_things():
    # do other things
    print(something)

而不是像下面那样显式传递“某事”变量:

def do_other_things(something):
    # do other things
    print(something)

with get_something() as something:
    # do some things with it
    # then call another function for more things to happen
    do_other_things(something)

因为我们在 with-statement 上下文中,有没有办法,神奇的关键字,装饰器,或者允许在“with”中调用的函数在不传递它的情况下访问它的变量。

谢谢。

标签: pythonwith-statementcontextmanager

解决方案


推荐阅读