473,414 Members | 1,911 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,414 software developers and data experts.

Registry of Methods via Decorators

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(object):

methods = []

@classmethod
def collect_methods(cls, method):
cls.methods.append(method.__name__)
return method

class dec2(decorated):

@collect_methods
def first_func(self):
pass

@collect_methods
def second_func(self):
pass
def main():
print dec2.methods

if __name__ == '__main__':
main()

This does not work and exits with "NameError: ("name 'collect_methods'
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?

Jun 22 '06 #1
5 2713
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(object):

methods = []

@classmethod
def collect_methods(cls, method):
cls.methods.append(method.__name__)
return method

class dec2(decorated):

@collect_methods
def first_func(self):
pass

@collect_methods
def second_func(self):
pass
def main():
print dec2.methods

if __name__ == '__main__':
main()

This does not work and exits with "NameError: ("name 'collect_methods'
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__(meta, class_name, bases, new_attrs)
cls.__classinit__.im_func(cls, new_attrs)
return cls
class Declarative(object):
__metaclass__ = DeclarativeMeta
def __classinit__(cls, new_attrs): pass

class MethodCollector(Declarative):
def __classinit__(cls, new_attrs):
cls.methods = [name for name, attr in new_attrs.items() \
if callable(attr)]

class dec2(MethodCollector):
def first_func(self):
pass

def second_func(self):
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__(cls, new_attrs):
cls.methods = [name for name, attr in new_attrs.items() \
if callable(attr) \
and getattr(attr, '_collected', False)]

class dec2(MethodCollector):
@collect
def first_func(self):
pass

@collect
def second_func(self):
pass

def not_collected(self):
pass

*BUT* is it really useful to go thru all this mess ?

class DeadSimple(object):
@classmethod
def methods(cls):
return [name for name in dir(cls) \
if not name.startswith('__') \
and callable(getattr(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('@')])"
Jun 22 '06 #2
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(type): .... def __init__(cls, name, bases, classdict):
.... cls.methods = []
.... for name, value in classdict.iteritems():
.... if inspect.isfunction(value):
.... if hasattr(value, 'registered'):
.... cls.methods.append(name)
.... class C(object): .... __metaclass__ = RegisterFuncs
.... @registered
.... def first_func(self):
.... pass
.... @registered
.... def second_func(self):
.... 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
Jun 22 '06 #3
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__.items() if isinstance(v,
types.FunctionType) ]
Out[44]: ['b']

In [45]: [ k for k, v in a.__dict__.items() if isinstance(v, classmethod) ]
Out[45]: ['c']

Warning :

In [46]: list(isinstance(i, types.MethodType) for i in (a.b, a().b,
a.__dict__['b']))
Out[46]: [True, True, False]

In [47]: list(isinstance(i, types.FunctionType) 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(object):

methods = []

@classmethod
def collect_methods(cls, method):
cls.methods.append(method.__name__)
return method

class dec2(decorated):

@collect_methods
def first_func(self):
pass

@collect_methods
def second_func(self):
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.collect_methods because the methods will
be appended to the decorated.methods list and not one list specific to dec2.
You neither can refer it as dec2.collect_methods because dec2 is still
undefined.

def main():
print dec2.methods

if __name__ == '__main__':
main()

This does not work and exits with "NameError: ("name 'collect_methods'
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_methods' 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
Jun 22 '06 #4
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(object):

methods = []

@classmethod
def collect_methods(cls, method):
cls.methods.append(method.__name__)
return method

class dec2(decorated):

@collect_methods
def first_func(self):
pass

@collect_methods
def second_func(self):
pass


replace '@collect_methods' with '@decorated.collect_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.
Jun 22 '06 #5
Stephan Diehl wrote:
replace '@collect_methods' with '@decorated.collect_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.collect_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).
Jun 22 '06 #6

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

Similar topics

4
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...
2
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...
0
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...
5
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()...
51
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...
3
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...
6
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...
8
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,...
20
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...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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,...
0
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...
0
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...
0
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...

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.