Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Location for configuration in a virtualenv

Where is the common location/directory to store configuration in a python virtualenv?

For Linux there is /etc for user stuff there is XDG_CONFIG_HOME (~/.config) but for virtualenv ...?

I know that I can store my configuration in any location that I want, but maybe there is a common location, which makes my application easier to understand by python experts.

like image 597
guettli Avatar asked May 04 '16 19:05

guettli


1 Answers

So I think this is the most common approach...

1. postactivate with virtualenvwrapper

I've always done this in the postactivate file myself. In this approach, you can either define environment variables directly in that file (my preference) or in a separate file in your project dir which you source in the postactivate file. To be specific, this is actually a part of virtualenvwrapper, as opposed to virtualenv itself.

http://virtualenvwrapper.readthedocs.io/en/latest/scripts.html#postactivate

(If you want to be really clean, you can also unset your environment vars in the postdeactivate file.)

Alternatively, you can do this directly in the activate file. I find that approach less desirable because there are other things going on in there too.

https://virtualenv.pypa.io/en/latest/userguide.html#activate-script

Two popular alternatives I've also used are:

2. .env with autoenv

Independent of virtualenv, another approach towards solving the same problem is Kenneth Reitz' autoenv, which automatically sources a .env whenever you cd into the project directory. I do not use this one much anymore.

https://github.com/kennethreitz/autoenv

3. .env with Python Decouple

If you only need the environment variables for Python code (and not, for example, in a shell script inside your project) then Python Decouple is a related approach which uses a simplified .env file in the root of your project. I find myself using it more and more these days personally.

https://github.com/henriquebastos/python-decouple/


I'm somewhat surprised to see this is not discussed in detail in The Hitchhiker's Guide to Python - Virtual Environments. Perhaps we can generate a pull request about it from this question.

like image 184
Taylor D. Edmiston Avatar answered Sep 30 '22 02:09

Taylor D. Edmiston