internal circular class references

Terry Reedy tjreedy at udel.edu
Thu Dec 11 03:59:07 CET 2008


James Stroud wrote:

> I resisted posting a similar question recently. After much 
> consideration, I realized that the inability to reference a class inside 
> its own definition must have been a deliberate design of the language. 

The class *does not exist* to be referenced from inside its body until 
after the body is executed and type(name, bases, namespace) is called.

class name(bases): body

is more or less equivalent to

name = type('name', bases, exec(body,{}))

except that the exec function (in 3.0) returns None instead of the 
passed in namespace.

I think is would be possible to create and name-bind a blank class 
first, but then there would need to be a mechanism delete the class if 
the body execution failed.  Because class definition can be nested, the 
mechanism would need a stack of classes.  In addition, this would be a 
change in sequence from the usual assignment statement.

tjr




More information about the Python-list mailing list