Trying to understand __getattr__ and __setattr__ I use test modules from Micropython, but by fact it's work as __dict__ and not as written in standart, and when value go to __dict__, __getattr__ and __setattr__ not worked at all.
I use Micropython 1.10
In comments - reaction of print()
May be I do something wrong?
-----------------------------------------------------------------------------------
# this class acts like a dictionary
class B:
def __init__(self, d):
# store the dict in the class, not instance, so
# we don't get infinite recursion in __getattr_
B.d = d
def __getattr__(self, attr):
if attr in B.d:
print('__getattr__ {} is {}'.format(attr,B.d))
return B.d[attr]
else:
raise AttributeError(attr)
def __setattr__(self, attr, value):
print('__setattr__ {} is {}'.format(attr,B.d))
B.d[attr] = value
def __delattr__(self, attr):
print('__delattr__ {} is {}'.format(attr,B.d))
del B.d[attr]
print('after __delattr__ {} is {}'.format(attr,B.d))
a = B({"a":1, "b":2})
print(a.__dict__)
# {} :: empty __dict__
print(a.a, a.b)
# __getattr__ a is {'a': 1, 'b': 2}
# __getattr__ b is {'a': 1, 'b': 2}
# 1 2
print(a.a)
# __getattr__ a is {'a': 1, 'b': 2}
# 1
a.a = 3
print(a.__dict__)
# {'a': 3} :: now __dict__ has value 'a' !!!!!
print(a.a, a.b)
# __getattr__ b is {'a': 1, 'b': 2} :: ONLY 'b' CROSS __getattr__
# 3 2 :: 'a' SHOWN FROM __dict__ !!!
print(a.a)
# 1 :: WHERE IS __getattr__ ???
print('============ DEL ============')
del a.a
# NOTHING HAPPEND ??? WHERE IS __delattr__ ???
print(a.__dict__)
# {} :: but now __dict__ is empty
try:
print(a.a, a.b)
# __getattr__ a is {'a': 1, 'b': 2} :: WOW!!! GO BACK TO PREV VALUE 'a'
# __getattr__ b is {'a': 1, 'b': 2}
except AttributeError:
print("AttributeError")
print('============ DEL 2u ============')
del a.a
# AttributeError: 'B' object has no attribute 'a' :: RISE EXCEPTION
print(a.__dict__)
print(a.a)
Not stable __getattr__ __setattr__ in micropython/tests/basics/class_delattr_setattr.py
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
It looks like a bug to me
As far as I can see you're right. I've raised this issue.
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.
Re: It looks like a bug to me
I'll be glad if this issue help to do source betterpythoncoder wrote: ↑Wed Feb 27, 2019 6:46 amAs far as I can see you're right. I've raised this issue.
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: Not stable __getattr__ __setattr__ in micropython/tests/basics/class_delattr_setattr.py
It has emerged that the feature is deliberately omitted from the Unix build. In my opinion the Unix build should include all MicroPython language features: this is under discussion by the maintainers.
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.