Detecting a Python virtual environment

From PEP 668 – Marking Python base environments as “externally managed”:

A “virtual environment” now has a fairly precise definition: it uses the pyvenv.cfg mechanism, which causes sys.base_prefix != sys.prefix. […] In older versions of virtualenv, the mechanism is instead to set a new attribute, sys.real_prefix, and it does not use the standard library support for virtual environments, so sys.base_prefix is the same as sys.prefix. So the logic for robustly detecting a virtual environment is something like:

def is_virtual_environment():
    return sys.base_prefix != sys.prefix or hasattr(sys, "real_prefix")