another newbie question: why should you use "*args" ?

Dustan 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
language.

> 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
name.

> # calling method 1:
> execute (S[0], S[4] )
>
> # calling method 2:
> execute ( ( S[0], S[4] ) )

Let's take a look at those side-by-side:
execute (S[0], S[4] )
execute ( ( S[0], S[4] ) )

Now, which one *looks* better?

> # or *the extra flexibility)
> mylist = ( S[0], S[4] )
> 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):
  # etc.
Which is clearer?
someFunction(*args)
someFunction(args[0], args[1], args[2])

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.

> thanks,
> Stef Mientki




More information about the Python-list mailing list