UnboundLocalError: local variable 'url_request' referenced before assignment

I think I'm going down here.

url_request = 0 def somefunction(): url_request+=1 if __name__ =='__main__': somefunction() 

Gives me an UnboundLocalError. What important concept am I missing here?

+7
source share
2 answers

You assign a global variable, which means you need to mark it as global:

 def somefunction(): global url_request url_request+=1 

When you assign a variable in a local scope, it is considered a local variable unless you use the global operator to say python first.

+10
source

For Python 2.7, we have variable types: global, local. Each function creates its own local area for variables.

From the local area you can read without any restrictions. You can also call global object methods, so you can change a variable from the global. But you cannot reassign the value.

Take a look at this code:

 requests = [1,2,3] def modify(): requests.append(4) def redeclare(): requests = [10,20,30] modify() print requests # will give you [1,2,3,4] redeclare() print requests # will give you [1,2,3,4] 

What's happening? You cannot reassign the requests variable from the local scope, so the interpreter creates another variable for you - in the local scope for the context of the redeclare call.

As for your code ... First, you are trying to reassign a variable from a global scope. What for? url_request int , int unchanged, so the operation url_request+=1 does not matter change , it must reassign the new value for the variable name. Secondly, you do not specify a global identifier for this variable. Therefore, only one option for the interpreter is to consider url_request local variable. But ... You have not stated this value anywhere.

UnboundLocalError means you are trying to perform operations on a variable without declaring it before. Hope this helps you learn more about Python variables / names / areas.

+4
source

All Articles