Home > Back-end >  How does the `type` callable show two overloaded signatures in PyCharm?
How does the `type` callable show two overloaded signatures in PyCharm?

Time:03-12

The type callable in Python can be used in two ways; with one argument it returns the class of the argument, and with three arguments it returns a new class.

In PyCharm, code completion for the type callable makes it appear that type is overloaded, by presenting both the first and second option for invoking type:

enter image description here

How is PyCharm able to display the two ways of invoking type as seen in the picture above ?

Is this something we can also accomplish with our own user defined callables, or is this a special case that PyCharm hardcodes for type?


In PyCharm if I double click on type I get sent to the __init__ defintion of type in builtins.py. However this shows something different:

enter image description here

This shows that Pycharm isn't inspecting the doc string or anything fancy.

In addition, this definition doesn't include any type hints, yet the pycharm code completion shows type hints for both ways of calling type. How does it know to do this?

CodePudding user response:

PyCharm uses the Typeshed package to get the annotations and definitions for the Python standard library as described here. This package contains stub files (.pyi files) that provide the annotations. Specifically, the type stub can be found here:

@overload
def __init__(self, __o: object) -> None: ...
@overload
def __init__(self, __name: str, __bases: tuple[type, ...], __dict: dict[str, Any], **kwds: Any) -> None: ...

To annotate a function with multiple different signatures you can use the typing.overload decorator to provide multiple annotations for the same function, example below. This is how Typeshed provides two different definitions for the type function

@overload
def foo(bar: int) -> int:
    ...

@overload
def foo(bar: str) -> str:
    ...

def foo(bar):
    # func body
  • Related