Need help with Python scoping rules

Carl Banks pavlovevidence at
Wed Aug 26 13:52:43 CEST 2009

On Aug 26, 3:57 am, kj <no.em... at> wrote:
> In <7figv3F2m3p0... at> "Diez B. Roggisch" <de... at> writes:
> >Classes are not scopes.
> This looks to me like a major wart, on two counts.

Class statements *are* scopes, they are just not accessible from
scopes nested within them.

> First, one of the goals of OO is encapsulation, not only at the
> level of instances, but also at the level of classes.  Your comment
> suggests that Python does not fully support class-level encapsulation.

I can't answer this, I don't even know what you are talking about.
The OO notion of encapsulation that I'm familar means that an object
can seal off access to private data.  This has nothing to do with
class statement scoping.

> Second, my example shows that Python puts some peculiar restrictions
> on recursion.  Recursion!  One of the central concepts in the theory
> of functions!  This is shown most clearly by the following elaboration
> of my original example:
> class Demo(object):
>     def fact_rec(n):
>         if n < 2:
>             return 1
>         else:
>             return n * fact_rec(n - 1)
>     def fact_iter(n):
>         ret = 1
>         for i in range(1, n + 1):
>             ret *= i
>         return ret
>     classvar1 = fact_iter(5)
>     classvar2 = fact_rec(5)
> This code won't compile as shown, but it does compile if the last
> line (the call to the recursive fact_rec) is commented out.  There
> is no justification for discriminating against recursive functions
> in this context.  Recursive functions should be OK wherever functions
> are OK.  I can't think of any other language that allows recursion
> but not anywhere.

Inside class statements are not the place for this kind of thing.
Define functions like fact_rec outside the class statement.

> Is there any good reason (from the point of view of Python's overall
> design) for not fixing this?

I suspect that no reason, however profound, would satisfy you.
Therefore I will merely answer your question without fanfare, and you
can take it as you will.

1. One of the key aspects of Python's design is that attributes must
be accessed explicitly with dot notation.  Accessing class scopes from
nested functions would (seemingly) allow access to class attributes
without the dotted notation.  Therefore it is not allowed.

2. This is considered more important that your ability to define
recursive functions in the class statement.

Carl Banks

More information about the Python-list mailing list