0

I'm working on a big python project where user input is required during runtime. The requirement for input is encapsuled in a class Decision holding some meta information. Currently the decisions are handled in their own __init__ (see below). These decisions are widely distributed over the code.

What I want to achive, is to turn the work() function into a generator which yields the decisions and they can be handled on top level (see comments).

In the example below I could easily yield the decisions from somewhere_deep_in_code to work and upwards, but this is not possible in the actual code. I although could process everything inside work in an other thread and wait for occuring decisions. But there is nothing actual async here and it seems wrong to do so. Maybe events or coroutines could do the trick, but I have no idea how. Due tue the fact this is a very special problem I did not find anything helpful in the comment sources. Therefore I would apriciate any help or ideas.

def handle_decision(decision):
    decision.value = 42

class Decision:
    def __init__(self, questions):
        self.questions = questions
        self.value = None
        handle_decision(self)  # this should go to top level

def somewhere_deep_in_code():
    decision = Decision("item1")
    # do sth with decision.value
    print(decision.value)
    somewhere_even_deeper_in_code()

def somewhere_even_deeper_in_code():
    decision = Decision("item2")
    # do sth with decision.value
    print(decision.value)

def work():
    somewhere_deep_in_code()

def main():
    # current implementation
    work()
    
    # how it should be
    for decision in work():
        handle_decision(decision)

if __name__ == '__main__':
    main()

1 Answers1

0

Once you request a decision do you want to wait for one or rather proceed with other tasks? This article lists quite recent list of event systems available in Python: Event system in Python. GUI frameworks like Kivy are handling user interactions like events. Perhaps you can look at one for inspiration?

Jacek Błocki
  • 452
  • 3
  • 9
  • the decision.value needs to be set properly before continuing. As I said: nothing async here. I've read the linked question before. I just dont know how to use events to do what i want (or if its even possible). And thanks for the Kivy hint! We already have a GUI but it looks like a great alternative. – christian.w Feb 23 '21 at 11:58