-
Notifications
You must be signed in to change notification settings - Fork 256
How to declare type variables #1
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
Also, should Var (or typevar) be added to collections.abc, or only to typing? |
Renamed Var to TypeVar in b7d16de to leave space for variable types in the future. |
As for the name not being PEP8-compliant, neither is Union, which is also a factory. That's minor. As for accepting subclasses of constrained types for arguments but limiting return values to explicitly listed classes, that's reasonable but subtle and thus confusing. Seems like it's the covariance discussion in disguise. It's problematic because of this example in the PEP:
|
I explained the naming/syntax issue in #5 (I hope). mypy currently doesn't like something like Iterable[X] as a typevar constraint (the 'values=' kwarg). This may be because it doesn't support parametrized types as type aliases; e.g. this fails:
I propose that in the first published draft of the PEP we use a simpler example that actually works when translated to mypy syntax, and think more deeply about constraints on type variables a bit later. E.g. this works as an example using Callable and generic types:
For constrained types it would be better to discuss the AnyStr example in the PEP. |
FYI, we have bounded type variables in PyCharm. There are 46 bounded parameterized types out of 1186 typed parameters in our stubs. Most of them are our variant of |
We're agreed on |
Clarify pep-0484 as opt-in conventions only like WSGI
There are two issues around type variables:
Currently, mymy uses
while the PEP currently proposes
In any case it should be noted in the PEP that this is not the same as
The reason is quite subtle, and the best example is currently the predefined type variable
Consider a polymorphic function that does something to filenames and works on both bytes and str, e.g.
We really need AnyStr to be a type variable here, because we want to express that if the argument is a bytes, so is the return value, and if the argument is a str, the return value is too.
But that's not all! Such a type variable is constrained to exactly the given types. Consider the case where the argument is an instance of a user-defined subclass of bytes. We don't want the declaration to mean that the return value is then also an instance of that same subclass -- we want it to mean that the return value is a bytes (not a str).
I believe this makes the use of such a type variable equivalent to a collection of overloaded functions; in the above example
Open issues:
The text was updated successfully, but these errors were encountered: