Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 835
angvillar Avatar asked May 29 '13 01:05

angvillar


People also ask

Is a list not iterable Python?

For instance, a list object is iterable and so is an str object. The list numbers and string names are iterables because we are able to loop over them (using a for-loop in this case). In this article, we are going to see how to check if an object is iterable in Python.

What can you do with lists but not strings in Python?

Lists are mutable so you can change the contents of them (either adding, removing or changing elements). On the other hand, strings are immutable so can not change. This means that there are no append or equivalent methods.

What is* iterables in Python?

Iterable is an object which can be looped over or iterated over with the help of a for loop. Objects like lists, tuples, sets, dictionaries, strings, etc. are called iterables. In short and simpler terms, iterable is anything that you can loop over.

How do you wrap around a string in Python?

Using Python's inferred line continuation within parentheses, brackets, and braces is the recommended method of wrapping lengthy lines. You can put an extra pair of parentheses around an expression if required. We have to apply these parenthesized line breaks to the long lines that we would want to wrap.


1 Answers

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
like image 113
karthikr Avatar answered Oct 21 '22 19:10

karthikr