I am writing a small simulation in python, which is supposed to aggregate results in different ways depending on command line arguments.
Once the simulation has run and the Simulation object contains the raw results, I want to use the Simulation.sample(list_of_objects) method or the Simulation.sample_differently() method to generate some outputs for each specified sampler. list_of_objects should either be a range(N) or a list explicitly specified on the command line.
For example, I would like the following calculations to happen.
$ simulation --sample 5
[Simulation.sample(range(5))]
$ simulation --sample-objects 0 1 2 3 a
[Simulation.sample([0, 1, 2, 3, "a"])]
$ simulation --sample 4 --sample-objects 1 3 "b"
[Simulation.sample(range(4)), Simulation.sample([1, 3, "b"])]
$ simulation --sample-differently --sample-objects 1
[Simulation.sample_differently(), Simulation.sample([1])]
$ simulation --sample-objects 0 1 2 --sample-objects 3 4
[Simulation.sample([0, 1, 2]), Simulation.sample([3, 4])]
I thought I would do it as follows.
def parse_objects_to_sampler(object_strings):
objects = []
for entry in object_strings:
try:
objects.append(int(entry))
except ValueError:
objects.append(entry)
return lambda simulation: simulation.sample(objects))
parser = argparse.ArgumentParser()
parser.add_argument(
"--sample", action=append,
type=lambda x: lambda simulation: simulation.sample(range(int(x))))
parser.add_argument(
"--sample-differently", action="append_const", dest="sample",
const=Simulation.sample_differently)
parser.add_argument(
"--sample-objects", nargs="*", action="append", dest="sample",
type=parse_objects_to_sampler)
for sampler in parser.parse().sample:
sampler(Simulation)
Unfortunately, the type constructor operates on each individual command line argument, not on the list of several of them generated for nargs≠None, so the approach above does not work.
What is the best pythonic way to achieve the behaviour sketched above?