Search code examples
pythonpython-3.xpeewee

How to reference another nested class from within nested class


I have the following nested structure:

from peewee import *

class Parent:
    ...
    class A:
        name = TextField()

    class B:
        from_A = ForeignKeyField(A)

I am trying to reference class A within a ForeignKeyField within class B, but both A and Parent.A return a name not found error. What is the proper way to reference class A from within class B? Is this possible?


Solution

  • At the time of definition of class B, class Parent is not fully defined so it cannot be used: at definition time, you can only use:

    • global variables
    • variables belonging to the element being defined

    But you have no access to variables defined in an enclosing block be them classes or not.

    So you are left with only two options:

    • define class B outside of Parent
    • initialize the element at run time after everything has been defined (in that sense, run time starts immediately the end of the class Parent block`):

      class Parent:
          ...
          class A:
              name = TextField()
      
          class B:
               ...
      
      Parent.B.from_A = ForeignKeyField(Parent.A)