-
-
Save pobocks/bff0bea494f2b7ec7eba1e8ae281b888 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Here are some actually-real situations where I've wanted this: | |
## set (dedup args) | |
parser.add_argument('foo', nargs="+", type=int, colltype=set) | |
parser.parse_args(['1','1','2','2','3','3','3']) | |
# Namespace(foo={1,2,3}) | |
## sorted (sort args) | |
parser.add_argument('foo', nargs="+", type=int, colltype=sorted) | |
parser.parse_args(['10', '5', '30', '14']) | |
# Namespace(foo=[5, 10, 14, 30]) | |
## tuple (avoid mutable object!) | |
parser.add_argument('foo', type=int, colltype=tuple) | |
parser.parse_args(['1','2']) | |
# Namespace(foo=(1,2,)) | |
## Ranges (I'd like to at-parse-time check that a <= b) | |
def fwds_range(args): | |
if args[0] > args[1]: | |
raise ArgumentTypeError("beginning of range must be smaller than end") | |
return range(*args) | |
parser.add_argument('foo', nargs=2, type=int, colltype=fwds_range) | |
parser.parse_args(['5','10']) | |
# This has broader applications for any case where args have some kind of | |
# relation to each other that should be enforced | |
## Dates: Give a date or time as parts and then collect them all into a date) | |
from datetime import date | |
parser.add_argument('foo', nargs=3, type=int, colltype=lambda d: date(*d)) | |
parser.parse_args(['2011', '12', '2']) | |
# Namespace(foo=datetime.Date(2011,12,2)) | |
## Key value pairs where the value has a different type | |
def kv(args): | |
if len(args) % 2 != 0: | |
raise ArgumentTypeError("number of arguments for foo must be even") | |
return {str(k):int(v) for k,v in zip(*[iter(args)] * 2)} | |
parser.add_argument('foo', nargs='+', colltype=kw) | |
parser.parse_args(["bar", "3", "baz", "2"]) | |
# Namespace(foo={'bar': 3, 'baz': 2}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment