len() should always return something
Diez B. Roggisch
deets at nospam.web.de
Sat Jul 25 03:55:26 EDT 2009
Dr. Phillip M. Feldman schrieb:
> Here's a simple-minded example:
>
> def dumbfunc(xs):
> for x in xs:
> print x
>
> This function works fine if xs is a list of floats, but not if it is single
> float. It can be made to work as follows:
>
> def dumbfunc(xs):
> if isinstance(xs,(int,float,complex)): xs= [xs]
> for x in xs:
> print x
>
> Having to put such extra logic into practically every function is one of the
> annoying things about Python.
And where comes "len(xs)" into play here? What you want is iteration
over scalars.
I do think that if you frequently have to write code like that, you are
writing errorneous code.
But might that as it is, a simple
def iterable(i):
if isinstance(i, (int, float, complex)):
return [i]
return i
is all you need. So you can write
for x in iterable(xs):
wherever you expect values to be either scalar or iterable.
Diez
More information about the Python-list
mailing list