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

Cannot use Literal variable inside Literal type #8187

Closed
intgr opened this issue Dec 20, 2019 · 4 comments
Closed

Cannot use Literal variable inside Literal type #8187

intgr opened this issue Dec 20, 2019 · 4 comments

Comments

@intgr
Copy link
Contributor

intgr commented Dec 20, 2019

Using mypy 0.761, Python 3.7.5 here. The ANIMALS2 value is highlighted as incorrect by Mypy:

COW: Literal['cow'] = 'cow'
PIG: Literal['pig'] = 'pig'
ANIMALS1: Literal['cow', 'pig']  # This is OK
ANIMALS2: Literal[COW, PIG]
#         ^^^^^^^ Mypy: Parameter 1 of Literal[...] is invalid

But it seems Mypy should be able to deduce that ANIMALS1 and ANIMALS2 are the same thing?

I'm not sure if the more lax version should be allowed as well, but seems useful:

OX = 'ox'
ANIMALS = Literal[OX]
@TH3CHARLie
Copy link
Collaborator

Well, I find #3494 maybe related to this

@ilevkivskyi
Copy link
Member

Well, I find #3494 maybe related to this

Essentially yes, variables and type aliases should be never mixed. If you want an alias, use COW = Literal['cow'].

@TH3CHARLie
Copy link
Collaborator

TH3CHARLie commented Dec 20, 2019

@ilevkivskyi indeed and I misunderstand this, too. However, I found a TODO:

mypy/mypy/typeanal.py

Lines 425 to 427 in fe8309a

if isinstance(sym.node, Var):
# TODO: add a link to alias docs, see #3494.
message = 'Variable "{}" is not valid as a type'

which I think it would be useful to add a note here to point to the docs to help the anyone encounters this error message in the future

Furthermore, I check the docs in both common issues and solutions and alias part and find no specific docs describing this behavior, maybe we should document this and add note in message

@ilevkivskyi
Copy link
Member

Yes, but fixing this TODO depends on fixing #3494 first.

JukkaL pushed a commit that referenced this issue Jan 30, 2020
Resolves #3494 (Since module types are tracked in #3500)

Following #8187 (comment) and #3494, if I understand correctly and the semantics 
in #3494's example code has been fixed (report error on re-assign Alias = B, the 
remaining work of #3494 is to update the docs, which is the main focus of this PR.

Newly added docs are in common issues and solutions section, with the content mostly adapted from Ivan's example in #3494. And a note point to the docs is also added.
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

3 participants