Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly does inspect.signature work with classes?

The inspect.signature doc states that it supports classes as input, but it doesn't go into any sort of detail:

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

If I call inspect.signature(MyClass), what signature does it return? Does it return the signature of MyClass.__init__? Or MyClass.__new__? Or something else?

like image 588
Aran-Fey Avatar asked May 29 '19 08:05

Aran-Fey


People also ask

Which of the following is used to view the signature and documentation for a function in Python?

Using signature() function We can get function Signature with the help of signature() Function. It takes callable as a parameter and returns the annotation. It raises a value Error if no signature is provided.

What is inspect stack?

inspect. stack() returns a list with frame records. In function whoami() : inspect. stack()[1] is the frame record of the function that calls whoami , like foo() and bar() . The fourth element of the frame record ( inspect.

What is inspect in Python?

The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.


1 Answers

It tries pretty much everything it reasonably could. I think the details are probably deliberately undocumented, because they're complicated and likely to get more so as new Python versions add more stuff to try.

For example, as of CPython 3.7.3, the code path tries the following things in order:

  • If the metaclass has a custom __call__ defined in Python, it uses the signature of the metaclass __call__ with the first argument removed.
  • Otherwise, if the class has a __new__ method defined in Python, it uses the __new__ signature with the first argument removed.
  • Otherwise, if the class has an __init__ method defined in Python, it uses the __init__ signature with the first argument removed.
  • Otherwise, it traverses the MRO looking for a __text_signature__. If it finds one, it parses __text_signature__ to get the signature information.
  • If it still hasn't found anything, if the type's __init__ is object.__init__ and the type's __new__ is object.__new__, it returns the signature of the object class. (There's a misleading comment and a possible bug involving metaclasses around this point - the comment says it's going to check for type.__init__, but it doesn't do that. I think this commit may have made a mistake here.)
  • If it still hasn't found anything, it gives up and raises a ValueError saying it couldn't find anything.
like image 157
user2357112 supports Monica Avatar answered Sep 28 '22 18:09

user2357112 supports Monica