decorators and mangled names for "private" methods
Peter Otten
__peter__ at web.de
Fri Oct 25 16:01:01 EDT 2013
Tim Chase wrote:
> 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()
The above __private literal is in the (statically determined) scope of the
require_keys class and therefore magically mangled to
_require_keys__private.
Unfortunately I can't think of an elegant way to work around that...
> 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