Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
mkrd opened this issue Oct 31, 2022 · 0 comments
Open

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

mkrd opened this issue Oct 31, 2022 · 0 comments
Labels
enhancement New feature or request

Comments

@mkrd
Copy link
Owner

mkrd commented Oct 31, 2022

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)
@mkrd mkrd modified the milestone: v2.2.0 Nov 7, 2022
@mkrd mkrd added the enhancement New feature or request label Nov 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant