Optparse with an integer argument

I find 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 some time, it turned out that my application does not work if the number is 0 , but this should be a 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 complicated?

+4
source share
2 answers

In Python, integers can be used as booleans, while any nonzero value is allowed for True and 0 to False . Therefore, if you want to check if the --number option is --number , you must check it for None (which would mean that the option is not set).

So:

 if options.number is not None: 

excellent.

+4
source

Also, consider using the argparse module instead of optparse, since the latter has been deprecated since Python 2.7. The final argparse documentation section focuses on updating optparse code:

http://docs.python.org/library/argparse.html

I do not know how this relates to your specific problem.

+2
source

Source: https://habr.com/ru/post/1389441/


All Articles