Importing Two Files into eachother in python

Viewed 29

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?

1 Answers

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.

Related