title: Checking whether a method was called from inside the class
body: <p><a href="https://stackoverflow.com/questions/54876597/is-it-possible-to-have-protected-class-variables-or-methods-in-python#54876671">This</a> 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.</p>
  
  <p>My plan was to check whether the <code>__getattribute__</code> method is being called from 
  the inside the class, similar to how <a href="https://stackoverflow.com/a/53772947/5843769">this</a> answer does it.</p>
  
  <p>From my understanding, I can get the next outer frame object using <code>f_back</code> until I eventually arive at the class from where it is being called. To my surprise, all calls of <code>frame.__self__</code> resulted in AttributeError until I eventually arrived at <code>None</code> by excessively calling <code>f_back</code>:</p>
  
  <pre><code>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())
  </code></pre>
  
  <p>Since all I'm getting is "Nope" even though the getter calls <code>__getattribute__</code> 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.</p>
  
  <ol>
  <li>Something has changed since the answer was posted?</li>
  <li>I'm missing a key detail</li>
  </ol>
  
  <p>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.</p>
  
  <p>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 <em>this</em> code working?</p>