decorators and mangled names for "private" methods

Tim Chase python.list at tim.thechases.com
Fri Oct 25 15:44:23 EDT 2013


Given the following example 2.7 code:

from functools import wraps
class require_keys:
  def __init__(self, *keys):
    self.keys = keys
  def __call__(decorator_self, fn):
    @wraps(fn)
    def result_fn(method_self, *args, **kwargs):
      # import pdb; pdb.set_trace()
      req = method_self.__private()
      for key in decorator_self.keys:
        if key not in req:
          raise ValueError("Missing [%s] parameter" % key)
      return fn(method_self, *args, **kwargs)
    return result_fn
class Foo(object):
  def __init__(self, *params):
    self.params = params
    self.__private = params * 2
  def __private(self, *args, **kwargs):
    return self.__private
  @require_keys("hello", "world")
  def action(self):
    print self.params
f1 = Foo("hello", "world")
f1.action()
f2 = Foo("world")
f2.action()


I'm surprised to get the exception:

Traceback (most recent call last):
  File "dec_examp.py", line 28, in <module>
    f1.action()
  File "dec_examp.py", line 10, in result_fn
    req = method_self.__private()
AttributeError: 'Foo' object has no attribute '_require_keys__private'

For some reason, it's looking for "_require_keys__private" (which
obviously doesn't exist) instead of "_Foo__private" which exists
and would be what I expect.

What am I missing here?  Why is the decorator class finding the wrong
private-scope?

Thanks,

-tkc







More information about the Python-list mailing list