简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM