Variable scope inside and outside functions - global statement being overridden by assignation unless preceded by reference

Roel Schroeven roel at roelschroeven.net
Wed Mar 6 12:33:17 EST 2024


Op 6/03/2024 om 17:40 schreef Jacob Kruger via Python-list:
> >>> from scoping2 import *
Ah yes, that explains what's happening. After that statement, the name 
dt_expiry in the current namespace is bound to the same object that the 
name dt_expiry in the namespace of module scoping2 is bound to. Function 
do_it re-binds that last one to a new one, with the new value; name 
dt_expiry in the current namespace is still bound to the old object. (If 
all of that sounds like gibberish, have a look at "Facts and myths about 
Python names and values" (text: 
https://nedbatchelder.com/text/names.html; slides and video: 
https://nedbatchelder.com/text/names1.html)

I would advice not to use 'import *', if at all possible, for multiple 
reasons, one of which is to prevent problems like this.

I would also advice not to use global variables from other modules 
directly, and in fact would advice to minimize the use of globals in 
general as much as possible. If you need to keep state between methods, 
it might be better to use a class.

-- 
"There is a theory which states that if ever anyone discovers exactly what the
Universe is for and why it is here, it will instantly disappear and be
replaced by something even more bizarre and inexplicable.
There is another theory which states that this has already happened."
         -- Douglas Adams, The Restaurant at the End of the Universe



More information about the Python-list mailing list