From 0f59cc642b434059a38cccf0da87bb5e3c6d6be6 Mon Sep 17 00:00:00 2001 From: AnythingTechPro Date: Thu, 28 Jun 2018 19:17:25 -0400 Subject: [PATCH] db: added set_default method which will set a default value to a specified key only if it is not already set, otherwise the method will return the already existing value of the key --- semidbm/db.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/semidbm/db.py b/semidbm/db.py index 5530508..9b3b987 100644 --- a/semidbm/db.py +++ b/semidbm/db.py @@ -166,6 +166,19 @@ def keys(self): def values(self): return [self[key] for key in self._index] + + def set_default(self, key, default_value): + """ + If the key already exists in the items dictionary, the value + will be returned in the dictionary; else the value will be added + to the dictionary and the default_value will be returned. + """ + + if key in self: + return self[key] + + self[key] = default_value + return default_value def close(self, compact=False): """Close the db.