DRY and class variables

Thomas Jollans t at jollybox.de
Thu Sep 8 12:22:33 CEST 2011

On 08/09/11 11:55, egbert 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 ?

You should be able to do this with a metaclass (almost certainly
overkill), or with a class decorator (Python 2.6+):

def with_metadata (cls):
    cls.m = Metadata (cls.__name__)
    cls.m.do_something ()
    return cls

class TableOne:
   # foo

More information about the Python-list mailing list