Class-level variables - a scoping issue

Gregory Ewing greg.ewing at canterbury.ac.nz
Mon Oct 11 19:51:34 EDT 2010


Lawrence D'Oliveiro wrote:
> In message <8hfq23FetrU1 at mid.individual.net>, Gregory Ewing wrote:
> 
>>How would you intend to enforce such a restriction?
> 
> The same way it’s already enforced.

I don't see how that's possible, except in a very limited and
unreliable way. The compiler would have to be able to determine,
statically, when there was some piece of code that could assign
to a given instance variable of some instance of a class, and
arrange for an "unbound attribute error" to be raised if you
try to reference it before it's been assigned.

When you consider that potential assignments to attributes
can occur in any module, not necessarily the one where the class
is defined, and that classes and instances can be dynamically
modified just about any way at all, this does not seem to be
feasible.

Name lookup and attribute lookup are really quite different
things. The former occurs in an extremely restricted context,
so much so that the compiler knows exactly where every name
is or could be defined. The latter is completely open, and
the compiler can hardly tell anything at all.

So, any enforcement of "unbound attribute" conditions would have
to be done at run time. But this is impossible, because at the
point where you reference an attribute that has no instance
binding, there's no way of telling whether something might give
it an instance binding in the future. At least not without
Guido releasing the time machine's kernel code so that it can
be incorporated into the Python VM...

-- 
Greg



More information about the Python-list mailing list