mkrd / DictDataBase

A python NoSQL dictionary database, with concurrent access and ACID compliance
MIT License
234 stars 11 forks source link

Unintuitive behavior when session with sub key value is a primitive #16

Open mkrd opened 2 years ago

mkrd commented 2 years ago
DDB.at("test").create({"a": 0}, force_overwrite=True)
    with DDB.at("test", key="a").session() as (session, a):
        a = 1
        session.write()
    print(DDB.at("test").read())

prints 0, but it would be more intuitive if it was 1. The reason is that primitives like int are passed by value, not by ref.

The current way to solve this is:

DDB.at("test").create({"a": 0}, force_overwrite=True)
    with DDB.at("test_pd").session() as (session, d):
        d["a"] = 1
        session.write()
    print(DDB.at("test").read())

But this is not as efficient, since, the whole test file has to be loaded instead of only the key.

Another solution would be to pass the variable into the session.write()

DDB.at("test").create({"a": 0}, force_overwrite=True)
    with DDB.at("test", key="a").session() as (session, a):
        a = 1
        session.write(a)
    print(DDB.at("test").read())

A possible solution without changing the syntax is using the current frame with inspect:

import inspect

class ObtainVarInWith:
    def __enter__(self):
        f = inspect.currentframe().f_back
        self.x = 2
        self.oldvars = dict(f.f_locals)  # Take copy of locals dict.

        return self.x

    def __exit__(self, type, value, tb):
        f = inspect.currentframe().f_back
        for name, val in f.f_locals.items():
            if name not in self.oldvars:
                print("New variable:", name, val)
            elif val is not self.oldvars[name]:
                print("Changed variable", name, val)

with ObtainVarInWith() as x:
    print("in with block", x)
    x = 2
    print("after assign with block", x)