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
?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With