Skip to content

Commit

Permalink
Handle self obtained via LOAD_DEREF not LOAD_FAST. Fixes #9
Browse files Browse the repository at this point in the history
  • Loading branch information
cjrh committed Dec 22, 2022
1 parent a36ea37 commit 5b896b8
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
5 changes: 4 additions & 1 deletion autoslot.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ def assignments_to_self(method) -> set:
names = set()
# a and b are a pair of bytecode instructions; b follows a.
for a, b in zip(i0, i1):
accessing_self = (a.argval == instance_var and a.opname == 'LOAD_FAST')
accessing_self = (
a.argval == instance_var
and a.opname in ('LOAD_FAST', 'LOAD_DEREF')
)
storing_attribute = (b.opname == 'STORE_ATTR')
if accessing_self and storing_attribute:
names.add(b.argval)
Expand Down
39 changes: 39 additions & 0 deletions tests/test_slots.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,45 @@ def __init__(self, a, b):
a.z = 3


def test_slots_load_deref():
"""Values can come from either LOAD_FAST or LOAD_DEREF
opcodes, so we need to handle both."""
class A(Slots):
def __init__(self, a, b):
self.x = a

def f():
"""Simply by referring to self in another scope
is enough to change the `self` accessing opcodes
in __init__ to become LOAD_DEREF instead of
LOAD_FAST. We don't even have to call `f`."""
print(self)

self.y = b

# Testing to see that the
# bytecode processor identifies things
# correctly.
self.x = 'bleh'

assert '__module__' in A.__dict__
assert '__init__' in A.__dict__
assert '__slots__' in A.__dict__
assert A.__dict__['__slots__'] == {'x', 'y'}

a = A(1, 2)
assert hasattr(a, 'x')
assert hasattr(a, 'y')
# Just checking that we didn't pick up the wrong names
assert not hasattr(a, 'a')
assert not hasattr(a, 'b')
assert hasattr(a, '__slots__')
assert not hasattr(a, '__dict__')
# Can't assign new attributes
with pytest.raises(AttributeError):
a.z = 3


def test_slots_weakref():
"""Basic usage of the Slots metaclass."""
class A(Slots):
Expand Down

0 comments on commit 5b896b8

Please sign in to comment.