Qohelet
Qohelet

Reputation: 1616

What is the scope of global variables in the views.py?

If I declare a global variable myglobalvar in my views.py

myglobalvar = "value"

def home(request):
    print(myglobalvar)

def thatOneLink(request):
    myglobalvar = "different value"

When someone calls thatOneLink what is the scope of the change? Will myglobalvar = "different value" only for this request? Or only for the session? Or until the server restarts?

In JSP by default there were settings on the scope. Django seems to have another package for that: https://pypi.org/project/django-scopes/ But in the very default case without any additional packages, how does Django handle scopes? Or do they have different names or definitions?

Upvotes: 0

Views: 484

Answers (1)

Nafees Anwar
Nafees Anwar

Reputation: 6608

Python as a language has the concept of scoping and global variables. The same applies here regardless of Django. See this example

x = 10

def first():
    x = 20
    print(x)

def second():
    global x
    print(x)
    x = 30
    print(x)

def third():
    print(x)


first()
second()
third()

Output

20
10
30
30

In the first function x is redeclared with a new value and has no effect on the outer value. The function second prints the x just to verify that and then makes x global using the global keyword. Now, x is reinitialized in the outer scope, and function third confirms that.

In particular to your scenario, myglobalvar will only change for that particular request and the outer scope value will remain unchanged. However, if you use the global keyword.

global myglobalvar
myglobalvar = "different value"

inside thatOneLink, the value of myglobalvar will change for all the requests served by that process (even for all threads in that process) until you restart the process.

Upvotes: 2

Related Questions