Suppose I have a generic function f. I want to programmatically create a function f2 that behaves the same as f, but has a customised signature.
More detail
Given a list l and and dictionary d I want to be able to:
- Set the non-keyword arguments of f2 to the strings in l
- Set the keyword arguments of f2 to the keys in d and the default values to the values of d
ie. Suppose we have
l=["x", "y"]
d={"opt":None}
def f(*args, **kwargs):
#My code
Then I would want a function with signature:
def f2(x, y, opt=None):
#My code
A specific use case
This is just a simplified version of my specific use case. I am giving this as an example only.
My actual use case (simplified) is as follows. We have a generic initiation function:
def generic_init(self,*args,**kwargs):
"""Function to initiate a generic object"""
for name, arg in zip(self.__init_args__,args):
setattr(self, name, arg)
for name, default in self.__init_kw_args__.items():
if name in kwargs:
setattr(self, name, kwargs[name])
else:
setattr(self, name, default)
We want to use this function in a number of classes. In particular, we want to create a function init that behaves like generic_init, but has the signature defined by some class variables at creation time:
class my_class:
__init_args__=["x", "y"]
__kw_init_args__={"my_opt": None}
__init__=create_initiation_function(my_class, generic_init)
setattr(myclass, "__init__", __init__)
We want create_initiation_function to create a new function with the signature defined using init_args and kw_init_args. Is it possible to writ create_initiation_function?
Please note:
- If I just wanted to improve the help, I could set doc.
- We want to set the function signature on creation. After that, it doesn't need to be changed.
- Instead of creating a function like generic_init, but with a different signature we could create a new function with the desired signature that just calls generic_init
- We want to define create_initiation_function. We don't want to manually specify the new function!
Related
- Preserving signatures of decorated functions: This is how to preserve a signature when decorating a function. We need to be able to set the signature to an arbitrary value