In this issue I am looking for a neat way of adopting/utilising the choices capability from ArgParse so my positional and or keyword arguments can be decorated with a fixed set of choices.
One approach that may work is to add an additional interface to begin which allows us to wrap "choices" into the function decorator. Here is my prototype code:
@begin.choices(arg=('foo', 'moo', 'cow'))
Now when we violate these choices we get the following behaviour:
> python test.py blad
usage: test.py [-h] ARG
test.py: error: argument ARG: invalid choice: 'blad' (choose from 'foo', 'moo',
Post coffee / lunch, an alternative strategy to the above solution could be to implicitly treat the default value of an arg as its set of choices iff the value has a baseclass of set.
def main(arg=set('foo', 'moo', 'cow')):
If the arg default value has a baseclass of set, treat it as the set of choices for that arg.
Thanks, this design looks quite solid. It's definately the best solution I've seen so far for supporting choices. Although I'm not (yet) sold on using a default value that's a set instance as the choice of values. That interferes with the design goal of being able to call the function directly from code. Failing to pass in a value would result in non-deterministic errors rather than a consistent TypeError over a missing argument.
Agree on not using implicit set solution, it breaks one of the fundamental awesome features of begins that is to be able to call the interface as it were a normal function.
Example solution using begin.convert
This nearly works out of the box with enum.Enum introduced in 3.4. Example: https://gist.github.com/evanunderscore/3a621f3f5c810b1444c7
Note that main(Choices.bar) would work if #57 ends up being fixed.
Sample solution here: https://github.com/evanunderscore/begins/tree/enums
I added an examples folder with a runnable example showing explicit and automatic enum types. Thoughts?