Name | dotvar JSON |
Version |
0.1.1
JSON |
| download |
home_page | https://github.com/geyang/dotvar |
Summary | A simple module to load environment variables from a .env file |
upload_time | 2025-02-08 05:57:59 |
maintainer | None |
docs_url | None |
author | Ge Yang |
requires_python | >=3.6 |
license | None |
keywords |
|
VCS |
 |
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# dotvar: Enhanced Environment Variable Management for Python
A simple Python module to load environment variables from a `.env` file with robust interpolation support.
## Rationale
Managing environment variables through a `.env` file streamlines application configuration.
### The Problem with `python-dotenv`
While `python-dotenv` is a popular choice for loading environment variables, it has a notable limitation: **it does not support variable
interpolation**. This means that environment variables cannot reference other variables within the `.env` file, leading to redundancies and
increased potential for errors.
For example, the `CACHE_DIR` variable in the following `.env` file would not automatically resolve to
`$HOME/.cache/myapp`. In fact, your app will create a `$HOME` directory.
```env
CACHE_DIR=$HOME/.cache/myapp
```
In the following example, `python-dotenv` will not resolve `API_ENDPOINT` to `https://api.example.com/v1/`,
requiring manual variable exapantion in your code.
```env
BASE_URL=https://api.example.com
API_ENDPOINT=${BASE_URL}/v1/
```
**python:**
```python
import os
base_url = os.environ.get("BASE_URL")
api_endpoint = os.environ.get("API_ENDPOINT") # Would be "${BASE_URL}/v1/" instead of the resolved URL
```
This lack of interpolation support can lead to repetitive configurations and make the environment setup less intuitive.
## Introducing `dotvar`
`dotvar` addresses the limitations of `python-dotenv` by providing **robust variable interpolation** capabilities. This feature allows
environment variables to reference and build upon each other within the `.env` file, promoting DRY (Don't Repeat Yourself) principles and
reducing redundancy.
## Installation
```bash
pip install dotvar
```
## Simple Usage
```python
import dotvar
# Load environment variables from the nearest .env file
dotvar.load_env()
# Or specify the path to the .env file
dotvar.load_env(env_path="/path/to/your/.env")
```
## Interpolated Variables
`dotvar` supports variable interpolation, enabling environment variables to reference other variables within the `.env` file. This feature
enhances flexibility and reduces duplication in configuration files.
### Example `.env` File
```env
# Sample .env file with interpolated variables
BASE_URL=https://api.example.com
API_ENDPOINT=${BASE_URL}/v1/
SECRET_KEY=s3cr3t
API_KEY=${SECRET_KEY}_api
```
### Usage in Python
```python
import os
import dotvar
# Load environment variables from the .env file
dotvar.load_env()
base_url = os.environ.get("BASE_URL")
api_endpoint = os.environ.get("API_ENDPOINT")
secret_key = os.environ.get("SECRET_KEY")
api_key = os.environ.get("API_KEY")
print(f"Base URL: {base_url}")
print(f"API Endpoint: {api_endpoint}")
print(f"Secret Key: {secret_key}")
print(f"API Key: {api_key}")
```
### Output
```
Base URL: [https://api.example.com](https://api.example.com)
API Endpoint: [https://api.example.com/v1/](https://api.example.com/v1/)
Secret Key: s3cr3t
API Key: s3cr3t_api
```
## Differences from `python-dotenv`
While both `dotvar` and `python-dotenv` serve the primary purpose of loading environment variables from a `.env` file, there are key
differences that set `dotvar` apart:
- **Variable Interpolation**: Unlike `python-dotenv`, `dotvar` natively supports variable interpolation, allowing environment variables to
reference other variables within the `.env` file. This reduces redundancy and enhances readability.
- **Simplicity and Lightweight**: `dotvar` is designed to be lightweight with minimal dependencies, making it ideal for projects that
require a straightforward solution without the overhead of additional features.
- **Performance**: `dotvar` is optimized for faster loading of environment variables, which can be beneficial in large projects or
applications where startup time is critical.
- **Error Handling**: `dotvar` includes improved error handling mechanisms to provide clearer feedback when issues arise in the `.env` file,
such as missing variables or invalid formats.
- **Customization**: `dotvar` allows for greater customization in how environment variables are loaded and managed, offering developers more
control over the configuration process.
Choosing between `dotvar` and `python-dotenv` depends on the specific needs of your project. If you require a lightweight, performant tool
with robust interpolation and customization options, `dotvar` is the ideal choice. On the other hand, if your project already heavily
integrates with `python-dotenv` and you rely on its specific features, it may be more practical to continue using it.
## Autoload Feature
`dotvar` offers an **autoload** feature that automatically loads environment variables without requiring explicit calls to `load_env()` in
your code. This ensures that environment variables are available as soon as your application starts, simplifying the configuration process.
### Enabling Autoload
To enable the autoload feature, simply import `dotvar` at the beginning of your application's entry point. `dotvar` will automatically
detect and load the `.env` file without any additional function calls.
```python
import dotvar
import os
# Environment variables are automatically loaded
database_url = os.environ.get("DATABASE_URL")
secret_key = os.environ.get("SECRET_KEY")
debug_mode = os.environ.get("DEBUG")
api_key = os.environ.get("API_KEY")
print(f"Database URL: {database_url}")
print(f"Secret Key: {secret_key}")
print(f"Debug Mode: {debug_mode}")
print(f"API Key: {api_key}")
```
### Testing Autoload
To ensure that the autoload feature is working correctly, you can write tests that verify environment variables are loaded automatically
upon application startup.
#### Example Test Using `pytest`
```python
# tests/test_autoload.py
import os
import pytest
import tempfile
# this automatically loads the env vars
from dotvar import autoload
@pytest.fixture
def temp_env_file_autoload(monkeypatch):
# Create a temporary .env file
temp_dir = tempfile.TemporaryDirectory()
env_path = os.path.join(temp_dir.name, ".env")
with open(env_path, "w") as f:
f.write("""
# Sample .env file with autoload
DATABASE_URL=postgres://user:password@localhost:5432/dbname
SECRET_KEY=s3cr3t
DEBUG=True
API_KEY=${SECRET_KEY}_api
""")
# Mock the path to the .env file
monkeypatch.setattr(dotvar, 'find_env_path', lambda: env_path)
# Importing dotvar will trigger autoload
import dotvar
yield env_path
temp_dir.cleanup()
def test_autoload(temp_env_file_autoload):
database_url = os.environ.get("DATABASE_URL")
secret_key = os.environ.get("SECRET_KEY")
debug_mode = os.environ.get("DEBUG")
api_key = os.environ.get("API_KEY")
assert database_url == "postgres://user:password@localhost:5432/dbname"
assert secret_key == "s3cr3t"
assert debug_mode == "True"
assert api_key == "s3cr3t_api"
```
#### Running the Test
To run the test, navigate to your project directory and execute:
```bash
pytest tests/test_autoload.py
```
If the autoload feature is functioning correctly, all assertions should pass, confirming that environment variables are loaded
automatically.
## A Detailed Example
```python
import dotvar
# Autoload is enabled by simply importing dotvar
# No need to call load_env()
# Now you can access the variables via os.environ
import os
database_url = os.environ.get("DATABASE_URL")
secret_key = os.environ.get("SECRET_KEY")
debug_mode = os.environ.get("DEBUG")
api_key = os.environ.get("API_KEY")
print(f"Database URL: {database_url}")
print(f"Secret Key: {secret_key}")
print(f"Debug Mode: {debug_mode}")
print(f"API Key: {api_key}")
```
## To Develop:
### Description of Makefile Targets
- **help**: Displays available Makefile targets.
- **install**: Installs or upgrades the necessary packaging tools (`pip`, `setuptools`, `wheel`, and `twine`).
- **test**: Runs the test suite using `pytest`.
- **build**: Builds the source and wheel distribution packages.
- **clean**: Removes build artifacts to ensure a clean state.
- **upload**: Uploads the built distribution packages to PyPI using `twine`. This target depends on the `build` target.
### Usage
To use the Makefile, open your terminal, navigate to your project directory (where the Makefile is located), and run the desired target. For
example:
- To install dependencies:
```bash
make install
```
- To run tests:
```bash
make test
```
- To build the package:
```bash
make build
```
- To upload the package to PyPI:
```bash
make upload
```
- To clean build artifacts:
```bash
make clean
```
## License
MIT License
Raw data
{
"_id": null,
"home_page": "https://github.com/geyang/dotvar",
"name": "dotvar",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.6",
"maintainer_email": null,
"keywords": null,
"author": "Ge Yang",
"author_email": "ge.ike.yang@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/52/6a/27e4b8ea03b4cde815c118f7b0c49356fae2a617f0e727f9aaa52ceb028f/dotvar-0.1.1.tar.gz",
"platform": null,
"description": "# dotvar: Enhanced Environment Variable Management for Python\n\nA simple Python module to load environment variables from a `.env` file with robust interpolation support.\n\n## Rationale\n\nManaging environment variables through a `.env` file streamlines application configuration.\n\n### The Problem with `python-dotenv`\n\nWhile `python-dotenv` is a popular choice for loading environment variables, it has a notable limitation: **it does not support variable\ninterpolation**. This means that environment variables cannot reference other variables within the `.env` file, leading to redundancies and\nincreased potential for errors. \n\nFor example, the `CACHE_DIR` variable in the following `.env` file would not automatically resolve to\n`$HOME/.cache/myapp`. In fact, your app will create a `$HOME` directory.\n\n```env\nCACHE_DIR=$HOME/.cache/myapp\n```\n\nIn the following example, `python-dotenv` will not resolve `API_ENDPOINT` to `https://api.example.com/v1/`,\nrequiring manual variable exapantion in your code.\n\n```env\nBASE_URL=https://api.example.com\nAPI_ENDPOINT=${BASE_URL}/v1/\n```\n\n**python:**\n```python\nimport os\n\nbase_url = os.environ.get(\"BASE_URL\")\napi_endpoint = os.environ.get(\"API_ENDPOINT\") # Would be \"${BASE_URL}/v1/\" instead of the resolved URL\n```\n\nThis lack of interpolation support can lead to repetitive configurations and make the environment setup less intuitive.\n\n## Introducing `dotvar`\n\n`dotvar` addresses the limitations of `python-dotenv` by providing **robust variable interpolation** capabilities. This feature allows\nenvironment variables to reference and build upon each other within the `.env` file, promoting DRY (Don't Repeat Yourself) principles and\nreducing redundancy.\n\n## Installation\n\n```bash\npip install dotvar\n```\n\n## Simple Usage\n\n```python\nimport dotvar\n\n# Load environment variables from the nearest .env file\ndotvar.load_env()\n\n# Or specify the path to the .env file\ndotvar.load_env(env_path=\"/path/to/your/.env\")\n```\n\n## Interpolated Variables\n\n`dotvar` supports variable interpolation, enabling environment variables to reference other variables within the `.env` file. This feature\nenhances flexibility and reduces duplication in configuration files.\n\n### Example `.env` File\n\n```env\n# Sample .env file with interpolated variables\nBASE_URL=https://api.example.com\nAPI_ENDPOINT=${BASE_URL}/v1/\nSECRET_KEY=s3cr3t\nAPI_KEY=${SECRET_KEY}_api\n```\n\n### Usage in Python\n\n```python\nimport os\nimport dotvar\n\n# Load environment variables from the .env file\ndotvar.load_env()\n\nbase_url = os.environ.get(\"BASE_URL\")\napi_endpoint = os.environ.get(\"API_ENDPOINT\")\nsecret_key = os.environ.get(\"SECRET_KEY\")\napi_key = os.environ.get(\"API_KEY\")\n\nprint(f\"Base URL: {base_url}\")\nprint(f\"API Endpoint: {api_endpoint}\")\nprint(f\"Secret Key: {secret_key}\")\nprint(f\"API Key: {api_key}\")\n```\n\n### Output\n\n```\nBase URL: [https://api.example.com](https://api.example.com)\nAPI Endpoint: [https://api.example.com/v1/](https://api.example.com/v1/)\nSecret Key: s3cr3t \nAPI Key: s3cr3t_api\n```\n\n## Differences from `python-dotenv`\n\nWhile both `dotvar` and `python-dotenv` serve the primary purpose of loading environment variables from a `.env` file, there are key\ndifferences that set `dotvar` apart:\n\n- **Variable Interpolation**: Unlike `python-dotenv`, `dotvar` natively supports variable interpolation, allowing environment variables to\n reference other variables within the `.env` file. This reduces redundancy and enhances readability.\n\n- **Simplicity and Lightweight**: `dotvar` is designed to be lightweight with minimal dependencies, making it ideal for projects that\n require a straightforward solution without the overhead of additional features.\n\n- **Performance**: `dotvar` is optimized for faster loading of environment variables, which can be beneficial in large projects or\n applications where startup time is critical.\n\n- **Error Handling**: `dotvar` includes improved error handling mechanisms to provide clearer feedback when issues arise in the `.env` file,\n such as missing variables or invalid formats.\n\n- **Customization**: `dotvar` allows for greater customization in how environment variables are loaded and managed, offering developers more\n control over the configuration process.\n\nChoosing between `dotvar` and `python-dotenv` depends on the specific needs of your project. If you require a lightweight, performant tool\nwith robust interpolation and customization options, `dotvar` is the ideal choice. On the other hand, if your project already heavily\nintegrates with `python-dotenv` and you rely on its specific features, it may be more practical to continue using it.\n\n## Autoload Feature\n\n`dotvar` offers an **autoload** feature that automatically loads environment variables without requiring explicit calls to `load_env()` in\nyour code. This ensures that environment variables are available as soon as your application starts, simplifying the configuration process.\n\n### Enabling Autoload\n\nTo enable the autoload feature, simply import `dotvar` at the beginning of your application's entry point. `dotvar` will automatically\ndetect and load the `.env` file without any additional function calls.\n\n```python\nimport dotvar\nimport os\n\n# Environment variables are automatically loaded\ndatabase_url = os.environ.get(\"DATABASE_URL\")\nsecret_key = os.environ.get(\"SECRET_KEY\")\ndebug_mode = os.environ.get(\"DEBUG\")\napi_key = os.environ.get(\"API_KEY\")\n\nprint(f\"Database URL: {database_url}\")\nprint(f\"Secret Key: {secret_key}\")\nprint(f\"Debug Mode: {debug_mode}\")\nprint(f\"API Key: {api_key}\")\n```\n\n### Testing Autoload\n\nTo ensure that the autoload feature is working correctly, you can write tests that verify environment variables are loaded automatically\nupon application startup.\n\n#### Example Test Using `pytest`\n\n```python\n# tests/test_autoload.py\n\nimport os\nimport pytest\nimport tempfile\n\n# this automatically loads the env vars\nfrom dotvar import autoload\n\n@pytest.fixture\ndef temp_env_file_autoload(monkeypatch):\n # Create a temporary .env file\n temp_dir = tempfile.TemporaryDirectory()\n env_path = os.path.join(temp_dir.name, \".env\")\n with open(env_path, \"w\") as f:\n f.write(\"\"\"\n # Sample .env file with autoload\n DATABASE_URL=postgres://user:password@localhost:5432/dbname\n SECRET_KEY=s3cr3t\n DEBUG=True\n API_KEY=${SECRET_KEY}_api\n \"\"\")\n # Mock the path to the .env file\n monkeypatch.setattr(dotvar, 'find_env_path', lambda: env_path)\n # Importing dotvar will trigger autoload\n import dotvar\n yield env_path\n temp_dir.cleanup()\n\n\ndef test_autoload(temp_env_file_autoload):\n database_url = os.environ.get(\"DATABASE_URL\")\n secret_key = os.environ.get(\"SECRET_KEY\")\n debug_mode = os.environ.get(\"DEBUG\")\n api_key = os.environ.get(\"API_KEY\")\n\n assert database_url == \"postgres://user:password@localhost:5432/dbname\"\n assert secret_key == \"s3cr3t\"\n assert debug_mode == \"True\"\n assert api_key == \"s3cr3t_api\"\n```\n\n#### Running the Test\n\nTo run the test, navigate to your project directory and execute:\n\n```bash\npytest tests/test_autoload.py\n```\n\nIf the autoload feature is functioning correctly, all assertions should pass, confirming that environment variables are loaded\nautomatically.\n\n## A Detailed Example\n\n```python\nimport dotvar\n\n# Autoload is enabled by simply importing dotvar\n# No need to call load_env()\n\n# Now you can access the variables via os.environ\nimport os\n\ndatabase_url = os.environ.get(\"DATABASE_URL\")\nsecret_key = os.environ.get(\"SECRET_KEY\")\ndebug_mode = os.environ.get(\"DEBUG\")\napi_key = os.environ.get(\"API_KEY\")\n\nprint(f\"Database URL: {database_url}\")\nprint(f\"Secret Key: {secret_key}\")\nprint(f\"Debug Mode: {debug_mode}\")\nprint(f\"API Key: {api_key}\")\n```\n\n## To Develop:\n\n### Description of Makefile Targets\n\n- **help**: Displays available Makefile targets.\n- **install**: Installs or upgrades the necessary packaging tools (`pip`, `setuptools`, `wheel`, and `twine`).\n- **test**: Runs the test suite using `pytest`.\n- **build**: Builds the source and wheel distribution packages.\n- **clean**: Removes build artifacts to ensure a clean state.\n- **upload**: Uploads the built distribution packages to PyPI using `twine`. This target depends on the `build` target.\n\n### Usage\n\nTo use the Makefile, open your terminal, navigate to your project directory (where the Makefile is located), and run the desired target. For\nexample:\n\n- To install dependencies:\n ```bash\n make install\n ```\n- To run tests:\n ```bash\n make test\n ```\n- To build the package:\n ```bash\n make build\n ```\n- To upload the package to PyPI:\n ```bash\n make upload\n ```\n- To clean build artifacts:\n ```bash\n make clean\n ```\n\n## License\n\nMIT License\n",
"bugtrack_url": null,
"license": null,
"summary": "A simple module to load environment variables from a .env file",
"version": "0.1.1",
"project_urls": {
"Homepage": "https://github.com/geyang/dotvar"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "cbf7ac0b86e7b861e3565b82f99b770f8e5a3e3cd395a57a0b712dd13162f7d8",
"md5": "9c637ee9111cd5a760818f0159e738bc",
"sha256": "27aea277c91430ca81845e820a5b207f194e30965e7f4cef218130d09b5a70cc"
},
"downloads": -1,
"filename": "dotvar-0.1.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "9c637ee9111cd5a760818f0159e738bc",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.6",
"size": 7441,
"upload_time": "2025-02-08T05:57:57",
"upload_time_iso_8601": "2025-02-08T05:57:57.494403Z",
"url": "https://files.pythonhosted.org/packages/cb/f7/ac0b86e7b861e3565b82f99b770f8e5a3e3cd395a57a0b712dd13162f7d8/dotvar-0.1.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "526a27e4b8ea03b4cde815c118f7b0c49356fae2a617f0e727f9aaa52ceb028f",
"md5": "38a81d2a4d48c4e7c5cf4fc6b1d2af00",
"sha256": "406ea04211eb7616fe17b9dabedc05796c34157f78ef14241c2e4b77681c0a77"
},
"downloads": -1,
"filename": "dotvar-0.1.1.tar.gz",
"has_sig": false,
"md5_digest": "38a81d2a4d48c4e7c5cf4fc6b1d2af00",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.6",
"size": 8645,
"upload_time": "2025-02-08T05:57:59",
"upload_time_iso_8601": "2025-02-08T05:57:59.387886Z",
"url": "https://files.pythonhosted.org/packages/52/6a/27e4b8ea03b4cde815c118f7b0c49356fae2a617f0e727f9aaa52ceb028f/dotvar-0.1.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-02-08 05:57:59",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "geyang",
"github_project": "dotvar",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "dotvar"
}