Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions bibtexparser/model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import abc
from collections.abc import Iterator
from typing import Any

_ALLOWED_ENCLOSINGS = (None, "{", '"', "no-enclosing")
Expand Down Expand Up @@ -454,6 +455,16 @@ def items(self) -> list[tuple[str, Any]]:
("ID", self.key),
] + [(f.key, f.value) for f in self.fields]

def keys(self) -> list[str]:
"""Dict-mimicking, for partial v1.x backwards compatibility.

Same keys and order as in `items()`, e.g. allowing ``dict(entry)``."""
return [key for key, _ in self.items()]

def __iter__(self) -> Iterator[str]:
"""Dict-mimicking iteration over the keys, as in `keys()`."""
return iter(self.keys())

def __hash__(self) -> int:
return hash((type(self), self._start_line_in_file, self._raw, self._entry_type, self._key))

Expand Down
8 changes: 8 additions & 0 deletions tests/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,14 @@ def test_entry_contains():
assert "ID" in entry


def test_entry_dict_conversion():
entry = Entry("article", "key", [Field("field", "value", 1), Field("foo", "bar", 2)], 1, "raw")
assert list(entry) == ["ENTRYTYPE", "ID", "field", "foo"]
expected = {"ENTRYTYPE": "article", "ID": "key", "field": "value", "foo": "bar"}
assert dict(entry) == dict(entry.items()) == expected
assert {**entry} == expected


def test_entry_setitem_field():
entry = Entry("article", "key", [Field("field", "value", 1)], 1, "raw")
entry["field"] = "new_value"
Expand Down
Loading