Skip to content

Commit

Permalink
Fix evaluation of stringified annotations during namespace inspection (
Browse files Browse the repository at this point in the history
  • Loading branch information
Viicos authored and sydney-runkle committed Sep 9, 2024
1 parent 3d364cb commit 2c61bfd
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
9 changes: 7 additions & 2 deletions pydantic/_internal/_model_construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from abc import ABCMeta
from functools import lru_cache, partial
from types import FunctionType
from typing import Any, Callable, ForwardRef, Generic, Literal, NoReturn
from typing import Any, Callable, Generic, Literal, NoReturn

import typing_extensions
from pydantic_core import PydanticUndefined, SchemaSerializer
Expand All @@ -30,6 +30,7 @@
from ._schema_generation_shared import CallbackGetCoreSchemaHandler
from ._signature import generate_pydantic_signature
from ._typing_extra import (
_make_forward_ref,
eval_type_backport,
is_annotated,
is_classvar,
Expand Down Expand Up @@ -436,6 +437,8 @@ def inspect_namespace( # noqa C901
is_valid_privateattr_name(ann_name)
and ann_name not in private_attributes
and ann_name not in ignored_names
# This condition is a false negative when `ann_type` is stringified,
# but it is handled in `set_model_fields`:
and not is_classvar(ann_type)
and ann_type not in all_ignored_types
and getattr(ann_type, '__module__', None) != 'functools'
Expand All @@ -446,7 +449,9 @@ def inspect_namespace( # noqa C901
frame = sys._getframe(2)
if frame is not None:
ann_type = eval_type_backport(
ForwardRef(ann_type), globalns=frame.f_globals, localns=frame.f_locals
_make_forward_ref(ann_type, is_argument=False, is_class=True),
globalns=frame.f_globals,
localns=frame.f_locals,
)
if is_annotated(ann_type):
_, *metadata = typing_extensions.get_args(ann_type)
Expand Down
4 changes: 3 additions & 1 deletion tests/test_forward_ref.py
Original file line number Diff line number Diff line change
Expand Up @@ -581,10 +581,12 @@ def test_class_var_as_string(create_module):
class Model(BaseModel):
a: ClassVar[int]
_b: ClassVar[int]
"""
)

assert module.Model.__class_vars__ == {'a'}
assert module.Model.__class_vars__ == {'a', '_b'}
assert module.Model.__private_attributes__ == {}


def test_json_encoder_str(create_module):
Expand Down

0 comments on commit 2c61bfd

Please sign in to comment.