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