UnboundLocalError: local variable 'url_request' referenced before assignment [duplicate]

Think I'm going nuts here.

url_request = 0

def somefunction():
    url_request+=1

if __name__ =='__main__':
    somefunction()

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


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

def somefunction():
    global url_request
    url_request+=1

When you assign to a variable in a local scope, it is assumed to be a local variable unless you use a global statement to tell python otherwise first.


For Python 2.7 we have to types of variables: global, local. Each function create it's own local scope for variables.

From local scope you can read without any restrictions. You can also call global object methods, so you can modify variable from global. But you can't reassign value.

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 going on? You can't reassign requests variable from local scope, so interpreter create for you other variable - in local scope for redeclare call context.

Regarding to your code... Firstly, you try to reassign variable from global scope. Why? url_request is int, int is immutable, so operation url_request+=1 doesn't change value, it should reassign new value to variable name. Secondly, you don't specify global identify for this variable. So only one option for interpreter - to assume url_request as local variable. But... You didn't declare it's value anywhere....

UnboundLocalError means that you try to perform operations with variable value without declaring it before. Hope this will help you to understand more about Python variables/names/scopes.