UnicodeDecodeError when importing random? (running with -U)

Robert Kern robert.kern at gmail.com
Fri Apr 13 06:59:23 CEST 2007

Ben wrote:
> Is the following a known bug?
> [temp]$  python -U
> Python 2.4.4 (#1, Oct 23 2006, 13:58:18)
> [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import random
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "/usr/lib64/python2.4/random.py", line 834, in ?
>     _inst = Random()
>   File "/usr/lib64/python2.4/random.py", line 94, in __init__
>     self.seed(x)
>   File "/usr/lib64/python2.4/random.py", line 108, in seed
>     a = long(_hexlify(_urandom(16)), 16)
>   File "/usr/lib64/python2.4/os.py", line 723, in urandom
>     bytes += read(_urandomfd, n - len(bytes))
> UnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in position
> 0: ordinal not in range(128)

It's unsurprising, certainly. It's not a bug in 2.4, though. -U is for
experimentation only, not for actual use. Python will change to only using
Unicode strings in 3.0, but not before then. Python 3.0 will add a bytes type to
replace non-text strings like those read from /dev/urandom in that piece of
code. os.urandom() and the random module will have to be modified to use it
instead of a string. Looking at the Python 3.0 branch, I see that this hasn't
quite happened, yet.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

More information about the Python-list mailing list