Question

Reproduce with bottle app below.

I have a class with a list property. I create a new instance of this class on each request and append one element to the class' list property. Then, I print the length of the list back to the user.

Why does the count grow when visiting the page multiple times? If I set the property to an empty list in the class' init method everything is ok.

I'm running the app with gunicorn with a gevent worker proxied behind nginx

import bottle


class MyClass:
    my_list = []

    def __init__(self):
        pass

    def add_to_list(self, var):
        self.my_list.append(var)


app = bottle.app()


@app.route('/')
def index():
    var = 'test'
    my_class = MyClass()
    my_class.add_to_list(var)
    return str(len(my_class.my_list))


if __name__ == '__main__':
    app.run(host="localhost", port=80)
Was it helpful?

Solution

Class attributes are shared among all instances of a class. What you're looking for is an instance attribute:

class MyClass:
    def __init__(self):
        self.my_list = []

    def add_to_list(self, var):
        self.my_list.append(var)

See this question for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top