Python class definitions can be nested

June 25, 2010

Here is something that I was surprised to discover the other day: you can nest class definitions inside other things. In a way this is just what I should have expected given that class is an executable statement in Python, just like def is (cf), but I still found it surprising to see it actually happen.

At least in the simple case, the only thing that nesting a class inside another class does is make the first class's name harder to get to; the inner class has no special access to the outer class's namespace or the like. I tend to think that the uses for this are at best somewhat obscure, since it is not very often that you need one class to appear inside another class's namespace.

Class definitions nested inside functions are potentially more useful, because they act as closures. Both the class definition itself and its methods can access variables from the outer function, just as inner functions can. As usual, these outer function variables are read only (well, non-assignable).

(Note that as with all closures, this is a great way to accidentally leak memory by keeping objects alive when you didn't expect it.)

In both cases, you can't tell that these are nested inner classes by any straightforward inspection of the resulting class or instances. They don't have special names or any other marker, and will show up in debugging output as if they were ordinary classes defined at the module level. Given class definitions nested inside functions, this can create the amusing situation where two things that claim to be the same class in repr() output are not; each time you call the function you create a different class, although they all have the same name.

(Since class definitions are evaluated only once, a class nested inside another class does not create this situation.)

Written on 25 June 2010.
« The elements of fileserver infrastructure
The Unix system UID and login name problem »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Fri Jun 25 02:16:02 2010
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.