mirror of
https://github.com/micropython/micropython.git
synced 2025-08-08 11:42:04 +02:00
py: Support non-boolean results for equality and inequality tests.
This commit implements a more complete replication of CPython's behaviour for equality and inequality testing of objects. This addresses the issues discussed in #5382 and a few other inconsistencies. Improvements over the old code include: - Support for returning non-boolean results from comparisons (as used by numpy and others). - Support for non-reflexive equality tests. - Preferential use of __ne__ methods and MP_BINARY_OP_NOT_EQUAL binary operators for inequality tests, when available. - Fallback to op2 == op1 or op2 != op1 when op1 does not implement the (in)equality operators. The scheme here makes use of a new flag, MP_TYPE_FLAG_NEEDS_FULL_EQ_TEST, in the flags word of mp_obj_type_t to indicate if various shortcuts can or cannot be used when performing equality and inequality tests. Currently four built-in classes have the flag set: float and complex are non-reflexive (since nan != nan) while bytearray and frozenszet instances can equal other builtin class instances (bytes and set respectively). The flag is also set for any new class defined by the user. This commit also includes a more comprehensive set of tests for the behaviour of (in)equality operators implemented in special methods.
This commit is contained in:
committed by
Damien George
parent
c3450effd4
commit
3aab54bf43
@@ -467,7 +467,7 @@ const byte mp_binary_op_method_name[MP_BINARY_OP_NUM_RUNTIME] = {
|
||||
[MP_BINARY_OP_EQUAL] = MP_QSTR___eq__,
|
||||
[MP_BINARY_OP_LESS_EQUAL] = MP_QSTR___le__,
|
||||
[MP_BINARY_OP_MORE_EQUAL] = MP_QSTR___ge__,
|
||||
// MP_BINARY_OP_NOT_EQUAL, // a != b calls a == b and inverts result
|
||||
[MP_BINARY_OP_NOT_EQUAL] = MP_QSTR___ne__,
|
||||
[MP_BINARY_OP_CONTAINS] = MP_QSTR___contains__,
|
||||
|
||||
// If an inplace method is not found a normal method will be used as a fallback
|
||||
@@ -1100,7 +1100,7 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict)
|
||||
// TODO might need to make a copy of locals_dict; at least that's how CPython does it
|
||||
|
||||
// Basic validation of base classes
|
||||
uint16_t base_flags = 0;
|
||||
uint16_t base_flags = MP_TYPE_FLAG_NEEDS_FULL_EQ_TEST;
|
||||
size_t bases_len;
|
||||
mp_obj_t *bases_items;
|
||||
mp_obj_tuple_get(bases_tuple, &bases_len, &bases_items);
|
||||
|
Reference in New Issue
Block a user