-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Mypy doesn't handle namedtuples with dynamic fields #848
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
It would be reasonable to fall back to a "namedtuple with unknown item names" in a case like above in a weak type checking mode. I'm still unsure about how this weak mode could be enabled for particular files. In the normal type checking mode we'd probably still want to give a warning about the above code. |
I actually think the long-term correct approach will be to track the values of constants. |
@JukkaL shouldn't there be basic constant propagation, just before the semantic analysis? It will be most helpful, with ints and strings. And it shouldn't do anything tricky - no fixpoint or anything; just a single pass. At least it can be another optional feature. |
Yeah, it seems that this should be possible for ints, strings and booleans and maybe tuples and lists, at least within a single module. So these could be okay:
We know with certainty the values of However, this is trickier:
And what about this:
Constant propagation could work somewhat like this:
Before spending more time on this I'd like to see more use cases where this would be useful. Named tuples are clearly a potential example, but that is a pretty narrow use case. |
Tracking types is a form of constant propagation, and the questions you raise apply to class names, function definitions etc. We already assume the code behaves nicely. (If I understand your description correctly, you want the join operation on different constants to result in Top. That's the sensible thing to do; but maybe there's a place for a plugin here too?). |
An example like the OP's here is usually a proxy for a more dynamic source of field names, which won't work even if we implement constant propagation. |
I used code similar to the example just to separate the fields part, which is very noisy, from the inheriting class, without introducing a temporary type name. |
Note that this error is also triggered when passing a tuple instead of a list literal:
Is this within the scope of this issue or should I open a separate one? |
This has been fixed in #2262, in the repo version. It is unrelated to this issue. |
This just never will happen (the dynamic version). |
Instantiating NamedTuple dynamically is not supported by mypy. python/mypy#848
Given:
We get:
error: List literal expected as the second argument to namedtuple()
. Mypy should be able to handle this somehow, e.g., by allowing any operation onT
instances if the second argument tonamedtuple
is not a list literal.The text was updated successfully, but these errors were encountered: