【问题标题】:Check whether variable is int or long in Python 2.7 and 3.x在 Python 2.7 和 3.x 中检查变量是 int 还是 long
【发布时间】:2019-01-24 08:41:24
【问题描述】:

我想对在 Python 2.7 及更高版本中工作的 API 函数进行输入类型检查。 API 采用自纪元以来以毫秒为单位的时间戳作为其参数。我需要确保输入是正数。

根据值,Python 2.7 将时间戳表示为integerlong。所以类型检查看起来像这样:

isinstance(timestamp, (int, long)) 

但是,long 类型在 Python 3 中与 int 合并。实际上,long 类型不再存在。所以上面的行会导致异常。相反,检查将如下所示:

isinstance(timestamp, int) 

为了与 Python 2.7 兼容,我尝试将时间戳转换为 int。但是,如果值超出 integer 范围,则转换操作仍会返回 long。这意味着对于Sun Jan 25 1970 20:31:23 之后的任何时间戳,检查都将失败。另请参阅this question 的答案。

要使它成为适用于两个 Python 版本的通用检查,最好的方法是什么?

【问题讨论】:

    标签: python python-3.x python-2.7


    【解决方案1】:

    检查任何整数,使用numbers.Integral:

    isinstance(timestamp, numbers.Integral)
    

    【讨论】:

      【解决方案2】:

      或关注此cheat sheet 获取python 2-3 兼容代码

      只需安装future 包:pip install future

      # Python2
      >>> x = 9999999999999999999999L
      >>> isinstance(x, int)
      False
      >>> from builtins import int
      >>> isinstance(x, int)
      True
      

      【讨论】:

        【解决方案3】:

        借用six 包:

        import sys
        
        PY3 = sys.version_info[0] == 3
        
        if PY3:
            integer_types = (int,)
        else:
            integer_types = (long, int)
        
        long_type = integer_types[0]
        

        然后你可以检查

        if isinstance(value, integer_types):
        

        并使用

        value = long_type(value)
        

        【讨论】:

          【解决方案4】:

          如果您想检查变量的类型是否完全等于 intgiven,那么只需使用type() 函数即可:

          import sys
          if sys.version_info >= (3,0):
              long = int
          
          type(v) in (int, long)
          

          【讨论】:

          • 使用 isinstance() 代替 type()。
          【解决方案5】:
          # This will works in both Python2, Python3
          # Just check type of the variable and compare
          import time
          timestamp = time.time()
          
          type(timestamp) == int
          type(timestamp) == float
          

          【讨论】:

            猜你喜欢
            • 2023-03-31
            • 2015-04-13
            • 2014-03-19
            • 1970-01-01
            • 2016-08-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-31
            相关资源
            最近更新 更多