Skip to content

Instantly share code, notes, and snippets.

@himaprasoonpt
Created July 18, 2020 05:08
Show Gist options
  • Save himaprasoonpt/1106aaab3d2e46f79af2138d3c996b79 to your computer and use it in GitHub Desktop.
Save himaprasoonpt/1106aaab3d2e46f79af2138d3c996b79 to your computer and use it in GitHub Desktop.
Create dynamic init function for base class based on annotations
from types import FunctionType
class BaseClass:
def __new__(cls, *args, **kwargs):
# Creating a custom __init__ function
params_string = ",".join(cls.params) # For init function arguments
params_kwargs = ','.join([f"{i}={i}" for i in cls.params]) # Creating
k=f"""def __init__(self,{params_string}):\n\tBaseClass.__init__(self, {params_kwargs})
"""
# print(k)
init_code = compile(k, __file__, 'exec')
__init__ = FunctionType(init_code.co_consts[0], globals(), "__init__")
cls.__init__ = __init__
instance = super(BaseClass, cls).__new__(cls)
return instance
def __init__(self, **kwargs):
print("params", kwargs)
def param(name):
def hello(custom_class):
if not hasattr(custom_class, 'params'):
custom_class.params = []
custom_class.params.append(name)
return custom_class
return hello
@param(name="k")
@param(name="j")
class A(BaseClass):
def __init__(self, **kwargs):
pass
@param(name="l")
@param(name="m")
class M(BaseClass):
def __init__(self, **kwargs):
pass
A(j=3, k=5)
M(l=2, m=5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment