Python style advice

Wayne Folta wfolta at netmail.to
Tue Feb 10 00:00:24 EST 2004


In the specific case where you're trying to map a variable-length 
argument list to local variables in a function, you can do the more 
Pythonic:

def myfunc (a = None, b = None, c = None)

I'd say the answer is similar for other tasks. There's probably a 
Pythonic way to do the overall task as opposed to a 
statement-by-statement translation.

> I'm tring to write what I would have expressed in Perl as
>
>     my ($a, $b, $c) = @array;
>
> This is very similar to the python statement
>
>     a, b, c = array
>
> BUT, the Python will throw an exception if array isn't exactly 3
> elements long, wheras the Perl will work for any length of @array,
> either throwing away excess elements or setting the variables to
> undef, ie like this
>
>     if len(array) >= 1:
>        a = array[0]
>     else:
>        a = None
>     if len(array) >= 2:
>        b = array[1]
>     else:
>        b = None
>     if len(array) >= 3:
>        c = array[2]
>     else:
>        c = None
>
> This works if array has >= 3 elements
>
>     a, b, c = array[:3]
>
> And this works however many elements array has
>
>     a, b, c = (array + 3*[None])[:3]
>
> but it doesn't seem very Pythonic - is there a better way?
>
> -- 
> Nick Craig-Wood
> ncw at axis.demon.co.uk
> -- 
> http://mail.python.org/mailman/listinfo/python-list
>





More information about the Python-list mailing list