[Python-ideas] Keyword only argument on function call

Steven D'Aprano steve at pearwood.info
Tue Sep 11 08:20:39 EDT 2018

On Tue, Sep 11, 2018 at 08:53:55PM +1000, Steven D'Aprano wrote:
> Or perhaps we could have an officially blessed way to give tools a hint 
> as to what the real signature is.
> class Child(Parent):
>     @signature_hint(Parent.method)
>     def method(self, **kwargs):
>         pass

Here's an untested implementation:

import inspect

def signature_hint(callable_or_sig, *, follow_wrapped=True):
    if isinstance(callable_or_sig, inspect.Signature):
        sig = callable_or_sig
        sig = inspect.signature(callable_or_sig, follow_wrapped=follow_wrapped)
    def decorator(func):
        func.__signature_hint__ = sig
        return func
    return decorator

inspect.signature would need to become aware of these hints too:

def f(a, b=1, c=2):

def g(*args):

def h(*args):

At this point h.__signature_hint__ ought to give

<Signature (a, b=1, c=2)>

(Note that this is not quite the same as the existing follow_wrapped 
argument of inspect.signature.)

This doesn't directly help Ander's problem of having to make calls like

    func(a=a, b=b, c=c)  # apologies for the toy example

but at least it reduces the pain of needing to Repeat Yourself when 
overriding methods, which indirectly may help in some (but not all) of 
Ander's cases.


More information about the Python-ideas mailing list