'Python "if" statement appears to allow namespaces to be defined even if the statement is bypassed
I have a script (delete.py) that calls an API to delete an object. And I have a script (remote.py) that calls the delObj() function in delete.py to delete an object. The function in delete.py (delObj()) doesn't need any arguments when it runs as main, but when it is called by remote.py it needs arguments. So (part of) the script looks like:
def delObj(*args):
if __name__ != "__main__":
var0 = args[0]
var1 = args[1]
.
.
.
if __name__ == "__main__":
var0 = "name of item to delete"
var1 = "ID of item to delete"
delObj()
The code above works as expected when called by remote.py. But when I run delete.py -- which fails the "name doesn't equal main" statement, the script fails saying:
UnboundLocalError: local variable 'var0' referenced before assignment
If I change the if statement to:
def delObj(*args):
if args != '':
var0 = args[0]
var1 = args[1]
I get an error message:
var0 = args[0]
IndexError: tuple index out of range
To fix either error I can place a "global var0, var1" statement above the "if" block.
So that sounds to me like the "var0, var0" names are actually created in function local namespace regardless of whether the "if" statement is true or false. So I have to declare a global variable in order to change the values for var0 and var1, either from NULL if no arguments are passed or to the values that are passed from the opening of the script.
Does that sound right? Thanks, Steve
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
