This recent question raised my interest whether we can simulate private variable behaviour in python. I attempted to do just that with the help of inspect module.
My plan was to check whether the __getattribute__
method is being called from
the inside the class, similar to how this answer does it.
From my understanding, I can get the next outer frame object using f_back
until I eventually arive at the class from where it is being called. To my surprise, all calls of frame.__self__
resulted in AttributeError until I eventually arrived at None
by excessively calling f_back
:
import inspect
class MyClass:
def __init__(self):
self.variable = 1
def __getattribute__(self, attr):
frame = inspect.currentframe()
try:
while frame != None:
try:
frame.__self__ # Can I do that?
print("Yes I can")
except AttributeError:
print("Nope")
frame = frame.f_back
finally:
del frame
return super().__getattribute__(attr)
def get_variable(self):
return self.variable
A = MyClass()
print(A.get_variable())
Since all I'm getting is "Nope" even though the getter calls __getattribute__
from inside the class (and I would assume going back frame by frame I should arrive at the class from which it's beeing called) I can think of two possibilities why this isn't working.
- Something has changed since the answer was posted?
- I'm missing a key detail
Since my code is super similar to the code posted in the answer mentioned above, I'll go and assume it has something to do with the versions of python.
So my question is, how can I check from what class is the method beeing called? Is there some other way to do it? But most importantly why isn't this code working?