-
-
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
Recursive types not working correctly #13786
Comments
I think mypy is doing the correct thing here. In your first sample, |
Thank you for the answer. How should I proceed with the |
Casting is one option. Another option is possible if you don't need the resulting type to be mutable. You could define another type for a read-only JSON value. JSON_RO = Union[
Mapping[str, "JSON_RO"], Sequence["JSON_RO"], str, int, float, bool, None
]
some_data = {"eggs": "spam"}
json_data: JSON_RO = {"foo": "bar", "python": some_data} This works because the type parameters for |
@erictraut The problem with that is that you often genuinely don't want generic mappings and sequences to be considered valid JSON-like types, because certain JSON libraries won't accept them. Python's own builtin import json
from typing import Mapping, Sequence, Union
JSON_RO = Union[
Mapping[str, "JSON_RO"], Sequence["JSON_RO"], str, int, float, bool, None
]
class MyMapping(Mapping[str, int]):
def __init__(self):
self.data = {"a": 1, "b": 2}
def __iter__(self):
return iter(self.data)
def __getitem__(self, key):
return self.data[key]
def __len__(self):
return len(self.data)
def dumps(j: JSON_RO):
json.dumps(j)
dumps(MyMapping()) Mypy doesn't complain about this, of course, but it fails at runtime with
So in that case, using Is there a way to fix the type alias while keeping it limited to |
Bug Report
Related to #731
The new recursive types support (enabled by flag
--enable-recursive-aliases
) does not behave correctly.To Reproduce
Expected Behavior
The MyPy should not detect any errors since
some_data
is a valid JSON representation and can be safely nested in another JSON.Actual Behavior
Please note that explicitly marking
some_data
asJSON
does not return the error, e.g.Your Environment
0.981
--enable-recursive-aliases
mypy.ini
(and other config files): -3.10
The text was updated successfully, but these errors were encountered: