Add some useful argument types#1522
Conversation
|
@BillTompkins Hey Bill, its nice to make your acquaintance. Most large That being said, I think this does provide an excellent example for how to do this sort of thing which would be of use to many What would you think about moving this to the |
60b7123 to
9365da7
Compare
Sure, I think that makes sense, I'll put that together. |
- integer: like 'int', but accepts arbitrary bases (i.e. 0x10), and optional suffix like "10K" or "64Mi" - hexadecimal: base 16 integer, with nicer error text than using a lambda - Range: integer from specified range, when that may be too large for 'choices' - IntSet: set of integers from specified range
9365da7 to
5410c4c
Compare
|
@BillTompkins Thanks for the PR! |
Hi! I've made a collection of a few utility argument types that I've found useful over the years. I think it would be useful to have them in
cmd2itself so users can find them easily and not re-invent this wheel.integer
Usage
Failures
Limitations
Because the base can be specified, Python does not allow a leading zero. This avoids confusion where a user might expect the "C" behavior of that specifying an octal value, or expect the "normal" behavior of ignoring the leading zero.
The default
intconstructor only uses decimal, so allows the leading zero.Notes
It is tempting to allow a "B" after the suffixes, since my typical use case has been specifying sizes in bytes, but I suspect there would be other similar special cases.
hexadecimal
Usage
Failures
Note
We could avoid having a standalone function for this, and instead the user could use:
Unfortunately, the error text then becomes
Similarly for other one-liner strategies using partial evaluation.
Range
Usage
Failures
Notes
type=int, choices=range(5)works well, but it becomes unwieldy for large ranges of valid values.rangebuilt-in), and is compact.IntSet
Allows the user to specify multiple values from within a range, in a flexible format.
Usage
Errors
Notes
yield/yield fromto return an iterable without constructing a list. Unfortunately, then the value checks are only performed when the iteration is done by the user code, not when the argument is being parsed. So we would need another function/generator to do the yielding, returned by this function after the parsing. It's not that much extra code, but it seems like an unlikely corner case that the user would be specifying a range so large that this matters.set, and there is no uniqueness check on the values. But I don't really likeIntListany more thanIntSet.__repr__, we could aim for error text likeError: argument value: invalid set of values from [0..99] value:'100'but I was trying to stay a little closer to the spirit of__repr__P.S.
Thanks for all the work on cmd2! I've used it several times over the years for internal tools, and users are always so impressed with the polish (esp. help and tab completion). I've glued in
richin the past and have been looking forward to 3.0, I think that'll be great.