Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4fe0020

Browse files
authored
bpo-40325: Deprecate set object support in random.sample() (GH-19591)
1 parent 482259d commit 4fe0020

File tree

4 files changed

+17
-2
lines changed

4 files changed

+17
-2
lines changed

Doc/library/random.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,13 @@ Functions for sequences
230230
If the sample size is larger than the population size, a :exc:`ValueError`
231231
is raised.
232232

233+
.. deprecated:: 3.9
234+
In the future, the *population* must be a sequence. Instances of
235+
:class:`set` are no longer supported. The set must first be converted
236+
to a :class:`list` or :class:`tuple`, preferably in a deterministic
237+
order so that the sample is reproducible.
238+
239+
233240
Real-valued distributions
234241
-------------------------
235242

Lib/random.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,9 +367,12 @@ def sample(self, population, k):
367367
# causing them to eat more entropy than necessary.
368368

369369
if isinstance(population, _Set):
370+
_warn('Sampling from a set deprecated\n'
371+
'since Python 3.9 and will be removed in a subsequent version.',
372+
DeprecationWarning, 2)
370373
population = tuple(population)
371374
if not isinstance(population, _Sequence):
372-
raise TypeError("Population must be a sequence or set. For dicts, use list(d).")
375+
raise TypeError("Population must be a sequence. For dicts or sets, use sorted(d).")
373376
randbelow = self._randbelow
374377
n = len(population)
375378
if not 0 <= k <= n:

Lib/test/test_random.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,6 @@ def test_sample_distribution(self):
147147

148148
def test_sample_inputs(self):
149149
# SF bug #801342 -- population can be any iterable defining __len__()
150-
self.gen.sample(set(range(20)), 2)
151150
self.gen.sample(range(20), 2)
152151
self.gen.sample(range(20), 2)
153152
self.gen.sample(str('abcdefghijklmnopqrst'), 2)
@@ -156,6 +155,11 @@ def test_sample_inputs(self):
156155
def test_sample_on_dicts(self):
157156
self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2)
158157

158+
def test_sample_on_sets(self):
159+
with self.assertWarns(DeprecationWarning):
160+
population = {10, 20, 30, 40, 50, 60, 70}
161+
self.gen.sample(population, k=5)
162+
159163
def test_choices(self):
160164
choices = self.gen.choices
161165
data = ['red', 'green', 'blue', 'yellow']
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Deprecated support for set objects in random.sample().

0 commit comments

Comments
 (0)