Currently EnvBuilder allows for a number of customizations of virtual
environments, changing which python is used, automatically installing
libraries, etc...  However, it does not allow for any modifications of the
activate script itself (unless one wants to rewrite it completely).
However, a fairly common requirement for python packages is to edit some
environmental variable e.g., DJANGO_SETTINGS_MODULE=<settings>.

Which leaves developers with two options set the variables globally or
manually edit the activate script.  Granted the activate script has been
fairly static for the past few years, so a patch file can be used after
manually editing once but its not the most elegant solution.  Further,
there is no guarantee that activate script will be static going forward.
In my mind there is a very simple solution, allow EnvBuilder to extend the
set of variables which are set and restored on activate / deactivate (or
more generally have activate / deactivate hooks).

In the cpython implementation of venv there is a number of template
parameters in the skeleton activate scripts which are filled by the
EnvBuilder (__VENV_DIR__, __VENV_NAME__, ...).  A simple solution would be
to extend these with __VENV_ACTIVATE_EXTRAS__ and
__VENV_DEACTIVATE_EXTRAS__ where by default
```
#Let env_vars: Dict[str, str] be the custom environmental variables
__VENV_ACTIVATE_EXTRAS__ = ''.join(f'''
_OLD_VIRTUAL_{key}="${key}"
{key}="{value}"
export {key}
''' for key,value in env_vars.items())

__VENV_DEACTIVATE_EXTRAS__ = ''.join(f'''
    if [ -n "${{_OLD_VIRTUAL_{key}:-}}" ] ; then
        {key}="${{_OLD_VIRTUAL_{key}:-}}"
        export {key}
        unset _OLD_VIRTUAL_{key}
    fi
''' for key in env_vars)
```

With __VENV_ACTIVATE_EXTRAS__ at
https://github.com/python/cpython/blob/54cf2e0780ca137dd9abea5d3d974578ce0c18a9/Lib/venv/scripts/common/activate#L46
and __VENV_DEACTIVATE_EXTRAS__ at
https://github.com/python/cpython/blob/54cf2e0780ca137dd9abea5d3d974578ce0c18a9/Lib/venv/scripts/common/activate#L16

Full activate / deactivate hooks could be achieved by setting
__VENV_*_EXTRAS__ to be arbitrary shell commands.

Caleb Donovick
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/MJNFEFT4GBVBEETJWZUQM5SS6C34PT3K/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to