Skip to content

Instantly share code, notes, and snippets.

@laundmo
Last active February 18, 2025 18:35
Show Gist options
  • Save laundmo/a5a007d99b0f087079346f3479afe7e9 to your computer and use it in GitHub Desktop.
Save laundmo/a5a007d99b0f087079346f3479afe7e9 to your computer and use it in GitHub Desktop.
Copy a functions/methods signature for typing without specifying each individual argument type
# this needs only a single line, besides imports! only tested with pyright/pylance.
# downside: no functools.wraps, at runtime __doc__ etc. will be wrong
from functools import partial, wraps
from typing import cast
# just copy this and replace "otherfunc" with the function you want to copy from
@partial(cast, type(otherfunc))
def myfunc(*args, **kwargs):
return otherfunc(*args, **kwargs)
# a version with functools.wraps, probably not worth it
# use the proper function from below instead
@partial(partial(cast, type(otherfunc)), wraps(otherfunc))
def myfunc(*args, **kwargs):
return otherfunc(*args, **kwargs)
# just for fun, a version where you don't have to paste otherfunc twice. definitely NOT worth it
@(lambda src: partial(partial(cast, type(src)), wraps(src)))(otherfunc)
def myfunc(*args, **kwargs):
return otherfunc(*args, **kwargs)
# License: MIT
from functools import partial, wraps
from typing import Callable, ParamSpec, TypeVar, cast
P = ParamSpec("P")
R = TypeVar("R")
def copy_sig(s: Callable[P, R]) -> Callable[[Callable[..., R]], Callable[P, R]]:
"""Decorator to copy the function signature from another function.
Especially useful when overwriting methods with many arguments
Note: Only works towards the outside. Inside the function the types won't show up.
@copy_sig(source_func)
def other_func(*args, **kwargs):
...
"""
def return_func(func: Callable[..., R]) -> Callable[P, R]:
return cast(Callable[P, R], wraps(s)(func))
return return_func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment