Python UnboundLocalError: local variable 'abs' referenced before assignment
In python you can see error like:
UnboundLocalError: local variable 'abs' referenced before assignment
The error is very descriptive but maybe is not obvious for beginners. In order to make it clear I'll show an example below:
def f(x, y):
sum = x + y
abs = abs(y - y)
percx = (100 * float(x)/float(y))
percy = (100 * float(y)/float(x))
return (sum, abs, percx, percy)
a = 4
b = 15
print(f(a , b))
The example above should calculate some values for two numbers and return information about them. As you can see we have variable named abs which is the same as the build-in function abs. Finally we are returning the result from the function. This will cause error:
UnboundLocalError: local variable 'abs' referenced before assignment
In order to solved it you need to change the variable name to absval(or anything else different from the method name).
Now lets see another example which is a bit similar but is working because the variable that is used is not local:
abs = abs(6 - 5)
print(abs)
So the output of this code will be 1.
In all the cases you need to be careful for variable and method names.