gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:39:40 25 4
gpt4 key购买 nike

我有一个关于 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")

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

我需要将这些操作执行到函数 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 方法修饰。

关于python - 使用 python 中的语句获取上下文管理器中定义的函数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27979648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com