[New-bugs-announce] [issue33219] x in IntFlag() should test int x's inclusion in IntFlag

Dutcho report at bugs.python.org
Tue Apr 3 16:38:20 EDT 2018


New submission from Dutcho <dutcho at ziggo.nl>:

While `enum.IntFlag.__and__` accepts an int arg `other` and converts it to `IntFlag` before masking, `enum.IntFlag.__contains__` handles an int arg `other` no different from a different type arg `other` (i.e. returns `True` in Python 3.6 due to issue 33217, but would raise `TypeError` after that's fixed):
    >>> import enum
    >>> ABC = enum.Flag('ABC', 'a, b, c')
    >>> ac = ABC.a | ABC.c
    >>> ABC.b in ac # works
    False
    >>> 2 in ac # should be the same; no exception due to issue 33217
    True
    >>> ac & 3 # works, equivalent to ac & ABC(3)
    <ABC.a: 1>

This is caused by a lack of specialized `IntFlag.__contains__`, so `Flag.__contains__` does the work. Can be fixed by adding a specialization, which (like in `IntFlag.__and__`) tests for `isinstance(other, (IntFlag, int))`.

    >>> def __contains__(self, other):
    ...     if not isinstance(other, (self.__class__, int)):
    ...         return TypeError
    ...     return other & self == other # conversion of int to IntFlag implicitly handled by IntFlag.__and__
    >>> IntFlag.__contains__ = __contains__

----------
components: Library (Lib)
messages: 314893
nosy: Dutcho
priority: normal
severity: normal
status: open
title: x in IntFlag() should test int x's inclusion in IntFlag
type: enhancement
versions: Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue33219>
_______________________________________


More information about the New-bugs-announce mailing list