title: How can I avoid to use global variables? (python - flask-socketio app)
body: <p>I'm trying to figure out how to not use global variables for my application but I can't think of anything else. </p>
  
  <p>I'm actually coding a web interface with the help of the Flask-SocketIO module to interact in real time with a music player. </p>
  
  <p>This is a snippet of my code containing the play function (I think I only need one example and then I can adapt it for all the other functions): </p>
  
  <pre><code>from flask import Flask, render_template
  from flask_socketio import SocketIO
  
  app = Flask(__name__)
  socketio = SocketIO(app)
  isPlaying = False #This is the variable that I would like to avoid making global
  
  @socketio.on('request_play')
  def cycle_play():
      global isPlaying
      if isPlaying == True:
          socketio.emit('pause', broadcast=True)
          isPlaying = False
      else:
          socketio.emit('play', broadcast=True)
          isPlaying = True
  
  if __name__ == '__main__':
      socketio.run(app, port=5001)
  </code></pre>
  
  <p>This is only a stripped down version of the code but I think it's enough to understand what I'm trying to accomplish. </p>
  
  <p>I need to access that variable also from other functions and I need to do the same with the song name, duration and current time.</p>
  
  <p>Thanks in advance for the help and sorry if my English is not clear.</p>
  
  <hr>
  
  <p>Here is the solution that I used:</p>
  
  <pre><code>from flask import Flask, render_template
  from flask_socketio import SocketIO
  
  app = Flask(__name__)
  socketio = SocketIO(app)
  
  class Player():
      def __init__(self):
          self.isPlaying = False
  
  
      def cycle_play(self):
          if self.isPlaying == True:
              socketio.emit('pause', broadcast=True)
              self.isPlaying = False
          else:
              socketio.emit('play', broadcast=True)
              self.isPlaying = True
  
  
  if __name__ == '__main__':
      player = Player()
      socketio.on('request_play')(player.cycle_play) #this is the decorator
      socketio.run(app, port=5001)
  </code></pre>