Passing a variable number of arguments to a function

Chris Rebert clp2 at rebertia.com
Fri Feb 13 00:51:25 CET 2009


On Thu, Feb 12, 2009 at 3:44 PM, mercado <python.dev.9 at gmail.com> wrote:
> I have the following piece of code that is bugging me:
>
> #-------------------------------------------------------------------------------
> def someFunc(arg1, arg2=True, arg3=0):
>     print arg1, arg2, arg3
>
> someTuple = (
>     ("this is a string",),
>     ("this is another string", False),
>     ("this is another string", False, 100)
> )
>
> for argList in someTuple:
>     if len(argList) == 1:
>         someFunc(argList[0])
>     elif len(argList) == 2:
>         someFunc(argList[0], argList[1])
>     elif len(argList) == 3:
>         someFunc(argList[0], argList[1], argList[2])
> #-------------------------------------------------------------------------------
>
> Is it possible to rewrite this code so I don't have that awkward if
> statement at the bottom that passes every variation in the number of
> arguments to the function?  I know that it's possible to define a function
> to accept a variable number of parameters using *args or **kwargs, but it's
> not possible for me to redefine this function in the particular project I'm
> working on.

There is a nicely symmetrical calling syntax that does the inverse of
* in a function declaration:

for argList in someTuple:
    someFunc(*argList)

There's also an analogous func(**dictOfKwdArgs) call syntax.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list