File size: 1,256 Bytes
ac59957
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import argparse


def json_to_args(json_path: str) -> argparse.Namespace:
    """Convert JSON configuration file to argparse.Namespace object.

    Parameters
    ----------
    json_path : str
        Path to the JSON configuration file.

    Returns
    -------
    argparse.Namespace
        Namespace object containing configuration parameters.
    """
    args = argparse.Namespace()

    with open(json_path, "r") as f:
        data = json.load(f)
    args.__dict__.update(data)
    return args


def parse_args(parser: argparse.ArgumentParser) -> argparse.Namespace:
    """Parse command line arguments and merge them with JSON configuration.

    This function first parses command line arguments, then loads configuration
    from a JSON file specified by the 'cfg' argument, and finally merges both
    configurations with command line arguments taking precedence.

    Parameters
    ----------
    parser : argparse.ArgumentParser
        Argument parser instance with defined arguments.

    Returns
    -------
    argparse.Namespace
        Merged configuration from both command line and JSON file.
    """
    entry = parser.parse_args()
    args = json_to_args(entry.cfg)
    args.__dict__.update(vars(entry))
    return args