Skip to content

Commit

Permalink
✨ Allow deletion of fields on entries by key (#445)
Browse files Browse the repository at this point in the history
  • Loading branch information
MiWeiss authored Jan 18, 2024
1 parent 16b881c commit 4db7d59
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
18 changes: 18 additions & 0 deletions bibtexparser/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions tests/test_model.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from copy import copy, deepcopy
from textwrap import dedent

import pytest

from bibtexparser.model import (
Entry,
ExplicitComment,
Expand Down Expand Up @@ -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"]

0 comments on commit 4db7d59

Please sign in to comment.