Python descriptor protocol (for more or less structured data)
tjreedy at udel.edu
Wed Jul 31 19:44:15 CEST 2013
On 7/31/2013 5:16 AM, CWr wrote:
> 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:
DEFAULT_4_TWO = <somethint> # for following code to work
>>>> def __init__(self, one, two=None, three=None, four=None, five=None, ...):
>>>> if not two is None:
"if two is not None:" reads better and is the preferred form.
'is not' is a single comparison operator, just like '!=' and 'not in'.
The current CPython AST or peephole optimizer happens to notice that the
'is' operator followed by the 'not' operator can be replaced by the 'is
not' operator, but this is not guaranteed for all implementations.
>>>> self.two = Value(two)
>>>> self.two = Value(self.DEFAULT_4_TWO)
self.two = Value(two if two is not None else self.DEFAULT_4_TWO)
There is no need to introduce the new name DEFAULT_4_TWO. It is a
symptom of using the wrong namespace to get the default.
two = <default>
def __init__(self, two=None):
self.two = Value(two if two is not None else C.two)
Terry Jan Reedy
More information about the Python-list