Need help with Python scoping rules

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Aug 27 04:18:59 EDT 2009


kj a écrit :
(snip)
> 
>> I fully agree that this case is rather vexing to my (and obviously your)
>> biased brain. I wouldn't call this a bug before fully understanding why
>> e.g. you can not access a class before its definition is finished.
> 
> I understand this, what I don't understand is why do it this way.
> I've been trying to understand this particular design point for
> *literally* years.

It's quitye simple: 'class' is an executable statement that creates a 
class object (yes, all this happens at runtime) and bind it in the 
current namespace. So until the class statement is executed, the class 
object doesn't exist and it's name is not bound.

Now if you don't understand why it's a GoodThing(tm) that all this 
happens at runtime, have a look at metaclasses, how they are used in 
most major Python frameworks, and how this allows to vastly reduce the 
amount of needed boring and erreor-prone boilerplate code one cand find 
elsewhere.

>> I think
>> someone mentioned one or two PEPs, which are the design documents that
>> explain Python including the rationale, I'd use that as a starting point.
> 
> I'm reading PEP 227 now, suggested by Steven D'Aprano.  In it I
> find statements like the following alert: 
> 
>     (Note: If a region is contained within a class definition, the
>     name bindings that occur in the class block are not visible to
>     enclosed functions.)
> 
> I've seen this before, but never an explanation for why having this
> restriction. 

You should re-read Carl Bank's answers more carefully then.

> It's just one of life's mysteries.  (Incidentally,
> the fact that the author of PEP 227 felt it necessary to add that
> parenthetical remark suggests that the expectation it warns against
> is not so crazy after all.)

It's not so crazy for someone coming from a more static language. 
Python's object model is indeed a bit peculiar, and it can take some 
times getting the big picture, but be sure it has been carefully 
designed, and is incredibly powerfull once you start understanding the 
whole thing.

> But I'm still not done with PEP 227.  Maybe I'll see the light by
> the time I'm done.

My 2 cents : learn about metaclasses, attributes lookup rules, and the 
descriptor protocol (and some practical applications of these features). 
Then you might decide that the few resulting restrictions are really 
worth the price.




More information about the Python-list mailing list