Python Forum

Full Version: Running function from parent module which has a loop in it.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I have a parent module that imports various other modules and runs a “While True” loop within it.

I’m essentially building a spotify radio clock with the Parent module and a UI module that gets commands depending on input on the interface.
- The parent calls a UI.window.update() to refresh the TKinter.

Currently I am using a messy setup where the parent module checks whether a variable is “None” otherwise executes a command based on whatever string that “None” is replaced with.

A more optimal solution would be for the UI class to be able to run a function in the parent. Lets say for example “play music”.

What is the best way for two modules to work but with one slave child module to have the ability to run functions in the master function?

If I use a double import then things get messy with circular referencing etc...
ta2909i Wrote:What is the best way for two modules to work but with one slave child module to have the ability to run functions in the master function?
I think a simple way is to use classes and pass class instances as object parameters, for example
# parent.py
import uipart

class MusicPlayer:
    def play_music(self):
        ...

if __name__ == '__main__':
    player = MusicPlayer()
    ui = uipart.Ui(player)
    while True:
        ...
# uipart.py

class Ui:
    def __init__(self, player):
        self.player = player

    def spam(self):
        # call the parent's callback as a player instance's method
        self.player.play_music()

...