len() should always return something

Chris Rebert clp2 at rebertia.com
Fri Jul 24 23:02:40 EDT 2009


On Fri, Jul 24, 2009 at 7:50 PM, Dr. Phillip M.
Feldman<pfeldman at verizon.net> wrote:
>
> 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.

You can easily fix that using decorators:

(disclaimer: untested, except mentally)

#bit of setup; pays off later
def list_or_single(func):
    def wrapper(arg):
        try: iter(arg)
        except TypeError: arg = [arg]
        return func(arg)
    return wrapper

#now just prefix functions with @list_or_single

@list_or_single
def dumbfunc(xs):
    for x in xs:
        print x

Using the extended call syntax as I explained earlier is another option.

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list