Implementation of Global variables vs Dereferenced variables
closures, global-variables, python
Solution
Local and closed-over names are enumerated during compilation. At runtime, they're stored in C arrays and accessed using integers/indices. `LOAD_FAST` and `LOAD_DEREF` take a C integer and perform a C array lookup.
Global names cannot be enumerated at compile time, they can be added and removed during run time by any code in the whole process. This is similar to object attributes - because globals essentially are a module object's attributes. Therefore, they are stored in a dictionary and the implementation accesses them quite differently from local and closed-over names. `LOAD_GLOBAL` takes a string (constant) and performs a dictionary lookup.
Problem
Functions declared at module level never have a closure and access non-local variables via `LOAD_GLOBAL`. Functions declared not at module level may have a closure and access non-local, variables via `LOAD_DEREF` if those variables are not global. So basically we have three ways of storing and loading variables `GLOBAL` (global), `FAST` (local) and `DEREF` (non-local, enclosed, covered). Why the `GLOBAL`? Wouldn't `FAST` and `DEREF` suffice, if you let all functions have their closures? Is there some important difference between a non-local variable and global variable I fail to spot? Is this maybe due to performance issues, as perhaps global variables (like all functions and classes (including their methods) defined at module level plus the builtins) are generally more common than non-local variables?