Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions docarray/base_doc/doc.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@ def __setattr__(self, field, value) -> None:
object.__setattr__(self, '__dict__', dict_ref)

def __eq__(self, other) -> bool:
if not isinstance(other, BaseDoc):
return False

if self.__fields__.keys() != other.__fields__.keys():
return False

Expand Down Expand Up @@ -249,7 +252,8 @@ def json(
# we need to do this because pydantic will not recognize DocList correctly
original_exclude = original_exclude or {}
if field not in original_exclude:
data[field] = [doc.dict() for doc in getattr(self, field)]
val = getattr(self, field)
data[field] = [doc.dict() for doc in val] if val is not None else None

# this is copy from pydantic code
if self.__custom_root_type__:
Expand Down Expand Up @@ -319,7 +323,8 @@ def dict(
# we need to do this because pydantic will not recognize DocList correctly
original_exclude = original_exclude or {}
if field not in original_exclude:
data[field] = [doc.dict() for doc in getattr(self, field)]
val = getattr(self, field)
data[field] = [doc.dict() for doc in val] if val is not None else None

return data

Expand Down
25 changes: 25 additions & 0 deletions tests/units/document/test_base_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,28 @@ def test_nested_to_dict_exclude_dict(nested_docs):
def test_nested_to_json(nested_docs):
d = nested_docs.json()
nested_docs.__class__.parse_raw(d)


@pytest.fixture
def nested_none_docs():
class SimpleDoc(BaseDoc):
simple_tens: NdArray[10]

class NestedDoc(BaseDoc):
docs: Optional[DocList[SimpleDoc]]
hello: str = 'world'

nested_docs = NestedDoc()

return nested_docs


def test_nested_none_to_dict(nested_none_docs):
d = nested_none_docs.dict()
assert d == {'docs': None, 'hello': 'world', 'id': nested_none_docs.id}


def test_nested_none_to_json(nested_none_docs):
d = nested_none_docs.json()
d = nested_none_docs.__class__.parse_raw(d)
assert d.dict() == {'docs': None, 'hello': 'world', 'id': nested_none_docs.id}