如何判断`<type'something'=“”>`的声明在哪里?</type>

时间:2013-11-26 17:53:22

标签: python built-in object-type squish

我正在使用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)x = cast(x, "int")   代替。或者,如果您愿意,请执行import __builtin__,然后使用x = __builtin__.int(x)。 (这是必要的,因为Squish在Python中实现了自己的int对象。)

所以,好的。但我的问题是:如果存在名称冲突,如何检查Python对象类型?如何判断<type 'something'>的宣告位置?

1 个答案:

答案 0 :(得分: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