Skip to content

Commit

Permalink
fix ClassVars, better fix for #3679
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelcolvin committed May 14, 2022
1 parent 9baec86 commit 98dab9e
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
2 changes: 1 addition & 1 deletion changes/3679-samuelcolvin.md
@@ -1 +1 @@
Allow self referencing `ClassVar`s in models but checking for class vars after forward refs are resolved.
Allow self referencing `ClassVar`s in models.
3 changes: 0 additions & 3 deletions pydantic/fields.py
Expand Up @@ -38,7 +38,6 @@
display_as_type,
get_args,
get_origin,
is_classvar,
is_literal_type,
is_new_type,
is_none_type,
Expand Down Expand Up @@ -614,8 +613,6 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity)
return
elif origin is Callable:
return
elif is_classvar(origin):
return
elif is_union(origin):
types_ = []
for type_ in get_args(self.type_):
Expand Down
10 changes: 9 additions & 1 deletion pydantic/typing.py
Expand Up @@ -387,7 +387,15 @@ def _check_classvar(v: Optional[Type[Any]]) -> bool:


def is_classvar(ann_type: Type[Any]) -> bool:
return _check_classvar(ann_type) or _check_classvar(get_origin(ann_type))
if _check_classvar(ann_type) or _check_classvar(get_origin(ann_type)):
return True

# this is an ugly workaround for class vars that contain forward references and are therefore themselves
# forward references, see #3679
if ann_type.__class__ == ForwardRef and ann_type.__forward_arg__.startswith('ClassVar['):
return True

return False


def update_field_forward_refs(field: 'ModelField', globalns: Any, localns: Any) -> None:
Expand Down

0 comments on commit 98dab9e

Please sign in to comment.