Registry of Methods via Decorators
Maric Michaud
maric at aristote.info
Thu Jun 22 10:52:45 EDT 2006
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
More information about the Python-list
mailing list