Skip to content

[Bug] Inline comment is included as value when key has empty value (KEY= # comment) #600

Description

@Turtle-Hwan

Summary

When a key has an empty value followed by an inline comment, the comment text becomes the value instead of being stripped.

Reproduction

from dotenv import dotenv_values

with open('.env.test', 'w') as f:
    f.write('''
WITH_VALUE=hello  # comment
EMPTY_VALUE=  # comment
JUST_EMPTY=
''')

values = dotenv_values('.env.test')

print("WITH_VALUE:", repr(values.get('WITH_VALUE')))
print("EMPTY_VALUE:", repr(values.get('EMPTY_VALUE')))
print("JUST_EMPTY:", repr(values.get('JUST_EMPTY')))

Output:

WITH_VALUE: 'hello'
EMPTY_VALUE: '# comment'
JUST_EMPTY: ''

Expected vs Actual

Input Expected Actual
KEY=value # comment 'value' 'value'
KEY= # comment '' '# comment'
KEY= '' ''

Question

Is this the intended behavior? It seems inconsistent that inline comments are stripped when there's a value, but included when the value is empty.

Workaround

Use quoted empty values:

KEY=""  # comment

This correctly parses to ''.

Environment

  • python-dotenv version: 1.2.1
  • Python version: 3.11

Volunteering

If this is considered a bug rather than intended behavior, I'd be good to work on a fix and submit a PR.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions