22# SPDX-License-Identifier: BSD-3-Clause
33
44import contextlib
5+ import os
56import sys
67from types import TracebackType
7- from typing import TypedDict
8+ from typing import Any , TypedDict , cast , get_type_hints
89
910if sys .version_info >= (3 , 11 ):
1011 from typing import Unpack
@@ -17,22 +18,37 @@ class Options(TypedDict):
1718 max_sampling_iterations : int
1819
1920
20- def default_options () -> Options :
21+ _ENV_PREFIX = "DATAFRAMELY_"
22+
23+
24+ def _builtin_defaults () -> Options :
2125 return {
2226 "max_sampling_iterations" : 10_000 ,
2327 }
2428
2529
30+ def _init_options () -> Options :
31+ options : dict [str , Any ] = dict (_builtin_defaults ())
32+ for key , target_type in get_type_hints (Options ).items ():
33+ env_name = f"{ _ENV_PREFIX } { key .upper ()} "
34+ if env_name in os .environ :
35+ options [key ] = target_type (os .environ [env_name ])
36+ return cast (Options , options )
37+
38+
39+ _DEFAULT_OPTIONS = _init_options ()
40+
41+
2642class Config (contextlib .ContextDecorator ):
2743 """An object to track global configuration for operations in dataframely."""
2844
2945 #: The currently valid config options.
30- options : Options = default_options ()
46+ options : Options = _DEFAULT_OPTIONS . copy ()
3147 #: Singleton stack to track where to go back after exiting a context.
3248 _stack : list [Options ] = []
3349
3450 def __init__ (self , ** options : Unpack [Options ]) -> None :
35- self ._local_options : Options = {** default_options () , ** options }
51+ self ._local_options : Options = {** _DEFAULT_OPTIONS , ** options }
3652
3753 @staticmethod
3854 def set_max_sampling_iterations (iterations : int ) -> None :
@@ -43,7 +59,7 @@ def set_max_sampling_iterations(iterations: int) -> None:
4359 @staticmethod
4460 def restore_defaults () -> None :
4561 """Restore the defaults of the configuration."""
46- Config .options = default_options ()
62+ Config .options = _DEFAULT_OPTIONS . copy ()
4763
4864 # ------------------------------------ CONTEXT ----------------------------------- #
4965
0 commit comments