Is there a standard library function or more pythonic way to do this ?
def itemize(i):
if type(i) is list:
return i
return [i]
Context:
Useful in db (nosql style) migrations from single value to a list
doc = <get doc from db>
for i in itemize(doc.var1):
#blah
or
doc.var1 = itemize(doc.var1)
Usually, enforcing this sort of thing is a bad idea. In many cases, the most pythonic thing you can do is check if your item is a sequence:
One instance where this passes something that you may not want to pass is with strings … strings are sequences, so
to_sequence('foo')will return'foo', not['foo']— but it’s unlikely that you want it to be['f','o','o']either … so you might need to special case for that if it’s desired.One simple fix for that would be (for python2.x):
But again, usually the “pythonic” thing to do is to defer this sort of checking and try to use the object in some context — if it fails, then you can do something to react.