Avoiding circular imports in two forms referencing each other

I have a master form with a navigation column. Within the content_panel, I have subforms (opened through add_component) that should link to each other:

Form A

from B import B
def btn_other_form_click(self):
     get_open_form().content_panel.clear()
     get_open_form().content_panel.add_component(B())

Form B

from A import A
def btn_other_form_click(self):
     get_open_form().content_panel.clear()
     get_open_form().content_panel.add_component(A())

This creates a circular reference, and I haven’t found out a way to avoid it. I thought of having a global module, with references to all forms, and then reference them by name, rather than the forms themselves, using a dict. This does not, however, solve the circular reference problem, as I will have to import the globals module in order to use them.

Globals

from A import A
from B import B
forms = {'A': A, 'B':B}

How do I solve this?

Welcome to Anvil.

I have a client side module called routing, with functions like :

def show_main():
  from main import main
  get_open_form().content_panel.add_component(main())

It’s a bit more complex than that, but broadly speaking that works.

Wherever you are likely to swap forms, just do :

import routing
...
routing.show_main()
4 Likes

Thank you so much!

I did, however, have to import the “get_open_form” function from anvil, as I previously got a NameError calling it from the routing module. Is this something you recongnize?

Sorry, I typed that from memory which at my age is a bad idea!

This is how I actually call it from the routing module :

anvil.get_open_form()....