1

Simple example of class which goes into loop

class L:
   def __init__(self):
      self.data = []
      self.current = 0
      self.loop()

   def loop(self):
      while True:
         self.data.append(self.current)
         self.current += 1
         time.sleep(2)

if __name__ == '__main__':
   obj = L()

How is it possible to access obj.current?

Is it possible to create flask app, so that the loop would go in the background, so that query /get would return the obj.current?

(For example I have this object connected to Telegram. /start starts the loop, /get should receive obj.current. /start however goes into infinite loop ... )

Nick
  • 3
  • 2
  • 1
    The `obj` name won't be valid until `L()` returns, and that never happens because `L.__init__` doesn't return until `L.loop` returns, and that's stuck in an infinite loop. I think you need to read about the `threading` module. – PM 2Ring May 20 '18 at 09:25
  • But if we remove self.loop() in __init__ and call it after L(). Will something change? – Nick May 20 '18 at 09:29
  • As suggesting PM 2Ring, you are going to need 2 threads: in one thread, you create and start the loop which will be run in background, in the other main thread, you can access to the result. – phi May 20 '18 at 09:31
  • You might find this example helpful: https://stackoverflow.com/a/48448941/4014959 And there are _lots_ of other examples on SO. I just chose that one for obvious reasons. ;) – PM 2Ring May 20 '18 at 09:35

0 Answers0