Skip to content
Snippets Groups Projects
Commit b1cee273 authored by Pavel Kácha's avatar Pavel Kácha
Browse files

Implement correct setdefault method (returning possibly coerced data instead of original)

parent c69476c1
No related branches found
No related tags found
No related merge requests found
Pipeline #6738 passed with warnings
...@@ -134,6 +134,16 @@ class TestTypedDict(unittest.TestCase): ...@@ -134,6 +134,16 @@ class TestTypedDict(unittest.TestCase):
("note", None) ("note", None)
]) ])
def testSetDefaultNonexistent(self):
res = self.person.setdefault("tel", "1234")
self.assertEqual(res, 1234)
self.assertEqual(self.person["tel"], 1234)
def testSetDefaultExistent(self):
res = self.person.setdefault("age", "50")
self.assertEqual(res, 34)
self.assertEqual(self.person["age"], 34)
class IntList(TypedList): class IntList(TypedList):
item_type = int item_type = int
......
...@@ -201,6 +201,15 @@ class TypedDict(MutableMapping): ...@@ -201,6 +201,15 @@ class TypedDict(MutableMapping):
del self.data[key] del self.data[key]
self.initItemDefault(key) self.initItemDefault(key)
def setdefault(self, key, default=None):
""" Return coerced value instead of original """
try:
return self[key]
except KeyError:
self[key] = default
return self[key]
# Following definitions are not strictly necessary as MutableMapping # Following definitions are not strictly necessary as MutableMapping
# already defines them, however we can override them by calling to # already defines them, however we can override them by calling to
# possibly more optimized underlying implementations. # possibly more optimized underlying implementations.
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment