1

In a view I call a method from a template like so:

{{ stakeholder.get_avg_endorsement|floatformat:1 }}

The method looks something like this:

def get_avg_endorsement(self, stakeholder_cache={}):
    if stakeholder_cache.has_key(self.id):
        print "gae cached:", stakeholder_cache[self.id], stakeholder_cache, locals()
        return stakeholder_cache[self.id]
    ...

What I would expect is for that particular call to always have an empty stakeholder_cache. However sometimes get_avg_endorsement produces a wrong value and then the print trace looks like this:

[Thu May 05 17:31:46 2016] [error] ot----- <- start of the view
[Thu May 05 17:31:47 2016] [error] gae cached: 1.33333333333 {5661L: 1.3333333333333333}
[Thu May 05 17:31:47 2016] [error] gae cached: 1.33333333333 {5661L: 1.3333333333333333}
[Thu May 05 17:31:47 2016] [error] gae cached: 1.33333333333 {5661L: 1.3333333333333333}

As you can see all of the calls to get_avg_endorsement have something in their stakeholder_cache. How is that possible when I'm calling it from the template at least once? I've used traceback and it shows at least one call from the template renderer.

I'm using an older version of Django (1.4.3). Could this be a bug in Django? get_avg_endorsement is also called from other places that does use the stakeholder_cache.

I've spent hours on this and I don't have the foggiest idea how this can happen or how to proceed. Any help would be greatly appreciated.

Rolf
  • 96
  • 1
  • 7

1 Answers1

2

Your problem lies in the parameters in your function.

def get_avg_endorsement(self, stakeholder_cache={})

This is creating problem because default parameters are always evaluated when the function is executed. For details, check:

Default Parameter Values in Python

Do this instead:

def get_avg_endorsement(self, stakeholder_cache=None):
    if stakeholder_cache is None:
        stakeholder_cache ={}
SivNiz
  • 108
  • 3
  • Thank you so much! That totally explains the race condition and your advice seems to have fixed the issue. – Rolf May 08 '16 at 15:15