MCPcopy Index your code
hub / github.com/theskumar/python-dotenv / set_key

Function set_key

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

Adds or Updates a key/value to the given .env The target .env file is created if it doesn't exist. This function doesn't follow symlinks by default, to avoid accidentally modifying a file at a potentially untrusted path. If you don't need this protection and need symlinks to b

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

Source from the content-addressed store, hash-verified

191
192
193def set_key(
194 dotenv_path: StrPath,
195 key_to_set: str,
196 value_to_set: str,
197 quote_mode: str = "always",
198 export: bool = False,
199 encoding: Optional[str] = "utf-8",
200 follow_symlinks: bool = False,
201) -> Tuple[Optional[bool], str, str]:
202 """
203 Adds or Updates a key/value to the given .env
204
205 The target .env file is created if it doesn't exist.
206
207 This function doesn't follow symlinks by default, to avoid accidentally
208 modifying a file at a potentially untrusted path. If you don't need this
209 protection and need symlinks to be followed, use `follow_symlinks`.
210 """
211 if quote_mode not in ("always", "auto", "never"):
212 raise ValueError(f"Unknown quote_mode: {quote_mode}")
213
214 quote = quote_mode == "always" or (
215 quote_mode == "auto" and not value_to_set.isalnum()
216 )
217
218 if quote:
219 value_out = "'{}'".format(value_to_set.replace("'", "\\'"))
220 else:
221 value_out = value_to_set
222 if export:
223 line_out = f"export {key_to_set}={value_out}\n"
224 else:
225 line_out = f"{key_to_set}={value_out}\n"
226
227 with rewrite(dotenv_path, encoding=encoding, follow_symlinks=follow_symlinks) as (
228 source,
229 dest,
230 ):
231 replaced = False
232 missing_newline = False
233 for mapping in with_warn_for_invalid_lines(parse_stream(source)):
234 if mapping.key == key_to_set:
235 dest.write(line_out)
236 replaced = True
237 else:
238 dest.write(mapping.original.string)
239 missing_newline = not mapping.original.string.endswith("\n")
240 if not replaced:
241 if missing_newline:
242 dest.write("\n")
243 dest.write(line_out)
244
245 return True, key_to_set, value_to_set
246
247
248def unset_key(

Callers 1

set_valueFunction · 0.85

Calls 3

rewriteFunction · 0.85
parse_streamFunction · 0.85

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…