Skip to content

Commit

Permalink
fix(types): fix repr and str magic methods (#1852)
Browse files Browse the repository at this point in the history
  • Loading branch information
hanxiao authored Feb 3, 2021
1 parent 5c68831 commit 23090e0
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 5 deletions.
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,7 @@ with f:
```python
# retrieve top-3 neighbours of 🐲, this print 🐲🐦🐢 with score 0, 1, 1 respectively
with f:
f.search(docs[0], top_k=3,
on_done=lambda x: [print(m.dict()) for m in x.docs[0].matches])
f.search(docs[0], top_k=3, on_done=lambda x: print(x.docs[0].matches))
```

<sup>
Expand Down
15 changes: 15 additions & 0 deletions jina/types/sets/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

import numpy as np

from ...helper import typename

try:
# when protobuf using Cpp backend
from google.protobuf.pyext._message import RepeatedCompositeContainer as RepeatedContainer
Expand Down Expand Up @@ -167,3 +169,16 @@ def new(self) -> 'Document':
"""Create a new empty document appended to the end of the set"""
from ..document import Document
return self.append(Document())

def __str__(self):
from ..document import Document
content = ',\n'.join(str(Document(d)) for d in self._docs_proto[:3])
if len(self._docs_proto) > 3:
content += f'in total {len(self._docs_proto)} items'
return content

def __repr__(self):
content = ' '.join(f'{k}={v}' for k, v in {'length': len(self._docs_proto)}.items())
content += f' at {id(self)}'
content = content.strip()
return f'<{typename(self)} {content}>'
2 changes: 1 addition & 1 deletion jina/types/sets/match.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,4 @@ def granularity(self) -> int:
@property
def adjacency(self) -> int:
"""The adjacency of all document in this set """
return self._ref_doc.adjacency + 1
return self._ref_doc.adjacency + 1
8 changes: 6 additions & 2 deletions tests/unit/types/test_repr_str.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@

from jina import Document, Request, QueryLang, NdArray
from jina.types.score import NamedScore
from jina.types.sets.chunk import ChunkSet
from jina.types.sets.match import MatchSet


@pytest.mark.parametrize('obj', [Document(),
Request(),
QueryLang(),
NamedScore(),
NdArray()])
NdArray(),
MatchSet([Document()], Document()),
ChunkSet([Document()], Document())])
def test_builtin_str_repr_no_content(obj):
print(obj)
print(f'{obj!r}')
Expand All @@ -24,6 +28,6 @@ def test_builtin_str_repr_no_content(obj):
ref_id='10' * 16,
description='score description'),
NdArray(np.random.random([3, 5]))])
def test_builtin_str_repr_no_content(obj):
def test_builtin_str_repr_has_content(obj):
print(obj)
print(f'{obj!r}')

0 comments on commit 23090e0

Please sign in to comment.