0

Garbage collection not working? Data seems to persist across browser requests with Flask/Gunicorn/Python.

If I make successive requests to a webserver hosting the code below, the output grows - it starts with ["test"] and next ["test", "test"] and so on. Can anyone explain the way Python garbage collection allows this? I would expect each request to the webserver to create a new instance of class Bad and each new instance to start of with example as an empty list.

@app.route('/bad')
def bad():
    b = Bad()
    b.append("test")
    return b.output()


class Bad:
    example = []

    def append(self, data):
        self.example.append(data)

    def output(self):
        return str(self.example)

I'm new to Python coming from PHP where the behaviour would be a single item array returned for every request to the webserver. I realise I can avoid the problem by using:

def __init__(self)
    self.example = []

But I would like to properly understand what's happening.

Phil Roach
  • 55
  • 4
  • 1
    You're code adds to the class/static variable `Bad.example`, not the instance variable `self.example` (which is never defined). – c z Aug 15 '19 at 10:23

1 Answers1

1

If your code on the webserver is loaded into memory and continually running then it is not surprising that the "example" list is growing.

If you wish to start fresh then in my opinion there are several ways you can do this: 1) Make sure that whenever you make a call to webserver you run and properly quit "Bad" code. 2) If you wish to run "Bad" code continuously on the webserver then perhaps you can implement a queue like handling of "example", i.e. you not only append wanted data but also dequeue data that you've finished processing, leaving a list empty. You can achieve that in various ways, such as implementing the below methods:

example.clear()

example *= 0

del example[:]

or even more sophisticated method of using Python collections https://docs.python.org/2/library/collections.html#collections.deque, dequeuing elements.

Brozo
  • 277
  • 1
  • 9
  • Two lessons for me: 1. Class variables are static by default (a gotcha for those coming from PHP) 2. Flask/Gunicorn does not create a fresh environment for each request like apache – Phil Roach Aug 15 '19 at 14:04