I am trying to determine the signature of a PyTorch function at runtime (e.g. torch.empty or torch.zeros). But something like inspect.signature(torch.empty) doesn't work here:
>>> 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>
I am guessing the underlying reason to be the absence of the __code__ attribute
>>> 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__'
Is there any way to inspect the signatures of python functions in such cases?
May be not best option, but workaround, - parse 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:
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With