envwrap 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
envwrap/__init__.py ADDED
@@ -0,0 +1,166 @@
1
+ """envwrap - 🚀 Override function defaults with environment variables.
2
+
3
+ MIT License
4
+
5
+ Copyright © 2024 Parker Wahle
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+ """ # noqa: E501, B950
25
+
26
+ from __future__ import annotations
27
+
28
+ import inspect
29
+ import os
30
+ from functools import wraps
31
+ from inspect import signature
32
+ from typing import Optional, Dict, Callable
33
+
34
+ from typing_extensions import ParamSpec, TypeVar, Any, cast
35
+
36
+ F = TypeVar('F', bound=Callable[..., Any])
37
+
38
+
39
+ def get_root_function(func: F) -> F:
40
+ """
41
+ Get the root method of a method or function, unwrapping any decorators.
42
+
43
+ Parameters
44
+ ----------
45
+ func : callable
46
+ The method or function to get the root method of.
47
+
48
+ Returns
49
+ -------
50
+ callable
51
+ The root method of the given method or function.
52
+ """
53
+ while hasattr(func, "__func__"):
54
+ func = func.__func__
55
+ return func
56
+
57
+
58
+ def is_likely_method(func: Callable[..., Any]) -> bool:
59
+ # Check if the first parameter is named 'self' or 'cls'
60
+ params = inspect.signature(func).parameters
61
+ if not params:
62
+ return False
63
+ first_param = next(iter(params.values()))
64
+ return first_param.name in ('self', 'cls')
65
+
66
+ P = ParamSpec("P")
67
+ R = TypeVar("R")
68
+
69
+
70
+ def envwrap(
71
+ prefix: str,
72
+ types: Optional[Dict[str, type]] = None,
73
+ is_method: Optional[bool] = None,
74
+ ) -> Callable[[Callable[P, R]], Callable[P, R]]:
75
+ """
76
+ Override parameter defaults via `os.environ[prefix + param_name]`.
77
+ Maps UPPER_CASE env vars map to lower_case param names.
78
+ camelCase isn't supported (because Windows ignores case).
79
+
80
+ Precedence (highest first):
81
+
82
+ - call (`foo(a=3)`)
83
+ - environ (`FOO_A=2`)
84
+ - signature (`def foo(a=1)`)
85
+
86
+ Types are handled by typehints and are automatically determined, if possible.
87
+ The types argument can be used to override the typehint inference.
88
+ Envwrap will fallback to str if no typehint, override, or default value is found.
89
+
90
+ `from __future__ import annotations` annotations are not supported.
91
+
92
+ Parameters
93
+ ----------
94
+ prefix : str
95
+ Env var prefix, e.g. "FOO_"
96
+ types : dict, optional
97
+ Fallback mappings `{'param_name': type, ...}` if types cannot be
98
+ inferred from function signature.
99
+ Consider using `types=collections.defaultdict(lambda: ast.literal_eval)`.
100
+ is_method : bool, optional
101
+ Whether the function is a method. This will be detected automatically
102
+
103
+ Examples
104
+ --------
105
+ ```
106
+ $ cat foo.py
107
+ from envwrap import envwrap
108
+ @envwrap("FOO_")
109
+ def test(a=1, b=2, c=3):
110
+ print(f"received: a={a}, b={b}, c={c}")
111
+
112
+ $ FOO_A=42 FOO_C=1337 python -c 'import foo; foo.test(c=99)'
113
+ received: a=42, b=2, c=99
114
+ ```
115
+ """
116
+
117
+ if types is None:
118
+ types = {}
119
+
120
+ def wrapper(func: Callable[P, R]) -> Callable[P, R]:
121
+ params = signature(func).parameters
122
+ root_function = get_root_function(func)
123
+
124
+ is_method_explicit = is_method or is_likely_method(root_function)
125
+
126
+ # if we are wrapping a method, we need to skip the first parameter
127
+ params_method_safe = list(params.keys())[1:] if is_method_explicit else list(params.keys())
128
+
129
+ if not callable(func):
130
+ raise TypeError(f"{func} is not callable")
131
+
132
+ @wraps(func)
133
+ def final_callable(*args: P.args, **kwargs: P.kwargs) -> R:
134
+ env_overrides = {k[len(prefix):].lower(): v for k, v in os.environ.items() if k.startswith(prefix)}
135
+ overrides = {k: v for k, v in env_overrides.items() if k in params_method_safe}
136
+
137
+ for k in overrides:
138
+ param = params[k]
139
+ if param.annotation is not param.empty: # typehints
140
+ for typ in getattr(param.annotation, '__args__', (param.annotation,)):
141
+ try:
142
+ overrides[k] = typ(overrides[k])
143
+ except Exception:
144
+ pass
145
+ else:
146
+ break
147
+ elif param.default is not None: # type of default value
148
+ overrides[k] = type(param.default)(overrides[k])
149
+ else:
150
+ try: # `types` fallback
151
+ overrides[k] = types[k](overrides[k])
152
+ except KeyError: # keep unconverted (`str`)
153
+ pass
154
+
155
+ default_kwargs = {k: v.default for k, v in params.items() if v.default is not v.empty}
156
+
157
+ final_kwargs = cast(P.kwargs, {**default_kwargs, **overrides, **kwargs})
158
+
159
+ return func(*args, **final_kwargs)
160
+
161
+ return final_callable
162
+
163
+ return wrapper
164
+
165
+
166
+ __all__ = ("envwrap",)
envwrap/py.typed ADDED
File without changes
File without changes
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Parker Wahle
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.1
2
+ Name: envwrap
3
+ Version: 0.1.0
4
+ Summary: 🚀 Override function defaults with environment variables
5
+ Home-page: https://github.com/regulad/envwrap
6
+ License: MIT
7
+ Author: Parker Wahle
8
+ Author-email: regulad@regulad.xyz
9
+ Requires-Python: >=3.8,<4.0
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.8
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Requires-Dist: typing-extensions (>=4.12.2,<5.0.0)
19
+ Project-URL: Changelog, https://github.com/regulad/envwrap/releases
20
+ Project-URL: Documentation, https://envwrap.readthedocs.io
21
+ Project-URL: Repository, https://github.com/regulad/envwrap
22
+ Description-Content-Type: text/markdown
23
+
24
+ # envwrap
25
+
26
+ [![PyPI](https://img.shields.io/pypi/v/envwrap.svg)][pypi status]
27
+ [![Status](https://img.shields.io/pypi/status/envwrap.svg)][pypi status]
28
+ [![Python Version](https://img.shields.io/pypi/pyversions/envwrap)][pypi status]
29
+ [![License](https://img.shields.io/pypi/l/envwrap)][license]
30
+
31
+ [![Read the documentation at https://envwrap.readthedocs.io/](https://img.shields.io/readthedocs/envwrap/latest.svg?label=Read%20the%20Docs)][read the docs]
32
+
33
+ [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)][pre-commit]
34
+ [![Black](https://img.shields.io/badge/code%20style-black-000000.svg)][black]
35
+
36
+ [pypi status]: https://pypi.org/project/envwrap/
37
+ [read the docs]: https://envwrap.readthedocs.io/
38
+ [tests]: https://github.com/regulad/envwrap/actions?workflow=Tests
39
+ [codecov]: https://app.codecov.io/gh/regulad/envwrap
40
+ [pre-commit]: https://github.com/pre-commit/pre-commit
41
+ [black]: https://github.com/psf/black
42
+
43
+ ## Features
44
+
45
+ - TODO
46
+
47
+ ## Requirements
48
+
49
+ - TODO
50
+
51
+ ## Installation
52
+
53
+ You can install _envwrap_ via [pip] from [PyPI]:
54
+
55
+ ```console
56
+ $ pip install envwrap
57
+ ```
58
+
59
+ ## Contributing
60
+
61
+ Contributions are very welcome.
62
+ To learn more, see the [Contributor Guide].
63
+
64
+ ## License
65
+
66
+ Distributed under the terms of the [MIT license][license],
67
+ _envwrap_ is free and open source software.
68
+
69
+ ## Issues
70
+
71
+ If you encounter any problems,
72
+ please [file an issue] along with a detailed description.
73
+
74
+ ## Credits
75
+
76
+ This project was generated from [@regulad]'s [neopy] template.
77
+
78
+ [@regulad]: https://github.com/regulad
79
+ [pypi]: https://pypi.org/
80
+ [neopy]: https://github.com/regulad/cookiecutter-neopy
81
+ [file an issue]: https://github.com/regulad/envwrap/issues
82
+ [pip]: https://pip.pypa.io/
83
+
84
+ <!-- github-only -->
85
+
86
+ [license]: https://github.com/regulad/envwrap/blob/main/LICENSE
87
+ [contributor guide]: https://github.com/regulad/envwrap/blob/main/CONTRIBUTING.md
88
+ [command-line reference]: https://envwrap.readthedocs.io/en/latest/usage.html
89
+
@@ -0,0 +1,7 @@
1
+ envwrap/__init__.py,sha256=Oh0qQXOSDwn__eIB7iRFhdzNMEv1ml0n1EQFHoFWRE0,5652
2
+ envwrap/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ envwrap/resources/.gitkeep,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ envwrap-0.1.0.dist-info/LICENSE,sha256=XYfLl3V76-4IE3A33ssDIhjpl_fh0PAZqZvhOtq5X_U,1069
5
+ envwrap-0.1.0.dist-info/METADATA,sha256=-hQr1UwOZvHGo2J_EqZl1lWTZIolepcg4z5XyrNiV5E,2892
6
+ envwrap-0.1.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
7
+ envwrap-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.9.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any