Is this type of forward referencing possible?

R. David Murray rdmurray at
Sun Mar 15 17:05:01 CET 2009

Kooks are people too <greedware at> wrote:
> If I try this:
> class  A:
>     someType = B
> class B:
>     anotherType = A
> I get:
> <type 'exceptions.NameError'>: name 'B' is not defined
>       args = ("name 'B' is not defined",)
>       message = "name 'B' is not defined"
> Presumably because I'm instantiating an instance of a type object (B)
> that doesn't exist yet.

You've gotten some answers to how to do this already, but just to be
clear, you aren't instantiating anything in the code above, not even a
type object.  someType = B is simply creating 'someType' as a name in the
'class A' namespace that references whatever it is that B references.
This doesn't work, as others have pointed out, because at the point at
which class A's namespace is being constructed, 'B' does not yet have any
value in either the local namespace of class A or the global namespace
of the module.

To figure out how to write code like this that does what you want,
you need to understand how Python namespaces work.  A search on
'python namespace' should get you good information.  I found this
one, which is a nice summary but doesn't give examples:

R. David Murray 

More information about the Python-list mailing list