Python Forum
Running function from parent module which has a loop in it. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Running function from parent module which has a loop in it. (/thread-22562.html)



Running function from parent module which has a loop in it. - ta2909i - Nov-17-2019

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...


RE: Running function from parent module which has a loop in it. - Gribouillis - Nov-18-2019

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()

...