Skip to content

Commit

Permalink
Add a get method to the Vertex object to simulate a dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
mitchnegus committed Feb 5, 2025
1 parent d42b807 commit 6126345
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/firewheel/control/experiment_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,26 @@ def __init__(self, graph, name=None, graph_id=None):
if name:
self.name = name

def get(self, key, default=None):
"""
Dictionary-style access to read :py:class:`Vertex` attributes.
Args:
key (str): A key to query.
Returns
The value of the requested attribute if the attribute is in
the set of available attributes, else ``default``. If
``default`` is not given, it defaults to :py:data:`None`, so
that this method never raises a `KeyError`.
Raises:
RuntimeError: If the :py:class:`Vertex` is not :py:attr:`Vertex.valid`.
"""
if not self.valid:
raise RuntimeError("Attempted operation on invalid Vertex instance.")
return self.g.g.nodes[self.graph_id].get(key, default=default)

def get_object(self):
"""
Get the :py:class:`Vertex` object attribute (i.e. ``self``).
Expand Down
11 changes: 11 additions & 0 deletions src/firewheel/tests/unit/control/test_experiment_graph_vertex.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,17 @@ def test_get_invalid_attribute(self):
# pylint: disable=pointless-statement
v["name"]

def test_get(self):
v = Vertex(self.g)
self.assertIsNone(v.get("name"))

v["name"] = "test"
self.assertEqual(v.get("name"), "test")

def test_get_alternate_default(self):
v = Vertex(self.g)
self.assertEqualNone(v.get("name", default="test"), "test")

def test_has(self):
v = Vertex(self.g)
self.assertFalse("name" in v)
Expand Down

0 comments on commit 6126345

Please sign in to comment.