使用 python 中的语句获取上下文管理器中定义的函数列表

Get the list of functions defined in a contextmanager with statement in python

我在python中有一个问题,如果有人可以帮忙 这是示例,我有一个上下文管理器,如下所示

from contextlib import contextmanager

@contextmanager
def main_func(name):
    print("<%s>" % name)
    yield
    print("</%s>" % name)
    # Retreive the list of function here : tag_func1 and tag_func2 then run the one I need to run

然后像下面这样使用它

with main_func("h1"):
   def tag_func1():
       print("foo1")

   def tag_func2():
       print("foo2")

我想知道是否可以在此处检索 with 语句中定义的函数列表 tag_func1tag_func1 和 运行 它们在代码中动态显示。

我需要在函数 main_func 中执行这些操作 上下文管理器

非常感谢你的帮助,

class ContextManager():

    def __init__(self):
        self.functions = []

    def func(self, f):
        self.functions.append(f)
        return f

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        for f in self.functions:
            print(f.__name__)


with ContextManager() as cm:

    @cm.func
    def add(x, y):
        return x + y

    def foo():
        return "foo"

    @cm.func
    def subtract(x, y):
        return x - y


# this code prints "add" and "subtract"

此自定义上下文管理器可以访问 with 语句内定义的所有函数,这些函数用 func 方法修饰。