[issue1551113] random.choice(setinstance) fails
wim glenn
report at bugs.python.org
Wed May 8 04:49:45 CEST 2013
wim glenn added the comment:
The implementation suggested by the OP
def choice(self, seq):
"""Choose a random element from a non-empty
sequence."""
idx = int(self.random() * len(seq))
try:
result = seq[idx] # raises IndexError if seq
is empty
except TypeError:
result = list(seq)[idx]
return result
Is broken because input may be a dict with, for example, keys 0 1 and 7 - potentially causing the line result = seq[idx] to pass when logically it should raise. Rather it would be needed to determine from the input whether it was a non-sequence type collection, which sounds pretty hairy...
----------
nosy: +wim.glenn
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue1551113>
_______________________________________
More information about the Python-bugs-list
mailing list