cast.from_env(): Add function

cast.from_env() takes an environment variable name instead of the
string as the first argument and does the obvious thing. It also
takes a default and saves the conversion in case the environment
variable doesn't exist.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2025-07-05 10:54:30 +02:00
commit 1a267dd2e5

View file

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import pytimeparse import pytimeparse, os
from datetime import datetime, timedelta from datetime import datetime, timedelta
from collections import OrderedDict from collections import OrderedDict
@ -97,6 +97,14 @@ def from_str(s: str, target_type=None, default_type=None, throw=True, log_level=
slog(log_level, msg) slog(log_level, msg)
return None return None
def from_env(key: str, default=None, target_type=None, default_type=None, throw=True, log_level=WARNING, caller=None): # export
val = os.getenv(key)
if val is None:
return default
if target_type is None and default is not None:
target_type = type(default)
return from_str(val, target_type=target_type, default_type=default_type, throw=throw, log_level=log_level, caller=caller)
# deprecated name # deprecated name
def cast_str(s: str, target_type=None, default_type=None, throw=True, log_level=WARNING, caller=None): def cast_str(s: str, target_type=None, default_type=None, throw=True, log_level=WARNING, caller=None):
return from_str(s, target_type=target_type, default_type=None, throw=True, log_level=WARNING, caller=None) return from_str(s, target_type=target_type, default_type=None, throw=True, log_level=WARNING, caller=None)