Class decorators do not inherit properly

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Jul 13 03:52:59 EDT 2007


Chris Fonnesbeck a écrit :
> I have a class that does MCMC sampling (Python 2.5) that uses decorators 
> -- one in particular called _add_to_post that appends the output of the 
> decorated method to a class attribute.

> However, when I 
> subclass this base class, the decorator no longer works:
> 
> Traceback (most recent call last):
>   File "/Users/chris/Projects/CMR/closed.py", line 132, in <module>
>     class M0(MetropolisHastings):
>   File "/Users/chris/Projects/CMR/closed.py", line 173, in M0
>     @_add_to_post
> NameError: name '_add_to_post' is not defined
> 
> yet, when I look at the dict of the subclass (here called M0), I see the 
> decorator method:
> 
> In [5]: dir(M0)
> Out[5]: 
> ['__call__',
>  '__doc__',
>  '__init__',
>  '__module__',
>  '_add_to_post',
> ...
> 
> I dont see what the problem is here -- perhaps someone could shed 
> some light. I thought it might be the underscore preceding the name, 
> but I tried getting rid of it and that did not help.

A minimal runnable code snippet reproducing the problem would *really* 
help, you know...

Anyway: the body of a class statement is it's own namespace. So in the 
body of your base class, once the _add_to_post function is defined, you 
can use it. But when subclassing, the subclass's class statement creates 
a new namespace, in which _add_to_post is not defined - hence the 
NameError. To access this symbol, you need to use a qualified name, ie:

class SubClass(BaseClass):
   @BaseClass._add_to_post
   def some_method(self):
     # code here

Now there may be better solutions, but it's hard to tell without knowing 
more about your concrete use case.

HTH



More information about the Python-list mailing list