0

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.

Sparkofska
  • 1,280
  • 2
  • 11
  • 34
  • Can you provide multiple examples of how `postprocess` can be called? Thank you. – Yaseen Ssenyonjo Sep 30 '18 at 12:42
  • You could `try` iterating over it, and assume it's not a collection if you can't (`except TypeError:`). The only problem there might be if `results` could be a string, which is both iterable and usually considered a value. – jonrsharpe Sep 30 '18 at 12:43
  • How would I implement the `try` and `except TypeError` version to execute the inner part of the loop on the single object without duplicating code? – Sparkofska Sep 30 '18 at 12:51
  • 1
    def is_collection(unknown_type): return isinstance(unknown_type, collections.Iterable) – Yaseen Ssenyonjo Sep 30 '18 at 12:52

0 Answers0