Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type alias as a class member is not valid as a type #7866

Closed
simsa-st opened this issue Nov 4, 2019 · 4 comments
Closed

Type alias as a class member is not valid as a type #7866

simsa-st opened this issue Nov 4, 2019 · 4 comments

Comments

@simsa-st
Copy link

simsa-st commented Nov 4, 2019

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

@ilevkivskyi
Copy link
Member

This is intended behavior, see #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.

@simsa-st
Copy link
Author

simsa-st commented Nov 4, 2019

I see, thanks for the explanation.

@Mattwmaster58
Copy link
Contributor

Mattwmaster58 commented Apr 2, 2020

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

@hauntsaninja
Copy link
Collaborator

See PEP 613

mcwitt added a commit to proteneer/timemachine that referenced this issue Apr 14, 2022
Add typing-extensions for TypeAlias annotation. See:
- python/mypy#7866
- https://peps.python.org/pep-0613/
mcwitt added a commit to proteneer/timemachine that referenced this issue Apr 15, 2022
Add typing-extensions for TypeAlias annotation. See:
- python/mypy#7866
- https://peps.python.org/pep-0613/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants