Idiom for default values when unpacking a tuple

Carlos Ribeiro carribeiro at gmail.com
Wed Nov 17 21:20:41 EST 2004


On Tue, 16 Nov 2004 16:42:57 GMT, Paul McGuire
<ptmcg at austin.rr._bogus_.com> wrote:
> I'm trying to manage some configuration data in a list of tuples, and I
> unpack the values with something like this:
> 
> configList = [
>     ("A",1,2,3),
>     ("F",1,3,4),
>     ("X",2,3,4),
>     ("T",1,5,4),
>     ("W",6,3,4),
>     ("L",1,3,8),
>     ]
> for data in configList:
>     name,a,b,c = data
>     ... do something with a,b, and c
> 
> Now I would like to add a special fourth config value to "T":
>     ("T",1,5,4,0.005),
> 
> and I would like to avoid having to put 0's or None's in all of the others.
> Is there a clean Python idiom for unpacking a tuple so that any unassigned
> target values get a default, or None, as in:
> 
>     tup = (1,2)
>     a,b,c = tup
> 
> gives a = 1, b = 2, and c = None.
> 
> I've tried creating a padUnpack class, but things aren't quite clicking...
> 
> TIA,
> -- Paul

How about having a iterator function that is guaranteed to always
return a fixed number of elements, regardless of the size of the
sequence? I've checked it, and it does not exist in itertools.
Something like this (simple-minded, just a proof of concept, and
highly optimizable in at least a hundred different ways :-):

def iterfixed(seq, times, defaultitem=None):
    for i in range(times):
        if i < len(seq):
            yield seq[i]
        else:
            yield defaultitem

To unpack a tuple using it, it's simply a matter to use it like this:

>>> tuple(iterfixed((1,2,3,4), 3))
(1, 2, 3)
>>> tuple(iterfixed((1,2,3,4), 6))
(1, 2, 3, 4, None, None)

In fact, if you *are* doing tuple unpacking, *you don't have to build
the tuple*. You can simply do it like this:

>>> a,b,c = iterfixed((1,2,3,4), 3)
>>> a,b,c
(1, 2, 3)
>>> a,b,c,d,e,f = iterfixed((1,2,3,4), 6)
>>> a,b,c,d,e,f
(1, 2, 3, 4, None, None)

The only catch is that, if you have only one parameter, then all you
will get is the generator itself. But that's a corner case, and not
the intended use anyway.

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list