Home > Net >  Importing two python modules from each other
Importing two python modules from each other

Time:07-15

I have two modules one for the Main Menu lets call it MainMenu.py and another one for the game InGame.py, there is a button in each module that when clicked should take me to the other module:

NOTE: I always run MainMenu.py first then i open InGame using the button, I just need a way to go back to MainMenu.py then again back to a new ran InGame, I tried using classes for both modules but It didnt work because i have circular dependencies between other modules and InGame.py

# MainMenu.py
if button_clicked:
    # run InGame.py

and

# InGame.py
if button_clicked:
    #run MainMenu.py

I tried directly importing each module at first which obviously didnt work, it would take me from MainMenu to InGame, back to MainMenu and stops there, pressing the button in MainMenu wont do anything.

then I tried:

# MainMenu.py
if button_clicked:
    if __name__ == "main":
        import InGame
    else:
        del InGame
        sys.modules.pop('InGame')
        import InGame

and

# InGame.py
if button_clicked:
    import MainMenu

But it also did nothing after going to MainMenu and trying to press the button to InGame, it just stops there.

I am sure this means my design is a mess but I even tried changing the whole design with no success so im looking for an easier fix.

CodePudding user response:

I believe what you are trying to do is discouraged, there are a number of alternative approaches you can take which will remove the need for such cyclic references. The first immediate idea I have to solve your problem involves using an event driven design pattern. The general concept behind it is to have the MainMenu register an event that is called by your button. Your button does not need to know who is listening to the event but the main menu can still just as easily receive the message.

EDIT: The name was eluding me whilst typing the answer, its typically called the Observer Pattern.

When you run into problems like these, it generally indicates bad design, Its good that you were able to recognise that its a bit messy. I highly suggest looking into design patterns (if you dont know them already) even if they are in languages you dont know since the concept behind them is whats important.

In your case having something which mediates the flow between the two modules is the way to go, it will act as a parent in a sense and let you go between the two children

  • Related