environs icon indicating copy to clipboard operation
environs copied to clipboard

Add support for reading .env without altering os.environ

Open sloria opened this issue 11 months ago • 5 comments

should be possible using https://github.com/theskumar/python-dotenv?tab=readme-ov-file#load-configuration-without-altering-the-environment

sloria avatar Jan 13 '25 20:01 sloria

Um, isn't this the default behavior? env.read_env() doesn't mutate os.environ does it?

mecampbellsoup avatar Jun 04 '25 22:06 mecampbellsoup

env.read_env calls doteenv.load_dotenv(), which mutates os.environ: https://github.com/theskumar/python-dotenv/blob/8411987b9301f716245074872afa30646e9b9eb7/src/dotenv/main.py#L89-L102

sloria avatar Jun 06 '25 00:06 sloria

Sorry I got confused having initially set up our app to use django-environ (before later switching to use environs) which AFAICT behaves differently, but might also be wrong about that... https://django-environ.readthedocs.io/en/latest/faq.html#:~:text=Why%20is%20it%20not%20overriding%20existing%20environment%20variables%3F

mecampbellsoup avatar Jun 11 '25 17:06 mecampbellsoup

django-environ appears to also mutate os.environ in the same way: https://github.com/joke2k/django-environ/blob/176e812d8624f6937ba3dd276a0032929d87eb69/environ/environ.py#L1021-L1033

sloria avatar Jun 11 '25 17:06 sloria

Yes, and the os.environ mutation probably causes issues like https://github.com/joke2k/django-environ/issues/523 (values added to os.environ persist over reloads if the reload implementation reuses existing worker processes).

In the django-environ case it's reasonably easy to replace the default ENVIRON = os.environ with something else (e.g., ChainMap({}, os.environ)) as a workaround (https://github.com/joke2k/django-environ/issues/523#issuecomment-3410910229); but environs would need more extensive changes.

sigprof avatar Oct 19 '25 18:10 sigprof