Taking the argument signature from a different function

I wrote a Stackoverflow for this (same solution as Eric Traut) and also created an Issue to include this in stdlib.

Currently working on PR.

2 Likes

PR is at gh-107001: Add a stdlib decorator that copies/applies the ParameterSpec from one function to another by CarliJoy · Pull Request #121693 · python/cpython · GitHub waiting for some arguments to be merged.

Type checkers don’t seem to understand setting __signature__ which has been part of python since 3.3 which means even when using the type checking appropriate method to transform the signature with a decorator, if you also try to update the signature as-transformed for inspect, ipython, etc, type checkers generate false positives.

I understand why static analysis can’t use the signature object as it exists at runtime, but setting it for runtime introspection to be correct as well should not be causing type-checking errors.

A different solution to the problem, given:

external - the function whose signature we want to reuse
ours - the function we want to define with the signature of external

from functools import wraps
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    ours = external
else:
    @wraps(external)
    def ours(*args, **kwargs):
        return external(*args, **kwargs)

I added an issue for a slightly more general ask: how to copy a method’s superclass method: How should we annotate functions that forward to their superclass? · Issue #1471 · python/typing · GitHub