Skip to content

Commit

Permalink
✨ Add get to mimic dict (#468)
Browse files Browse the repository at this point in the history
  • Loading branch information
tdegeus authored Feb 14, 2024
1 parent e3757c1 commit 0eaf264
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
7 changes: 7 additions & 0 deletions bibtexparser/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,13 @@ def pop(self, key: str, default=None) -> Optional[Field]:
self._fields = [f for f in self._fields if f.key != key]
return field

def get(self, key: str, default=None) -> Optional[Field]:
"""Returns the field with the given key, or the default value if it does not exist.
:param key: The key of the field.
:param default: The value to return if the field does not exist."""
return self.fields_dict.get(key, default)

def __contains__(self, key: str) -> bool:
"""Dict-mimicking ``in`` operator."""
return key in self.fields_dict
Expand Down
12 changes: 12 additions & 0 deletions tests/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,18 @@ def test_entry_deepcopy():
assert entry_1.fields_dict["field"] == entry_2.fields_dict["field"]


def test_entry_get():
entry1 = Entry(
"article", "key", [Field("field", "value", 1), Field("foo", "bar", 2)], 1, "raw"
)
entry2 = Entry(
"article", "key", [Field("field", "value", 1), Field("foo", "bar", 2)], 1, "raw"
)
assert entry1.get("other", "default") == "default"
assert entry1.get("foo") == Field("foo", "bar", 2)
assert entry1 == entry2


def test_entry_pop():
entry1 = Entry(
"article", "key", [Field("field", "value", 1), Field("foo", "bar", 2)], 1, "raw"
Expand Down

0 comments on commit 0eaf264

Please sign in to comment.