Skip to content

Commit

Permalink
Fix containers and out of order tables dict behavior (#82)
Browse files Browse the repository at this point in the history
  • Loading branch information
sdispater authored Feb 29, 2020
1 parent 6bdaadc commit a8e1a09
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 3 deletions.
1 change: 0 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ after_success:
jobs:
include:
- python: "2.7"
- python: "3.4"
- python: "3.5"
- python: "3.6"
- python: "3.7"
Expand Down
20 changes: 18 additions & 2 deletions tests/test_toml_document.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,5 +551,21 @@ def test_out_of_order_tables_are_still_dicts():
assert isinstance(doc["a"], dict)
assert isinstance(doc["a"]["a"], dict)

assert "key" in doc["a"]["a"]
assert "c" in doc["a"]["a"]
table = doc["a"]["a"]
assert "key" in table
assert "c" in table
assert "value" == table.get("key")
assert {} == table.get("c")
assert table.get("d") is None
assert "foo" == table.get("d", "foo")

assert "bar" == table.setdefault("d", "bar")
assert "bar" == table["d"]

assert "value" == table.pop("key")
assert "key" not in table

assert "baz" == table.pop("missing", default="baz")

with pytest.raises(KeyError):
table.pop("missing")
33 changes: 33 additions & 0 deletions tomlkit/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
from .items import item as _item


_NOT_SET = object()


class Container(dict):
"""
A container for items within a TOMLDocument.
Expand Down Expand Up @@ -501,6 +504,19 @@ def get(self, key, default=None): # type: (Any, Optional[Any]) -> Any

return self[key]

def pop(self, key, default=_NOT_SET):
try:
value = self[key]
except KeyError:
if default is _NOT_SET:
raise

return default

del self[key]

return value

def setdefault(
self, key, default=None
): # type: (Union[Key, str], Any) -> Union[Item, Container]
Expand Down Expand Up @@ -698,6 +714,23 @@ def keys(self):
def values(self):
return self._internal_container.values()

def items(self): # type: () -> Generator[Item]
return self._internal_container.items()

def update(self, other): # type: (Dict) -> None
self._internal_container.update(other)

def get(self, key, default=None): # type: (Any, Optional[Any]) -> Any
return self._internal_container.get(key, default=default)

def pop(self, key, default=_NOT_SET):
return self._internal_container.pop(key, default=default)

def setdefault(
self, key, default=None
): # type: (Union[Key, str], Any) -> Union[Item, Container]
return self._internal_container.setdefault(key, default=default)

def __contains__(self, key):
return key in self._internal_container

Expand Down

0 comments on commit a8e1a09

Please sign in to comment.