Skip to content

Commit

Permalink
ENH: implement Graph.__repr__ (#711)
Browse files Browse the repository at this point in the history
* ENH: implement Graph.__repr__

* update the formatting
  • Loading branch information
martinfleis committed Jun 7, 2024
1 parent 34a7fe1 commit f028d26
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
10 changes: 10 additions & 0 deletions libpysal/graph/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,16 @@ def __getitem__(self, item):
)
return self._adjacency.loc[item]

def __repr__(self):
if len(self.unique_ids) > 5:
unique_ids = f"{str(self.unique_ids[:5].tolist())[:-1]}, ...]"
else:
unique_ids = self.unique_ids.tolist()
return (
f"<Graph of {self.n} nodes and {self.nonzero} nonzero edges indexed by\n"
f" {unique_ids}>"
)

def copy(self, deep=True):
"""Make a copy of this Graph's adjacency table and transformation
Expand Down
20 changes: 20 additions & 0 deletions libpysal/graph/tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,26 @@ def test_init(self):
with pytest.raises(ValueError, match="'transformation' needs to be"):
graph.Graph(self.adjacency_int_binary, transformation="foo")

def test___repr__(self):
expected = (
"<Graph of 10 nodes and 25 nonzero edges indexed by\n"
" [0, 1, 2, 3, 4, ...]>"
)
assert repr(self.g_int) == expected

expected = (
"<Graph of 10 nodes and 25 nonzero edges indexed by\n"
" ['a', 'b', 'c', 'd', 'e', ...]>"
)
assert repr(self.g_str) == expected

nybb = graph.Graph.build_contiguity(self.nybb)
expected = (
"<Graph of 5 nodes and 10 nonzero edges indexed by\n"
" ['Staten Island', 'Queens', 'Brooklyn', 'Manhattan', 'Bronx']>"
)
assert repr(nybb) == expected

def test_copy(self):
g_copy = self.g_str.copy()
assert g_copy == self.g_str
Expand Down

0 comments on commit f028d26

Please sign in to comment.