473,761 Members | 10,365 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class decorators do not inherit properly

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(MetropolisHa stings):
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.

Thanks.


Jul 12 '07 #1
6 3419
Traceback (most recent call last):
File "/Users/chris/Projects/CMR/closed.py", line 132, in <module>
class M0(MetropolisHa stings):
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:

I think the term "class decorator" is going to eventually
mean something other than what you are doing here. I'd
avoid the term for now.
When you decorate a class method, the function you use
needs to be defined before the method definition.

Using a class method to decorate another class method is
going to be tricky. The way I usually do it is to create
a separate function outside of the class definition for
the decorator function.
You're going to have to show us the actual code you are
having trouble with, or else (probably more useful, really)
try to put together a minimal example of what you are
trying to do and show us that code.

Jul 12 '07 #2
Lee Harr a écrit :
>Traceback (most recent call last):
File "/Users/chris/Projects/CMR/closed.py", line 132, in <module>
class M0(MetropolisHa stings):
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:


I think the term "class decorator" is going to eventually
mean something other than what you are doing here. I'd
avoid the term for now.
When you decorate a class method,
the function you use
needs to be defined before the method definition.
This is true whatever you are decorating - class method, static method,
instance method, function. And FWIW, the term "class method" has a
definite meaning in Python.
Using a class method to decorate another class method is
going to be tricky. The way I usually do it is to create
a separate function outside of the class definition for
the decorator function.
The problem is then that this function cannot easily access the class
object - which is what the OP want.
>
You're going to have to show us the actual code you are
having trouble with, or else (probably more useful, really)
try to put together a minimal example of what you are
trying to do and show us that code.
+1 on this

Jul 13 '07 #3
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(MetropolisHa stings):
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(BaseCl ass):
@BaseClass._add _to_post
def some_method(sel f):
# code here

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

HTH
Jul 13 '07 #4
Chris Fonnesbeck schrieb:
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(MetropolisHa stings):
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.
Does this simple example show your problem?
class Meta(type):
def __init__(cls, *args):
print "Meta.__ini t__ called"
return super(Meta, cls).__init__(* args)
class A(object):
__metaclass__ = Meta

def decorator(f):
print "decorator called"
return f

@decorator
def foo(self):
pass
class B(A):
#@decorator
def bar(self):
pass
print dir(A())
print dir(B())
then it explains the problem easily: the class-statement (class
Name(base): <definitions) is evaluated _before_ the actual class is
created. Thus at that moment, there is no decorator known in the
surrounding scope.

Use a function level decorator instead, that delegates it's work to a
classmethod/instancemethod. Something like this (can't be more precise
as you didn't show us code):

def decorator(f):
def _d(self, *args, **kwargs):
self._a_decorat or_method()
return f(self, *args, **kwargs)
return _d
Diez
Jul 13 '07 #5
>I think the term "class decorator" is going to eventually
>mean something other than what you are doing here. I'd
avoid the term for now.
When you decorate a class method,
the function you use
needs to be defined before the method definition.

FWIW, the term "class method" has a
definite meaning in Python.

Certainly. But "class decorator" is being introduced in
Python 3000 with PEP 3129:
http://www.python.org/dev/peps/pep-3129/

Jul 13 '07 #6
Lee Harr a écrit :
>>>I think the term "class decorator" is going to eventually
mean something other than what you are doing here. I'd
avoid the term for now.
When you decorate a class method,
the function you use
needs to be defined before the method definition.

FWIW, the term "class method" has a
definite meaning in Python.

Certainly. But "class decorator" is being introduced in
Python 3000 with PEP 3129:
http://www.python.org/dev/peps/pep-3129/
Certainly. But [1] "class methods" have been introduced in Python 2.2 !-)

[1] IIRC - please someone correct me if I'm wrong
Jul 16 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
1571
by: Humpty Dumpty | last post by:
Hello, I'm experimenting with different ways of extending a class (for a plug-ins framework for a GUI) with more than one extension when some of these extensions need to collaborate, but others mustn't know about each other. I.e., if I have a class A, and I want to add a block of functionality, I can derive it into a B that adds that fucntionality. If I want to add more functionality, I can derive B into a C. But if I want to add a...
4
1401
by: Doug Holton | last post by:
First let me say please see the wiki page about python decorators if you haven't already: http://www.python.org/cgi-bin/moinmoin/PythonDecorators I propose (and others have) that built-in features have keyword support, like static and class methods. Also, I believe it is more readable if decorators, especially longer ones, are moved to the top of the function body, just like docstrings, instead of coming before the function is even...
22
2237
by: Ron_Adam | last post by:
Hi, Thanks again for all the helping me understand the details of decorators. I put together a class to create decorators that could make them a lot easier to use. It still has a few glitches in it that needs to be addressed. (1) The test for the 'function' object needs to not test for a string but an object type instead.
9
4996
by: Banaticus Bart | last post by:
I wrote an abstract base class from which I've derived a few other classes. I'd like to create a base class array where each element is an instance of a derived object. I can create a base class pointer which points to an instance of a derived class, but when I pass that base class pointer into a function, it can't access the derived object's public functions. Although, the base class pointer does call the appropriate virtual function...
2
6923
by: SpotNet | last post by:
Hi Newsgroup, Reconstructing my common dialog assembly using C# 2.0 .NET Framework 2.0. I have the following; public class FileDialogBase: System.Windows.Forms.FileDialog { //No constructor seem to do me any justice.... }
0
2834
by: emin.shopper | last post by:
I had a need recently to check if my subclasses properly implemented the desired interface and wished that I could use something like an abstract base class in python. After reading up on metaclass magic, I wrote the following module. It is mainly useful as a light weight tool to help programmers catch mistakes at definition time (e.g., forgetting to implement a method required by the given interface). This is handy when unit tests or...
7
2282
by: MR | last post by:
Hello All, I have a question about decorators, and I think an illustration would be helpful. Consider the following simple class: #begin code class Foo: def fooDecorator(f): print "fooDecorator"
20
1732
by: vbgunz | last post by:
I remember learning closures in Python and thought it was the dumbest idea ever. Why use a closure when Python is fully object oriented? I didn't grasp the power/reason for them until I started learning JavaScript and then BAM, I understood them. Just a little while ago, I had a fear of decorators because I really couldn't find a definitive source to learn them (how to with with @). How important are they? They must be important...
0
765
by: Laszlo Nagy | last post by:
Aigars Aigars wrote: First of all, you should always inherit from "object" whenever it is possible. Then the answer: you did not return the result. Instead of self.func(*args, **kwargs)
0
9345
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9957
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9905
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9775
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6609
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5229
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3881
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3456
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2752
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.