another newbie question: why should you use "*args" ?
DustanGroups at gmail.com
Wed Jan 31 13:48:57 CET 2007
On Jan 31, 5:41 am, stef <s.mien... at id.umcn.nl> wrote:
> why should I use *args,
> as in my ignorance,
> making use of a list (or tupple) works just as well,
> and is more flexible in it's calling.
Others have mentioned the instances in which it's actually useful -
for catch-all arguments. But you also should take into consideration
the aesthetics, since python is supposed to be an aesthetically nice
> So the simple conclusion might be: never use "*args",
> or am I overlooking something ?
> # method 1
> def execute (self, *args):
> for i in range ( len(args) ):
> ... do something
> # method 2
> def chunk_plot(self, list):
> for i in range ( len(list) ):
> .... do something
It's bad practice to use built-ins like 'list' as a regular variable
> # calling method 1:
> execute (S, S )
> # calling method 2:
> execute ( ( S, S ) )
Let's take a look at those side-by-side:
execute (S, S )
execute ( ( S, S ) )
Now, which one *looks* better?
> # or *the extra flexibility)
> mylist = ( S, S )
> execute ( mylist )
Also, take into consideration the opposite end of the pole; you have
your list of arguments (args), and your about to call a function that
was declared something like this:
def someFunction(arg1, arg2, arg3):
Which is clearer?
someFunction(args, args, args)
And if you've got a variable number of arguments, it becomes virtually
impossible to avoid using the *args syntax.
And that doesn't even begin to cover the need for **kargs! (which, if
you haven't noticed, is generally used next to *args)
It turns out that it's not really necessary in a static-typed language
like java (although java 5.0 introduced it); it's the dynamic nature
of python that makes these syntactic sugars necessary. And without
them, function calls can get really ugly.
> Stef Mientki
More information about the Python-list