Skip to content

Commit

Permalink
type inferencer
Browse files Browse the repository at this point in the history
  • Loading branch information
dhpitt committed Feb 9, 2024
1 parent c6c429a commit 19f1d17
Showing 1 changed file with 5 additions and 11 deletions.
16 changes: 5 additions & 11 deletions src/configmypy/argparse_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from .bunch import Bunch
from .utils import iter_nested_dict_flat
from .utils import update_nested_dict_from_flat
from .type_inference import infer_numeric, infer_boolean
from .type_inference import TypeInferencer

class ArgparseConfig:
"""Read config from the command-line using argparse
Expand Down Expand Up @@ -61,16 +61,10 @@ def read_conf(self, config=None, **additional_config):

parser = argparse.ArgumentParser(description='Read the config from the commandline.')
for key, value in iter_nested_dict_flat(config, return_intermediate_keys=self.overwrite_nested_config):
if self.infer_types and value is not None:
# use type inferencing callable if available, otherwise strictly infer type
if type(value) == int or type(value) == float:
parser.add_argument(f'--{key}', type=infer_numeric, default=value)
elif type(value) == bool:
parser.add_argument(f'--{key}', type=infer_boolean, default=value)
else:
parser.add_argument(f'--{key}', type=type(value), default=value)
else:
parser.add_argument(f'--{key}', default=value)
# smartly infer types if
inferencer = TypeInferencer(orig_type=type(value), strict=(not self.infer_types))

parser.add_argument(f'--{key}', type=inferencer, default=value)

args = parser.parse_args()
self.config = Bunch(args.__dict__)
Expand Down

0 comments on commit 19f1d17

Please sign in to comment.