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,]
source share