-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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
Strange error message with variable type annotation #2398
Comments
If you remove the comments, everything is checked as Any and works fine. |
Where's the List? where's the Tuple[str, str] coming from? |
The List and Tuple are coming from the translation mypy does from dict literals to a call to the The reason you are getting type errors here is that you can't use string literals where a Ticker or SecurityId is expected. This version is clean: SYMBOLS = {
Ticker('ham'): SecurityID('4a24ab25-766d-4d6c-99e2-337da6d0ba45'),
Ticker('spam'): SecurityID('e8248888-b413-4def-b11a-763b10faf9c0'),
} # type: Dict[Ticker, SecurityID]
INDICES = {
Ticker('eggs'),
Ticker('mayo'),
} # type: Set[Ticker] |
Indeed, the purpose of |
@gvanrossum do you think for literals a cast is nicer? from typing import NewType, cast
Ticker = NewType('Ticker', str)
SecurityID = NewType('SecurityID', str)
SYMBOLS = cast(Dict[Ticker, SecurityID], {
'ham': '4a24ab25-766d-4d6c-99e2-337da6d0ba45',
'spam': 'e8248888-b413-4def-b11a-763b10faf9c0',
})
INDICES = cast(Set[Ticker], {
'eggs',
'mayo',
})
TICKERS = INDICES | SYMBOLS.keys() # type: Set[Ticker] |
No, cast() doesn't check anything -- it would let through non-strings without errors. |
This would be type safe:
|
@JukkaL that's nicer than putting the NewType on each item, but it's still not very elegant |
If you want to use |
@JukkaL I think this usecase is worth a syntactical shortcut, as quite often when you want to use a dict as a table of data it will benefit from NewType |
Feel free to suggest a better syntax (please create a new issue, as this was closed). |
Results in:
The text was updated successfully, but these errors were encountered: