Python, wrap and object to list if it is not iterable

I want to have a function that wraps both the object in the iterable, to allow clients the functions handle the same collections and separate objects, I did the following:

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

Is there a pythonic way for this ?, what if obj is a string, and I want to treat strings as single objects ?, instead of isinstance instead of iter ?

+4
source share
2 answers

Your approach is good: it would have to bind the string object to iterable, although

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

One more thing you can check:

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

To check line types:

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

Here's a general solution with some doctrines to demonstrate:

 def listify(arg): """ SYNOPSIS Wraps scalar objects in a list; passes through lists without alteration. DESCRIPTION Normalizes input to always be a list or tuple. If already iterable and not a string, pass through. If a scalar, make into a one-element list. If a scalar is wrapped, the same scalar (not a copy) is preserved. PARAMETERS arg Object to listify. RETURNS list EXAMPLES >>> listify(1) [1] >>> listify('string') ['string'] >>> listify(1, 2) Traceback (most recent call last): ... TypeError: listify() takes exactly 1 argument (2 given) >>> listify([3, 4,]) [3, 4] ## scalar is preserved, not copied >>> x = 555 >>> y = listify(x) >>> y[0] is x True ## dict is not considered a sequence for this function >>> d = dict(a=1,b=2) >>> listify(d) [{'a': 1, 'b': 2}] >>> listify(None) [None] LIMITATIONS TBD """ if is_sequence(arg) and not isinstance(arg, dict): return arg return [arg,] 
+2
source

Source: https://habr.com/ru/post/1483262/


All Articles