iterating over a variable which could be None, a single object, or a list

2008-11-27 Thread adam carr
I call a function get_items() which returns a list of items.
However, in some cases, it returns just one item.
It returns the item as an object though, not as a list containing one object.
In other cases it simply returns None.

What is the cleanest way to iterate over the return value of this function?
Or would it be better to fix the get_items() function itself to always
return lists no matter what?

Thanks,
--
http://mail.python.org/mailman/listinfo/python-list


Re: iterating over a variable which could be None, a single object, or a list

2008-11-27 Thread adam carr
2008/11/27 Stefan Behnel <[EMAIL PROTECTED]>:
> adam carr wrote:
>> I call a function get_items() which returns a list of items.
>> However, in some cases, it returns just one item.
>> It returns the item as an object though, not as a list containing one object.
>> In other cases it simply returns None.
>>
>> What is the cleanest way to iterate over the return value of this function?
>> Or would it be better to fix the get_items() function itself to always
>> return lists no matter what?
>
> Given the name "get_items()" in plural, I'd opt for letting it always
> return a list. That also reduces the special case of returning None, where
> it would now return an empty list.

You are of course right.

I'm still in the position of having to right code to deal with
converting None to an empty list and one object to a list with a
single entry.
Python casting doesn't work here.

Maybe it's just wishful thinking, but I would have thought there would
be a cleaner way of doing this.

Thanks,
--
http://mail.python.org/mailman/listinfo/python-list


Re: iterating over a variable which could be None, a single object, or a list

2008-11-27 Thread adam carr
Denis kindly provided the following code which does this well:

def mkiter( x ):
   """ list -> list, el -> [el], None -> []
   usage: for x in mkiter( func returning list or
singleton ): ...
   """
   return (x if hasattr( x, "__iter__" )  # list tuple ...
   else [] if x is None
   else [x]
   )

# test --
print mkiter( 1 )
print mkiter( (2,3) )
print mkiter( None )
--
http://mail.python.org/mailman/listinfo/python-list