I have this (below) code pattern in my project, which is a FOREX client. My question stems from this code review. The outcome of that review resulted in my class definitions that previously derived from tuple
now derive form object
. This was done to allow for simpler reifying than my suggested idea in the review (and resulted in large performance improvements).
The implementation is done in a similar fashion to the class Foo
(below).
reify = lambda x: x
class Foo(object):
def __init__(self, value):
self._value = value
def __getattr__(self, item):
print('Reifying')
attr = object.__getattribute__(self, '_'+item)
value = reify(attr)
setattr(self, item, value)
return value
Example reify
ing
>>> foo = Foo(1)
>>> foo.value
Reifying
1
>>> foo.value
1
But also allows for attribute assignment. (After all nothing in python is private)
>>> foo.value = 2
>>> foo.value
2
I would really like to reclaim the safety of tuple
instances. Knowing that information from the server can't be accidentally changed and acted upon. (For myself and other's who may choose to use my code)
Ok, so that's context of this Question: How could I implement the above Foo class in cython that presents an immutable instance? inspired by this question.
I naively tried this:
cdef class Bar:
cdef readonly int value
cdef int _value
def __init__(self, value):
self._value = value
def __getattr__(self, item):
attr = object.__getattribute__(self, '_'+item)
value = reify(attr)
setattr(self, item, value)
return value
But quickly found out that __getattr__
is never called because value
is initialized with 0
>>> a = Bar(1)
>>> a.value
0
>>>