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?
Asked
Active
Viewed 299 times
1

user10031120
- 15
- 2
-
2`str` uses `in` to search for a substring, e.g. `"abc" in "fooabcbar"` is true. – Barmar Jul 05 '18 at 18:26
-
Oh yes. thanks, that helped.. – user10031120 Jul 05 '18 at 18:29
2 Answers
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.

Barmar
- 741,623
- 53
- 500
- 612
0
Any class can implement
__contains__
in any fashion it desires. For example, a class that subclassesint
can implement__contains__
so it checks if a number is a factor of the integer that it represents., eg2 in special_integer(6)
.I tend to disagree with your assessment that
str
,bytes
(and obviouslybytearray
) 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