Skip to content

Commit

Permalink
♻️ Rename pop_field -> pop (with default) to make API closer to `…
Browse files Browse the repository at this point in the history
…dict` (#466)
  • Loading branch information
tdegeus authored Feb 9, 2024
1 parent a997eea commit e3757c1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
13 changes: 8 additions & 5 deletions bibtexparser/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,12 +305,15 @@ def set_field(self, field: Field):
else:
self._fields.append(field)

def pop_field(self, key: str) -> Optional[Field]:
"""Removes and returns the field with the given key, if present."""
def pop(self, key: str, default=None) -> Optional[Field]:
"""Removes and returns the field with the given key.
:param key: The key of the field to remove.
:param default: The value to return if the field does not exist."""
try:
field = self.fields_dict.pop(key)
except KeyError:
return None
return default

self._fields = [f for f in self._fields if f.key != key]
return field
Expand Down Expand Up @@ -345,9 +348,9 @@ def __delitem__(self, key):
"""Dict-mimicking index.
This serves for partial v1.x backwards compatibility,
as well as for a shorthand for `pop_field`.
as well as for a shorthand for `pop`.
"""
self.pop_field(key)
self.pop(key)

def items(self):
"""Dict-mimicking, for partial v1.x backwards compatibility.
Expand Down
12 changes: 11 additions & 1 deletion tests/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,17 @@ def test_entry_deepcopy():
assert entry_1.fields_dict["field"] == entry_2.fields_dict["field"]


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


def test_entry_contains():
entry = Entry("article", "key", [Field("field", "value", 1)], 1, "raw")
assert "field" in entry
assert "other" not in entry
Expand Down

0 comments on commit e3757c1

Please sign in to comment.