Search code examples
pythonpipcommand-line-interfacesetuptoolsmonkeypatching

How to monkey patch the "python --version" command?


The -v/--version flag is used to print out the version of the respective python interpreter.

For example, if python is aliased to the Python 3.7.9 interpreter, the flag would print out the following:

$ python --version
Python3.7.9

Can one create a Python module which on installation monkey patches this command for the user? Caveat is that this needs to be cross-platform. How would one about doing so?

For example, say I have my-package uploaded on PyPI. If I installed it, it would modify the behaviour of pyhton -v/python --version.

$ python --version
Python3.7.9
$ pip install my-package
...
$ python --version
<some custom text>

Preferably on uninstallation, the -v/--version goes back to normal.


Solution

  • We can review the code that parses the command-line arguments (in this example , for CPython) which is on initconfig.c line 1900.

    If the --version or -V flags are provided then print_version becomes non-zero which triggers the condition on line 2051:

    if (print_version) {
        printf("Python %s\n",
                (print_version >= 2) ? Py_GetVersion() : PY_VERSION);
        return _PyStatus_EXIT(0);
    }
    

    So, the said module would need to somehow modify the value of PY_VERSION or the output of Py_GetVersion().

    Changing PY_VERSION is impossible since it is hard-coded in patchlevel.h.

    Modifying the output of Py_GetVersion() is also impossible since it uses PY_VERSION.

    So it appears that the answer is no, this is not possible without recompiling the entire interpreter.