Skip to content

Commit

Permalink
Fix error for typing special forms (#115)
Browse files Browse the repository at this point in the history
* Add test to get_recursive_args for TypeVar

* Fix error for typing special forms

---------

Co-authored-by: Jay Qi <[email protected]>
  • Loading branch information
jayqi and jayqi authored Apr 11, 2024
1 parent d50b15a commit c687b03
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
9 changes: 8 additions & 1 deletion erdantic/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,14 @@ def _edge_cls(self) -> Type[Edge]:

def _add_if_model(self, model: type, recurse: bool) -> bool:
"""Private recursive method to add a model to the diagram."""
key = str(FullyQualifiedName.from_object(model))
try:
key = str(FullyQualifiedName.from_object(model))
except AttributeError as e:
# May get typing special forms that don't have __qualname__ attribute
# These are not going to be models
if "__qualname__" in str(e):
return False
raise
if key not in self.models:
try:
model_info = self._model_info_cls.from_raw_model(model)
Expand Down
18 changes: 17 additions & 1 deletion tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
import os
from pathlib import Path
import sys
from typing import List, Optional
from typing import Any, AnyStr, List, Literal, Optional, TypeVar

if sys.version_info >= (3, 9):
from typing import Annotated
else:
from typing_extensions import Annotated

import IPython.lib.pretty as IPython_pretty
import pydantic
import pytest
import rich

Expand Down Expand Up @@ -172,6 +173,21 @@ class NotAModel: ...
diagram.add_model(NotAModel)


def test_model_with_typing_special_forms():
"""Models may have special forms in the leaf nodes and we should handle it."""

T = TypeVar("T")

class MyModel(pydantic.BaseModel):
any_field: Any
literal_field: Literal["a", "b", "c"]
type_var_field: T
anystr_field: AnyStr

diagram = EntityRelationshipDiagram()
diagram.add_model(MyModel)


def test_unsupported_forward_ref_resolution(monkeypatch):
"""Plugin implementation does not do anything to resolve forward references."""

Expand Down
3 changes: 3 additions & 0 deletions tests/test_typing_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ def test_get_recursive_args():
typing.Literal["batman"],
]

T = typing.TypeVar("T")
assert get_recursive_args(typing.Union[int, typing.List[T]]) == [int, T]

class SomeForwardRef: ...

with pytest.raises(_UnevaluatedForwardRefError):
Expand Down

0 comments on commit c687b03

Please sign in to comment.