MCPcopy Create free account
hub / github.com/theskumar/python-dotenv / set_key

Function set_key

src/dotenv/main.py:147–193  ·  view source on GitHub ↗

Adds or Updates a key/value to the given .env If the .env path given doesn't exist, fails instead of risking creating an orphan .env somewhere in the filesystem

(
    dotenv_path: StrPath,
    key_to_set: str,
    value_to_set: str,
    quote_mode: str = "always",
    export: bool = False,
    encoding: Optional[str] = "utf-8",
)

Source from the content-addressed store, hash-verified

145
146
147def set_key(
148 dotenv_path: StrPath,
149 key_to_set: str,
150 value_to_set: str,
151 quote_mode: str = "always",
152 export: bool = False,
153 encoding: Optional[str] = "utf-8",
154) -> Tuple[Optional[bool], str, str]:
155 """
156 Adds or Updates a key/value to the given .env
157
158 If the .env path given doesn't exist, fails instead of risking creating
159 an orphan .env somewhere in the filesystem
160 """
161 if quote_mode not in ("always", "auto", "never"):
162 raise ValueError(f"Unknown quote_mode: {quote_mode}")
163
164 quote = (
165 quote_mode == "always"
166 or (quote_mode == "auto" and not value_to_set.isalnum())
167 )
168
169 if quote:
170 value_out = "'{}'".format(value_to_set.replace("'", "\\'"))
171 else:
172 value_out = value_to_set
173 if export:
174 line_out = f'export {key_to_set}={value_out}\n'
175 else:
176 line_out = f"{key_to_set}={value_out}\n"
177
178 with rewrite(dotenv_path, encoding=encoding) as (source, dest):
179 replaced = False
180 missing_newline = False
181 for mapping in with_warn_for_invalid_lines(parse_stream(source)):
182 if mapping.key == key_to_set:
183 dest.write(line_out)
184 replaced = True
185 else:
186 dest.write(mapping.original.string)
187 missing_newline = not mapping.original.string.endswith("\n")
188 if not replaced:
189 if missing_newline:
190 dest.write("\n")
191 dest.write(line_out)
192
193 return True, key_to_set, value_to_set
194
195
196def unset_key(

Callers 1

setFunction · 0.85

Calls 3

rewriteFunction · 0.85
parse_streamFunction · 0.85

Tested by

no test coverage detected