Mypy: Type alias as a class member is not valid as a type

Created on 4 Nov 2019  路  4Comments  路  Source: python/mypy

I am not sure if this is a bug or intended behaviour but I have problems when using type aliases as class members. This is the code I thought should work:

from typing import NamedTuple

class A:
    Alias = NamedTuple("Alias", [("field", str)])
    def f(self, x: Alias) -> str: return x.field

class B:
    Alias = A.Alias
    def f(self, x: Alias) -> str: return x.field

gives the following errors:

mypy_alias.py:9: error: Variable "mypy_alias.B.Alias" is not valid as a type
mypy_alias.py:9: error: Alias? has no attribute "field"

I noticed this simpler code also does not work, I am not sure if it is connected?

class A:
    Alias = str
    def f(self, x: Alias) -> str: return x

This gives: mypy_alias.py:3: error: Variable "mypy_alias.A.Alias" is not valid as a type

I am using python 3.6.9 and mypy 0.730

Most helpful comment

This is intended behavior, see https://github.com/python/mypy/issues/3494

To give a bit more context, currently there is no explicit way to distinguish between type aliases and variables with type Type[...], so mypy uses some implicit rules. In particular, at class scope anything that is a plain name or attribute is considered a variable. The workaround is to write Alias = Union[A.Alias], which will define an alias.

All 4 comments

This is intended behavior, see https://github.com/python/mypy/issues/3494

To give a bit more context, currently there is no explicit way to distinguish between type aliases and variables with type Type[...], so mypy uses some implicit rules. In particular, at class scope anything that is a plain name or attribute is considered a variable. The workaround is to write Alias = Union[A.Alias], which will define an alias.

I see, thanks for the explanation.

@ilevkivskyi Is there any issues tracking/plans for a resolution instead of a workaround? (Which does work perfectly as far as I can tell 馃憤 )

See PEP 613

Was this page helpful?
0 / 5 - 0 ratings