edit: This is now a classified as a bug in PyCharm.
Link to bug report: https://youtrack.jetbrains.com/issue/PY-46247
PyCharm's type checker doesn't recognize that bitwise operations on an IntFlag instance are still IntFlags. It gives warnings (inline in comments below). The python docs say, "IntFlag members can be combined using the bitwise operators (&, |, ^, ~) and the result is still an IntFlag member." The code works fine when I run it.
How to I satisfy the type checker for all of these situations without turning it off?
from enum import IntFlag
class Foo(IntFlag):
bar = 1,
baz = 2,
bog = 4
def complement(self):
return 7 & ~self
def doit(flag1: Foo, flag2: Foo) -> Foo:
return flag1 | flag2 # warning: "Expected type 'Foo', got 'int' instead."
def doitagain(flag1: Foo, flag2: Foo) -> Foo:
return (flag1 | flag2).complement() # warning: "Unresolved attribute reference 'complement' for class 'int'"
print(doit(Foo.bar, Foo.baz)) # prints: "Foo.baz|bar" (as expected)
print(doitagain(Foo.bar, Foo.baz)) # prints: "Foo.bog" (as expected)
edit: I have thought of 3 really bad solutions:
- Turn off the type checker. This is obviously not desirable.
- Remove the type annotations. This removes some but not all of this kind of warning in my code. The downside, is that it removes useful and correct type annotations.
- Make the type annotations WRONG. That is, say I'm returning 'int' when I am really returning an IntFlag subtype. Better to have no type annotations at all.
For now I am going with number 2.