diff --git a/bibtexparser/model.py b/bibtexparser/model.py index b53876a..2e37b00 100644 --- a/bibtexparser/model.py +++ b/bibtexparser/model.py @@ -304,6 +304,16 @@ 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.""" + try: + field = self.fields_dict.pop(key) + except KeyError: + return None + + self._fields = [f for f in self._fields if f.key != key] + return field + def __getitem__(self, key: str) -> Any: """Dict-mimicking index. @@ -326,6 +336,14 @@ def __setitem__(self, key: str, value: Any): """ self.set_field(Field(key, value)) + def __delitem__(self, key): + """Dict-mimicking index. + + This serves for partial v1.x backwards compatibility, + as well as for a shorthand for `pop_field`. + """ + self.pop_field(key) + def items(self): """Dict-mimicking, for partial v1.x backwards compatibility. diff --git a/tests/test_model.py b/tests/test_model.py index a2d5c3b..4807bc8 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -1,6 +1,8 @@ from copy import copy, deepcopy from textwrap import dedent +import pytest + from bibtexparser.model import ( Entry, ExplicitComment, @@ -311,3 +313,9 @@ def test_entry_fields_shorthand(): assert entry.fields_dict["myNewField"].key == "myNewField" assert entry.fields_dict["myNewField"].value == "new_value" assert entry.fields_dict["myNewField"].start_line is None + + del entry["myNewField"] + assert "myNewField" not in entry.fields_dict + assert len([f for f in entry.fields if f.key == "myNewField"]) == 0 + with pytest.raises(KeyError): + entry["myNewField"]