From 58cbb4d661ee40af5ef2b6a6a7f15b1b2ee5b4e5 Mon Sep 17 00:00:00 2001 From: Damien George Date: Tue, 10 Jun 2014 23:07:56 +0100 Subject: [PATCH] py: Implement __contains__ special method. --- py/objtype.c | 4 +++- tests/basics/class-contains.py | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 tests/basics/class-contains.py diff --git a/py/objtype.c b/py/objtype.c index f96a29beb..80f39d7f1 100644 --- a/py/objtype.c +++ b/py/objtype.c @@ -384,7 +384,9 @@ STATIC const qstr binary_op_method_name[] = { MP_BINARY_OP_LESS_EQUAL, MP_BINARY_OP_MORE_EQUAL, MP_BINARY_OP_NOT_EQUAL, - MP_BINARY_OP_IN, + */ + [MP_BINARY_OP_IN] = MP_QSTR___contains__, + /* MP_BINARY_OP_IS, */ [MP_BINARY_OP_EXCEPTION_MATCH] = MP_QSTR_, // not implemented, used to make sure array has full size diff --git a/tests/basics/class-contains.py b/tests/basics/class-contains.py new file mode 100644 index 000000000..b6dd3661c --- /dev/null +++ b/tests/basics/class-contains.py @@ -0,0 +1,23 @@ +# A contains everything +class A: + def __contains__(self, key): + return True + +a = A() +print(True in a) +print(1 in a) +print(() in a) + +# B contains given things +class B: + def __init__(self, items): + self.items = items + def __contains__(self, key): + return key in self.items + +b = B([]) +print(1 in b) +b = B([1, 2]) +print(1 in b) +print(2 in b) +print(3 in b)