Class-level variables - a scoping issue

John Nagle nagle at animats.com
Sun Oct 10 15:07:10 EDT 2010


On 10/10/2010 12:53 AM, Lawrence D'Oliveiro wrote:
> In message<4cb14f8c$0$1627$742ec2ed at news.sonic.net>, John Nagle wrote:
>
>> Within "fn1", the first reference to "self.classvar" references the class-
>> level version of "classvar".  The assignment overrides that and creates an
>> object-level instance of "self.classvar". Further references to
>> self.classvar" in f1 then reference the object-level "classvar"
>
> I’d say there is definitely an inconsistency with the absoutely anal
> restrictions on global variables, i.e. the well-known sequence
>
>      ... reference to globalvar ...
>      globalvar = newvalue
>
> which triggers the error “UnboundLocalError: local variable 'globalvar'
> referenced before assignment”.
>
> It seems to me the same principle, that of disallowing implicit overriding
> of a name from an outer scope with that from an inner one after the former
> has already been referenced, should be applied here as well.

     Right.  That's what I'm getting at.

     I understand how the current semantics fall out of the obvious
implementation.  But I don't see those semantics as particularly
desirable.  The obvious semantics for globals are similar, but
that case is so error-prone that it was made an error.

     (If you want default values for an instance, you define them
in __init__, not as class-level attributes.)

				John Nagle



More information about the Python-list mailing list