@@ -39,7 +39,7 @@ def get():
39
39
40
40
41
41
def to_list (value : str , * , strip : bool = True , separator : str = "," ) -> List [str ]:
42
- """Split a string to a list, properly handling leading/trailing whitespace and empty items."""
42
+ """Split a string to a list, properly stripping leading/trailing whitespace and skipping empty items."""
43
43
result = value .split (separator )
44
44
if strip :
45
45
result = [s .strip () for s in result ]
@@ -52,7 +52,7 @@ def from_env_as_list(
52
52
) -> Callable [[], List [str ]]:
53
53
"""
54
54
Attrs default factory to get a list from an env var
55
- (properly handling leading/trailing whitespace and empty items).
55
+ (automatically splitting with separator, stripping leading/trailing whitespace and skipping empty items):
56
56
57
57
Usage example:
58
58
@@ -84,3 +84,31 @@ def get():
84
84
return value
85
85
86
86
return get
87
+
88
+
89
+ def default_from_env_as_list (
90
+ var : str , * , default : Union [str , List [str ]] = "" , strip : bool = True , separator : str = ","
91
+ ):
92
+ """
93
+ Build an attrs default value that, by default, takes the value of given environment variable
94
+ and splits it into a list (automatically stripping leading/trailing whitespace and skipping empty items):
95
+
96
+ >>> @attrs.define
97
+ ... class Config:
98
+ ... colors: List[str] = default_from_env_as_list("COLORS")
99
+
100
+ >>> Config().colors
101
+ []
102
+ >>> os.environ["COLORS"] = "blue,black"
103
+ >>> Config().color
104
+ ["blue", "black"]
105
+ >>> Config(colors=["green", "white"]).colors
106
+ ["green", "white"]
107
+
108
+ :param var: env var name
109
+ :param default: fallback value to parse if env var is not set
110
+ :param strip: whether to strip surrounding whitespace
111
+ :param separator: item separator
112
+ :return: default value to use for attributes in a `@attrs.define` class
113
+ """
114
+ return attrs .field (factory = from_env_as_list (var = var , default = default , strip = strip , separator = separator ))
0 commit comments