Style question - defining immutable class data members
matthew at woodcraft.me.uk
Sun Mar 15 21:54:17 CET 2009
John Posner <jjposner at snet.net> writes:
> My question is ... WHY does the interpreter silently create the
> instance attribute at this point, causing a "surprising decoupling"
> from the class attribute? WHY doesn't the interpreter behave as it
> would with a simple, non-instance variable:
> > python
> Python 2.6.1 ...
> Type "help", "copyright", "credits" or "license" for more information.
> >>> x += 1
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> NameError: name 'x' is not defined
> Is there a beneficial effect of silently creating the instance
> attribute, which outweighs the detrimental effects: (1) inconsistency,
> (2) the "surprising" decoupling?
I doubt it's because anyone particularly wanted this behaviour; it just
falls out of the way '+=' is defined.
At the point where 'inst.x += 1' is compiled, Python doesn't know
whether 'inst.x' is going to turn out to be a class attribute or an
instance attribute or a property. So really the only thing it can do is
generate code to read inst.x in the usual way and then assign to inst.x
in the usual way (where 'the usual way' for CPython is LOAD_ATTR and
More information about the Python-list