Sam The Sid
Sam The Sid

Reputation: 93

Python : Iterate a list which is shared by several method in a class

I'm using tornado.websocket, where class-methods are overrides of the WebSocketHandler methods. Anyway, my code look like that:

class SocketHandler(tornado.websocket.WebSocketHandler):
    current_ninja_pool = enumerate(return_dependency_lvl_0())
    current_ninja = next(current_ninja_pool)
    file_to_upload = []

    def check_origin(self, origin):
        return True

    def open(self):
        logging.info("A client connected.")
        self.run()

    def run(self):
        if condition:
            do_this()
    else:
        do_that()
        self.current_ninja = next(self.current_ninja_pool)
        self.run()

def on_message(self, message):
    do_a_lot_of_stuff()
    if message == 'next one':
        self.current_ninja = next(self.current_ninja_pool)

def on_close(self):
    logging.info("A client disconnected")

So, what I want is to be able to iterate my enumerate, so that every element can be processed in the methods run or on_message depending on how my client-websocket will answer. The problem is that I want to iterate under particular conditions, and I don't have a clue on how to do this. Since I'm not very familiar with the way you manipulate class- and instance-variables, I'm probably missing a point here. Thank you

Upvotes: 0

Views: 62

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

You need an iterator. Luckily, enumerate already returns an iterator; you just need to access that, rather than storing the current item.

I also suspect that current_ninja_pool should be an instance variable, not a class one (which would be shared across all instances of the class).

class SocketHandler(tornado.websocket.WebSocketHandler):
    def __init__(self, *args, **kwargs)
        self.current_ninja_pool = enumerate(return_dependency_lvl_0())
        file_to_upload = []

        def run(self):
            item = next(self.current_ninja_pool)
            do_something_with(item)

Upvotes: 1

Related Questions