| 1 |
####################################### |
| 2 |
# C Globals and CPython Runtime State. |
| 3 |
|
| 4 |
CPython's C code makes extensive use of global variables. Each global |
| 5 |
falls into one of several categories: |
| 6 |
|
| 7 |
* (effectively) constants (incl. static types) |
| 8 |
* globals used exclusively in main or in the REPL |
| 9 |
* freelists, caches, and counters |
| 10 |
* process-global state |
| 11 |
* module state |
| 12 |
* Python runtime state |
| 13 |
|
| 14 |
Of the different categories, the last two are problematic and |
| 15 |
generally should not exist in the codebase. |
| 16 |
|
| 17 |
Globals that hold module state (i.e. in Modules/*.c) cause problems |
| 18 |
when multiple interpreters are in use. For more info, see PEP 3121, |
| 19 |
which addresses the situation for extension modules in general. |
| 20 |
|
| 21 |
Globals in the last category should be avoided as well. The problem |
| 22 |
isn't with the Python runtime having state. Rather, the problem is with |
| 23 |
that state being spread throughout the codebase in dozens of individual |
| 24 |
globals. Unlike the other globals, the runtime state represents a set |
| 25 |
of values that are constantly shifting in a complex way. When they are |
| 26 |
spread out it's harder to get a clear picture of what the runtime |
| 27 |
involves. Furthermore, when they are spread out it complicates efforts |
| 28 |
that change the runtime. |
| 29 |
|
| 30 |
Consequently, the globals for Python's runtime state have been |
| 31 |
consolidated under a single top-level _PyRuntime global. No new globals |
| 32 |
should be added for runtime state. Instead, they should be added to |
| 33 |
_PyRuntimeState or one of its sub-structs. The check-c-globals script |
| 34 |
should be run to ensure that no new globals have been added: |
| 35 |
|
| 36 |
python3 Tools/c-analyzer/check-c-globals.py |
| 37 |
|
| 38 |
You can also use the more generic tool: |
| 39 |
|
| 40 |
python3 Tools/c-analyzer/c-analyzer.py |
| 41 |
|
| 42 |
If it reports any globals then they should be resolved. If the globals |
| 43 |
are runtime state then they should be folded into _PyRuntimeState. |