[Python] inspect.signature on class methods

Discussão em 'Python' iniciado por Stack, Março 17, 2025.

  1. Stack

    Stack Membro Participativo

    Can someone help me understand why the Signature.bind(...).arguments are different when I call directly for a class method vs. when used in a decorator?

    I have the decorator below.

    def decorator(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
    print(inspect.signature(func).bind(*args, **kwargs).arguments)
    return func(*args, **kwargs)
    return inner


    When this decorator runs on a class method, I get the cls parameter in the signature like below.

    class MyClass:

    @classmethod
    @decorator
    def mymethod(cls, a, b):
    return a + b

    MyClass.mymethod(1, 2)

    # returns:
    # {'cls': <class '__main__.MyClass'>, 'a': 1, 'b': 2}
    # 3


    If I call inspect.signature on the class method directly, I get a different result or an error.

    This first block runs successfully but does not return the class parameter.

    print(inspect.signature(MyClass.mymethod).bind(1, 2).arguments)
    # returns {'a': 1, 'b': 2}


    This errors out.

    print(inspect.signature(MyClass.mymethod).bind(MyClass, 1, 2).arguments)
    # TypeError: too many positional arguments

    Continue reading...

Compartilhe esta Página