Friday, February 20, 2015

Python: distinguish strings from other iterable objects

I often want to do a sanity check on a parameter that is supposed to be an iterable. The problem is that strings are also iterable, but iterating over the characters in a string is basically never what I want. This will raise if I'm passed a string or something that isn't iterable.
import collections

def CheckForIterable(someparam):
  if (isinstance(someparam, basestring) or not isinstance(someparam, collections.Iterable)):
    raise ValueError("Expected an iterable, got %s" % str(someparam))
In [50]: CheckForIterable("a")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
 in ()
----> 1 CheckForIterable("a")

 in CheckForIterable(someparam)
      1 def CheckForIterable(someparam):
      2   if (isinstance(someparam, basestring) or not isinstance(someparam, collections.Iterable)):
----> 3     raise ValueError("Expected an iterable, got %s" % str(someparam))

ValueError: Expected an iterable, got a

In [51]: CheckForIterable(["a"])

In [52]: CheckForIterable((1,2))

In [53]: CheckForIterable((1))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
 in ()
----> 1 CheckForIterable((1))

 in CheckForIterable(someparam)
      1 def CheckForIterable(someparam):
      2   if (isinstance(someparam, basestring) or not isinstance(someparam, collections.Iterable)):
----> 3     raise ValueError("Expected an iterable, got %s" % str(someparam))

ValueError: Expected an iterable, got 1

No comments: