Sep-30-2019, 10:33 AM
Actually it's a perfect example as to why using global variables should be avoided... There are problems on so many levels. You need to read about scope and namespaces.
In your
Then just for experiment, let's change your and remove a altogether:
Now just imagine what kind of nightmare you would have to debug such code.
Few more observations:
You don't need to declare them globals on line 3. You use global statement only in the narrow scope (e.g. function f1) when you will change values of global variables. If you don't declare them global and there is no local variable with same name the module level global variable will be accessible within the function, e.g.
You call your functions and assign the returned value to
You are using star import -
In your
testglobalsextimport.py
a is not defined whatsoever. b and c are defined as global variables, BUT only if you call f1(). If you don't call f1 and call just f2 they will not be defined too. functions in testglobalsextimport.py cannot know about variables in the module where they just may be imported...Then just for experiment, let's change your and remove a altogether:
def f1(x): global b,c b = "f1b" c = "f1c" print ("f1 ",b,c,x) def f2(x): global b,c print ("f2 ",b,c,x)now, if you run testglobalsextmain.py you will get
Output:main a b c ?
f1 f1b f1c a
f2 f1b f1c a
f2 f1b f1c a
end a b2 c ?
as you can see, changing b value to b2 has no effect on b variable in testglobalsextimport.pyNow just imagine what kind of nightmare you would have to debug such code.
Few more observations:
You don't need to declare them globals on line 3. You use global statement only in the narrow scope (e.g. function f1) when you will change values of global variables. If you don't declare them global and there is no local variable with same name the module level global variable will be accessible within the function, e.g.
foo = 'spam' def bar(): print(foo) bar()in the above code it will print 'spam' - global variable
foo
is accessible in the function. You call your functions and assign the returned value to
d
. That is not neccessary. Your functions do not return anything and you can just call them. At the moment the value of d
is None
because they don't return anything explicitly.You are using star import -
from testglobalsextimport import *
. Like globals this is bad practice and strongly discouraged.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs