Repository: sciunto-org/python-bibtexparser

Issue:
Implement `__setitem__` on entries
For easier compatiblitiy with (and migration from), we should add a `__setitem__` shorthand on entries, allowing to create new fields and add them to their entry.

Specifically, `myentry["somekey"] = some_value` should create a new field with key `"somekey"` (string type) and value `some_value` (any type), and then add it to the entry using `set_field`




Discussion:

Patch:
diff --git a/bibtexparser/model.py b/bibtexparser/model.py
index d3b99be..b53876a 100644
--- a/bibtexparser/model.py
+++ b/bibtexparser/model.py
@@ -318,6 +318,14 @@ class Entry(Block):
             return self.key
         return self.fields_dict[key].value
 
+    def __setitem__(self, key: str, value: Any):
+        """Dict-mimicking index.
+
+        This serves for partial v1.x backwards compatibility,
+        as well as for a shorthand for `set_field`.
+        """
+        self.set_field(Field(key, value))
+
     def items(self):
         """Dict-mimicking, for partial v1.x backwards compatibility.
 


Test patch:
diff --git a/tests/test_model.py b/tests/test_model.py
index a52894e..a2d5c3b 100644
--- a/tests/test_model.py
+++ b/tests/test_model.py
@@ -290,3 +290,24 @@ def test_entry_str():
     )
 
     assert str(entry) == expected
+
+
+def test_entry_fields_shorthand():
+    entry = Entry(
+        entry_type="article",
+        key="myEntry",
+        fields=[
+            Field("myFirstField", "firstValue"),
+            Field("mySecondField", "secondValue"),
+        ],
+    )
+
+    entry["myFirstField"] = "changed_value"
+    assert entry["myFirstField"] == "changed_value"
+    assert entry.fields_dict["myFirstField"].value == "changed_value"
+
+    entry["myNewField"] = "new_value"
+    assert entry["myNewField"] == "new_value"
+    assert entry.fields_dict["myNewField"].key == "myNewField"
+    assert entry.fields_dict["myNewField"].value == "new_value"
+    assert entry.fields_dict["myNewField"].start_line is None