Suppose I have two classes...
class A:
def __init__(self, *args, arg1="default1", arg2="default2"):
# Initialise class A
class B:
def __init__(self, arg3="default3", arg4="default4"):
# Initialise class B
Each class has its own keyword arguments, and one has positional arguments.
Now suppose there is a function which creates an instance of each of these classes, using its own arguments to do so:
def make_objs(*args, arg1="default1", arg2="default2", arg3="default3", arg4="default4"):
objA = ClassA(*args, arg1=arg1, arg2=arg2)
objB = ClassB(arg3=arg3, arg4=arg4)
Here I manually allocate the keyword arguments that the function received to the correct class. This is a bit tedious though - I have to duplicate the keywords in the function definition, and changing the classes will mean changing the function's arguments.
Ideally, I would do something like this:
def make_objs(*args, **kwargs):
objA = ClassA(*args, **kwargs)
objB = ClassB(**kwargs)
Where each class would take all the keyword arguments and extract only those which are relevant to it. That's not what the above code would actually do of course, it will throw an Exception because ClassA
is not expecting an argument called arg3
.
Is there anyway to do this? Some way of making the function take **kwargs
as an argument and determine which arguments can go to which class?
To avoid all the repetitious typing you could create a utility function which uses the
inspect
module to examine the calling sequence of the functions / methods involved.Here's a runnable example of applying it to your code. The utility function is the one named
get_kwarg_names
:Output: