Nested inner classes and inheritance -> namespace problem

Larry Hastings larry at
Wed Apr 13 11:12:30 CEST 2011

The problem: if you're currently in a nested class, you can't look up 
variables in the outer "class scope".

For example, this code fails in Python 3:

    class Outer:
       class Inner:
         class Worker:

       class InnerSubclass(Inner):
         class Worker(Inner.Worker):

It fails at the definition of Worker inside InnerSubclass.  Python 3 
can't find "Inner", in order to get to "Inner.Worker".

Adding "global Inner" just above that line doesn't help--it's not a global.
Adding "nonlocal Inner" just above that line doesn't help either--I 
suppose it's the /wrong kind/ of nonlocal.  nonlocal is for nested 
functions, and this uses nested classes.

You can tell me YAGNI, but I tripped over this because I wanted it.  
It's not a contrived example.  I actually use inner classes a lot; I 
suppose I'm relatively alone in doing so.

Yes, I could make the problem go away if I didn't have nested inner 
classes like this.  But I like this structure.  Any idea how I can make 
it work while preserving the nesting and inheritance?


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list