Skip to content

Commit 381d4d2

Browse files
committed
Added envmod_loader implementation
1 parent 2e633a5 commit 381d4d2

2 files changed

Lines changed: 40 additions & 1 deletion

File tree

README.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,41 @@ class Config:
9191
ENVMod.save_example('.my_example_path')
9292
ENVMod.load_dotenv('.my_env')
9393
ENVMod.sync_env_file('.my_env')
94+
```
95+
96+
#### Recommended (Type-safe, IDE-friendly) Argument Loading
97+
98+
```python
9499
config = Config(**ENVMod.load_args(Config.__init__), session=Session())
95100
```
96101

102+
**Why this is recommended:**
103+
104+
* Full IDE autocompletion
105+
* No static type checker errors
106+
* Explicit and predictable behavior
107+
* Best for libraries, frameworks, production code
108+
109+
---
110+
111+
#### Convenience Mode (Runtime Magic) Argument Loading
112+
113+
```python
114+
config = Config(envmod_loader, session=Session()) #type: ignore
115+
```
116+
117+
**What this does:**
118+
119+
* Automatically loads environment variables
120+
* Injects them into `__init__`
121+
* Overrides missing arguments
122+
123+
**Why `# type: ignore` is required:**
124+
125+
* Static analyzers cannot infer runtime argument injection
126+
* This is intentional and documented behavior
127+
128+
97129
### Method Monitor
98130

99131
```python

classmods/_env_mod.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,11 +259,15 @@ def register(
259259
>>> api_service = APIService(**ENVMod.load_args(APIService.__init__))
260260
>>> db_service = AnotherService(**ENVMod.load_args(AnotherService.connect_db))
261261
262+
## Not Recommended ##
263+
>>> api_service = APIService(envmod_loader=True) #type: ignore
264+
262265
Notes:
263266
- Type hints must be provided to ensure proper type casting from environment strings.
264267
- Default values are automatically handled; required parameters are those without defaults.
265268
- Environment variable names are generated using the section name and the parameter name
266269
(e.g., "API_HOST").
270+
- You can use the `envmod_loader` as a parameter to magicly load args, but it is not IDE friendly.
267271
"""
268272
exclude = exclude or []
269273

@@ -307,11 +311,14 @@ def decorator(func: Callable) -> Callable:
307311

308312
@wraps(func)
309313
def wrapper(*args: Any, **kwargs: Any) -> Any:
314+
if kwargs.pop("envmod_loader", False):
315+
loaded_args = cls.load_args(func)
316+
kwargs = {**loaded_args, **kwargs}
310317
return func(*args, **kwargs)
311318

312319
cls._registry[wrapper] = section
313-
return wrapper
314320

321+
return wrapper
315322
return decorator
316323

317324
@classmethod

0 commit comments

Comments
 (0)