Skip to content
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

Fix mishandling of unions while freezing types in the mypy plugin #7411

Merged
merged 5 commits into from Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 13 additions & 2 deletions pydantic/mypy.py
Expand Up @@ -126,6 +126,10 @@ def plugin(version: str) -> type[Plugin]:
return PydanticPlugin


class _DeferAnalysis(Exception):
pass


class PydanticPlugin(Plugin):
"""The Pydantic mypy plugin."""

Expand Down Expand Up @@ -353,7 +357,10 @@ def expand_type(self, current_info: TypeInfo) -> Type | None:
# however this plugin is called very late, so all types should be fully ready.
# Also, it is tricky to avoid eager expansion of Self types here (e.g. because
# we serialize attributes).
return expand_type(self.type, {self.info.self_type.id: fill_typevars(current_info)})
expanded_type = expand_type(self.type, {self.info.self_type.id: fill_typevars(current_info)})
if isinstance(self.type, UnionType) and not isinstance(expanded_type, UnionType):
raise _DeferAnalysis()
return expanded_type
return self.type

def to_var(self, current_info: TypeInfo, use_alias: bool) -> Var:
Expand Down Expand Up @@ -445,7 +452,11 @@ def transform(self) -> bool:
is_settings = any(base.fullname == BASESETTINGS_FULLNAME for base in info.mro[:-1])
self.add_initializer(fields, config, is_settings, is_root_model)
self.add_model_construct_method(fields, config, is_settings)
self.set_frozen(fields, frozen=config.frozen is True)
try:
self.set_frozen(fields, frozen=config.frozen is True)
except _DeferAnalysis:
if not self._api.final_iteration:
self._api.defer()

self.adjust_decorator_signatures()

Expand Down
1 change: 1 addition & 0 deletions tests/mypy/configs/mypy-plugin-strict-no-any.ini
@@ -1,6 +1,7 @@
[mypy]
plugins = pydantic.mypy

warn_unreachable = true
follow_imports = silent
strict_optional = True
warn_redundant_casts = True
Expand Down