globalAdvanced Examples

Declares a variable inside a function as belonging to the global scope

Global in modules and namespaces

How global interacts with the module system.

python
import sys

# globals() returns the module namespace
g = globals()
print(f"Type: {type(g)}")
print(f"__name__: {g['__name__']}")

# You can modify globals dynamically
globals()["dynamic_var"] = 42
print(f"dynamic_var = {dynamic_var}")

# Global vs module-level
def show_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 in globals().items()
                if not k.startswith("_") and k != "sys"}
print(f"User globals: {list(user_globals.keys())[:5]}...")

globals() returns the module's namespace dict. Variables declared with 'global' modify this dict. You can also add variables dynamically via globals()['name'] = value.

Want to try these examples interactively?

Open Advanced Playground