Saturday, January 29, 2011

Testing whether an object is iterable or not in Python

Following is a simple snippet for checking whether an object is iterable or not in Python:

  1: def can_loop_over(maybe):
  2:     """Test value to see if it is list like"""
  3:     try:
  4:         iter(maybe)
  5:     except:
  6:         return 0
  7:     else:
  8:         return 1


Courtesy: satchmo_utils [http://www.satchmoproject.com/]

No comments: