From 1a267dd2e58bed44cbdbf7a6f6c6e973fe62077d Mon Sep 17 00:00:00 2001 From: Jan Lindemann Date: Sat, 5 Jul 2025 10:54:30 +0200 Subject: [PATCH] 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 --- tools/python/jwutils/cast.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tools/python/jwutils/cast.py b/tools/python/jwutils/cast.py index 74043d2..1579a35 100644 --- a/tools/python/jwutils/cast.py +++ b/tools/python/jwutils/cast.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- -import pytimeparse +import pytimeparse, os from datetime import datetime, timedelta 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) 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 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)