Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Pythonic way to share state inside one module?

Tags:

python

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?

like image 973
Cory Avatar asked May 06 '15 14:05

Cory


1 Answers

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()
like image 145
chepner Avatar answered Nov 11 '22 10:11

chepner