perf(descriptor): use weakref

refuse weak reference to a value in WeakRefDict instead of polluting instance namespace
This commit is contained in:
mpa 2020-05-30 20:49:57 +04:00
parent fb63619e52
commit a2e85c5a42
No known key found for this signature in database
GPG key ID: BCCFBFCCC9B754A8
3 changed files with 21 additions and 78 deletions

View file

@ -49,14 +49,9 @@ class TestBaseSession:
return json.dumps
session.json_dumps = custom_dumps
assert session.json_dumps == custom_dumps == session._json_dumps
assert session.json_dumps == custom_dumps
session.json_loads = custom_loads
assert session.json_loads == custom_loads == session._json_loads
different_session = CustomSession()
assert all(
not hasattr(different_session, attr) for attr in ("_json_loads", "_json_dumps", "_api")
)
assert session.json_loads == custom_loads
def test_timeout(self):
session = CustomSession()

View file

@ -139,7 +139,6 @@ class TestDefaultDescriptor:
obj = type("ClassA", (), {})()
default_x_val = "some_x"
x = DefaultProperty(default_x_val)
x.__set_name__(owner=obj.__class__, name="x")
# we can omit owner, usually it's just obj.__class__
assert x.__get__(instance=obj, owner=None) == default_x_val
@ -161,45 +160,12 @@ class TestDefaultDescriptor:
x.__delete__(instance=obj)
assert x.__get__(instance=obj, owner=obj.__class__) == default_x_val
def test_set_name(self):
class A:
x = DefaultProperty("default")
a = A()
assert "_x" not in vars(a)
a.x = "new value"
assert "_x" in vars(a)
del a.x
assert "_x" not in vars(a)
assert a.x == "default"
class B:
x = DefaultProperty("default", name_resolver=lambda name: f"_{name}_4_{name}_")
b = B()
b.x = ">>"
assert "_x_4_x_" in vars(b)
C = type("C", (), {"x": DefaultProperty("default")})
c = C()
assert c.x == "default"
c.x = "new value"
assert "_x" in vars(c)
d = type("D", (), {})()
x = DefaultProperty("default")
with pytest.raises(AttributeError) as exc:
x.__set__(d, "new_value")
assert f"Name for descriptor was never set in {d}" in str(exc.value)
def test_init(self):
class A:
x = DefaultProperty(fget=lambda a_inst: "nothing")
assert isinstance(A.__dict__["x"], DefaultProperty)
a = A()
assert a.x == "nothing"
@ -207,9 +173,9 @@ class TestDefaultDescriptor:
assert x.__get__(None, None) == "x"
assert x.fget(None) == x.__get__(None, None)
with pytest.raises(ValueError) as exc:
def test_nullability(self):
class A:
x = DefaultProperty(default=None, fget=None)
class _:
x = DefaultProperty(default=None, fget=None)
assert "Either default or fget should be passed." in str(exc.value)
assert A.x is None
assert A().x is None