Skip to main content
 首页 » 编程设计

python之获取任何可调用对象的参数

2024年10月17日6Renyi-Fan

我对获取可调用 Python 对象采用的参数和关键字参数列表的通用方法很感兴趣。这对于具有 inspect.getargspec 函数的函数来说是直接的,例如:

import inspect 
from functools import partial 
 
def foo(*args, **kwargs): 
    return args, kwargs 
 
print(inspect.getargspec(foo)) 
>>ArgSpec(args=[], varargs='args', keywords='kwargs', defaults=None) 
 
def bar(*args): 
    return args 
 
print(inspect.getargspec(bar)) 
>>ArgSpec(args=[], varargs='args', keywords=None, defaults=None) 

但是,这在以下情况下会失败:

partial_function = partial(foo, kwarg="value") 
 
inspect.getargspec(partial_function) 
>>TypeError: <functools.partial object at 0x11748bc58> is not a Python function 
 
class Foo(object): 
    def __call__(self, *args, **kwargs): 
        return args, kwargs 
 
foo_instance = Foo() 
 
inspect.getargspec(foo_instance) 
>>TypeError: <__main__.Foo object at 0x116c13ed0> is not a Python function 
 
inspect.getargspec(zip) 
>>TypeError: <built-in function zip> is not a Python function 

请注意,有一些方法可以获得部分函数和可调用对象的参数,即:

inspect.getargspec(partial_function.func) 
>>ArgSpec(args=[], varargs='args', keywords='kwargs', defaults=None) 
 
inspect.getargspec(foo_instance.__call__) 
>>ArgSpec(args=['self'], varargs='args', keywords='kwargs', defaults=None) 

但如果可能的话,我想要一种更通用的方法来获得这些结果。

请您参考如下方法:

所有这些都可以通过使用 inspect.signature 来处理辅助函数,如其文档中所述:

Accepts a wide range of python callables, from plain functions and classes to functools.partial() objects.

signature 的作用是获取您的可调用对象并从中构造一个Signature 对象:

>>> from inspect import signature 
>>> s = signature(Foo())  # class as shown in your example 

参数现在位于 Signature 实例的 parameters 映射属性中:

>>> s.parameters 
mappingproxy({'args': <Parameter "*args">, 'kwargs': <Parameter "**kwargs">}) 

使用 partial 对象,您将获得相应的表示:

>>> def foo(a, b, c): pass 
>>> p = partial(foo, c = 30) 
>>> signature(p).parameters 
<Signature (a, b, *, c=20)> 

至于内置函数,例如 zip,这并不总是可行的,其中一些函数不会公开适当的元数据来构造签名,from PEP 362 :

Some functions may not be introspectable in certain implementations of Python. For example, in CPython, built-in functions defined in C provide no metadata about their arguments. Adding support for them is out of scope for this PEP.

因此,虽然 zip 不是公开有关其自身信息的类型,但其他类型是,例如 all:

>>> signature(all) 
<Signature (iterable, /)> 

不幸的是,你需要一个 try-except 来做这些,没有别的办法了。

signature 助手处理的情况在 implementation section of PEP 362 中列举介绍了它。

一般来说,inspect.getargspec 在 Python 3 中已经弃用了一段时间,建议的方法(如果您使用的是 Python 3)是使用通过 提供的表示code>Signature 对象。

如果在 Python 2 上,我敢肯定你不能直接用 getargspec 来做,你应该使用 getfullargspec 作为 Anttis ' 回答暗示。