Skip to content Skip to sidebar Skip to footer

Another Unboundlocalerror In Python2.7

When I execute a testing script in my company's Python project, I got an error as below: UnboundLocalError: local variable 'a' referenced before assignment I wrote some simpler co

Solution 1:

Assigning to a name makes the name a local variable, which means that you can't assign to a non-local variable without extra syntax. In your code:

fromvarsimport *

defmyFunc1():
    print a         # the local variable `a` is used before it is createdifFalse:
        a = '111'# this creates a local variable `a`print a

adding global a as the first line in myFunc1 will tell Python that it shouldn't create a local variable when it sees an assignment to a. It will almost certainly not do what you expect though (assuming you expect the a in vars to be changed..). from vars import * creates local "copies" of the names in vars, and using the global statement just means that you are assigning to this module's a variable. Other modules that import vars will not see the assignment.

Removing the if statements also removes the assignment, which is why that eliminates the error.

I understand that from vars import * and using variables in the vars.py is not a good design... But I can't pass all needed variables to the function since the function may use 20+ variables from the vars.py in company's project

shudder.. please refactor.

For this particular problem you should use this pattern:

importvarsdefmyFunc1():
    printvars.a
    ifFalse:
        vars.a = '111'printvars.a

Solution 2:

You should be passing the value to the function, not relying on global variables. Also if False doesn't really do anything, since it will always return True. You may have meant to say if variable:

#!/usr/bin/env pythonfromvarsimport *


defmyFunc1(x):
    print x

    if x:
        x = '111'print x

myFunc1(a)

Post a Comment for "Another Unboundlocalerror In Python2.7"