在Python中寻找函数参数
我想知道一个类的 __init__
方法有哪些参数。最简单的方法是这样做:
cls.__init__.__func__.__code__.co_varnames[:code.co_argcount]
但是,如果这个类有装饰器的话,这个方法就不管用了。因为它会给出装饰器返回的函数的参数列表。我想要的是原始的 __init__
方法和它的参数。如果有装饰器的话,装饰器函数会在装饰器返回的函数的闭包中找到:
cls.__init__.__func__.__closure__[0]
不过,如果闭包里还有其他东西,那就更复杂了,装饰器有时会这样做:
def Something(test):
def decorator(func):
def newfunc(self):
stuff = test
return func(self)
return newfunc
return decorator
def test():
class Test(object):
@Something(4)
def something(self):
print Test
return Test
test().something.__func__.__closure__
(<cell at 0xb7ce7584: int object at 0x81b208c>, <cell at 0xb7ce7614: function object at 0xb7ce6994>)
这时我就得决定是要装饰器的参数,还是原始函数的参数。装饰器返回的函数可能有 *args
和 **kwargs
作为参数。如果有多个装饰器,我又该如何选择我关心的那个呢?
那么,如何才能找到一个函数的参数,即使这个函数可能被装饰过?还有,怎样才能沿着装饰器的链条回到被装饰的函数呢?
更新:
这是我现在实际操作的方式(为了保护被指控者的身份,名字已经更改):
import abc
import collections
IGNORED_PARAMS = ("self",)
DEFAULT_PARAM_MAPPING = {}
DEFAULT_DEFAULT_PARAMS = {}
class DICT_MAPPING_Placeholder(object):
def __get__(self, obj, type):
DICT_MAPPING = {}
for key in type.PARAMS:
DICT_MAPPING[key] = None
for cls in type.mro():
if "__init__" in cls.__dict__:
cls.DICT_MAPPING = DICT_MAPPING
break
return DICT_MAPPING
class PARAM_MAPPING_Placeholder(object):
def __get__(self, obj, type):
for cls in type.mro():
if "__init__" in cls.__dict__:
cls.PARAM_MAPPING = DEFAULT_PARAM_MAPPING
break
return DEFAULT_PARAM_MAPPING
class DEFAULT_PARAMS_Placeholder(object):
def __get__(self, obj, type):
for cls in type.mro():
if "__init__" in cls.__dict__:
cls.DEFAULT_PARAMS = DEFAULT_DEFAULT_PARAMS
break
return DEFAULT_DEFAULT_PARAMS
class PARAMS_Placeholder(object):
def __get__(self, obj, type):
func = type.__init__.__func__
# unwrap decorators here
code = func.__code__
keys = list(code.co_varnames[:code.co_argcount])
for name in IGNORED_PARAMS:
try: keys.remove(name)
except ValueError: pass
for cls in type.mro():
if "__init__" in cls.__dict__:
cls.PARAMS = tuple(keys)
break
return tuple(keys)
class BaseMeta(abc.ABCMeta):
def __init__(self, name, bases, dict):
super(BaseMeta, self).__init__(name, bases, dict)
if "__init__" not in dict:
return
if "PARAMS" not in dict:
self.PARAMS = PARAMS_Placeholder()
if "DEFAULT_PARAMS" not in dict:
self.DEFAULT_PARAMS = DEFAULT_PARAMS_Placeholder()
if "PARAM_MAPPING" not in dict:
self.PARAM_MAPPING = PARAM_MAPPING_Placeholder()
if "DICT_MAPPING" not in dict:
self.DICT_MAPPING = DICT_MAPPING_Placeholder()
class Base(collections.Mapping):
__metaclass__ = BaseMeta
"""
Dict-like class that uses its __init__ params for default keys.
Override PARAMS, DEFAULT_PARAMS, PARAM_MAPPING, and DICT_MAPPING
in the subclass definition to give non-default behavior.
"""
def __init__(self):
pass
def __nonzero__(self):
"""Handle bool casting instead of __len__."""
return True
def __getitem__(self, key):
action = self.DICT_MAPPING[key]
if action is None:
return getattr(self, key)
try:
return action(self)
except AttributeError:
return getattr(self, action)
def __iter__(self):
return iter(self.DICT_MAPPING)
def __len__(self):
return len(self.DICT_MAPPING)
print Base.PARAMS
# ()
print dict(Base())
# {}
此时,Base 报告四个常量的值不太有趣,而实例的字典版本是空的。不过,如果你创建一个子类,你可以重写这四个常量中的任何一个,或者在 __init__
中添加其他参数:
class Sub1(Base):
def __init__(self, one, two):
super(Sub1, self).__init__()
self.one = one
self.two = two
Sub1.PARAMS
# ("one", "two")
dict(Sub1(1,2))
# {"one": 1, "two": 2}
class Sub2(Base):
PARAMS = ("first", "second")
def __init__(self, one, two):
super(Sub2, self).__init__()
self.first = one
self.second = two
Sub2.PARAMS
# ("first", "second")
dict(Sub2(1,2))
# {"first": 1, "second": 2}
1 个回答
3
考虑一下这个装饰器:
def rickroll(old_function):
return lambda junk, junk1, junk2: "Never Going To Give You Up"
class Foo(object):
@rickroll
def bar(self, p1, p2):
return p1 * p2
print Foo().bar(1, 2)
在这里,rickroll 装饰器接收了 bar 方法,然后把它丢掉,换成一个新的函数。这个新函数不管原来参数的名字(甚至可能是数字!),而是直接返回一段经典歌曲的歌词。
之后再也没有提到过原来的函数,所以垃圾回收器随时可以把它清理掉。
在这种情况下,我看不出你怎么能找到参数名 p1 和 p2。根据我的理解,连 Python 的解释器自己都不知道它们原来叫什么。