0

I am making a text game in Python and I have two menus, the main menu and the attack menu. These functions are in two different files.

When I from attack import * in my main file to get the attack menu function it works and I can call the attack_menu() function.

However, when I go to my attack file and I from main import * and then try to call main_menu(), it doesn't work. Is there a way to import both the files into each other and not get an error?

2
  • What if you then want to use your attack menu in another game that doesn't use the same main menu? Why not have a main "loop" for your game play in another module that imports attack_menu and main_menu separately?
    – jonsca
    Commented Jun 19, 2022 at 1:37
  • I assume there is a main.py and attack.py in the same directory - and you run main.py as a script, something like python3 main.py?
    – tdelaney
    Commented Jun 19, 2022 at 1:56

1 Answer 1

2

Circular imports don't work, as you've found out. But there is a second problem lurking. Assuming you run main.py as a script, its a module named __main__, not main. When attack imports main, it gets a second copy of main. main imports attack again, and you've got your circular reference.

The solution is to take all of the stuff that attack wants from main and move it into a separate .py file. Lets call it commonstuff.py. Now attack imports commonstuff and main.py imports both of the modules and the import works.

main.py is the script and attack and commonstuff are modules.