From 97a26730529f6e02281f6fc09628cdea3ce33055 Mon Sep 17 00:00:00 2001 From: Aaron Zhang Date: Thu, 18 Apr 2024 21:44:18 +1000 Subject: [PATCH] add support for callable default (#8) * add support for callable default * remove unused file --------- Co-authored-by: Aaron --- ragdoll/base.py | 10 ++++++++-- ragdoll/utils.py | 6 ------ tests/test_env/test_bool_env.py | 7 +++++++ tests/test_env/test_int_env.py | 7 +++++++ tests/test_env/test_str_env.py | 7 +++++++ 5 files changed, 29 insertions(+), 8 deletions(-) delete mode 100644 ragdoll/utils.py diff --git a/ragdoll/base.py b/ragdoll/base.py index 4025a3c..f00f1b0 100644 --- a/ragdoll/base.py +++ b/ragdoll/base.py @@ -33,9 +33,15 @@ def __init__( @property def _default(self) -> Any: + if callable(self._default_value): + value = self._default_value() + else: + value = self._default_value + if self._process_default_value: - return self.to_python(self._default_value) - return self._default_value + return self.to_python(value) + + return value @property def name(self): diff --git a/ragdoll/utils.py b/ragdoll/utils.py deleted file mode 100644 index 133bb32..0000000 --- a/ragdoll/utils.py +++ /dev/null @@ -1,6 +0,0 @@ -class classproperty: - def __init__(self, func): - self._func = func - - def __get__(self, instance, cls): - return self._func(cls) diff --git a/tests/test_env/test_bool_env.py b/tests/test_env/test_bool_env.py index d685363..9759207 100644 --- a/tests/test_env/test_bool_env.py +++ b/tests/test_env/test_bool_env.py @@ -51,3 +51,10 @@ class MyEnvSetting(EnvSetting): FOO = BoolEnv(False) assert MyEnvSetting.__dict__["FOO"].name == "FOO" + + +def test_bool_env_callable_default(): + class MyEnvSetting(EnvSetting): + FOO = BoolEnv(lambda: False) + + assert MyEnvSetting.FOO is False diff --git a/tests/test_env/test_int_env.py b/tests/test_env/test_int_env.py index 00fb4ab..a066f8f 100644 --- a/tests/test_env/test_int_env.py +++ b/tests/test_env/test_int_env.py @@ -49,3 +49,10 @@ def test_process_default_value_choices_error(): class MyEnvSetting(EnvSetting): FOO = IntEnv("0", process_default_value=True, choices=[1]) + + +def test_int_env_callable_default(): + class MyEnvSetting(EnvSetting): + FOO = IntEnv(lambda: 300) + + assert MyEnvSetting.FOO == 300 diff --git a/tests/test_env/test_str_env.py b/tests/test_env/test_str_env.py index 792bd96..433508e 100644 --- a/tests/test_env/test_str_env.py +++ b/tests/test_env/test_str_env.py @@ -49,3 +49,10 @@ class MyEnvSetting(EnvSetting): FOO = StrEnv("") assert MyEnvSetting.__dict__["FOO"].name == "FOO" + + +def test_str_env_callable_default(): + class MyEnvSetting(EnvSetting): + FOO = StrEnv(lambda: "") + + assert MyEnvSetting.FOO == ""