Python descriptor protocol (for more or less structured data)

CWr christoph.wruck at gmail.com
Wed Jul 31 11:16:08 CEST 2013


Peter, thanks for your response.
Sure, you are right when you say that's easier to use standard attribute assigning via __init__.

But my intention was:
- reducing the complexiticity of __init__
- avoiding boiler-plates (mostly property descriptors inside of the main class)
- creating instances (for complex data strings) only if they will be needed, otherwise use default instances (descriptors) 
- make it prossible that the data structure can be used in static context - like MyClass.attr - to get default values

Standard procedure:

>>>class C:
>>>    def __init__(self, one, two=None, three=None, four=None, five=None, ...):
>>>        if not two is None:
>>>            self.two = Value(two)
>>>        else:
>>>            self.two = Value(self.DEFAULT_4_TWO)
>>>        ...

vs:

>>>class C:
>>>
>>>    two = MyDescriptor('default for two')
>>>
>>>    def __init__(self, one, two=None, three=None, four=None, five=None, ...):
>>>        self.one = one
>>>        if not two is None:
>>>            self.two = two
>>>        ...

Probably it will be necessary to set the attribute at first access. Alternatively it may be possible to observe the descriptor til an attribute will be setted e.g. instance.attr.value = 'whatever'. At this point a new instance (like Value) should be created on obj.__dict__.

It's the procedure what I'm looking for. ;)

Kind Regards,
Chris



More information about the Python-list mailing list