Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to decorate an object method?
    primarykey
    data
    text
    <p>I need to decorate a object's method. It needs to be at runtime because the decorators applied on the object depends on the arguments that the user gave when calling the program (arguments supplied with argv), so a same object could be decorated 3 times, 2 times, or not be decorated at all.</p> <p>Here is some context, the program is a puzzle solver, the main behavior is to find a solution for the puzzle automatically, by automatically I mean without user intervention. And here is where the decoration gets to play, one of the things I want to is draw a graph of what happened during the execution, but I want to do so only when the flag <code>--draw-graph</code> is used.</p> <p>Here is what I've tried:</p> <pre><code>class GraphDecorator(object): def __init__(self, wrappee): self.wrappee = wrappee def method(self): # do my stuff here self.wrappee.method() # do more of stuff here def __getattr__(self,attr): return getattr(self.wrappee,attr) </code></pre> <p>And why it did NOT work: It did not work because of the way I built the application, when a method that did not exist in my Decorator class was called it felt back to the implementation of the decorated class, the problem is that the application always started invoking the method <code>run</code> that did not need to be decorated, so the undecorated fall back was used and from inside the undecorated form it always called <strong>undecorated</strong> methods, what I needed was to replace the method from the object, not to proxy it:</p> <pre><code># method responsible to replace the undecorated form by the decorated one def graphDecorator(obj): old_method = obj.method def method(self): # do my stuff here old_method() # do more of my stuff setattr(obj,'method',method) # replace with the decorated form </code></pre> <p>And here is my problem, the decorated form does not receive <code>self</code> when it is called resulting on a TypeError because of the wrong number of arguments.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload