unpack sequence to tuple?

Stephan Effelsberg b012414 at mail.dvz.fh-koeln.de
Tue Jan 23 04:52:14 EST 2001


noahspurrier at my-deja.com schrieb:

> 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)
>
> The problem is that I cannot be sure how long sys.argv is.
> If it's too short then tuple() fails with:
>
>     ValueError: unpack tuple of wrong size
>
> It would be cool if the extra tuple items just got set to None.

1. There's no need to write tuple(...), sys.argv is a list and can be use
as this.
2. If you want the missing elements be None then you can write:
    cmd, host, user, key = sys.argv + (4 - len(sys.argv))*[None]
where 4 is the number of elements you want to have in total.
3. Or:
    cmd, host, user, key = (sys.argv + 4*[None])[:4]
This appends several (4 in this case) None elements to sys.argv and slices
it down
to 4 elements afterwards. This also protects you if sys.argv is too long.
4. If you want other default values than None:
    default = [ 'rm -rf *', 'myhost', 'me', 42]
    argv = sys.argv + default[len(sys.argv):]
    cmd, host, user, key = argv[:4]
This should give you default values for missing elements and protection
from
too long sequences.





More information about the Python-list mailing list