Using Python 2.7.6 as provided by Ubuntu 14.04.
I have some functions that reference variables that are defined by the caller. I wanted a way to find if the caller had set the variable(s) (where if they hadn't, I'd set a default value locally), so I found this answer on StackOverflow.
The problem I'm having is that the checking of the existence of the variable makes it invisible/not-exist to the following code.
For the convenience of anyone investigating this, the code block below should be able to be cut-n-pasted directly to a file on your system for testing.
#!/usr/bin/env python
# Tested on Python 2.7.6 from Ubuntu 14.04.
def calledfunction():
print globals()
print
print locals()
print
# Try commenting the next five lines out. While they're here, the variable
# becomes invisible to the print statement below.
if not 'globalvar' in globals():
globalvar = "created within the function"
print "assigning variable locally"
else:
print "variable assigned globally"
# global globalvar
# If you uncomment the above line, the variable is visible, but Python
# prints a syntax warning.
print
print globals()
print
print locals()
print
print "the variable 'globalvar' is:", globalvar
print
# -----------------
print "calling function before the variable is defined"
print
calledfunction()
globalvar = "created outside the function"
print "calling function after the variable is defined"
print
calledfunction()
My expectation is that the 'variable' in globals() test should not be causing the variable to disappear from the visibility of the print statement following it. Am I not correct in my expectation? (Python seems to think I'm not.)