When I define a class attribute named type, a type[Foo] annotation inside the same class causes mypy to report that the type name is a variable and therefore “not valid as a type”.
class Foo:
type: str
bar: type[Foo]
main.py:3: error: Variable "__main__.Foo.type" is not valid as a type [valid-type]
I expected type[Foo] to refer to the built-in type, but mypy treats type as the class attribute I just declared.
I found those workarounds:
- Rename the attribute (e.g.,
type_orkind). - Use the old
typing.Typeinstead of new builtintype
I found in PEP8 a convention of naming
single_trailing_underscore_: used by convention to avoid conflicts with Python keyword
but type is not a keyword.
Is this is aligned with language semantics, or just a mypy limitation?
typeis a built-in type; don't name your own variablestype. As suggested, usetype_for those varriables.type: stronly creates an annotation. However,type: str = 'foo'would break the following use oftype[Foo], as it's now an actual local name.