python - 在 Python 中, `is not int` 会返回 false 吗?

标签 python argparse

我正在使用参数解析器来允许将端口号传递给我的程序。然后我尝试验证该值,第一个测试是 is int 测试:

    parser = argparse.ArgumentParser(description='Provides XML-RPC API.')
    parser.add_argument('--port', dest='port', default=9666, type=int,
                       help='port to listen on, 9666 by default.');
    args = parser.parse_args()

    if args.port is not int:
        raise TypeError("Port must be integer (%s given), use -h argument to get help."%(type(args.port).__name__))
    if args.port>=65536 or args.port<=0:
        raise IndexError("Port must be lower than 65536, 65535 is the maximum port number. Also, port can only be positive, non-zero number. Use -h argument to get help.")
    if args.port<=1204:
        print("Notice: ports up to 1024 are reserved to well known services, using this port numbers often leads to conflicts. Use -h argument to get help.")

现在无论我做什么,我都会得到错误:

Port must be integer (int given), use -h argument to get help.

我的意思是,这到底是怎么回事?甚至错误都说它是 int,这是怎么回事?

最佳答案

args.port is not int 将返回 False 如果 args.port 曾被设置为 int输入:

args.port = int
args.port is int  # True

或者您将 int 重新绑定(bind)到 args.port 已经绑定(bind)到的同一对象:

int = args.port
args.port is int  # True

那是因为 is 测试两个引用是否指向完全相同的对象。

也许您对如何测试对象的类型感到困惑,因为您使用了 isinstance() function ,或测试 type() 的输出:

type(args.port) is not int  # False if args.port is a different type
not isinstance(args.port, int)  # False if args.port is a different type and not a subclass either

这也永远不会是这种情况,因为您将 ArgumentParser 选项配置为仅接受整数:

parser.add_argument('--port', dest='port', default=9666, type=int,
                   help='port to listen on, 9666 by default.')

type=int 参数很重要,因为这意味着任何不能解释为整数的东西都将被解析器拒绝。你永远不会通过 parser.parse_args() 这里:

>>> import argparse
>>> parser = argparse.ArgumentParser(description='Provides XML-RPC API.')
>>> parser.add_argument('--port', dest='port', default=9666, type=int,
...                     help='port to listen on, 9666 by default.')
_StoreAction(option_strings=['--port'], dest='port', nargs=None, const=None, default=9666, type=<type 'int'>, choices=None, help='port to listen on, 9666 by default.', metavar=None)
>>> parser.parse_args(['--port', 'not an integer'])
usage: [-h] [--port PORT]
: error: argument --port: invalid int value: 'not an integer'

那是因为'not an integer'不能被int()函数转换;引发了一个 ValueError 并且 argparse 将其转换为错误消息:

>>> int('not an integer')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'not an integer'

您可以提供自己的限制范围的对话函数:

def portnumber(value):
    port = int(value)  # may raise ValueError
    if not 0 <= port <= 65536:
        raise ValueError('Not a valid port number')
    return port

然后将其用作类型:

parser.add_argument('--port', dest='port', default=9666, type=portnumber,
                   help='port to listen on, 9666 by default.')

关于python - 在 Python 中, `is not int` 会返回 false 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446040/

相关文章:

python - bokeh.charts 消失了 - 什么库可以制作交互式彩色散点图?

python - 如果存在可选参数,则不需要所有位置参数

python - 如何在不锁定的情况下在python中的多个进程之间共享字典

python - 如何将数据附加到现有的 LMDB?

python - 将 json 文件拆分成句子

Python:引发 argparse.ArgumentError 后,argparse 引发一般错误

python - 子解析器 argparse "error: too few arguments"

python - 如何使用多处理for循环?

Python argparse 子解析器 dest 参数不适用于父级

python - argparse - 禁止出现相同的参数