Need help with Python scoping rules

kj no.email at please.post
Wed Aug 26 22:35:28 CEST 2009


In <2a7gm6-9h.ln1 at satorlaser.homedns.org> Ulrich Eckhardt <eckhardt at satorlaser.com> writes:

>kj wrote:
>> class Demo(object):
>>     def fact_iter(n):
>>         ret = 1
>>         for i in range(1, n + 1):
>>             ret *= i
>>         return ret
>> 
>>     def fact_rec(n):
>>         if n < 2:
>>             return 1
>>         else:
>>             return n * fact_rec(n - 1)
>> 
>>     classvar1 = fact_iter(5)
>>     classvar2 = fact_rec(5)
>> 
>> 
>> In the initialization of classvar1, fact_iter is invoked without
>> any problem even though the class is not yet created: no need to
>> qualify it with the name of the class.  This is completely inconsistent
>> with the requirement that fact_rec be so qualified when invoked
>> within fact_rec.

>Let me take a shot at explaining this, maybe it helps that I'm mostly a C++
>guy....

Thanks for your reply.

>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.

>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.  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.)

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

kynn



More information about the Python-list mailing list