Hey. I have two Python modules:

Unloader.py

and

GetRequest.py

In a script implemented in Unloader.py, a function is called that is 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 is invisible:

NameError: global name 'countFailResponse' is not defined 

I will give an example

Unloader.py:

 global countNullResponse response, isGetData = GetRequests.Request(query) 

GetRequest.py:

 def Request(query): global countNullResponse countNullResponse += 1 

How to fix the code so that Request see the global variable countNullResponse ?

  • global does not quite work like this) is a variable declared in the module (script) at the lowest level (without indents) and global is used inside the functions in the modules so that you can assign the value of that variable, because if you do not specify global a new one will be created variable in the scope of the function. Details and more examples I think right now will tell @jfs))) - gil9red

1 answer 1

The global created to access the global variable of the module, instead of creating a local variable in a function with the same name.

Suppose we have a variable countNullResponse in our module. If we try to write inside any function countNullResponse += 1 , then we get an error like NameError , because Python will look for this variable in the local namespace, that is, in the namespace of the function. To access the 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 get countNullResponse , but you don’t 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)