unpack sequence to tuple?

Alex Martelli aleaxit at yahoo.com
Tue Jan 23 04:46:23 EST 2001


"Moshe Zadka" <moshez at zadka.site.co.il> wrote in message
news:mailman.980234666.18231.python-list at python.org...
> On Tue, 23 Jan 2001 05:58:58 GMT, noahspurrier at my-deja.com wrote:
>
> > I want to easily read arguments in a sequence into separate variables.
> > Basically, I want to use a Per1 idiom and do this:
> >
> >     (cmd, host, user, key) = tuple(sys.argv)
>
> No need for the tuple() or the () on the LHS:
>
> cmd, host, user, key = sys.argv
>
> Will work just ine.

True (and I fully agree with your implication that it is
preferable: more readable, &c).

This will give errors if len(sys.argv) != 4.


> If you want padding, just roll your own class:
>
> class PaddedSeq:
>
> def __init__(self, s, n):
> self.s = s
> self.n = n
>
> def __len__(self):
> return self.n
>
> def __getitem__(self, i):
> if not (0<=i<n):
> raise IndexError
> try:
> return self.s[i]
> except IndexError:
> return None
>
> cmd, host, something, something_else = PaddedSeq(sys.argv, 4)

Actually, I think this is more complex than needed for the purpose
at hand (it may come in handy for some other uses, of course).


I would do it, not with a powerful, flexible class, but rather
with a tiny, little, extremely-simple function:

def padSequence(seq, length):
    return (tuple(seq)+(None,)*length)[:length]

Unfortunately, tuples and lists cannot be concatenated, which
is why we need to cast the sequence into a definite form here --
choosing list would of course work just as well:

def padSequence(seq, length):
    return (list(seq)+[None]*length)[:length]

or, one could, I guess, typeswitch, but that would (IMHO) be
an unwarranted increase in complexity.  Only if measurements
should show that 'extra/avoidable work' performed in this
function is a bottleneck for the application, would I think
it worthy to add complications for performance reasons; in
most cases, "we ain't gonna need it", and (IMHO) providing
a solution that is as simple as we can get away with is a
good general strategy.


Anyway, the use would now still be:

cmd, host, something, something_else = padSequence(sys.argv, 4)

no matter how padSequence is internally implemented.


Alex






More information about the Python-list mailing list