Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #57555

Re: decorators and mangled names for "private" methods

From Peter Otten <__peter__@web.de>
Subject Re: decorators and mangled names for "private" methods
Date 2013-10-25 22:01 +0200
Organization None
References <20131025144423.74c8e3c9@bigbox.christie.dr>
Newsgroups comp.lang.python
Message-ID <mailman.1541.1382731256.18130.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: decorators and mangled names for "private" methods Peter Otten <__peter__@web.de> - 2013-10-25 22:01 +0200

csiph-web