I have two packages:
Unloader.py
and
GetRequest.py
In the script implemented in Unloader.py, the function is called, which is located in GetRequest.py. In addition, a global variable is declared in Unloader.py, which is used in the above function from GetRequest.py. But for some reason this global variable turns out to be invisible:
NameError: global name 'countFailResponse' is not defined
Here’s an example
Unloader.py:
global countNullResponse
response, isGetData = GetRequests.Request (query)
GetRequest.py:
def Request (query):
global countNullResponse
countNullResponse + = 1
How can I fix the code so that Request
sees the global variable countNullResponse
?
Answer 1
The global
keyword is designed to refer to a module’s global variable, rather than creating a local variable in a function of the same name.
Suppose we have a countNullResponse
variable in our module. If we try to write countNullResponse + = 1
inside any function, then we get an error like NameError
, because Python will look for this variable in the local namespace, that is, in the namespace functions. To refer to a global variable and the global
keyword was created:
countNullResponse = 0
def Request (query):
global countNullResponse
countNullResponse + = 1
return countNullResponse, True
response, isGetData = Request ('some url')
print (response, isGetData)
If you want to receive countNullResponse
, but do not want to store everything in one module, then I suggest you move this variable to another module.
That is, your GetResponse
might look like this:
countNullResponse = 0
def Request (query):
global countNullResponse
result = Connect (query)
countNullResponse + = 1
return countNullResponse, result
And the Unlodaer
module is like this:
from GetResponse import *
response, isGetData = Request (query)