property for class objects

Bengt Richter bokr at oz.net
Wed Nov 10 14:26:56 EST 2004


On Wed, 10 Nov 2004 08:28:22 -0500, Steve Menard <foo at bar.com> wrote:
[...]
>I wasnt aware of those descriptors (I am just now delving in the "meta" 
>side of things), and it looks promising. So thanks for taking the time 
>to tlel me about it :)
>
>Static variables are not just constants however, and the __set__ has to 
>work as normal. I did a quick test and it seems by mistake you can even 
>erase the descriptor with a new value .. not good.
>
Yes, the __set__ only gets called for instance attributes, unless there
is something intercepting the class attribute setattr.

>At least I can use this for the constant static values (which probably 
>comprises the bulk) and use the __setattr__ to prevent overwriting them.
>
If they're actually constant, why couldn't they be plain old class variables
protected by __setattr__?

>Steve
>
>Still looking for a more complete solution howeber
Don't know what syntax restrictions you have, but if you are trying to simulate
shared static value assignment via an apparent instance attribute assignment, e.g.,

    inst.static = value

why do you need to write

    InstClass.static = something

at all? You could always make a dummy instance to use when all you
wanted to do was access the shared statics, e.g.,

    shared = InstClass()
    ...
    shared.static = something

or even a dynamically created throwaway instance, as in

    InstClass().static = something

If you wanted to designate certain names for shared statics to be stored
as class variables, you could do something like (only tested as you see here ;-):

 >>> class HasStatics(object):
 ...     static_names = 'sa sb sz'.split()
 ...     def __setattr__(self, name, value):
 ...         if name in self.static_names: setattr(type(self), name, value)
 ...         else: object.__setattr__(self, name, value)
 ...
 >>> hs = HasStatics()
 >>> vars(hs)
 {}
 >>> hs.x = 123
 >>> vars(hs)
 {'x': 123}
 >>> hs.sa = 456
 >>> vars(hs)
 {'x': 123}
 >>> HasStatics.sa
 456
 >>> hs.sa
 456
 >>> vars(HasStatics).keys()
 ['__module__', '__setattr__', '__dict__', 'sa', '__weakref__', '__doc__', 'static_names']

static_names would be faster as a dict of the names (with ignored values), or possibly now
a set.

Regards,
Bengt Richter



More information about the Python-list mailing list