0

我正在使用 Squish 框架为应用程序编写自动测试。在测试脚本中有代码调用randrange

a = 5.0
random.randrange( int(a) )

由于这个电话,我在网上lib/python2.6/random.py:171遇到了一个非常奇怪的错误:

TypeError: int() argument must be a string or a number, not 'int'

random.py 中的上下文,第 171 行是randrange函数中的第一行代码:

def randrange(self, start, stop=None, step=1, int=int, default=None,
              maxwidth=1L<<BPF):
    """Choose a random item from range(start, stop[, step]).

    This fixes the problem with randint() which includes the
    endpoint; in Python this is usually not what you want.
    Do not supply the 'int', 'default', and 'maxwidth' arguments.
    """

    # This code is a bit messy to make it fast for the
    # common case while still doing adequate error checking.
    istart = int(start)    # <---this is line 171
    if istart != start:
        raise ValueError, "non-integer arg 1 for randrange()"
    if stop is default:
        ...

当然我用调试器控制台检查过,类型确实是int

>>> __builtin__.type(start)
<type 'int'>
>>> 

经过一段时间的谷歌搜索后,我在 Squish API 文档中得到了答案:

Python 程序员应该知道,整数类型转换是int(x)行不通的;使用x = cast(x, int)orx = cast(x, "int") 代替。或者,如果您愿意,请执行import __builtin__,然后使用x = __builtin__.int(x). int(这是必要的,因为 Squish在 Python 中实现了它自己的对象。)

那么好吧。但我的问题是:如果存在名称冲突,如何检查 Python 对象类型?我怎么知道<type 'something'>是在哪里声明的?

4

1 回答 1

3

与其尝试追踪 的来源int,不如测试其行为:

import __builtin__

if not isinstance(int('0'), __builtin__.int):
    # uhoh, Squish replaced `int()` with a thoroughly broken version
    # replace it back for this module
    int = __builtin__.int
于 2013-11-26T17:58:52.577 回答