Question

I am writing automatic tests for an application using Squish framework. In test script there is code calling randrange:

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

As a result of this call I get on line lib/python2.6/random.py:171 a really bizzare error:

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

Context in random.py, line 171 is the first line of code in the randrange function:

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:
        ...

Of course I checked with the debugger console, the type indeed is int:

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

After a while of googling I got the answer in Squish API documentation:

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.)

So, OK. But my question is: How to check in Python object type if there is a name conflict? How can I tell where the <type 'something'> was declared?

Was it helpful?

Solution

Instead of trying to trace the origin of int, test for its behaviour:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top