Python3新增了一个
有没有一种方法可以识别和捕获闭包范围内声明的函数,以便我可以将这些函数与模块范围内声明的函数区分开,而无需引用封闭的函数(即
__prepare__
,这样你就可以替换用于从类声明中收集项目的字典类型(参见这里)。使用__prepare__
,我可以设置类以允许多个定义相同的成员函数。class MultiType(type):
@classmethod
def __prepare__(metacls, name, bases, **kwds):
return collections.defaultdict(list)
class Foo(metaclass=MultiType):
def bar(self, x):
return x - 1
def bar(self, x):
return x
在模块级别,我可以使用装饰器来进行一些技巧操作:
def capture(f):
module = importlib.import_module(f.__module__)
if not hasattr(module, 'my_cache'):
setattr(module, 'my_cache', [])
module.my_cache.append(f)
@functools.wraps(f)
def _wrapper(*args, **kwargs):
return (func(*args, **kwargs) for func in module.my_cache)
return _wrapper
@capture
def foo(x):
return x - 1
@capture
def foo(x):
return 42
然而,如果我在闭包内执行此操作,则可能会添加作用域为模块级别的内容,这是不应该的。
def foo(x):
@some_awesome_deco
def bar(y):
return y
@some_awesome_deco
def bar(y):
return 24
return bar(x+1)
有没有一种方法可以识别和捕获闭包范围内声明的函数,以便我可以将这些函数与模块范围内声明的函数区分开,而无需引用封闭的函数(即
@some_awesome_deco(foo)
)?
sys._getframe
函数。 - wheaties