-
Notifications
You must be signed in to change notification settings - Fork 258
Prefer the mypy restrictions on type variables #29
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
Comments
The core issue here is that we're trying to create an add-on to the language without modifying its syntax. Having
However, it would need to inject the name into the local scope which is just as ugly, I guess. By the way, why does importing type variables not work? |
I propose to use mypy's rules. Every TypeVar() call creates a unique type variable. The static checker enforces that TypeVar() must always be assigned to a local (or global, depending on the current scope) variable whose name is the same as the string passed as argument. The runtime doesn't enforce this, but it still treats each TypeVar() as a unique type. For example:
Now the following asserts all pass:
(Note that the first two simply check that issubclass of a type with itself should always be true.) |
Oh, my comment about import was simply that mypy will (of course) let you define type vars with the same name in multiple modules, and you can import them, but they will still be considered different. E.g. this passes in mypy:
I can also systematically substitute typing.AnyStr for AnyStr. It also works if I replace the import with:
But after that if fails if I replace the return type with typing.AnyStr:
The errors are:
|
OK, I understand. Will update the PEP accordingly. |
I updated the PEP at PyCon to describe the new type variable semantics. I think that this can be closed now. |
the PEP has this example:
In mypy, the equivalent thing with typevar() won't work --
Y = typevar('X')
is rejected because the variable name is not the same as the name argument, and a type variable imported from another module with the same name still doesn't make the example work.I like the mypy restrictions better.
See also python/mypy#539.
The text was updated successfully, but these errors were encountered: