Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: accept None to 'set_key' to write value-less environment variable #454

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

bricker
Copy link

@bricker bricker commented Mar 19, 2023

Changes the signature of set_key in the following ways:

  1. value_to_set: str to Optional[str]
  2. return: Tuple[Optional[bool], str, str] to Tuple[Optional[bool], str, Optional[str]]

The purpose of this change is to allow a program to pass in None to the value_to_set parameter, and therefore write the key to the dotenv file without a value. For example:

set_key(".env", "APP_ENVIRONMENT", None)

load_dotenv()

APP_ENVIRONMENT = os.getenv("APP_ENVIRONMENT", "development")

assert APP_ENVIRONMENT == "development"

The resulting .env file:

APP_ENVIRONMENT

The use-case is pretty specific, but I think valuable: I'm writing a Python script to parse a file to find environment variables being used, and then writing those to a gitignored .env file, so that running the script creates a .env file with stubbed values. By allowing None, any defaults defined in the config file will be used. In contrast, if the script wrote empty strings or mock values, the defaults would not be used.

Here's an example for illustration:

APP_ENVIRONMENT = os.getenv("APP_ENVIRONMENT", "development") # Optional
DATABASE_DRIVER = os.getenv("DATABASE_DRIVER", "postgresql+asyncpg") # Optional
DATABASE_USERNAME = os.getenv("DATABASE_USERNAME") # Required
DATABASE_PASSWORD = os.getenv("DATABASE_PASSWORD") # Required

After running the Python script to parse this file, the resulting .env file should contain something like:

APP_ENVIRONMENT
DATABASE_DRIVER
DATABASE_USERNAME="fill me in"
DATABASE_PASSWORD="fill me in"

Note: This is technically a breaking change
(the change to the return value of set_key is not backward-compatible). If this is a problem, we can instead return empty string in the case where None is passed for value_to_set.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant