This is a bit of a forum newbie question.
I have noticed
compose function in this notebook - 08_data block.ipynb has an
*args parameter which does not seem to be used. Here is the function:
def compose(x, funcs, *args, order_key='_order', **kwargs):
key = lambda o: getattr(o, order_key, 0)
for f in sorted(listify(funcs), key=key): x = f(x, **kwargs)
Is these some kind of magical use for it or is it not necessary and can be removed from the function?
*args and **kwargs are special arguments in Python. They’re used when you don’t know the number of arguments in advance. Google and read about them.
Here’s an article for example
Yes, but in the article you quoted you can find an example of the
z = 1
for num in args:
z *= num
*args is actually used. In the
compose function it is not. The question I have is: is it necessary or is there some kind of magic going on here?
I don’t know if it is necessary here but it does have an impact: it will catch any argument that is neither named nor used and ignore them (instead of triggering an error).
Oh okay, say for example you are building a plotting library on top of Matplotlib. You provide the user with a bunch of arguments they can pass. But you also additionally include *args and **kwargs for any extra arguments that they pass. These arguments can then be passed on to Matplotlib because it might support them.
Another reason is as @nestorDemeure mentioned, to avoid errors and we don’t know how many arguments can be expected.
But in general it is good to use them minimally.
Many thanks @nestorDemeure, @dipam7 .
OK, so whilst it is not necessary, it is used to make the function more “tolerant” to parameters which are not recognized.