globalExpert Examples

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

Global bytecode: LOAD_GLOBAL vs LOAD_FAST

How global changes variable access at the bytecode level.

python
import dis

x = 10

def without_global():
    y = x + 1  # LOAD_GLOBAL for x
    return y

def with_global():
    global x
    x = x + 1  # LOAD_GLOBAL + STORE_GLOBAL
    return x

def with_local():
    x = 20     # STORE_FAST (local)
    return x   # LOAD_FAST (local)

print("Reading global (no declaration needed):")
dis.dis(without_global)
print("\nWriting global (needs 'global'):")
dis.dis(with_global)
print("\nLocal variable:")
dis.dis(with_local)

Global reads use LOAD_GLOBAL, global writes use STORE_GLOBAL. Local variables use LOAD_FAST/STORE_FAST which are faster because they use indexed array access instead of dict lookup.

Want to try these examples interactively?

Open Expert Playground