Skip to content

Commit

Permalink
Simplifications and fixes to Task.get and Task.__setitem__ to red…
Browse files Browse the repository at this point in the history
…uce surprises.
  • Loading branch information
Adam Coddington committed Dec 8, 2014
1 parent 8843464 commit 4c579ce
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
30 changes: 16 additions & 14 deletions taskw/task.py
Expand Up @@ -14,7 +14,7 @@
StringField,
UUIDField,
)
from taskw.fields.base import Dirtyable
from taskw.fields.base import Dirtyable, DirtyableList, DirtyableDict

# Sentinel value for not specifying a default
UNSPECIFIED = object()
Expand Down Expand Up @@ -97,12 +97,10 @@ def _field_is_writable(self, key):
return False
return True

def get(self, key, default=UNSPECIFIED):
def get(self, key, default=None):
try:
return self[key]
except KeyError:
if default is UNSPECIFIED:
return self._deserialize(key, None)
return default

def _record_change(self, key, from_, to):
Expand Down Expand Up @@ -182,18 +180,22 @@ def serialized_changes(self, keep=False):
return serialized

def __setitem__(self, key, value, force=False):
if isinstance(value, dict) and not isinstance(value, DirtyableDict):
value = DirtyableDict(value)
elif isinstance(value, list) and not isinstance(value, DirtyableList):
value = DirtyableList(value)

existing_value = self.get(key)
if not existing_value and not value:
# Do not attempt to record changes if both the existing
# and previous values are Falsy. We cannot distinguish
# between `''` and `None` for...reasons.
return False
if force or value != existing_value:
self._record_change(
key,
self.get(key),
value,
)
if force or existing_value or value:
# Do not attempt to record changes if both the existing
# and previous values are Falsy. We cannot distinguish
# between `''` and `None` for...reasons.
self._record_change(
key,
self.get(key),
value,
)

# Serialize just to make sure we can; it's better to throw
# this error early.
Expand Down
2 changes: 2 additions & 0 deletions taskw/test/test_task.py
Expand Up @@ -27,11 +27,13 @@ def setUp(self):
})

def test_append_when_absent(self):
self.task['annotations'] = []
self.task['annotations'].append('awesome')
self.assertEqual(self.task['annotations'], ['awesome'])

def test_append_when_absent_but_with_tags(self):
self.task = Task({'uuid': str(uuid.uuid4()), 'description': 'Test'})
self.task['tags'] = []
self.task['tags'].append('awesome')
self.assertEqual(self.task['tags'], ['awesome'])

Expand Down

0 comments on commit 4c579ce

Please sign in to comment.