I'm learning Python coming from a good background with other languages. My question is mostly academic, as I know that what I'm asking is seldom needed and is definitely not a good programming practice.
Here is what I'm asking:
x = 'global scope' # global
def func():
x = 'local scope' # global x is now shadowed
print(global x) # is this somehow possible?
Attempt #1
def attempt1():
x = 'local scope' # shadowded
global x
print(x) # error
This results in an error: name 'x' is assigned to before global declaration.
Attempt #2
def attempt2():
x = 'local scope' # shadowded
print(__main__.x) # error: __main__ not defined
The Python documentation on namespaces states suggest that #2 (or something like it) should be possible. See Python Tutorial 9.2
"The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively, are considered part of a module called __main__, so they have their own global namespace."
However attempting to access __main__
from either a script or the console results in an error. Also, the global attribute __name__
refers to the outermost module as __builtins__
, but this only contains the built-in variables, not any user defined global ones. If the variable were delcared in an outside module, one that had been imported, it could be accessed with __module_name__.variable
.
Global variables can be used by everyone, both inside of functions and outside.
We Use a global keyword to use a global variable inside a function. There is no need to use global keywords outside a function.
Or use globlist[:] = list and drop the global keyword.
try globals():
x = 'global scope' # global
def func():
x = 'local scope' # global x is now shadowed
print(globals()['x']) # is this somehow possible?
func()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With