Search code examples
pythonoptparse

Optparse with integer argument


I hit the following interesting error:

parser.add_option("-n", "--number", metavar="NUMBER", type="int", 
                  help="number is NUMBER")
(options, args) = parser.parse_args()

if options.number: # User added a number
  do something
  exit(0)

After a while I found out that my application does not work if the number is 0 but this should be valid number (it should be >= 0). The problem is that 0 is False.

should I change it to:

if options.number is not None:

or something more sophisticated?


Solution

  • In Python, integers can be used as boolean values, whereas anything non-zero is resolved to True and 0 to False. So if you want to check if the option --number is set, you have to check against None (which would mean, that the option is not set).

    So:

    if options.number is not None:
    

    is perfectly fine.