Skip to content

Defining opening the ENV file#2

Merged
SorynTech merged 1 commit into
mainfrom
PRs
Dec 17, 2025
Merged

Defining opening the ENV file#2
SorynTech merged 1 commit into
mainfrom
PRs

Conversation

@SorynTech

@SorynTech SorynTech commented Dec 17, 2025

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • Refactor
    • Optimized internal environment variable loading and parsing during application startup for improved reliability and error handling of missing configuration files.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 17, 2025

Copy link
Copy Markdown

Walkthrough

The load_env_file function in Dice.py has been refactored to assign parsed environment variables directly to os.environ instead of returning a dictionary. The function now handles empty lines, comments, and quote trimming, and is invoked unconditionally at import time. Usage has shifted from dict-based retrieval to os.getenv() calls.

Changes

Cohort / File(s) Summary
Environment variable loading refactor
Dice.py
Modified load_env_file() to populate os.environ directly instead of returning a dict; added warning for missing .env file; updated password retrieval from dict access to os.getenv('PASSWORD') call; function now invoked at module load time

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Review the load_env_file() implementation for correct .env parsing logic (quote trimming, comment/blank line handling)
  • Verify the transition from dict-based to os.environ-based access is complete and no references to the old pattern remain
  • Confirm the function is called appropriately at module initialization

Possibly related PRs

Poem

🐰 Environment paths, once wrapped in dicts so tight,
Now dance through os.environ in the import's morning light!
Quotes trimmed, comments skipped, each variable in place,
The .env file's secrets now find their rightful space! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Defining opening the ENV file' is partially related to the changeset but lacks clarity and specificity about the main change. Revise the title to be more specific and grammatically clear, such as 'Load environment variables from .env file into os.environ' or 'Refactor environment variable loading to use os.environ directly'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch PRs

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
Dice project/Dice.py (1)

9-20: Add error handling for file operations.

The file operations lack try-except blocks, which could lead to unhandled exceptions (IOError, UnicodeDecodeError, PermissionError, etc.) that would crash the program at import time.

Apply this diff to add error handling:

+    try:
         with open(filepath, 'r') as f:
             for line in f:
                 line = line.strip()
                 # Skip empty lines and comments
                 if line and not line.startswith('#'):
                     # Split on first = sign
                     if '=' in line:
                         key, value = line.split('=', 1)
                         # Remove quotes if present
                         value = value.strip().strip('"').strip("'")
                         # Set in os.environ so it's accessible everywhere
                         os.environ[key.strip()] = value
+    except Exception as e:
+        print(f"Error loading {filepath}: {e}")
+        return
🧹 Nitpick comments (2)
Dice project/Dice.py (2)

3-20: Consider using the python-dotenv library.

The custom .env parsing logic reimplements functionality that's well-established in libraries like python-dotenv, which handles edge cases, multiple platforms, and complex scenarios more robustly.

You can replace the custom implementation with:

from dotenv import load_dotenv

load_dotenv()  # Loads .env file into os.environ

Install via: pip install python-dotenv


22-23: Consider conditional or explicit invocation.

Calling load_env_file() unconditionally at import time creates side effects that may cause issues in testing, REPL sessions, or when the module is imported for non-runtime purposes.

Consider one of these approaches:

Option 1: Use if __name__ == '__main__' guard

-# Load the variables
-load_env_file()
+if __name__ == '__main__':
+    # Load the variables
+    load_env_file()

Option 2: Make it explicit in main execution flow

def main():
    load_env_file()
    password = os.getenv('PASSWORD')
    # ... rest of logic

if __name__ == '__main__':
    main()
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 909d8b4 and 276b33f.

📒 Files selected for processing (1)
  • Dice project/Dice.py (2 hunks)
🔇 Additional comments (1)
Dice project/Dice.py (1)

3-7: LGTM!

The early return pattern with a warning message is appropriate for handling missing .env files gracefully.

Comment thread Dice project/Dice.py
@@ -16,16 +16,17 @@ def load_env_file(filepath='.env'):
key, value = line.split('=', 1)
# Remove quotes if present
value = value.strip().strip('"').strip("'")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Fix quote stripping logic to handle edge cases.

The current approach value.strip().strip('"').strip("'") has issues:

  • It strips both single and double quotes sequentially, which can incorrectly handle mixed quotes
  • It removes legitimate quotes that are part of the actual value

For example, if the value is 'value"with"quotes', it would incorrectly strip both quote types.

Apply this diff to handle matching quotes correctly:

-                    # Remove quotes if present
-                    value = value.strip().strip('"').strip("'")
+                    # Remove matching quotes if present
+                    value = value.strip()
+                    if len(value) >= 2 and ((value[0] == '"' and value[-1] == '"') or 
+                                            (value[0] == "'" and value[-1] == "'")):
+                        value = value[1:-1]

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In Dice project/Dice.py around line 18, replace the current quote-stripping
logic that does value.strip().strip('"').strip("'") with logic that first trims
whitespace, then only removes surrounding quotes when the first and last
characters are a matching quote character (either both ' or both "), leaving
values with mixed or internal quotes intact; specifically: trim whitespace,
check if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'),
and if so remove those outer quotes, otherwise keep the trimmed value as-is.

Comment thread Dice project/Dice.py
@SorynTech

Copy link
Copy Markdown
Owner Author

@coderabbitai
the password printing was for debugging and has been removed already just not commited as im doing more work on the file

@coderabbitai

coderabbitai Bot commented Dec 17, 2025

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

@SorynTech, thanks for the clarification! No worries about the debug code—it's perfectly normal to have that during development. I'll see the updated code once you commit your changes. Feel free to tag me if you'd like me to review anything specific when you're ready!

@SorynTech SorynTech merged commit 6396d38 into main Dec 17, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant