Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, is it possible to access the global namespace from within a function

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.

like image 824
BrianHVB Avatar asked Feb 02 '16 20:02

BrianHVB


People also ask

Can global variables be accessed inside functions?

Global variables can be used by everyone, both inside of functions and outside.

Can you call a global variable in a function Python?

We Use a global keyword to use a global variable inside a function. There is no need to use global keywords outside a function.

How do you access global list in Python?

Or use globlist[:] = list and drop the global keyword.


1 Answers

try globals():

x = 'global scope'      # global
def func():
    x = 'local scope'   # global x is now shadowed
    print(globals()['x'])     # is this somehow possible?


func()
like image 124
MaxU - stop WAR against UA Avatar answered Feb 01 '23 09:02

MaxU - stop WAR against UA