Skip to content

Instantly share code, notes, and snippets.

@kurtbrose
Last active August 16, 2023 23:03
Show Gist options
  • Save kurtbrose/d4c4a99d45ced819ca354aaae80ea899 to your computer and use it in GitHub Desktop.
Save kurtbrose/d4c4a99d45ced819ca354aaae80ea899 to your computer and use it in GitHub Desktop.
Function parameter matching type guard.
"""
This defines a decorator that works kind of like a type-guard (https://peps.python.org/pep-0647/) for the arguments
of a function.
The usefulness of this is for functions that "defer" their arguments to another function, e.g. places where you
would call functools.wraps().
@same_params_as(f)
@functools.wraps(f)
def passes_args_through(*a, **kw):
return f(*a, **kw)
"""
from typing import Callable, ParamSpec, TypeAlias
# pyright: reportMissingTypeArgument=true
_P = ParamSpec("_P")
_MatchFunc: TypeAlias = Callable[_P, object]
_MatchDecorator: TypeAlias = Callable[[_MatchFunc[_P]], _MatchFunc[_P]]
def same_params_as(_matching_func: _MatchFunc[_P]) -> _MatchDecorator[_P]:
"""For the purposes of static type checking, mark a function as having the same param spec as another."""
return lambda f: f
"""
def f(a): pass
@same_params_as(f)
def b(*a, **kw): pass
b() # test - this should be flagged as missing parameter 'a'
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment