Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python objects, garbage collection

Tags:

python

I have a python object which collects some request data so I can create the model queries based on the filters and sorters I receive via GET method. (sort=id&order=DESC...)

class Search( object ):

    sorters = []
    filters = []

If the request has filters and sorters the class properties get filled with the right params. This works well and the queries are built ok. The problem is when I trigger a second request, sorters and filters retain the values from the previous request so the Search object is not new but persistent.

Any idea why it behaves like this? Btw I'm new to python, PHP (my area) will just instantiate a new object per request.

like image 842
Romeo M. Avatar asked Feb 24 '23 19:02

Romeo M.


2 Answers

Because you are creating class variables rather than member variables this way. Class variables are shared among every instance (they belong to the class, not an instance); they are similar to static member variables in other languages.

To create member variables, you need to initialise them in the constructor, like this:

class Search(object):
    def __init__(self):
        self.sorters = []
        self.filters = []
like image 137
Liquid_Fire Avatar answered Mar 08 '23 14:03

Liquid_Fire


If you want sorters and filters as instance members of Search, you'll need to define them as such.

class Search( object ):
    def __init__(self, sorters=None, filters=None):
        self.sorters = [] if sorters == None else sorters
        self.filters = [] if filters == None else filters

This will allow you to instantiate either by providing the sorters and filters at initialization, or by assigning them to the object later on. Or both.

like image 35
JAB Avatar answered Mar 08 '23 12:03

JAB