Three ways to access the __main__ namespace

When run in a script, the x, y, and z below all point to the same dict object.

test_globals.py


import sys

x = globals()

y = sys.modules["__main__"].__dict__

def foo():
    print("foo.")

z = foo.__globals__

To check, run python -i test_globals.py and run the following in the interpreter.

python


>>> x is y is z
True
>>> [id(w) for w in (x, y, z)]
[10317376, 10317376, 10317376]

Recommended Posts

Three ways to access the __main__ namespace
How to access the Datastore from the outside
3 best ways to use the less command
How to access the global variable of the imported module
The road to Pythonista
The road to Djangoist
Access to dictionary fields
Various ways to calculate the similarity between data in python
I tried to output the access log to the server using Node.js