检查没有 __code__ 属性的 python 函数的签名(例如 PyTorch)

xiaoxingxing pytorch 541

原文标题Inspect signature of a python function without the __code__ attribute (e.g. PyTorch)

我试图在运行时确定 PyTorch 函数的签名(例如,torch.empty 或 torch.zeros)。但是像inspect.signature(torch.empty)这样的东西在这里不起作用:

>>> import inspect
>>> import torch
>>> def add(a,b):
...     return a+b
... 
>>> inspect.signature(add)
<Signature (a, b)>
>>> inspect.signature(torch.empty)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/anaconda/envs/gc/lib/python3.8/inspect.py", line 3105, in signature
    return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
  File "/home/anaconda/envs/gc/lib/python3.8/inspect.py", line 2854, in from_callable
    return _signature_from_callable(obj, sigcls=cls,
  File "/home/anaconda/envs/gc/lib/python3.8/inspect.py", line 2308, in _signature_from_callable
    return _signature_from_builtin(sigcls, obj,
  File "/home/anaconda/envs/gc/lib/python3.8/inspect.py", line 2119, in _signature_from_builtin
    raise ValueError("no signature found for builtin {!r}".format(func))
ValueError: no signature found for builtin <built-in method empty of type object at 0x7f382e1321c0>

我猜根本原因是没有__code__属性

>>> add.__code__
<code object add at 0x7f382f3a9710, file "<stdin>", line 1>
>>> torch.empty.__code__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute '__code__'

在这种情况下,有没有办法检查 python 函数的签名?

原文链接:https://stackoverflow.com//questions/71572847/inspect-signature-of-a-python-function-without-the-code-attribute-e-g-pyto

回复

我来回复
  • Alexey Birukov的头像
    Alexey Birukov 评论

    可能不是最佳选择,但解决方法,-解析torch.empty.__doc__

    print(torch.empty.__doc__)
    

        empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor
    
    Returns a tensor filled with uninitialized data. The shape of the tensor is
    defined by the variable argument :attr:`size`.
    
    Args:
    ...
    
    2年前 0条评论