DRY and static attribute for multiple classes.

Marc Aymerich glicerinu at gmail.com
Thu Feb 3 11:13:46 CET 2011


On Feb 3, 10:24 am, Peter Otten <__pete... at web.de> wrote:
> Marc Aymerich wrote:
> > On Feb 2, 12:11 am, Peter Otten <__pete... at web.de> wrote:
> >> Marc Aymerich wrote:
> > Hi!,
> > Unfortunately per_class attribute losses the "independence" when I try
> > to mix it with django models.Model .
>
> > from django.db import models
> > class Plugin(models.base.ModelBase):
> >     class __metaclass__(type):
> >         def __init__(self, *args):
> >             type.__init__(self, *args)
> >             self.per_class = []
>
> > class BaseService(models.Model):
> >     class Meta:
> >         abstract = True
>
> >     __metaclass__ = Plugin
>
> > class VirtualHost(BaseService):
> >     name = models.CharField(max_length=10)
>
> > class SystemUser(BaseService):
> >     name = models.CharField(max_length=10)
>
> >>>> VirtualHost.per_class is SystemUser.per_class
> > True
>
> > What am I doing wrong?
>
> I'm surprised that you are seeing the per_class-attribute at all as you are
> defining it in the metaclass of the metaclass, as far as I can tell.
> I think the following should work:
>
> from django.db import models
>
> class Plugin(models.base.ModelBase):
>     def __init__(self, *args):
>         super(Plugin, self).__init__(*args)
>         self.per_class = []
>
> class BaseService(models.Model):
>     class Meta:
>         abstract = True
>
>     __metaclass__ = Plugin
>
> class VirtualHost(BaseService):
>     name = models.CharField(max_length=10)
>
> class SystemUser(BaseService):
>     name = models.CharField(max_length=10)
>
> assert VirtualHost.per_class is not SystemUser.per_class
>
> But I have never worked with Django, and the approach based on dictionary
> lookup is less likely to interfere with the dark corners of the framework.
>
> Peter

Wow Peter, thanks for the correction, I've never used a metaclass
before :) With your correction seems that it works perfectly on
djando

>>> VirtualHost._plugin_registry.append('0000000')
>>> VirtualHost._plugin_registry
['0000000']
>>> SystemUser._plugin_registry
[]
>>>




More information about the Python-list mailing list