Function.apply (is even easier) in Python

I can't believe I've been using Python for several months now without really understanding the extended call syntax.

You know how in ActionScript you can do functionRef.apply(thisObj, argumentsArray) if you need to call a function with a dynamic list of arguments? I was looking for a way to do this in Python and googled for "apply". Lo and behold, I found that it was deprecated.

Instead of using a separate function, you can simply pass in your arguments (and keyword arguments) to the function itself.

e.g., to call function add_numbers(first_number=a,second_number=b) with the list special_arguments=[2,2], you'd write:

add_numbers(*special_arguments)

And, for keyword arguments, where my_awesome_keyword_arguments = {'first_number':2, 'second_number':2}:

add_numbers(**my_awesome_keyword_arguments)

Finally, you can mix both positional and keyword arguments (say positional=[2] and keyword={'second_number':2}):

add_numbers(*positional, **keyword)

The crazy thing is that I've been using methods that use extended syntax for months now and yet I didn't actually grok exactly what was going on until today. Ah, I love it when something clicks. (And did I mention that the more I use Python, the more I love it?) :)

Comments