Search code examples
pythonwindows-10pipenv

Cannot define empty environment variable with Pipenv .env file in Windows 10


I am new to Pipenv. I want to be able to assign an empty value to environment variables with .env file.

Here is my .env.

FOO=abc
BAR=

I activated the virtual environment with pipenv shell and expected variable BAR to be an empty string, but it was not defined at all.

> python -c "import os; print(repr(os.environ.get('FOO', 'Not defined')))"
'abc'
> python -c "import os; print(repr(os.environ.get('BAR', 'Not defined')))"
'Not defined'
  • OS: Windows 10
  • Python 3.9.2
  • Pipenv 2020.11.15

However, when I did the same in WSL2 Ubuntu with the same Pipenv version, BAR was defined with an empty string as expected.

$ python -c "import os; print(repr(os.environ.get('BAR', 'Not defined')))"
''

Could anyone give any suggestion?


Solution

  • SET BAR=
    

    in Windows batch is used to unset the variable instead of setting it to an empty value.

    So .env implementation in pipenv is basically setting any value to any variable defined in the file. There is probably no simple way to define a variable with an empty value in Windows Batch.

    Try to modify your script to use some kind of boolean value (0/1, on/off, true/false, …) if you need a boolean, or use a sensible value when either not defined or empty.

    from os import getenv
    
    var_x = getenv('BAR', '') or 'default_value'
    
    var_bool = getenv('BAZ', '0').strip() == '1'