0

I've got a weird behaviour when I raise an exception inside my Django application. Please loot at this snippet (I removed all the unnecessary code):

@csrf_exempt
def main(request):

  ems_db = EmsDatabase()
  # raise AssertionError

  return HttpResponse('OK\n', content_type='text/plain')

this is the EmsDatabase class:

class EmsDatabase:

    def __init__(self):
        pass

    def __del__(self):
        print('>>>>>>>>>>>>>>>> DEL')

running this function (obviously through a proper http call) the EmsDatabase class is instantiated e properly garbage-collected; I see the print output in the Django server log.

But if I uncomment the raise AssertionError line I got no print output and the object is still alive; just modifying a source file to trigger the server reload makes the object to lose the reference to itself and be garbage-collected (the print line appears).

The same thing happens running Django through Lighttpd + Gunicorn.

Why is Django (v2.0.7, python 3.6, Linux) keeping a reference to my object or, more likely, to the frame of the main() function? What can I do?

user6369958
  • 357
  • 3
  • 16
  • That makes sense. Objects are not per se removed immediately: if no element references to the object anymore it is a *candidate* for removal. But some systems for example wait until the amount of memory should be increased (asking the OS for a new memory "page") and thus first aim to throw away objects in an attempt to prevent that. – Willem Van Onsem Aug 03 '18 at 12:06
  • This might help: https://stackoverflow.com/questions/14969739/python-del-statement – user2390182 Aug 03 '18 at 12:07
  • The CPython standard interpreter frees objects as soon as their reference count goes to zero, as correctly stated in the schwobaseggl's link. There's no delayed garbage collection.I'm pretty sure here is Django is keeping (useless?) references when the function is interrupted by an exception. – user6369958 Aug 03 '18 at 12:59

0 Answers0