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

I am guessing the underlying reason to be the absence of the __code__ attribute
&gt;&gt;&gt; add.__code__
&lt;code object add at 0x7f382f3a9710, file &quot;&lt;stdin&gt;&quot;, line 1&gt;
&gt;&gt;&gt; torch.empty.__code__
Traceback (most recent call last):
  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;
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) -&gt; Tensor

Returns a tensor filled with uninitialized data. The shape of the tensor is
defined by the variable argument :attr:`size`.

Args:
...

