The method to get different number of arguments and still being able of selecting the right one is the use of *args and **keyword_args parameters.
From Mark Lutz's Learning Python
book:
*
and **
, are designed to support functions that take any number of arguments. Both can appear in either the function definition or a
function call, and they have related purposes in the two locations.
*
and **
in function definition
If you define a function:
def f1(param1, *argparams, **kwparams):
print 'fixed_params -> ', param1
print 'argparams --> ', argparams
print 'kwparams ---->,', kwparams
you can call it this way:
f1('a', 'b', 'c', 'd', kw1='keyw1', kw2='keyw2')
Then you get:
fixed_params -> a
argparams --> ('b', 'c', 'd')
kwparams ---->, {'kw1': 'keyw1', 'kw2': 'keyw2'}
So that you can send/receive any number of parameters and keywords.
One typical idiom to recover keyword args is as follows:
def f1(param1, **kwparams):
my_kw1 = kwparams['kw1']
---- operate with my_kw1 ------
In this way your function can be called with any number of params and it uses those it needs.
This type or arguments are frecuently used in some GUI code like wxPython class definition and subclassing as well as for function currying, decorators, etc
*
and **
in function call
*
and **
params in a function call are unpacked when taken by the function:
def func(a, b, c, d):
print(a, b, c, d)
args = (2, 3)
kwargs = {'d': 4}
func(1, *args, **kwargs)
### returns ---> 1 2 3 4
Great!