-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathutils.py
More file actions
83 lines (65 loc) · 2.54 KB
/
utils.py
File metadata and controls
83 lines (65 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""Module containing code to build automatically build the CL parser."""
import argparse
import importlib
import inspect
from inspect import signature
def add_arguments_from_signature(parser, obj, prefix="", exclude=[]):
"""Add arguments to parser base on obj default keyword parameters.
:meta private:
Args:
parser (ArgumentParser)): the argument parser to which we want to add arguments.
obj (type): the class from which we want to extract default parameters for the constructor.
prefix (str, Optional): prefix to add to created parser arguments.
exclude (list, Optional): list of arguments to be excluded.
"""
sig = signature(obj)
prefix = f"{prefix}-" if len(prefix) > 0 else ""
added_arguments = []
for p_name, p in sig.parameters.items():
if p.name not in exclude:
if p.kind == inspect._POSITIONAL_OR_KEYWORD:
arg_format = f"--{prefix}{p_name.replace('_', '-')}"
arg_kwargs = {"help": ""}
# check type int
if p.annotation is not inspect._empty:
arg_kwargs["type"] = p.annotation
arg_kwargs["help"] += f"Type[{p.annotation.__name__}]. "
# check default value
if p.default is not inspect._empty:
arg_kwargs["default"] = p.default
arg_kwargs["help"] += f"Defaults to '{str(p.default)}'. "
else:
arg_kwargs["required"] = True
parser.add_argument(
arg_format,
**arg_kwargs,
)
added_arguments.append(p_name)
return added_arguments
def str2bool(v):
"""Convert input string values to boolean.
:meta private:
"""
if isinstance(v, bool):
return v
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise argparse.ArgumentTypeError("Boolean value expected.")
def load_attr(str_full_module):
"""Loadd attribute from module.
Args:
str_full_module (str): string of the form ``{module_name}.{attr}``.
Returns:
Any: the attribute.
"""
if type(str_full_module) is str:
split_full = str_full_module.split(".")
str_module = ".".join(split_full[:-1])
str_attr = split_full[-1]
module = importlib.import_module(str_module)
return getattr(module, str_attr)
else:
return str_full_module