Pregunta

I have a list of some input values, of which the first couple of mandatory and the last couple optional. Is there any easy way to use tuple unpacking to assign these to variables, getting None if the optional parameters are missing.

eg.

a = [1,2]   
foo, bar, baz = a
# baz == None

ideally a could be any length - including longer than 3 (other items thrown away).

At the moment I'm using zip with a list of parameter names to get a dictionary:

items = dict(zip(('foo', 'bar', 'baz'), a))
foo = items.get('foo', None)
bar = items.get('bar', None)
baz = items.get('baz', None)

but it's a bit long-winded.

¿Fue útil?

Solución

From the linked question, this works:

foo, bar, baz == (list(a) + [None]*3)[:3]

Otros consejos

What about using Try Except:

>>> a = [1,2]
>>> try:
...     foo, bar, baz = a
... except:
...     foo, bar = a
...
>>>

Use itertools.izip_longest:

from itertools import izip_longest
max_params = 3
args = (1, 2)

foo, bar, baz = zip(*izip_longest(args, range(max_params)))[0]

I should note that if you find yourself having to do this, though, you should probably consider storing the parameters in a dict instead of unpacking them into variables.

Update: Since you're stuck with 2.5, try the following:

max_params = 3
args = (1, 2)

def unpack(args, param_length):
    return args + tuple(None for _ in range(param_length - len(args)))

foo, bar, baz = unpack(args, max_params)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top