-1

I'm writing a small app in Django and I'm keeping the state saved in a few variables I declare out of the methods in views.py. Here is the important part of this file:

from app.playerlist import fullList
auc_unsold = fullList[:]
auc_teams = []
auc_in_progress = []
auc_current_turn = -1
print(auc_in_progress)

def auc_action(request):
    data = json.loads(request.GET["data"])

    # ...

    elif data[0] == "start":
        random.shuffle(auc_teams)
        print(auc_unsold)
        print(auc_in_progress)
        auc_in_progress = [None, 0, None]
        print(auc_in_progress)

The auc_unsold and auc_teams variables work fine; the auc_in_progress variable is not seen by this method, though, giving the error in the title. If I take out the print statement and let this code assign a value to it, the exception will be thrown somewhere else in the code as soon as I use that variable again.

I have tried making another variable and this new one seems to suffer from this problem as well.

What is happening?


Edit: I found a solution: if I write global auc_in_progress just before the print statements, then everything works fine. If I try writing that as I declare the variable above it doesn't work, though, for some reason.

I am unsatisfied with this, because I don't know why this happens and because I dislike using global like that, but eh. Someone has an explanation?

user1846231
  • 315
  • 3
  • 12

1 Answers1

1

You should absolutely not be doing this, either your original code or your proposed solution with global.

Anything at module level will be shared across requests, not only for the current user but for all users for that process. So everyone will see the same auction, etc.

The reason for your error is because you assign to that variable within your function, which automatically makes it a local variable: see this question for more details. But the solution recommended there, which is the same as your workaround - ie use global - is not appropriate here; you should store the data somewhere specifically associated with the user, eg the session.

Community
  • 1
  • 1
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Well but the whole point is to let more people participate in the same auction... I agree that it looks ugly and I don't know the "correct" way, it probably involves databases and something more structured? However, this is just a simple app I'm making for me and a few friends, so quick and dirty works for me, especially because I'm on a deadline. – user1846231 Aug 25 '16 at 16:13