module wide metaclass for new style classes
Gabriel Genellina
gagsl-py at yahoo.com.ar
Sat Dec 16 22:34:30 EST 2006
On 16 dic, 14:44, "Daniel Nogradi" <nogr... at gmail.com> wrote:
> I used to have the following code to collect all (old style) class
> names defined in the current module to a list called reg:
>
> def meta( reg ):
> def _meta( name, bases, dictionary ):
> reg.append( name )
> return _meta
>
> reg = [ ]
> __metaclass__ = meta( reg )
>
> class c1:
> pass
>
> class c2:
> pass
>
> print reg
>
> This would correctly print [ 'c1', 'c2' ]. Now I would like to switch
> to new style classes but replacing class c1: and class c2: by class
> c1(object): and class c2(object): doesn't work because the metaclass
> associated with object will be called and not mine. Of course if I
> would add __metaclass__ = meta(reg) to all class definitions that
> would work, but how do I do this on the module level?
That code doesn't work even for classic classes. Anyway, you don't have
to add __metaclass__ everywhere, only to the base class(es).
If all you want to register is contained in a single module, I prefer a
function that iterates over all defined classes:
from inspect import isclass
for obj in globals().values():
if isclass(obj): # may be stricter too, like issubclass(obj, Base)
reg.append(obj)
--
Gabriel Genellina
More information about the Python-list
mailing list