What is the Pythonic way to share state inside a single module?

I need to process signals in my code, and I use global to share states between functions:

exit = False def setup_handler(): signal.signal(signal.SIGTERM, handler) def handler(num, frame): global exit exit = True def my_main(): global exit while not exit: do_something() if __name__ == '__main__': setup_handler() my_main() 

Is there a way to avoid a global variable in this case? What is the best way to share state in this case?

+5
source share
1 answer

You can use the class to encapsulate the global module, but whether it is worth doing depends on how much you really want to avoid the global one.

 class EventLoop(object): def __init__(self): self.exit = False def run(self): while not self.exit: do_something() def handler(self): self.exit = True # It up to you if you want an EventLoop instance # as an argument, or just a reference to the instance's # handler method. def setup_handler(event_loop): signal.signal(signal.SIGTERM, event_loop.handler) if __name__ == '__main__': loop = EventLoop() setup_handler(loop) loop.run() 
+6
source

All Articles