Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 741
Abdul Muneer Avatar asked Sep 13 '26 12:09

Abdul Muneer


1 Answers

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:
...
like image 106
Alexey Birukov Avatar answered Sep 15 '26 03:09

Alexey Birukov