import sys
# globals() returns the module namespace
g = globals()
print(f"Type: {type(g)}")
print(f"__name__: {g['__name__']}")
# You can modify globals dynamicallyglobals()["dynamic_var"] = 42print(f"dynamic_var = {dynamic_var}")
# Global vs module-leveldefshow_globals():
global new_var
new_var = "created by function"
show_globals()
print(f"new_var = {new_var}")
# List all user-defined globals
user_globals = {k: v for k, v inglobals().items()
ifnot k.startswith("_") and k != "sys"}
print(f"User globals: {list(user_globals.keys())[:5]}...")
Output
Click "Run" to execute your code
globals() returns the module's namespace dict. Variables declared with 'global' modify this dict. You can also add variables dynamically via globals()['name'] = value.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?