python, wrap and object into a list if not is an iterable

angvillar picture angvillar · May 29, 2013 · Viewed 7k times · Source

I want to have a function that wraps and object in an iterable one in order to allow the clients of the function treat the same way collections and single objects, i did the following:

 def to_iter(obj):
     try:
         iter(obj)
         return obj
     except TypeError:
         return [obj]

Is there a pythonic way to do this?, what if obj is a string and i want to treat strings as single objects?, should i use isinstance instead iter?

Answer

karthikr picture karthikr · May 29, 2013

Your approach is good: It would cast a string object to an iterable though

try:
    iter(obj)
except TypeError, te:
    obj = list(obj)

Another thing you can check for is:

if not hasattr(obj, "__iter__"): #returns True if type of iterable - same problem with strings
    obj = list(obj)
return obj

To check for string types:

import types
if not isinstance(obj, types.StringTypes) and hasattr(obj, "__iter__"):
    obj = list(obj)
return obj