Skip to content

Strip inline comment from an empty unquoted value - #672

Closed
eeshsaxena wants to merge 1 commit into
theskumar:mainfrom
eeshsaxena:fix-empty-value-inline-comment
Closed

eeshsaxena wants to merge 1 commit into
theskumar:mainfrom
eeshsaxena:fix-empty-value-inline-comment

Conversation

@eeshsaxena

Copy link
Copy Markdown

Fixes #600.

For a line where the key has an empty value followed by an inline comment, the comment text became the value:

>>> dotenv_values(stream=io.StringIO("EMPTY_VALUE=  # comment"))["EMPTY_VALUE"]
'# comment'   # expected ''

parse_unquoted_value() strips inline comments with re.sub(r"\s+#.*", "", part), which requires whitespace before the #. But _equal_sign (=[^\S\r\n]*) consumes the whitespace between = and the value, so for an empty value the remaining text starts at # with no leading whitespace, and the strip never matches.

The whitespace was there in the source, though — it's just been consumed. This threads a preceded_by_whitespace flag (derived from whether the _equal_sign match captured any whitespace) so that:

  • KEY= # comment / KEY= #c → "" (empty value, comment stripped)
  • KEY=#value → "#value" (no separating whitespace, so # is part of the value — unchanged)
  • KEY=v # c → "v", KEY=v#c → "v#c" — all unchanged

New parser test cases cover a= #c, a= # comment, and a=#b. Full suite: tests/test_parser.py 48 passed; tests/test_main.py unaffected. ruff clean.

For a line like ``KEY=  # comment`` the comment became the value because
the whitespace before ``#`` is consumed by the equal-sign match, so
parse_unquoted_value()'s ``\s+#`` strip never matched. Thread a
"preceded by whitespace" flag so an empty value followed by a comment
resolves to "" while a value that legitimately starts with ``#`` (e.g.
``KEY=#value``) is preserved.

Fixes #600
@eeshsaxena eeshsaxena closed this Jul 16, 2026
@eeshsaxena eeshsaxena reopened this Jul 16, 2026
@eeshsaxena

Copy link
Copy Markdown
Author

Hi! Gentle ping on this one; it's been open a couple of weeks and CI is green. Happy to rebase or make any changes if something's needed; whenever you get a chance to take a look, I'd really appreciate it. Thanks!

@theskumar

Copy link
Copy Markdown
Owner

Thanks @eeshsaxena — your fix was correct and all the edge cases matched. I went with #663 in the end because it's a bit more localized (no signature changes needed), but the behavior is identical. Appreciate the work!

@theskumar theskumar closed this Aug 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants