Enchancement suggestion for argparse: intuit type from default

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Mar 14 13:53:25 CET 2012


On Wed, 14 Mar 2012 08:35:12 +1100, Ben Finney wrote:

> roy at panix.com (Roy Smith) writes:
> 
>> Using argparse, if I write:
>>
>>     parser.add_argument('--foo', default=100)
>>
>> it seems like it should be able to intuit that the type of foo should
>> be int (i.e. type(default))
> […]
> 
> -0.5.
> 
> That feels too magical to me. I don't see a need to special-case that
> usage. There's not much burden in being explicit for the argument type.

And yet you are programming in Python instead of Java, Pascal or Ada :)

It's not magic at all, it's science! Or to be precise, it's a very simple 
form of type inference, similar to (but much more basic than) that used 
by languages such as Go, Haskell, Ocaml, and ML.

http://en.wikipedia.org/wiki/Type_inference

Given the premise that arguments in argparser are typed, if the argument 
can take the value 100 (the default), it is logical that it can't be a 
string (because 100 is not a string) or a boolean (because 100 is not a 
boolean) or a list (because... well, you get the point).

What if you want an argument --foo that will accept arbitrary types? Then 
you would need some way to tell argparse not to infer the type from the 
default.

Python *names* are not typed, but objects are. Python infers the type of 
the object from its syntax. We write:

n = 100

and not:

n = int 100

Assuming that argparse arguments are typed, and that there is a way to 
over-rule the type-inference, there is no need to declare types in the 
common case. Explicit declarations should be used only for the uncommon 
cases where type inference cannot cope.



-- 
Steven



More information about the Python-list mailing list