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

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Nov 27 20:37:10 EST 2008


On Thu, 27 Nov 2008 12:12:38 +0000, adam carr wrote:

> 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.

Python doesn't have type-casting. Python has type conversions:

mytype(obj)

doesn't force the type of obj to be "mytype", but constructs a new mytype 
object from obj.


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

What's wrong with something as simple as this?

def get_items():
    x = None
    # lots of work here...
    if isinstance(x, list):  # is x list-like?
        return x
    else:
        return [] if x is None else return [x]

Depending on your function, you may need to change the list test.

isinstance(x, list)  # x is a list, or a sub-class of list
type(x) is list  # x is a list, but not a sub-class
hasattr(x, '__iter__')  # x looks more or less list-like


-- 
Steven



More information about the Python-list mailing list