[Python] How can I get the _true_ signature of a Python function?

Discussão em 'Python' iniciado por Stack, Agosto 26, 2025.

  1. Stack

    Stack Membro Participativo

    tldr;


    inspect.signature gives us a function's signature, but this signature can lie (as assigning to the __signature__ attribute of a function will reveal.

    Is there a python function (builtin if possible) that will give me the true signature?

    a bit more about my context


    inspect.Parameter.empty is used as the value of the optional parameter attributes kind and default. Se that if you use it in your function definition, the function will sometimes behave like if you omitted it, and sometimes will not.

    Consider the two following functions:

    from inspect import Parameter, signature

    empty = Parameter.empty

    def chalk(x=empty, y=2):
    return True

    def cheese(x, y=2):
    return True



    The signatures (including signatures shown in help) are the same:

    assert signature(chalk) == signature(cheese)
    assert str(signature(chalk)) == str(signature(cheese)) =='(x, y=2)'


    But from a parameter hints point of view (when, in a fairly rich IDE, you get hints when entering arguments in a function) they are not the same. In VsCode,

    • chalk gives me (x: empty = empty, y: int = 2) -> Literal[True], which gives the impression that x has a default.
    • cheese gives me (x: Any, y: int = 2) -> Literal[True], which gives the impression that x does not have a default.

    inspect.signature basically gives us the value of the __signature__ attribute of the function, but that value is completely independent of the actual behavior of the function.

    Where does VsCode source its signature (string)? Is there a python function (builtin if possible) that will give me that true signature?

    Continue reading...

Compartilhe esta Página