1

In flat sequences(eg. str, bytes, bytearray etc) can we have in operator unlike container sequence(eg. list, tuple, collections.deque etc)? Is there anywhere else we can use in operator other than container sequence?

2 Answers2

2

The in operator will work for any class that implements the __contains__ method.

x in y

is implemented as:

y.__contains__(x)

For example, str implements in to search for a substring, rather than testing for a single element of the collection matching.

See Override Python's 'in' operator?.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0
  1. Any class can implement __contains__ in any fashion it desires. For example, a class that subclasses int can implement __contains__ so it checks if a number is a factor of the integer that it represents., eg 2 in special_integer(6).

  2. I tend to disagree with your assessment that str, bytes (and obviously bytearray) are "flat". After all, they are all iterable.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • Did you accidentally delete the rest of point #1? On point #2, you're technically correct, but that said, the rule for operator overloading is "only do it when it's intuitive and necessary"; factor checks would be neither. Just because you *can*, doesn't mean you *should*. – ShadowRanger Jul 05 '18 at 18:32
  • @ShadowRanger 1. I don't think something got deleted. 2. Well, it is just an example :) – DeepSpace Jul 05 '18 at 18:35
  • You rearranged and expanded since I comment (moved 2 to 1 and 1 to 2, and finished the thought in old #1/new #2). All's well now. – ShadowRanger Jul 05 '18 at 18:42