Reputation: 356
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?
Upvotes: 2
Views: 454
Reputation: 50076
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.
Upvotes: 2