[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Python-Dev] Enum, Flag, __contains__, and False vs TypeError

On 04/04/2018 01:24 PM, Glenn Linderman wrote:

> I think the "in" test should raise TypeError if tested against _anything_ that is not an Enum member.
> Why? I see a parallel between Enum and mappings.
> x = {'test':True, 'live':False}
> So it is True that  'test' in x   and  'live' in x  and False that True in x and False in x.
> It is False that  'foo' in x  and  3 in x
> It is TypeError that [4,5,6] in x, or {'foo': 'bar'} in x.
> Note that it is False that (4,5,6) in x  which is a little surprising given the above two, but not when you realize the
> differences between this and the above two.
> So with mappings, you can have any hashable type as a key: with Enum, you can only have Enum members as keys.

Technically, an Enum has strings as keys (the member names), while the members themselves are the values; but list()ing 
an Enum returns the values (members) while a mapping would return the names (keys);  Enums are definitely a bit strange!

> So I have no idea why you would want to return False, rather than TypeError, other than (1) the distinction probably
> doesn't matter to most people (2) backward compatibility.

To me, `in` is an equality test, and equality tests should never, ever raise exceptions -- they should return True or 
False.  Which is why I was surprised that `1 in "hello"` raised instead of returning False.  However, I have learned 
that in certain situations, such as str or dict or set, if it is impossible to contain the item being searched for then 
raising an exception is appropriate.

Hence my questions now on deciding what the behavior /should/ be, and whether practicality has a log to stand on in this 
case.  ;)