簡體   English   中英

我如何知道` <type 'something'> `被宣布了嗎?

[英]How can I tell where the `<type 'something'>` was declared?

我正在使用Squish框架為應用程序編寫自動測試。 在測試腳本中,有調用randrange代碼:

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

調用的結果是,我在lib/python2.6/random.py:171行上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'>聲明位置?

與其嘗試跟蹤int的起源, 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM