Skip to content
Advertisement

How to pass self attributes to a decorator?

I have a decorator for an object method:

JavaScript

I want to add another level of wrapping around this to allow parameters:

JavaScript

Now, what I want to be able to do is pass a self attribute as a wrapper parameter, i.e. call it with something like this

JavaScript

I see 2 options:

  1. make self._foo global
  2. don’t pass self._foo, and make the decorator access self._foo

Both are bad. (global can be changed from another place without my knowledge, and making the decorator access self._... means the decorator knows the class it operates on) Is there a good way to do this?

Advertisement

Answer

This example works just fine (You can pick _foo or _bar) and the wrapper itself knows nothing of Bar nor its members:

JavaScript

Output: 2

The wrapper decorator can be located in another module, or as part of a library and Bar as the client will be unknown to the decorator.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement