DRY and class variables

Eric Snow ericsnowcurrently at gmail.com
Thu Sep 8 12:44:04 EDT 2011


On Thu, Sep 8, 2011 at 3:55 AM, egbert <egbertum at xs4all.nl> wrote:
> My classes correspond to sql tables.
> In these classes I want to have several class variables
> that refer to data that are common to all instances.
>
> The assignment statements for the class variables are the same
> in all classes, except that of these instructions needs the name
> of the class itself. That name is used to read a file with meta-data.
>
> So what I have now is something like this (simplified):
>
> class TableOne(object):
>    m = Metadata('TableOne')
>    m.do_something()
>    def __init__(self):
>        etc
>
> class TableTwo(object):
>    m = Metadata('TableTwo')
>    m.do_something()
>    def __init__(self):
>        etc
>
> I have tried:
> - to eliminate the class name argument, but in this phase of the
>  object creation __class__ and __name__ are not available
> - to move the two statements to a superclass, but the class variables
>  come in the superclass namespace, not in the subclass namespace.
>
> Any ideas ?

Definitely an interesting problem I've run into before.  Here are two solutions:

1. in Python 3, use the metaclass __prepare__()  (see
http://code.activestate.com/recipes/577813/);
2. in Python 2 or 3, use a descriptor to defer creating your Metadata
objects until after the class object is available (see
http://code.activestate.com/recipes/577745/).

HTH

-eric

> e
> --
> Egbert Bouwman - Keizersgracht 197 II - 1016 DS  Amsterdam - 020 6257991
> ========================================================================
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list