Nested class structures

OKB (not okblacke) BrenBarn at aol.com
Fri Sep 10 21:07:26 CEST 2004


    	For a variety of reasons, I'm interested in putting together some 
code that will allow me to created structures out of nested classes, 
something like:

class class1:
    	def methA(self):
    	    	print "Some code here"
    	class class2:
    	    	propA = "A"
    	    	def methB(self):
    	    	    	print "Some more code here"
    	class class3:
    	    	# etc.
    	    	class class4:
    	    	    	pass
    	    	    	#etc

    	The main problem is that Python does not seem to provide enough 
information about the lexical context of definitions like this.  In 
particular, I would like the ability to have some of the nested classes 
be "anonymous" -- that is, I don't want to have to worry about choosing 
identifiers for them.  I'd LIKE to do this:

class class1:
    	class anon: pass
    	class anon: pass
    	class anon: pass

    	. . . and somehow intercept or monitor the name-binding that's 
going on there so I wind up with three separate classes which are bound 
to uniquely named attributes of class1.  But I can't do this because 
each anon stomps on the previous name binding, and there doesn't seem to 
be a way to intervene and bind a new attribute in class1, because class1 
isn't really created until after all the nested class definitions 
happen.

    	I've been playing around with various metaclass approaches, but I 
can't seem to get it to really work.  (In the nested class structures, 
the metaclass instantiations happen from the bottom up, and that's the 
main snag.)  Are there any hooks or hacks that would allow me to affect 
the way nested class definitions are bound to the attribute names of an 
enclosing class definition?  Or alternatively, a way to construct on the 
fly a separate list or tree that reflects the nesting structure?

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
	--author unknown



More information about the Python-list mailing list