python - Why can you assign functions to type, const and default? -
i want understand why code works. why can give type
, const
, default
built-in function?
def printlist(i): print("integer:", i) return(i) def getparser(): argparse import argumentparser parser = argumentparser() parser.add_argument("integers", type=printlist, nargs="+") parser.add_argument("--sum", dest="accumulate", const=sum, default=max, nargs="?") return(parser) args = getparser().parse_args(["2", "3", "9", "5"]) print(args.integers) print(args.accumulate(args.integers))
output:
>>> integer: 2 >>> integer: 3 >>> integer: 9 >>> integer: 5 >>> ['2', '3', '9', '5'] >>> 9
i want understand why working.
edit:
you misunderstood me.
for example "type" expect see "type=int", because want allow integers. give "type" something. in example "type" gives "printlist" functions, can print it. or example "default". expect give value, liken int or str. give "default". in example give build-in function "max". why "max" list? why working? want know.
parser.add_argument("--sum", dest="accumulate", const=sum, default=max, nargs="?")
is, assuming don't supply argument '--sum'
, little bit like:
args.accumulate = sum if '--sum' in arg_list else max # ^ needs in right place!
per the docs nargs='?'
:
one argument consumed command line if possible, , produced single item. if no command-line argument present, value default produced. note optional arguments, there additional case - option string present not followed command-line argument. in case value const produced.
functions first-class objects in python, , can passed around other object, there's no reason can't used const
, default
.
note if did supply argument '--sum'
, args.accumulate
value instead:
>>> args = getparser().parse_args(["1", "--sum", "this one"]) ('integer:', '1') >>> args.accumulate 'this one'
Comments
Post a Comment