bob morane
bob morane

Reputation: 660

Pass two variable argument list

I know this works very well:

def locations(city, *other_cities): 
    print(city, other_cities)

Now I need two variable argument list, like

def myfunction(type, id, *arg1, *arg2):
    # do somethong
    other_function(arg1)

    #do something
    other_function2(*arg2)

But Python does not allow to use this twice

Upvotes: 2

Views: 6722

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318518

This is not possible because *arg captures all positional args from that position on. So by definition, a second *args2 would always be empty.

An easy solution would be passing two tuples:

def myfunction(type, id, args1, args2):
    other_function(args1)
    other_function2(args2)

and call it like this:

myfunction(type, id, (1,2,3), (4,5,6))

In case the two functions expect positional arguments instead of a single argument, you would call them like this:

def myfunction(type, id, args1, args2):
    other_function(*arg1)
    other_function2(*arg2)

This would have the advantage that you can use any iterable, even a generator, when calling myfunction since the called functions would never get in contact with the passed iterables.


If you really want to work with two variable argument lists you need some kind of separator. The following code uses None as the separator:

import itertools
def myfunction(type, id, *args):
    args = iter(args)
    args1 = itertools.takeuntil(lambda x: x is not None, args)
    args2 = itertools.dropwhile(lambda x: x is None, args)
    other_function(args1)
    other_function2(args2)

It would be used like this:

myfunction(type, id, 1,2,3, None, 4,5,6)

Upvotes: 12

Ribtoks
Ribtoks

Reputation: 6922

You can use two dictionaries instead.

Upvotes: 0

Related Questions