Skip to content

Commit

Permalink
Fix for getting a non-existing key from a dict (#77)
Browse files Browse the repository at this point in the history
  • Loading branch information
berendkleinhaneveld authored Jun 1, 2022
1 parent b3c0e62 commit 7cc6040
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
7 changes: 5 additions & 2 deletions observ/observables.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,10 @@ def read_key_trap(method, obj_cls):
def inner(self, *args, **kwargs):
if Dep.stack:
key = args[0]
proxy_db.attrs(self)["keydep"][key].depend()
keydeps = proxy_db.attrs(self)["keydep"]
if key not in keydeps:
keydeps[key] = Dep()
keydeps[key].depend()
value = fn(self.target, *args, **kwargs)
if self.shallow:
return value
Expand Down Expand Up @@ -282,7 +285,7 @@ def inner(self, *args, **kwargs):

def write_key_trap(method, obj_cls):
fn = getattr(obj_cls, method)
getitem_fn = getattr(obj_cls, "__getitem__")
getitem_fn = getattr(obj_cls, "get")

@wraps(fn)
def inner(self, *args, **kwargs):
Expand Down
60 changes: 60 additions & 0 deletions tests/test_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -625,3 +625,63 @@ def _callback():
# write to a class attribute
a[2].foo = 10
assert called == 2 # class instances are NOT reactive


def test_watch_get_non_existing():
a = reactive({})

def result():
return a.get("foo", False)

watcher = watch(result, None, sync=True)

assert watcher.value is False

a["foo"] = True

assert watcher.value is True


def test_watch_get_non_existing_dict():
a = reactive(dict())

def result():
return "foo" in a

watcher = watch(result, None, sync=True)

assert watcher.value is False

a["foo"] = "bar"

assert watcher.value is True


def test_watch_get_non_existing_set():
a = reactive(set())

def result():
return "foo" in a

watcher = watch(result, None, sync=True)

assert watcher.value is False

a.add("foo")

assert watcher.value is True


def test_watch_get_non_existing_list():
a = reactive(list())

def result():
return "foo" in a

watcher = watch(result, None, sync=True)

assert watcher.value is False

a.append("foo")

assert watcher.value is True

0 comments on commit 7cc6040

Please sign in to comment.