[issue37319] Deprecate using random.randrange() with non-integers

Serhiy Storchaka report at bugs.python.org
Thu Jun 20 03:43:34 EDT 2019


Serhiy Storchaka <storchaka+cpython at gmail.com> added the comment:

Why this code uses int() at all? My guess is that it was added for earlier detection of user errors, otherwise the user could get a TypeError or AttributeError with unrelated message, or even a wrong result. int() is used just for type checking. But it is not good tool for this. int() does several different actions:

1. Parses string representation of integer.

2. Converts a real number to an integer with some truncation.

3. Losslessly converts an int-like number into an instance of int.

The first two options are not applicable here, so we need an additional check

        if istart != start:
            raise ValueError("non-integer arg 1 for randrange()")

And this is not perfect: for randrange('5') we get a ValueError instead of expected TypeError.

operator.index() is better tool for this.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue37319>
_______________________________________


More information about the Python-bugs-list mailing list