2
2
from __future__ import annotations
3
3
4
4
import os
5
+ from typing import Any
6
+ from typing import Callable
5
7
6
- from pytask import get_first_non_none_value
7
8
from pytask import hookimpl
8
9
from pytask_parallel .backends import PARALLEL_BACKENDS_DEFAULT
9
10
from pytask_parallel .callbacks import delay_callback
14
15
@hookimpl
15
16
def pytask_parse_config (config , config_from_cli , config_from_file ):
16
17
"""Parse the configuration."""
17
- config ["n_workers" ] = get_first_non_none_value (
18
+ config ["n_workers" ] = _get_first_non_none_value (
18
19
config_from_cli ,
19
20
config_from_file ,
20
21
key = "n_workers" ,
@@ -24,15 +25,15 @@ def pytask_parse_config(config, config_from_cli, config_from_file):
24
25
if config ["n_workers" ] == "auto" :
25
26
config ["n_workers" ] = max (os .cpu_count () - 1 , 1 )
26
27
27
- config ["delay" ] = get_first_non_none_value (
28
+ config ["delay" ] = _get_first_non_none_value (
28
29
config_from_cli ,
29
30
config_from_file ,
30
31
key = "delay" ,
31
32
default = 0.1 ,
32
33
callback = delay_callback ,
33
34
)
34
35
35
- config ["parallel_backend" ] = get_first_non_none_value (
36
+ config ["parallel_backend" ] = _get_first_non_none_value (
36
37
config_from_cli ,
37
38
config_from_file ,
38
39
key = "parallel_backend" ,
@@ -46,3 +47,31 @@ def pytask_post_parse(config):
46
47
"""Disable parallelization if debugging is enabled."""
47
48
if config ["pdb" ] or config ["trace" ]:
48
49
config ["n_workers" ] = 1
50
+
51
+
52
+ def _get_first_non_none_value (
53
+ * configs : dict [str , Any ],
54
+ key : str ,
55
+ default : Any | None = None ,
56
+ callback : Callable [..., Any ] | None = None ,
57
+ ) -> Any :
58
+ """Get the first non-None value for a key from a list of dictionaries.
59
+
60
+ This function allows to prioritize information from many configurations by changing
61
+ the order of the inputs while also providing a default.
62
+
63
+ Examples
64
+ --------
65
+ >>> _get_first_non_none_value({"a": None}, {"a": 1}, key="a")
66
+ 1
67
+ >>> _get_first_non_none_value({"a": None}, {"a": None}, key="a", default="default")
68
+ 'default'
69
+ >>> _get_first_non_none_value({}, {}, key="a", default="default")
70
+ 'default'
71
+ >>> _get_first_non_none_value({"a": None}, {"a": "b"}, key="a")
72
+ 'b'
73
+
74
+ """
75
+ callback = (lambda x : x ) if callback is None else callback # noqa: E731
76
+ processed_values = (callback (config .get (key )) for config in configs )
77
+ return next ((value for value in processed_values if value is not None ), default )
0 commit comments