I have an object that takes in a function name func, args, and kwargs, and at some point runs
func(*args, **kwargs)
The issue is, if func requires no args/kwargs, args/kwargs default to None, which leads to a TypeError. For example, if the function required no parameters, args, kwargs default to None:
def test():
pass
args = None
kwargs = None
test(*args, **kwargs)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-b9618694fbf2> in <module>()
----> 1 test(*args, **kwargs)
TypeError: test() argument after ** must be a mapping, not NoneType
I'm sure there's a good way to solve this without cascading if statements checking if args/kwargs exist, each with its own function call, but I'm not sure how. The main goal is to pass a function, and its unknown parameters to an object, which will then use them in a method later.
Edited: added an example for clarity
Calling functions with arbitrary arguments Just as you can define functions that take arbitrary keyword arguments, you can also call functions with arbitrary keyword arguments. By this I mean that you can pass keyword arguments into a function based on items in a dictionary.
With Python, we can use the *args or **kwargs syntax to capture a variable number of arguments in our functions. Using *args , we can process an indefinite number of arguments in a function's position. With **kwargs , we can retrieve an indefinite number of arguments by their name.
Python **kwargs In the function, we use the double asterisk ** before the parameter name to denote this type of argument. The arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the parameter excluding double asterisk ** .
Well, using *args in a function is Python's way to tell that this one will: Accept an arbitrary number of arguments. Pack the received arguments in a tuple named args. Note that args is just a name and you can use anything you want instead.
The issue is, if func requires no args/kwargs, args/kwargs default to None, which leads to a TypeError.
This is not true:
def func1(*args, **kwargs)
print args, kwargs
will print
() {}
In reverse,
def func2(): pass
can be perfectly called with
func2(*(), **{})
So just change your args
and kwargs
variables and you're fine.
Avoid to default your args
and kwargs
to None
.
args
should be a tuple : args = ()
kwargs
should be a dictionnary : kwargs = {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With