decorators and mangled names for "private" methods

T

Tim Chase

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,930
Messages
2,570,072
Members
46,522
Latest member
Mad-Ram

Latest Threads

Top