简体   繁体   中英

Argparse. nargs + not working when custom type

Usually I had an argument like this:

parser.add_argument(
    "--distances",
    nargs="+",
    type=int,
    default=[1, 2, 3],
)

Now I need to include +- np.inf, and my idea was to get the list as strings, and map 'inf' to np.inf for instance, like this:

mapper = {'inf': np.inf, '-inf': -np.inf}

def process_bins(distances: List[str]) -> List[float]:
    return [mapper[distance] if mapper.get(distance) else float(distance)
            for distance in distances
            ]
parser.add_argument(
        "--distances",
        nargs="+",
        type=process_bins,
        default=[-np.inf, 2, np.inf],
    )

But when I do this, the list distances becomes the first element, and it fails.

For instance if I call the script with --distances 1 2 3 , args.distances = '1'

What is happening?

The type is the converter for each element, not for all elements at once. It receives and should return only one element:

mapper = {'inf': np.inf, '-inf': -np.inf}

def process_bin(distances: str) -> float:
    return mapper.get(distance, float(str))

parser.add_argument(
        "--distances",
        nargs="+",
        type=process_bins,
        default=[-np.inf, 2, np.inf],
    )

Note that np.inf is equal to float('inf') – using type=float works just as well here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM