Skip to content

Instantly share code, notes, and snippets.

@jakelevi1996
Last active October 1, 2024 15:04
Show Gist options
  • Save jakelevi1996/f63006521d17153c6e49d5ec5e6f4c97 to your computer and use it in GitHub Desktop.
Save jakelevi1996/f63006521d17153c6e49d5ec5e6f4c97 to your computer and use it in GitHub Desktop.
Change function signature in Python
import inspect
def f1(a1: int, k1: str="v1", k2: str="v2") -> None:
print("f1", a1, k1, k2)
def f2(a2: int) -> int:
print("f2", a2)
return a2 + 1
def f3(a3: int, **kwargs: str) -> None:
f1((f2(a3)), **kwargs)
new_params = [
*[
p for p in inspect.signature(f3).parameters.values()
if p.kind is not p.VAR_KEYWORD
],
*[
p for p in inspect.signature(f1).parameters.values()
if p.default is not inspect.Parameter.empty
],
]
new_signature = inspect.signature(f3).replace(parameters=new_params)
print(inspect.signature(f1))
# (a1: int, k1: str = 'v1', k2: str = 'v2') -> None
print(inspect.signature(f3))
# (a3: int, **kwargs: str) -> None
f3.__signature__ = new_signature
print(inspect.signature(f3))
# (a3: int, k1: str = 'v1', k2: str = 'v2') -> None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment