Skip to content

Commit 58cbb4d

Browse files
committed
py: Implement __contains__ special method.
1 parent 62f7ba7 commit 58cbb4d

2 files changed

Lines changed: 26 additions & 1 deletion

File tree

py/objtype.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -384,7 +384,9 @@ STATIC const qstr binary_op_method_name[] = {
384384
MP_BINARY_OP_LESS_EQUAL,
385385
MP_BINARY_OP_MORE_EQUAL,
386386
MP_BINARY_OP_NOT_EQUAL,
387-
MP_BINARY_OP_IN,
387+
*/
388+
[MP_BINARY_OP_IN] = MP_QSTR___contains__,
389+
/*
388390
MP_BINARY_OP_IS,
389391
*/
390392
[MP_BINARY_OP_EXCEPTION_MATCH] = MP_QSTR_, // not implemented, used to make sure array has full size

tests/basics/class-contains.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# A contains everything
2+
class A:
3+
def __contains__(self, key):
4+
return True
5+
6+
a = A()
7+
print(True in a)
8+
print(1 in a)
9+
print(() in a)
10+
11+
# B contains given things
12+
class B:
13+
def __init__(self, items):
14+
self.items = items
15+
def __contains__(self, key):
16+
return key in self.items
17+
18+
b = B([])
19+
print(1 in b)
20+
b = B([1, 2])
21+
print(1 in b)
22+
print(2 in b)
23+
print(3 in b)

0 commit comments

Comments
 (0)