2013-11-26 43 views
0

我正在爲使用Squish框架的應用程序編寫自動測試。在測試腳本有代碼調用randrange如何判斷'<type'something'>`是在哪裏聲明的?

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

由於這個電話我得到線lib/python2.6/random.py:171一個非常錯誤的bizzare的結果:在random.py

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

背景下,線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'> 
>>> 

一段時間谷歌搜索得到的答覆擠流API文檔中後:

Python programmers should be aware that integer type conversions such as int(x) will not work; use x = cast(x, int) or x = cast(x, "int") instead. Or if you prefer, do import __builtin__ , and then use x = __builtin__.int(x) . (This is necessary because Squish implements its own int object in Python.)

所以,OK。但我的問題是:如果有名稱衝突如何檢查Python對象類型?我怎麼知道<type 'something'>是在哪裏申報的?

+0

爲什麼不直接使用'進口__builtin__',然後'random.randrange(__ __內置INT(A)。)'這裏?這對於普通的Python和Squish來說可以很好地工作。 –

回答

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 
+0

沒錯,最好用'isinstance'而不是'__builtin __。type'來檢查 – user2622016

+0

int'的重新定義的含義實際上是[在Squish文檔中提到的](http://doc.froglogic.com/squish/latest/ RGS-py.html#squish.int)。 –

+0

@FrerichRaabe:我在寫這個答案時搜索了那個信息;我不確定該文件是否在一年前可用。 –