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

Home Posts Topics Members FAQ

manipulating class attributes from a decorator while the class isbeing defined

Hi, is it possible to manipulate class attributes from within a decorator
while the class is being defined?

I want to register methods with some additional values in a class attribute.
But I can't get a decorator to change a class attribute while the class is
still being defined. Something like:

class Parser(object):

regexps = []
def reg(regexp):
def deco(func):
regexps.append( (regexp, func))
return func
return deco

@reg(r'".*"')
def quoted_string(s elf):
pass

How can I reach the class attribute `regexps' from within a decorator?

Thanks for any help,
Wilbert Berendsen

--
http://www.wilbertberendsen.nl/
"You must be the change you wish to see in the world."
-- Mahatma Gandhi
Jun 27 '08 #1
4 1622
On Apr 19, 10:19*pm, Wilbert Berendsen <wbs...@xs4all. nlwrote:
Hi, is it possible to manipulate class attributes from within a decorator
while the class is being defined?

I want to register methods with some additional values in a class attribute.
But I can't get a decorator to change a class attribute while the class is
still being defined. Something like:

class Parser(object):

* regexps = []
* def reg(regexp):
* * def deco(func):
* * * regexps.append( (regexp, func))
* * * return func
* * return deco

* @reg(r'".*"')
* def quoted_string(s elf):
* * pass

How can I reach the class attribute `regexps' from within a decorator?
In this particular example, it is enought to change the line

def reg(regexp):

to:

def reg(regexp, regexps=regexps ):

So that 'regexps' inside reg() will point to the same object as
'regexps' outside reg().

Of course it wouldn't work well with inheritance, but it seems to me
that you don't want to subclass 'Parser' anyway. If you did, you
could instead have something like this:

class Ruleset(list):

def add(self, regexp):
def decorator(func) :
self.append((re gexp, func))
return func
return decorator
class Parser(object):

rules = Ruleset()

@rules.add(r'". *"')
def quoted_string(s elf):
pass
Or, yet another solution is to change the metaclass of 'Parser' so
that it populates the class's rules by scanning its attributes.

HTH

--
Arnaud

Jun 27 '08 #2
Wilbert Berendsen a écrit :
Hi, is it possible to manipulate class attributes from within a decorator
while the class is being defined?

I want to register methods with some additional values in a class attribute.
But I can't get a decorator to change a class attribute while the class is
still being defined. Something like:

class Parser(object):

regexps = []
def reg(regexp):
def deco(func):
regexps.append( (regexp, func))
return func
return deco

@reg(r'".*"')
def quoted_string(s elf):
pass

How can I reach the class attribute `regexps' from within a decorator?
Simple answer : you can't. Because, as you noticed, the class object
doesn't exist yet.

The canonical solutions are either to store regexps outside the class
(ie: as a module level variable) - which can be problematic in some
cases -, or to use a two-pass scheme using a decorator and a metaclass,
where the decorator annotate the function with required informations for
latter processing, and the metaclass do the effective processing.

There are of course other solutions, some of them possibly simpler. The
'best' solution of course depends on intented use of your class...

HTH
Jun 27 '08 #3
Wilbert Berendsen <wb****@xs4all. nlwrote:
Hi, is it possible to manipulate class attributes from within a
decorator while the class is being defined?

I want to register methods with some additional values in a class
attribute. But I can't get a decorator to change a class attribute
while the class is still being defined. Something like:

class Parser(object):

regexps = []
def reg(regexp):
def deco(func):
regexps.append( (regexp, func))
return func
return deco

@reg(r'".*"')
def quoted_string(s elf):
pass

How can I reach the class attribute `regexps' from within a decorator?
Have you tried passing regexps into the decorator as a default argument?

def reg(regexp, regexps=regexps ):
def deco(func):
regexps.append( (regexp, func))
return func
return deco
Jun 27 '08 #4
On Apr 19, 11:19 pm, Wilbert Berendsen <wbs...@xs4all. nlwrote:
Hi, is it possible to manipulate class attributes from within a decorator
while the class is being defined?

I want to register methods with some additional values in a class attribute.
But I can't get a decorator to change a class attribute while the class is
still being defined. Something like:

class Parser(object):

regexps = []
def reg(regexp):
def deco(func):
regexps.append( (regexp, func))
return func
return deco

@reg(r'".*"')
def quoted_string(s elf):
pass

How can I reach the class attribute `regexps' from within a decorator?

Thanks for any help,
Wilbert Berendsen

--http://www.wilbertbere ndsen.nl/
"You must be the change you wish to see in the world."
-- Mahatma Gandhi
---------------------------------------------------

def reg(regexp):
def deco(func):
def inner(self, *args, **kw):
if not hasattr(self, 'regexps'):
self.regexps = []
self.regexps.ap pend((regexp, func))
return func(self, *args, **kw)
return inner
return deco

class Parser(object):

regexps = []
@reg(r'".*"')
def quoted_string(s elf):
print 'hi'

p = Parser()

p.quoted_string ()

print p.regexps
---------------------------------------------------
Jun 27 '08 #5

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...
5
1145
by: Neal | last post by:
Hi I need to change my mousepointer when the mouse moves over certain populated controls on my aspx page. I've tried the following but without success (after visiting a site recommended from this forum, ie css cursors tutorial) I have, in the HTML defined this <Head>
2
1501
by: lcaamano | last post by:
We have a tracing decorator that automatically logs enter/exits to/from functions and methods and it also figures out by itself the function call arguments values and the class or module the function/method is defined on. Finding the name of the class where the method we just entered was defined in is a bit tricky. Here's a snippet of the test code: class Base: @tracelevel(1)
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...
6
3419
by: Chris Fonnesbeck | last post by:
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...
0
904
by: Christian Heimes | last post by:
Wilbert Berendsen schrieb: It's really tricky . The class object doesn't exists yet. It's created after all functions are parsed and created. You have can walk up the stack frames but it's ugly. Christian
0
794
by: Karl-Heinz Ruskowski | last post by:
How can I reach the class attribute `regexps' from within a decorator? Now, the first way that comes to my mind is simply overloading the class and set your regexps variable in your new class. The other way is to create an object and set it more manually (obj.regexps = ). Which for me is an ugly this to do because the first way is far more elegant :) -- GPG key: 0x04B3BB96
13
2741
by: Hussein B | last post by:
Hi, I'm familiar with static method concept, but what is the class method? how it does differ from static method? when to use it? -- class M: def method(cls, x): pass method = classmethod(method) --
11
6257
by: Rafe | last post by:
Hi, I'm working within an application (making a lot of wrappers), but the application is not case sensitive. For example, Typing obj.name, obj.Name, or even object.naMe is all fine (as far as the app is concerned). The problem is, If someone makes a typo, they may get an unexpected error due accidentally calling the original attribute instead of the wrapped version. Does anyone have a simple solution for this?
0
10115
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
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
8780
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7332
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
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...
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.