Search code examples
pythoncpythonpython-internals

How do PyId_ variables resolve in CPython?


I've seen usages for PyId_ variables all around the CPython source code. I couldn't trace back to the definition of any of them.

Examples include PyId___name__ and others.

Who or what resolves them into strings? I've seen a C-analyzer with known.csv file on the CPython source, listing most of them (but not all). Not sure if it's relevant.


Solution

  • As @jasonharper said, PyId_ variables are defined using _Py_IDENTIFIER, usually found at the top of the source files.

    Snippet:

    #define _Py_IDENTIFIER(varname) _Py_static_string(PyId_##varname, #varname)
    

    _Py_IDENTIFIER works using stringizing and token-parsing operators which allow you to define new variables programmatically.

    The string values are then interned for better memory efficiency.