MCPcopy Create free account
hub / github.com/PierreGode/Ragnar / envwrap

Function envwrap

pager_lib/tqdm/utils.py:34–99  ·  view source on GitHub ↗

Override parameter defaults via `os.environ[prefix + param_name]`. Maps UPPER_CASE env vars map to lower_case param names. camelCase isn't supported (because Windows ignores case). Precedence (highest first): - call (`foo(a=3)`) - environ (`FOO_A=2`) - signature (`def

(prefix, types=None, is_method=False)

Source from the content-addressed store, hash-verified

32
33
34def envwrap(prefix, types=None, is_method=False):
35 """
36 Override parameter defaults via `os.environ[prefix + param_name]`.
37 Maps UPPER_CASE env vars map to lower_case param names.
38 camelCase isn't supported (because Windows ignores case).
39
40 Precedence (highest first):
41
42 - call (`foo(a=3)`)
43 - environ (`FOO_A=2`)
44 - signature (`def foo(a=1)`)
45
46 Parameters
47 ----------
48 prefix : str
49 Env var prefix, e.g. "FOO_"
50 types : dict, optional
51 Fallback mappings `{'param_name': type, ...}` if types cannot be
52 inferred from function signature.
53 Consider using `types=collections.defaultdict(lambda: ast.literal_eval)`.
54 is_method : bool, optional
55 Whether to use `functools.partialmethod`. If (default: False) use `functools.partial`.
56
57 Examples
58 --------
59 ```
60 $ cat foo.py
61 from tqdm.utils import envwrap
62 @envwrap("FOO_")
63 def test(a=1, b=2, c=3):
64 print(f"received: a={a}, b={b}, c={c}")
65
66 $ FOO_A=42 FOO_C=1337 python -c 'import foo; foo.test(c=99)'
67 received: a=42, b=2, c=99
68 ```
69 """
70 if types is None:
71 types = {}
72 i = len(prefix)
73 env_overrides = {k[i:].lower(): v for k, v in os.environ.items() if k.startswith(prefix)}
74 part = partialmethod if is_method else partial
75
76 def wrap(func):
77 params = signature(func).parameters
78 # ignore unknown env vars
79 overrides = {k: v for k, v in env_overrides.items() if k in params}
80 # infer overrides' `type`s
81 for k in overrides:
82 param = params[k]
83 if param.annotation is not param.empty: # typehints
84 for typ in getattr(param.annotation, '__args__', (param.annotation,)):
85 try:
86 overrides[k] = typ(overrides[k])
87 except Exception:
88 pass
89 else:
90 break
91 elif param.default is not None: # type of default value

Callers

nothing calls this directly

Calls 1

itemsMethod · 0.45

Tested by

no test coverage detected