I want to make a registry of methods of a class during creation. My
attempt was this
""" classdecorators .py
Author: Justin Bayer
Creation Date: 2006-06-22
Copyright (c) 2006 Chess Pattern Soft,
All rights reserved. """
class decorated(objec t):
methods = []
@classmethod
def collect_methods (cls, method):
cls.methods.app end(method.__na me__)
return method
class dec2(decorated) :
@collect_method s
def first_func(self ):
pass
@collect_method s
def second_func(sel f):
pass
def main():
print dec2.methods
if __name__ == '__main__':
main()
This does not work and exits with "NameError: ("name 'collect_method s'
is not defined",)". Which is understandable due to the fact that the
class dec2 is not complete.
Anyone can give me a hint how to work around this? 5 2742
bayerj wrote: I want to make a registry of methods of a class during creation. My attempt was this
""" classdecorators .py
Author: Justin Bayer Creation Date: 2006-06-22 Copyright (c) 2006 Chess Pattern Soft, All rights reserved. """
class decorated(objec t):
methods = []
@classmethod def collect_methods (cls, method): cls.methods.app end(method.__na me__) return method
class dec2(decorated) :
@collect_method s def first_func(self ): pass
@collect_method s def second_func(sel f): pass
def main(): print dec2.methods
if __name__ == '__main__': main()
This does not work and exits with "NameError: ("name 'collect_method s' is not defined",)". Which is understandable due to the fact that the class dec2 is not complete.
Anyone can give me a hint how to work around this?
If you insist on doing black-magic (else go directly to the end of this
post), here's a way to do it, based on Ian Bicking's __classinit__ recipe http://blog.ianbicking.org/a-conserv...metaclass.html
(BTW, Ian, many many thanks for this trick - I really love it).
class DeclarativeMeta (type):
def __new__(meta, class_name, bases, new_attrs):
cls = type.__new__(me ta, class_name, bases, new_attrs)
cls.__classinit __.im_func(cls, new_attrs)
return cls
class Declarative(obj ect):
__metaclass__ = DeclarativeMeta
def __classinit__(c ls, new_attrs): pass
class MethodCollector (Declarative):
def __classinit__(c ls, new_attrs):
cls.methods = [name for name, attr in new_attrs.items () \
if callable(attr)]
class dec2(MethodColl ector):
def first_func(self ):
pass
def second_func(sel f):
pass
If you want to choose which methods to collect, then it's just a matter
of adding a simple decorator and a test in MethodCollector .__classinit__:
def collect(func):
func._collected = True
return func
class MethodCollector (Declarative):
def __classinit__(c ls, new_attrs):
cls.methods = [name for name, attr in new_attrs.items () \
if callable(attr) \
and getattr(attr, '_collected', False)]
class dec2(MethodColl ector):
@collect
def first_func(self ):
pass
@collect
def second_func(sel f):
pass
def not_collected(s elf):
pass
*BUT* is it really useful to go thru all this mess ?
class DeadSimple(obje ct):
@classmethod
def methods(cls):
return [name for name in dir(cls) \
if not name.startswith ('__') \
and callable(getatt r(cls, name))]
My 2 cents...
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
bayerj wrote: I want to make a registry of methods of a class during creation.
I think you're going to need a metaclass for this, e.g.:: import inspect def registered(func ):
.... func.registered = True
.... return func
.... class RegisterFuncs(t ype):
.... def __init__(cls, name, bases, classdict):
.... cls.methods = []
.... for name, value in classdict.iteri tems():
.... if inspect.isfunct ion(value):
.... if hasattr(value, 'registered'):
.... cls.methods.app end(name)
.... class C(object):
.... __metaclass__ = RegisterFuncs
.... @registered
.... def first_func(self ):
.... pass
.... @registered
.... def second_func(sel f):
.... pass
.... C.methods
['first_func', 'second_func']
If you just want to store *all* method names, you can dispense with the
@registered decorator and the hasattr() check.
STeVe
Hi,
Le Jeudi 22 Juin 2006 15:32, bayerj a écrit*: I want to make a registry of methods of a class during creation.
Why ? you already have them in dec2.__dict__ :
In [42]: import types
In [43]: class a :
....: def b(self) : return
....: @classmethod
....: def c(self) : return
....:
....:
In [44]: [ k for k, v in a.__dict__.item s() if isinstance(v,
types.FunctionT ype) ]
Out[44]: ['b']
In [45]: [ k for k, v in a.__dict__.item s() if isinstance(v, classmethod) ]
Out[45]: ['c']
Warning :
In [46]: list(isinstance (i, types.MethodTyp e) for i in (a.b, a().b,
a.__dict__['b']))
Out[46]: [True, True, False]
In [47]: list(isinstance (i, types.FunctionT ype) for i in (a.b, a().b,
a.__dict__['b']))
Out[47]: [False, False, True]
I would prefer write some inspection method that retrieve all these infos.
My attempt was this
And that can't work, """ classdecorators .py
Author: Justin Bayer Creation Date: 2006-06-22 Copyright (c) 2006 Chess Pattern Soft, All rights reserved. """
class decorated(objec t):
methods = []
@classmethod def collect_methods (cls, method): cls.methods.app end(method.__na me__) return method
class dec2(decorated) :
@collect_method s def first_func(self ): pass
@collect_method s def second_func(sel f): pass
This is trying to do :
first_func = collect_methods (first_fun)
but collect_methods doesn't exists in the global namespace (indeed you got a
NameError exception).
You can't reference it as decorated.colle ct_methods because the methods will
be appended to the decorated.metho ds list and not one list specific to dec2.
You neither can refer it as dec2.collect_me thods because dec2 is still
undefined. def main(): print dec2.methods
if __name__ == '__main__': main()
This does not work and exits with "NameError: ("name 'collect_method s' is not defined",)". Which is understandable due to the fact that the class dec2 is not complete.
Not exactly.
At any moment in a python program, there are two and only two scope, global
and local, global is usually the module level scope (where
no 'collect_method s' exists), and, in the case of a class definition, local
is the class __dict__ (the local namespace is not same the class and its
method).
But I'm not sure of what you really want : a list of all decorated methods of
all subclasses of a class, or a list of marked method in each class ?
--
_____________
Maric Michaud
_____________
Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097
bayerj schrieb: I want to make a registry of methods of a class during creation. My attempt was this
""" classdecorators .py
Author: Justin Bayer Creation Date: 2006-06-22 Copyright (c) 2006 Chess Pattern Soft, All rights reserved. """
class decorated(objec t):
methods = []
@classmethod def collect_methods (cls, method): cls.methods.app end(method.__na me__) return method
class dec2(decorated) :
@collect_method s def first_func(self ): pass
@collect_method s def second_func(sel f): pass
replace '@collect_metho ds' with '@decorated.col lect_methods'
and this will do what you want.
But keep in mind, that the 'methods' list in decorated will be used for
all derived classes.
Stephan Diehl wrote: replace '@collect_metho ds' with '@decorated.col lect_methods' and this will do what you want.
That is unlikely as it will keep a single list of methods for all classes
derived from decorated: calling decorated.colle ct_methods will pass
decorated as the cls parameter. What the OP wants it a separate list for
each subclass.
The way to do that of course is as others have suggested, just stick an
attribute on each decorated function and then collect_methods goes through
the class dict when it is called and picks out the correct methods. It
could even build a list cached on the class at that time if it needs to
(although the speedup is unlikely to be significant over just iterating
through all the methods picking out the marked ones). This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: RebelGeekz |
last post by:
Just my humble opinion:
def bar(low,high):
meta:
accepts(int,int)
returns(float)
#more code
Use a metadata section, no need to introduce new messy symbols, or
mangling our beloved visual cleanliness of python.
|
by: Guido van Rossum |
last post by:
Robert and Python-dev,
I've read the J2 proposal up and down several times, pondered all the
issues, and slept on it for a night, and I still don't like it enough
to accept it. The only reason to accept it would be to pacify the
supporters of the proposal, and that just isn't a good enough reason
in language design.
However, it got pretty darn close! I'm impressed with how the
community managed to pull together and face the enormous...
|
by: Anthony Baxter |
last post by:
To go along with the 2.4a3 release, here's an updated version of
the decorator PEP. It describes the state of decorators as they
are in 2.4a3.
PEP: 318
Title: Decorators for Functions and Methods
Version: $Revision: 1.34 $
Last-Modified: $Date: 2004/09/03 09:32:50 $
Author: Kevin D. Smith, Jim Jewett, Skip Montanaro, Anthony Baxter
|
by: Irmen de Jong |
last post by:
Hi,
I've developed the Metaclass below, because I needed a way
to make a bunch of classes thread-safe.
I didn't want to change every method of the class by adding
lock.aqcuire()..lock.release() around the existing code.
So I made a metaclass that essentially replaces every method
of a class with a 'wrapper' method, that does the locking,
invocation, unlocking.
Is this the right approach? It seems to work fine. But I have
|
by: Noam Raphael |
last post by:
Hello,
I thought about a new Python feature. Please tell me what you think
about it.
Say you want to write a base class with some unimplemented methods, that
subclasses must implement (or maybe even just declare an interface, with
no methods implemented). Right now, you don't really have a way to do
it. You can leave the methods with a "pass", or raise a
NotImplementedError, but even in the best solution that I know of,
| |
by: Bruce Cropley |
last post by:
Hi all
I'm trying to generate test methods in a unittest TestCase
subclass, using decorators. I'd like to be able to say:
class MyTestCase(unittest.TestCase):
@genTests(, , )
def something(self, side, price, someFlag):
# etc...
|
by: JOSII |
last post by:
Getting a string of boolean value into and out of the registry is no problem.
Here's the problem:
Although you can place an object into the registry and retreive it, I need
to place an ArrayList object with 10 string items into the registry and
retreive them later. I tried this:
key.SetValue("lstNSXitems", lstNSX.Items)
where "lstNSXitems" is the name of the subkey, and lstNSX.Items is the
|
by: WakeBdr |
last post by:
I'm writing a class that will query a database for some data and return
the result to the caller. I need to be able to return the result of
the query in several different ways: list, xml, dictionary, etc. I was
wondering if I can use decorators to accomplish this.
For instance, I have the following method
def getUsers(self, params):
return users.query(dbc)
|
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...
|
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,...
|
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...
| |
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...
|
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,...
|
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...
|
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...
|
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...
|
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();...
| |
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...
| |