-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
Allow specifying length of sized object #7626
Comments
Could you expand on the motivations for this a bit more? |
Sometimes I receive an iterable that should have exactly one element and I need to extract it. The most common way to do this is x = next(items) but that fails to detect if there are too many items, so we can use [x] = items which raises Ideally we could check this at compile time, rather than having a runtime exception, by specifying items: Char or more generally items: Sized[1] |
But in order to implement a useful check, you don't just need a mechanism to specify the expected size -- you also need to implement the inference needed to keep track of the length of the value passed in. It looks to me as if you're thinking that that size is available, which it would be at run time (of course) -- but mypy doesn't execute the code, it just reads the code and tries to understand its meaning. In order to infer the length of a list, it would have to do inferences like the following:
IOW I don't believe this is as simple as you think. |
I think we can support fixed size collections, for example for tuples. But IMO this is pretty low priority. |
It may also be nice to support code like:
|
Sometimes I want to specify the size of a container. This could be done manually with casts, but it would be really cool if Mypy could figure this out automatically.
__len__()
is guaranteed to return anint
, and sincea
is defined as a literal the match could be statically inferrable. The same is true of other container types.Mypy reports
Mypy 0.720
CPython 3.7.3
The text was updated successfully, but these errors were encountered: