I'm wondering why I cannot find any solution to this by googling: I want to write a python function which can accept either a single object or any collection of the same type. My idea is to wrap a list around the parameter if it is a single instance, like so:
def postprocess(results):
""" An arbitrary function that takes a list or single object
and behaves smart depending on that. """
if not is_collection(results): # <-- How to implement this??
results = [results]
for result in results:
# do processing magic
print(result)
# to be called like one of those:
postprocess(result1) # single object
postprocess([result1, result2]) # a list
postprocess((result1, result2)) # a tuple
What is the best/most pythonic way to implement is_collection()
? (Might it bring problems, if result
is an iterable type itself?
I could do if type(results) is not list:
, but I explicitly want to allow any kind of iterable collection not only list
.