I need to handle signals in my code and I am using global to share state 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 global variable in this case? What is the best way to share state in this case?
You could use a class to encapsulate the module global, but whether it's worth doing depends on how much you really want to avoid the global.
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's 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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With