Skip to content

Commit

Permalink
Fix issue with ClassVar parsing (#3403)
Browse files Browse the repository at this point in the history
* Fix issue with ClassVar parsing

* Fix lint error

* Simplify test

* Fix condition and test
  • Loading branch information
uriyyo committed Nov 18, 2021
1 parent 8afdaab commit ee0b2e2
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
1 change: 1 addition & 0 deletions changes/3401-uriyyo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix issue when pydantic fail to parse `typing.ClassVar` string type annotation.
4 changes: 3 additions & 1 deletion pydantic/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,9 @@ def resolve_annotations(raw_annotations: Dict[str, Type[Any]], module_name: Opti
annotations = {}
for name, value in raw_annotations.items():
if isinstance(value, str):
if sys.version_info >= (3, 7):
if (3, 10) > sys.version_info >= (3, 9, 8) or sys.version_info >= (3, 10, 1):
value = ForwardRef(value, is_argument=False, is_class=True)
elif sys.version_info >= (3, 7):
value = ForwardRef(value, is_argument=False)
else:
value = ForwardRef(value)
Expand Down
17 changes: 17 additions & 0 deletions tests/test_forward_ref.py
Original file line number Diff line number Diff line change
Expand Up @@ -519,3 +519,20 @@ class NestedTuple(BaseModel):
NestedTuple.update_forward_refs()
obj = NestedTuple.parse_obj({'x': ('1', {'x': ('2', {'x': ('3', None)})})})
assert obj.dict() == {'x': (1, {'x': (2, {'x': (3, None)})})}


@skip_pre_37
def test_class_var_as_string(create_module):
module = create_module(
# language=Python
"""
from __future__ import annotations
from typing import ClassVar
from pydantic import BaseModel
class Model(BaseModel):
a: ClassVar[int]
"""
)

assert module.Model.__class_vars__ == {'a'}

0 comments on commit ee0b2e2

Please sign in to comment.