Skip to content

Commit a53d652

Browse files
authored
fix: out of scope error when "dest" variable is undefined #413
1 parent a7c811d commit a53d652

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

src/dotenv/main.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -125,15 +125,16 @@ def rewrite(
125125
path: Union[str, os.PathLike],
126126
encoding: Optional[str],
127127
) -> Iterator[Tuple[IO[str], IO[str]]]:
128+
dest = None
128129
try:
129130
if not os.path.isfile(path):
130131
with open(path, "w+", encoding=encoding) as source:
131132
source.write("")
132-
with tempfile.NamedTemporaryFile(mode="w+", delete=False, encoding=encoding) as dest:
133-
with open(path, encoding=encoding) as source:
134-
yield (source, dest) # type: ignore
133+
dest = tempfile.NamedTemporaryFile(mode="w+", delete=False, encoding=encoding)
134+
with open(path, encoding=encoding) as source:
135+
yield (source, dest) # type: ignore
135136
except BaseException:
136-
if os.path.isfile(dest.name):
137+
if dest and os.path.isfile(dest.name):
137138
os.unlink(dest.name)
138139
raise
139140
else:

tests/test_main.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,11 @@ def test_set_key_no_file(tmp_path):
2222
assert os.path.exists(nx_file)
2323

2424

25+
def test_set_key_invalid_file():
26+
with pytest.raises(TypeError):
27+
result = dotenv.set_key(None, "foo", "bar")
28+
29+
2530
@pytest.mark.parametrize(
2631
"before,key,value,expected,after",
2732
[

0 commit comments

Comments
 (0)