Nested inner classes and inheritance -> namespace problem

Jean-Michel Pichavant jeanmichel at
Wed Apr 13 06:08:21 EDT 2011

Larry Hastings wrote:
> 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:
>           pass
>       class InnerSubclass(Inner):
>         class Worker(Inner.Worker):
>           pass
> 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?
> Thanks,
> /larry/
class Outer:
  class Inner:
    class Worker:

  print 'Outer ', locals()
  class InnerSubclass(Inner):
    print 'InnerSubclass', locals()
    class Worker:

Outer  {'__module__': '__main__', 'Inner': <class __main__.Inner at 
InnerSubclass {'__module__': '__main__'}

I use myself nested classes a lot, but only as namespace / enum, meaning 
there is no inheritance involved. I don't think that you can do what you 
are trying to do.
Outer would actually be a module, not a class.


More information about the Python-list mailing list