Skip to content

Instantly share code, notes, and snippets.

@daddycocoaman
Created November 19, 2020 17:53
Show Gist options
  • Save daddycocoaman/129c367e84afd5a7ecd220348dffe915 to your computer and use it in GitHub Desktop.
Save daddycocoaman/129c367e84afd5a7ecd220348dffe915 to your computer and use it in GitHub Desktop.
Function Parameter Inheritance
# Don't actually use this. Why would you use this? Seriously, don't use it, fam.
import inspect
from types import FunctionType
from typing import Callable
def param_inherit(inherited_func: Callable):
"""Allows function to inherit the parameters of another function"""
def decorator(func: Callable):
def wrapper_param_inherit(*args, **kwargs):
# Get the signatures of the inherited and called functions
inherited_params = inspect.signature(inherited_func)
func_params = inspect.signature(func)
# Combine them. Inherited args first
combined_param_str = str(inherited_params) + str(func_params)
formatted_params = combined_param_str.replace(")(", ", ")
# Get the source code and replace parameters (add semicolon cause function)
func_code = inspect.getsourcelines(func)[0][1:]
func_code[0] = func_code[0].split("(")[0] + formatted_params + ":"
func_code = "\n".join(func_code)
# Create a new function with modified params and exec
modified_func_compiled = compile(func_code, "<string>", "exec")
modified_func_code_obj = list(filter(lambda x: x.__class__.__name__ == "code", modified_func_compiled.co_consts))[0]
modified_func = FunctionType(modified_func_code_obj, globals(), "sub_func")
return modified_func(*args, **kwargs)
return wrapper_param_inherit
return decorator
# Defined Functions
def base_function(a: int, b: int):
pass
@param_inherit(base_function)
def sub_function(d: int):
print(a + b + d)
# Call the "subclassed" function
sub_function(1, 1, 1)
@sdshlanta
Copy link

Thanks, this will solve some of the problems we are having in prod! /s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment