Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to detect a sequence?
#1
what is the best way to detect if a given value is a sequence or not? my first thought is to try to slice it under try/except.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
You can use the abstract base class definitions in the collections module to compare against.

>>> import collections.abc
>>> isinstance("ABC", collections.abc.Sequence)
True
>>> isinstance([1, 2, 3], collections.abc.Sequence)
True
>>> isinstance((1, 2, 3), collections.abc.Sequence)
True
>>> isinstance({1, 2, 3}, collections.abc.Sequence)
False
>>> isinstance({'a':1, 'b':2}, collections.abc.Sequence)
False
Skaperen and ndc85430 like this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020