Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether an object is a sequence

I can think of two ways to determine whether an object is a sequence:

  • hasattr(object, '__iter__').
  • And whether calling iter(object) raises a TypeError.

As it is most Pythonic to ask forgiveness than to ask permission, I'd use the second idiom, although I consider it more ugly (additionally, raising an exception once you've caught the TypeError to determine that the object isn't a sequence would yield an undesirable "double-exception" stack trace).

Ultimately, is checking that an object defines an __iter__ method exhaustive enough to determine whether an object is a sequence? (In older versions of Python, for example, str didn't define an __iter__ method; I've also heard that some objects can also simply define and use __getitem__ without defining an __iter__ and act like a sequence.) Or is defining __iter__ the contract of a sequence?

like image 623
Humphrey Bogart Avatar asked Oct 17 '25 21:10

Humphrey Bogart


1 Answers

Use isinstance(obj, collections.Sequence). Abstract base classes are exactly for this. They didn't exist prior to 2.6 though. In case you're forced to use older versions, you're out of luck and better stick with EAFP.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!