Is this type of forward referencing possible?

andrew cooke andrew at acooke.org
Sun Mar 15 12:33:44 CET 2009


someone else has answered this, but an extra trick that is sometimes
useful is that while there is no forward referencing you can often exploit
late binding and evaluation order.

your example will not work because code at the class level is evaluated
when the module is loaded.  but code at the method level is only evaluated
when called, so

class A:
  def __init__(self):
    self.someType = B

class B:
  anotherType = A

will work.

andrew



Kooks are people too 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.
>
> Is there any way to do this?
>
> Why I'd want to do this actually has to do with Google's datastore
> api.  I'm doing something similar to this:
>
> from google.appengine.ext import db
>
> class  A:
>     aB = db.ReferenceType(B)
>
> class B:
>     anA = db.ReferenceType(A)
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>





More information about the Python-list mailing list