byomtov
byomtov

Reputation: 21

Don't understand undefined reference

My understanding is that if I use a variable in a function without an assignment statement in the function, it will look "outside" the function for the variable.

This seems to be the case with a list, but not a simple variable.

In the following code I am told that the statement "aa += 1 contains an unresolved reference "aa", but the reference to bb[0] is just fine. Why is that?

aa = 0
bb = [9, 7]

def bbtest():
    aa += 1
    bb[0] += 1

Upvotes: 2

Views: 175

Answers (2)

KobiM1
KobiM1

Reputation: 81

That's because in python you can only access the global variables, but cannot modify them inside the functions. You can change the bb[0] value because of its something inside a global variable and not the var itself. Anyway, if you want it to work try to declare "global" in your function like this:

aa = 0
bb = [9, 7]

def bbtest():
    global aa
    aa += 1
    bb[0] += 1

Upvotes: 2

L3viathan
L3viathan

Reputation: 27283

This is a bit obscure, but there is a reason for this: When compiling a function, Python looks at all names used there and determines what scope they come from. Names that are not assigned to will use an outer scope (global or nonlocal), names that are assigned to are local. Since aa += 1 counts as an assignment, it marks aa as a local variable.

While the next line looks similar, it is doing something different: Nowhere do you assign something to the name bb. You are retrieving something from the nonlocal/global name (the list), and are then assigning to an element of it.

You can fix this by explicitly marking aa as nonlocal or global:

def bbtest():
    global aa
    aa += 1
    bb[0] += 1

On the other hand, you can make the bb case fail by assigning to the name, even afterwards:

def bbtest():
    bb[0] += 1
    bb = "foo"

Upvotes: 4

Related Questions