Fix-up the enumerate type example and move it to the end.
[python.git] / Objects / setobject.c
blobb379845d7a979f6bbddeea27b79d14597045cfb4
2 /* set object implementation
3 Written and maintained by Raymond D. Hettinger <python@rcn.com>
4 Derived from Lib/sets.py and Objects/dictobject.c.
6 Copyright (c) 2003-2007 Python Software Foundation.
7 All rights reserved.
8 */
10 #include "Python.h"
11 #include "structmember.h"
13 /* Set a key error with the specified argument, wrapping it in a
14 * tuple automatically so that tuple keys are not unpacked as the
15 * exception arguments. */
16 static void
17 set_key_error(PyObject *arg)
19 PyObject *tup;
20 tup = PyTuple_Pack(1, arg);
21 if (!tup)
22 return; /* caller will expect error to be set anyway */
23 PyErr_SetObject(PyExc_KeyError, tup);
24 Py_DECREF(tup);
27 /* This must be >= 1. */
28 #define PERTURB_SHIFT 5
30 /* Object used as dummy key to fill deleted entries */
31 static PyObject *dummy = NULL; /* Initialized by first call to make_new_set() */
33 #ifdef Py_REF_DEBUG
34 PyObject *
35 _PySet_Dummy(void)
37 return dummy;
39 #endif
41 #define INIT_NONZERO_SET_SLOTS(so) do { \
42 (so)->table = (so)->smalltable; \
43 (so)->mask = PySet_MINSIZE - 1; \
44 (so)->hash = -1; \
45 } while(0)
47 #define EMPTY_TO_MINSIZE(so) do { \
48 memset((so)->smalltable, 0, sizeof((so)->smalltable)); \
49 (so)->used = (so)->fill = 0; \
50 INIT_NONZERO_SET_SLOTS(so); \
51 } while(0)
53 /* Reuse scheme to save calls to malloc, free, and memset */
54 #ifndef PySet_MAXFREELIST
55 #define PySet_MAXFREELIST 80
56 #endif
57 static PySetObject *free_list[PySet_MAXFREELIST];
58 static int numfree = 0;
61 The basic lookup function used by all operations.
62 This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
63 Open addressing is preferred over chaining since the link overhead for
64 chaining would be substantial (100% with typical malloc overhead).
66 The initial probe index is computed as hash mod the table size. Subsequent
67 probe indices are computed as explained in Objects/dictobject.c.
69 All arithmetic on hash should ignore overflow.
71 Unlike the dictionary implementation, the lookkey functions can return
72 NULL if the rich comparison returns an error.
75 static setentry *
76 set_lookkey(PySetObject *so, PyObject *key, register long hash)
78 register Py_ssize_t i;
79 register size_t perturb;
80 register setentry *freeslot;
81 register size_t mask = so->mask;
82 setentry *table = so->table;
83 register setentry *entry;
84 register int cmp;
85 PyObject *startkey;
87 i = hash & mask;
88 entry = &table[i];
89 if (entry->key == NULL || entry->key == key)
90 return entry;
92 if (entry->key == dummy)
93 freeslot = entry;
94 else {
95 if (entry->hash == hash) {
96 startkey = entry->key;
97 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
98 if (cmp < 0)
99 return NULL;
100 if (table == so->table && entry->key == startkey) {
101 if (cmp > 0)
102 return entry;
104 else {
105 /* The compare did major nasty stuff to the
106 * set: start over.
108 return set_lookkey(so, key, hash);
111 freeslot = NULL;
114 /* In the loop, key == dummy is by far (factor of 100s) the
115 least likely outcome, so test for that last. */
116 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
117 i = (i << 2) + i + perturb + 1;
118 entry = &table[i & mask];
119 if (entry->key == NULL) {
120 if (freeslot != NULL)
121 entry = freeslot;
122 break;
124 if (entry->key == key)
125 break;
126 if (entry->hash == hash && entry->key != dummy) {
127 startkey = entry->key;
128 cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
129 if (cmp < 0)
130 return NULL;
131 if (table == so->table && entry->key == startkey) {
132 if (cmp > 0)
133 break;
135 else {
136 /* The compare did major nasty stuff to the
137 * set: start over.
139 return set_lookkey(so, key, hash);
142 else if (entry->key == dummy && freeslot == NULL)
143 freeslot = entry;
145 return entry;
149 * Hacked up version of set_lookkey which can assume keys are always strings;
150 * This means we can always use _PyString_Eq directly and not have to check to
151 * see if the comparison altered the table.
153 static setentry *
154 set_lookkey_string(PySetObject *so, PyObject *key, register long hash)
156 register Py_ssize_t i;
157 register size_t perturb;
158 register setentry *freeslot;
159 register size_t mask = so->mask;
160 setentry *table = so->table;
161 register setentry *entry;
163 /* Make sure this function doesn't have to handle non-string keys,
164 including subclasses of str; e.g., one reason to subclass
165 strings is to override __eq__, and for speed we don't cater to
166 that here. */
167 if (!PyString_CheckExact(key)) {
168 so->lookup = set_lookkey;
169 return set_lookkey(so, key, hash);
171 i = hash & mask;
172 entry = &table[i];
173 if (entry->key == NULL || entry->key == key)
174 return entry;
175 if (entry->key == dummy)
176 freeslot = entry;
177 else {
178 if (entry->hash == hash && _PyString_Eq(entry->key, key))
179 return entry;
180 freeslot = NULL;
183 /* In the loop, key == dummy is by far (factor of 100s) the
184 least likely outcome, so test for that last. */
185 for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
186 i = (i << 2) + i + perturb + 1;
187 entry = &table[i & mask];
188 if (entry->key == NULL)
189 return freeslot == NULL ? entry : freeslot;
190 if (entry->key == key
191 || (entry->hash == hash
192 && entry->key != dummy
193 && _PyString_Eq(entry->key, key)))
194 return entry;
195 if (entry->key == dummy && freeslot == NULL)
196 freeslot = entry;
198 assert(0); /* NOT REACHED */
199 return 0;
203 Internal routine to insert a new key into the table.
204 Used by the public insert routine.
205 Eats a reference to key.
207 static int
208 set_insert_key(register PySetObject *so, PyObject *key, long hash)
210 register setentry *entry;
211 typedef setentry *(*lookupfunc)(PySetObject *, PyObject *, long);
213 assert(so->lookup != NULL);
214 entry = so->lookup(so, key, hash);
215 if (entry == NULL)
216 return -1;
217 if (entry->key == NULL) {
218 /* UNUSED */
219 so->fill++;
220 entry->key = key;
221 entry->hash = hash;
222 so->used++;
223 } else if (entry->key == dummy) {
224 /* DUMMY */
225 entry->key = key;
226 entry->hash = hash;
227 so->used++;
228 Py_DECREF(dummy);
229 } else {
230 /* ACTIVE */
231 Py_DECREF(key);
233 return 0;
237 Internal routine used by set_table_resize() to insert an item which is
238 known to be absent from the set. This routine also assumes that
239 the set contains no deleted entries. Besides the performance benefit,
240 using set_insert_clean() in set_table_resize() is dangerous (SF bug #1456209).
241 Note that no refcounts are changed by this routine; if needed, the caller
242 is responsible for incref'ing `key`.
244 static void
245 set_insert_clean(register PySetObject *so, PyObject *key, long hash)
247 register size_t i;
248 register size_t perturb;
249 register size_t mask = (size_t)so->mask;
250 setentry *table = so->table;
251 register setentry *entry;
253 i = hash & mask;
254 entry = &table[i];
255 for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) {
256 i = (i << 2) + i + perturb + 1;
257 entry = &table[i & mask];
259 so->fill++;
260 entry->key = key;
261 entry->hash = hash;
262 so->used++;
266 Restructure the table by allocating a new table and reinserting all
267 keys again. When entries have been deleted, the new table may
268 actually be smaller than the old one.
270 static int
271 set_table_resize(PySetObject *so, Py_ssize_t minused)
273 Py_ssize_t newsize;
274 setentry *oldtable, *newtable, *entry;
275 Py_ssize_t i;
276 int is_oldtable_malloced;
277 setentry small_copy[PySet_MINSIZE];
279 assert(minused >= 0);
281 /* Find the smallest table size > minused. */
282 for (newsize = PySet_MINSIZE;
283 newsize <= minused && newsize > 0;
284 newsize <<= 1)
286 if (newsize <= 0) {
287 PyErr_NoMemory();
288 return -1;
291 /* Get space for a new table. */
292 oldtable = so->table;
293 assert(oldtable != NULL);
294 is_oldtable_malloced = oldtable != so->smalltable;
296 if (newsize == PySet_MINSIZE) {
297 /* A large table is shrinking, or we can't get any smaller. */
298 newtable = so->smalltable;
299 if (newtable == oldtable) {
300 if (so->fill == so->used) {
301 /* No dummies, so no point doing anything. */
302 return 0;
304 /* We're not going to resize it, but rebuild the
305 table anyway to purge old dummy entries.
306 Subtle: This is *necessary* if fill==size,
307 as set_lookkey needs at least one virgin slot to
308 terminate failing searches. If fill < size, it's
309 merely desirable, as dummies slow searches. */
310 assert(so->fill > so->used);
311 memcpy(small_copy, oldtable, sizeof(small_copy));
312 oldtable = small_copy;
315 else {
316 newtable = PyMem_NEW(setentry, newsize);
317 if (newtable == NULL) {
318 PyErr_NoMemory();
319 return -1;
323 /* Make the set empty, using the new table. */
324 assert(newtable != oldtable);
325 so->table = newtable;
326 so->mask = newsize - 1;
327 memset(newtable, 0, sizeof(setentry) * newsize);
328 so->used = 0;
329 i = so->fill;
330 so->fill = 0;
332 /* Copy the data over; this is refcount-neutral for active entries;
333 dummy entries aren't copied over, of course */
334 for (entry = oldtable; i > 0; entry++) {
335 if (entry->key == NULL) {
336 /* UNUSED */
338 } else if (entry->key == dummy) {
339 /* DUMMY */
340 --i;
341 assert(entry->key == dummy);
342 Py_DECREF(entry->key);
343 } else {
344 /* ACTIVE */
345 --i;
346 set_insert_clean(so, entry->key, entry->hash);
350 if (is_oldtable_malloced)
351 PyMem_DEL(oldtable);
352 return 0;
355 /* CAUTION: set_add_key/entry() must guarantee it won't resize the table */
357 static int
358 set_add_entry(register PySetObject *so, setentry *entry)
360 register Py_ssize_t n_used;
362 assert(so->fill <= so->mask); /* at least one empty slot */
363 n_used = so->used;
364 Py_INCREF(entry->key);
365 if (set_insert_key(so, entry->key, entry->hash) == -1) {
366 Py_DECREF(entry->key);
367 return -1;
369 if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2))
370 return 0;
371 return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
374 static int
375 set_add_key(register PySetObject *so, PyObject *key)
377 register long hash;
378 register Py_ssize_t n_used;
380 if (!PyString_CheckExact(key) ||
381 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
382 hash = PyObject_Hash(key);
383 if (hash == -1)
384 return -1;
386 assert(so->fill <= so->mask); /* at least one empty slot */
387 n_used = so->used;
388 Py_INCREF(key);
389 if (set_insert_key(so, key, hash) == -1) {
390 Py_DECREF(key);
391 return -1;
393 if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2))
394 return 0;
395 return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
398 #define DISCARD_NOTFOUND 0
399 #define DISCARD_FOUND 1
401 static int
402 set_discard_entry(PySetObject *so, setentry *oldentry)
403 { register setentry *entry;
404 PyObject *old_key;
406 entry = (so->lookup)(so, oldentry->key, oldentry->hash);
407 if (entry == NULL)
408 return -1;
409 if (entry->key == NULL || entry->key == dummy)
410 return DISCARD_NOTFOUND;
411 old_key = entry->key;
412 Py_INCREF(dummy);
413 entry->key = dummy;
414 so->used--;
415 Py_DECREF(old_key);
416 return DISCARD_FOUND;
419 static int
420 set_discard_key(PySetObject *so, PyObject *key)
422 register long hash;
423 register setentry *entry;
424 PyObject *old_key;
426 assert (PyAnySet_Check(so));
427 if (!PyString_CheckExact(key) ||
428 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
429 hash = PyObject_Hash(key);
430 if (hash == -1)
431 return -1;
433 entry = (so->lookup)(so, key, hash);
434 if (entry == NULL)
435 return -1;
436 if (entry->key == NULL || entry->key == dummy)
437 return DISCARD_NOTFOUND;
438 old_key = entry->key;
439 Py_INCREF(dummy);
440 entry->key = dummy;
441 so->used--;
442 Py_DECREF(old_key);
443 return DISCARD_FOUND;
446 static int
447 set_clear_internal(PySetObject *so)
449 setentry *entry, *table;
450 int table_is_malloced;
451 Py_ssize_t fill;
452 setentry small_copy[PySet_MINSIZE];
453 #ifdef Py_DEBUG
454 Py_ssize_t i, n;
455 assert (PyAnySet_Check(so));
457 n = so->mask + 1;
458 i = 0;
459 #endif
461 table = so->table;
462 assert(table != NULL);
463 table_is_malloced = table != so->smalltable;
465 /* This is delicate. During the process of clearing the set,
466 * decrefs can cause the set to mutate. To avoid fatal confusion
467 * (voice of experience), we have to make the set empty before
468 * clearing the slots, and never refer to anything via so->ref while
469 * clearing.
471 fill = so->fill;
472 if (table_is_malloced)
473 EMPTY_TO_MINSIZE(so);
475 else if (fill > 0) {
476 /* It's a small table with something that needs to be cleared.
477 * Afraid the only safe way is to copy the set entries into
478 * another small table first.
480 memcpy(small_copy, table, sizeof(small_copy));
481 table = small_copy;
482 EMPTY_TO_MINSIZE(so);
484 /* else it's a small table that's already empty */
486 /* Now we can finally clear things. If C had refcounts, we could
487 * assert that the refcount on table is 1 now, i.e. that this function
488 * has unique access to it, so decref side-effects can't alter it.
490 for (entry = table; fill > 0; ++entry) {
491 #ifdef Py_DEBUG
492 assert(i < n);
493 ++i;
494 #endif
495 if (entry->key) {
496 --fill;
497 Py_DECREF(entry->key);
499 #ifdef Py_DEBUG
500 else
501 assert(entry->key == NULL);
502 #endif
505 if (table_is_malloced)
506 PyMem_DEL(table);
507 return 0;
511 * Iterate over a set table. Use like so:
513 * Py_ssize_t pos;
514 * setentry *entry;
515 * pos = 0; # important! pos should not otherwise be changed by you
516 * while (set_next(yourset, &pos, &entry)) {
517 * Refer to borrowed reference in entry->key.
520 * CAUTION: In general, it isn't safe to use set_next in a loop that
521 * mutates the table.
523 static int
524 set_next(PySetObject *so, Py_ssize_t *pos_ptr, setentry **entry_ptr)
526 Py_ssize_t i;
527 Py_ssize_t mask;
528 register setentry *table;
530 assert (PyAnySet_Check(so));
531 i = *pos_ptr;
532 assert(i >= 0);
533 table = so->table;
534 mask = so->mask;
535 while (i <= mask && (table[i].key == NULL || table[i].key == dummy))
536 i++;
537 *pos_ptr = i+1;
538 if (i > mask)
539 return 0;
540 assert(table[i].key != NULL);
541 *entry_ptr = &table[i];
542 return 1;
545 static void
546 set_dealloc(PySetObject *so)
548 register setentry *entry;
549 Py_ssize_t fill = so->fill;
550 PyObject_GC_UnTrack(so);
551 Py_TRASHCAN_SAFE_BEGIN(so)
552 if (so->weakreflist != NULL)
553 PyObject_ClearWeakRefs((PyObject *) so);
555 for (entry = so->table; fill > 0; entry++) {
556 if (entry->key) {
557 --fill;
558 Py_DECREF(entry->key);
561 if (so->table != so->smalltable)
562 PyMem_DEL(so->table);
563 if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so))
564 free_list[numfree++] = so;
565 else
566 Py_TYPE(so)->tp_free(so);
567 Py_TRASHCAN_SAFE_END(so)
570 static int
571 set_tp_print(PySetObject *so, FILE *fp, int flags)
573 setentry *entry;
574 Py_ssize_t pos=0;
575 char *emit = ""; /* No separator emitted on first pass */
576 char *separator = ", ";
577 int status = Py_ReprEnter((PyObject*)so);
579 if (status != 0) {
580 if (status < 0)
581 return status;
582 Py_BEGIN_ALLOW_THREADS
583 fprintf(fp, "%s(...)", so->ob_type->tp_name);
584 Py_END_ALLOW_THREADS
585 return 0;
588 Py_BEGIN_ALLOW_THREADS
589 fprintf(fp, "%s([", so->ob_type->tp_name);
590 Py_END_ALLOW_THREADS
591 while (set_next(so, &pos, &entry)) {
592 Py_BEGIN_ALLOW_THREADS
593 fputs(emit, fp);
594 Py_END_ALLOW_THREADS
595 emit = separator;
596 if (PyObject_Print(entry->key, fp, 0) != 0) {
597 Py_ReprLeave((PyObject*)so);
598 return -1;
601 Py_BEGIN_ALLOW_THREADS
602 fputs("])", fp);
603 Py_END_ALLOW_THREADS
604 Py_ReprLeave((PyObject*)so);
605 return 0;
608 static PyObject *
609 set_repr(PySetObject *so)
611 PyObject *keys, *result=NULL, *listrepr;
612 int status = Py_ReprEnter((PyObject*)so);
614 if (status != 0) {
615 if (status < 0)
616 return NULL;
617 return PyString_FromFormat("%s(...)", so->ob_type->tp_name);
620 keys = PySequence_List((PyObject *)so);
621 if (keys == NULL)
622 goto done;
623 listrepr = PyObject_Repr(keys);
624 Py_DECREF(keys);
625 if (listrepr == NULL)
626 goto done;
628 result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name,
629 PyString_AS_STRING(listrepr));
630 Py_DECREF(listrepr);
631 done:
632 Py_ReprLeave((PyObject*)so);
633 return result;
636 static Py_ssize_t
637 set_len(PyObject *so)
639 return ((PySetObject *)so)->used;
642 static int
643 set_merge(PySetObject *so, PyObject *otherset)
645 PySetObject *other;
646 register Py_ssize_t i;
647 register setentry *entry;
649 assert (PyAnySet_Check(so));
650 assert (PyAnySet_Check(otherset));
652 other = (PySetObject*)otherset;
653 if (other == so || other->used == 0)
654 /* a.update(a) or a.update({}); nothing to do */
655 return 0;
656 /* Do one big resize at the start, rather than
657 * incrementally resizing as we insert new keys. Expect
658 * that there will be no (or few) overlapping keys.
660 if ((so->fill + other->used)*3 >= (so->mask+1)*2) {
661 if (set_table_resize(so, (so->used + other->used)*2) != 0)
662 return -1;
664 for (i = 0; i <= other->mask; i++) {
665 entry = &other->table[i];
666 if (entry->key != NULL &&
667 entry->key != dummy) {
668 Py_INCREF(entry->key);
669 if (set_insert_key(so, entry->key, entry->hash) == -1) {
670 Py_DECREF(entry->key);
671 return -1;
675 return 0;
678 static int
679 set_contains_key(PySetObject *so, PyObject *key)
681 long hash;
682 setentry *entry;
684 if (!PyString_CheckExact(key) ||
685 (hash = ((PyStringObject *) key)->ob_shash) == -1) {
686 hash = PyObject_Hash(key);
687 if (hash == -1)
688 return -1;
690 entry = (so->lookup)(so, key, hash);
691 if (entry == NULL)
692 return -1;
693 key = entry->key;
694 return key != NULL && key != dummy;
697 static int
698 set_contains_entry(PySetObject *so, setentry *entry)
700 PyObject *key;
701 setentry *lu_entry;
703 lu_entry = (so->lookup)(so, entry->key, entry->hash);
704 if (lu_entry == NULL)
705 return -1;
706 key = lu_entry->key;
707 return key != NULL && key != dummy;
710 static PyObject *
711 set_pop(PySetObject *so)
713 register Py_ssize_t i = 0;
714 register setentry *entry;
715 PyObject *key;
717 assert (PyAnySet_Check(so));
718 if (so->used == 0) {
719 PyErr_SetString(PyExc_KeyError, "pop from an empty set");
720 return NULL;
723 /* Set entry to "the first" unused or dummy set entry. We abuse
724 * the hash field of slot 0 to hold a search finger:
725 * If slot 0 has a value, use slot 0.
726 * Else slot 0 is being used to hold a search finger,
727 * and we use its hash value as the first index to look.
729 entry = &so->table[0];
730 if (entry->key == NULL || entry->key == dummy) {
731 i = entry->hash;
732 /* The hash field may be a real hash value, or it may be a
733 * legit search finger, or it may be a once-legit search
734 * finger that's out of bounds now because it wrapped around
735 * or the table shrunk -- simply make sure it's in bounds now.
737 if (i > so->mask || i < 1)
738 i = 1; /* skip slot 0 */
739 while ((entry = &so->table[i])->key == NULL || entry->key==dummy) {
740 i++;
741 if (i > so->mask)
742 i = 1;
745 key = entry->key;
746 Py_INCREF(dummy);
747 entry->key = dummy;
748 so->used--;
749 so->table[0].hash = i + 1; /* next place to start */
750 return key;
753 PyDoc_STRVAR(pop_doc, "Remove and return an arbitrary set element.");
755 static int
756 set_traverse(PySetObject *so, visitproc visit, void *arg)
758 Py_ssize_t pos = 0;
759 setentry *entry;
761 while (set_next(so, &pos, &entry))
762 Py_VISIT(entry->key);
763 return 0;
766 static long
767 frozenset_hash(PyObject *self)
769 PySetObject *so = (PySetObject *)self;
770 long h, hash = 1927868237L;
771 setentry *entry;
772 Py_ssize_t pos = 0;
774 if (so->hash != -1)
775 return so->hash;
777 hash *= PySet_GET_SIZE(self) + 1;
778 while (set_next(so, &pos, &entry)) {
779 /* Work to increase the bit dispersion for closely spaced hash
780 values. The is important because some use cases have many
781 combinations of a small number of elements with nearby
782 hashes so that many distinct combinations collapse to only
783 a handful of distinct hash values. */
784 h = entry->hash;
785 hash ^= (h ^ (h << 16) ^ 89869747L) * 3644798167u;
787 hash = hash * 69069L + 907133923L;
788 if (hash == -1)
789 hash = 590923713L;
790 so->hash = hash;
791 return hash;
794 /***** Set iterator type ***********************************************/
796 typedef struct {
797 PyObject_HEAD
798 PySetObject *si_set; /* Set to NULL when iterator is exhausted */
799 Py_ssize_t si_used;
800 Py_ssize_t si_pos;
801 Py_ssize_t len;
802 } setiterobject;
804 static void
805 setiter_dealloc(setiterobject *si)
807 Py_XDECREF(si->si_set);
808 PyObject_Del(si);
811 static PyObject *
812 setiter_len(setiterobject *si)
814 Py_ssize_t len = 0;
815 if (si->si_set != NULL && si->si_used == si->si_set->used)
816 len = si->len;
817 return PyInt_FromLong(len);
820 PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
822 static PyMethodDef setiter_methods[] = {
823 {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc},
824 {NULL, NULL} /* sentinel */
827 static PyObject *setiter_iternext(setiterobject *si)
829 PyObject *key;
830 register Py_ssize_t i, mask;
831 register setentry *entry;
832 PySetObject *so = si->si_set;
834 if (so == NULL)
835 return NULL;
836 assert (PyAnySet_Check(so));
838 if (si->si_used != so->used) {
839 PyErr_SetString(PyExc_RuntimeError,
840 "Set changed size during iteration");
841 si->si_used = -1; /* Make this state sticky */
842 return NULL;
845 i = si->si_pos;
846 assert(i>=0);
847 entry = so->table;
848 mask = so->mask;
849 while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy))
850 i++;
851 si->si_pos = i+1;
852 if (i > mask)
853 goto fail;
854 si->len--;
855 key = entry[i].key;
856 Py_INCREF(key);
857 return key;
859 fail:
860 Py_DECREF(so);
861 si->si_set = NULL;
862 return NULL;
865 static PyTypeObject PySetIter_Type = {
866 PyVarObject_HEAD_INIT(&PyType_Type, 0)
867 "setiterator", /* tp_name */
868 sizeof(setiterobject), /* tp_basicsize */
869 0, /* tp_itemsize */
870 /* methods */
871 (destructor)setiter_dealloc, /* tp_dealloc */
872 0, /* tp_print */
873 0, /* tp_getattr */
874 0, /* tp_setattr */
875 0, /* tp_compare */
876 0, /* tp_repr */
877 0, /* tp_as_number */
878 0, /* tp_as_sequence */
879 0, /* tp_as_mapping */
880 0, /* tp_hash */
881 0, /* tp_call */
882 0, /* tp_str */
883 PyObject_GenericGetAttr, /* tp_getattro */
884 0, /* tp_setattro */
885 0, /* tp_as_buffer */
886 Py_TPFLAGS_DEFAULT, /* tp_flags */
887 0, /* tp_doc */
888 0, /* tp_traverse */
889 0, /* tp_clear */
890 0, /* tp_richcompare */
891 0, /* tp_weaklistoffset */
892 PyObject_SelfIter, /* tp_iter */
893 (iternextfunc)setiter_iternext, /* tp_iternext */
894 setiter_methods, /* tp_methods */
898 static PyObject *
899 set_iter(PySetObject *so)
901 setiterobject *si = PyObject_New(setiterobject, &PySetIter_Type);
902 if (si == NULL)
903 return NULL;
904 Py_INCREF(so);
905 si->si_set = so;
906 si->si_used = so->used;
907 si->si_pos = 0;
908 si->len = so->used;
909 return (PyObject *)si;
912 static int
913 set_update_internal(PySetObject *so, PyObject *other)
915 PyObject *key, *it;
917 if (PyAnySet_Check(other))
918 return set_merge(so, other);
920 if (PyDict_CheckExact(other)) {
921 PyObject *value;
922 Py_ssize_t pos = 0;
923 long hash;
924 Py_ssize_t dictsize = PyDict_Size(other);
926 /* Do one big resize at the start, rather than
927 * incrementally resizing as we insert new keys. Expect
928 * that there will be no (or few) overlapping keys.
930 if (dictsize == -1)
931 return -1;
932 if ((so->fill + dictsize)*3 >= (so->mask+1)*2) {
933 if (set_table_resize(so, (so->used + dictsize)*2) != 0)
934 return -1;
936 while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
937 setentry an_entry;
939 an_entry.hash = hash;
940 an_entry.key = key;
941 if (set_add_entry(so, &an_entry) == -1)
942 return -1;
944 return 0;
947 it = PyObject_GetIter(other);
948 if (it == NULL)
949 return -1;
951 while ((key = PyIter_Next(it)) != NULL) {
952 if (set_add_key(so, key) == -1) {
953 Py_DECREF(it);
954 Py_DECREF(key);
955 return -1;
957 Py_DECREF(key);
959 Py_DECREF(it);
960 if (PyErr_Occurred())
961 return -1;
962 return 0;
965 static PyObject *
966 set_update(PySetObject *so, PyObject *other)
968 if (set_update_internal(so, other) == -1)
969 return NULL;
970 Py_RETURN_NONE;
973 PyDoc_STRVAR(update_doc,
974 "Update a set with the union of itself and another.");
976 static PyObject *
977 make_new_set(PyTypeObject *type, PyObject *iterable)
979 register PySetObject *so = NULL;
981 if (dummy == NULL) { /* Auto-initialize dummy */
982 dummy = PyString_FromString("<dummy key>");
983 if (dummy == NULL)
984 return NULL;
987 /* create PySetObject structure */
988 if (numfree &&
989 (type == &PySet_Type || type == &PyFrozenSet_Type)) {
990 so = free_list[--numfree];
991 assert (so != NULL && PyAnySet_CheckExact(so));
992 Py_TYPE(so) = type;
993 _Py_NewReference((PyObject *)so);
994 EMPTY_TO_MINSIZE(so);
995 PyObject_GC_Track(so);
996 } else {
997 so = (PySetObject *)type->tp_alloc(type, 0);
998 if (so == NULL)
999 return NULL;
1000 /* tp_alloc has already zeroed the structure */
1001 assert(so->table == NULL && so->fill == 0 && so->used == 0);
1002 INIT_NONZERO_SET_SLOTS(so);
1005 so->lookup = set_lookkey_string;
1006 so->weakreflist = NULL;
1008 if (iterable != NULL) {
1009 if (set_update_internal(so, iterable) == -1) {
1010 Py_DECREF(so);
1011 return NULL;
1015 return (PyObject *)so;
1018 /* The empty frozenset is a singleton */
1019 static PyObject *emptyfrozenset = NULL;
1021 static PyObject *
1022 frozenset_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1024 PyObject *iterable = NULL, *result;
1026 if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds))
1027 return NULL;
1029 if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable))
1030 return NULL;
1032 if (type != &PyFrozenSet_Type)
1033 return make_new_set(type, iterable);
1035 if (iterable != NULL) {
1036 /* frozenset(f) is idempotent */
1037 if (PyFrozenSet_CheckExact(iterable)) {
1038 Py_INCREF(iterable);
1039 return iterable;
1041 result = make_new_set(type, iterable);
1042 if (result == NULL || PySet_GET_SIZE(result))
1043 return result;
1044 Py_DECREF(result);
1046 /* The empty frozenset is a singleton */
1047 if (emptyfrozenset == NULL)
1048 emptyfrozenset = make_new_set(type, NULL);
1049 Py_XINCREF(emptyfrozenset);
1050 return emptyfrozenset;
1053 void
1054 PySet_Fini(void)
1056 PySetObject *so;
1058 while (numfree) {
1059 numfree--;
1060 so = free_list[numfree];
1061 PyObject_GC_Del(so);
1063 Py_CLEAR(dummy);
1064 Py_CLEAR(emptyfrozenset);
1067 static PyObject *
1068 set_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1070 if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds))
1071 return NULL;
1073 return make_new_set(type, NULL);
1076 /* set_swap_bodies() switches the contents of any two sets by moving their
1077 internal data pointers and, if needed, copying the internal smalltables.
1078 Semantically equivalent to:
1080 t=set(a); a.clear(); a.update(b); b.clear(); b.update(t); del t
1082 The function always succeeds and it leaves both objects in a stable state.
1083 Useful for creating temporary frozensets from sets for membership testing
1084 in __contains__(), discard(), and remove(). Also useful for operations
1085 that update in-place (by allowing an intermediate result to be swapped
1086 into one of the original inputs).
1089 static void
1090 set_swap_bodies(PySetObject *a, PySetObject *b)
1092 Py_ssize_t t;
1093 setentry *u;
1094 setentry *(*f)(PySetObject *so, PyObject *key, long hash);
1095 setentry tab[PySet_MINSIZE];
1096 long h;
1098 t = a->fill; a->fill = b->fill; b->fill = t;
1099 t = a->used; a->used = b->used; b->used = t;
1100 t = a->mask; a->mask = b->mask; b->mask = t;
1102 u = a->table;
1103 if (a->table == a->smalltable)
1104 u = b->smalltable;
1105 a->table = b->table;
1106 if (b->table == b->smalltable)
1107 a->table = a->smalltable;
1108 b->table = u;
1110 f = a->lookup; a->lookup = b->lookup; b->lookup = f;
1112 if (a->table == a->smalltable || b->table == b->smalltable) {
1113 memcpy(tab, a->smalltable, sizeof(tab));
1114 memcpy(a->smalltable, b->smalltable, sizeof(tab));
1115 memcpy(b->smalltable, tab, sizeof(tab));
1118 if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type) &&
1119 PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) {
1120 h = a->hash; a->hash = b->hash; b->hash = h;
1121 } else {
1122 a->hash = -1;
1123 b->hash = -1;
1127 static PyObject *
1128 set_copy(PySetObject *so)
1130 return make_new_set(Py_TYPE(so), (PyObject *)so);
1133 static PyObject *
1134 frozenset_copy(PySetObject *so)
1136 if (PyFrozenSet_CheckExact(so)) {
1137 Py_INCREF(so);
1138 return (PyObject *)so;
1140 return set_copy(so);
1143 PyDoc_STRVAR(copy_doc, "Return a shallow copy of a set.");
1145 static PyObject *
1146 set_clear(PySetObject *so)
1148 set_clear_internal(so);
1149 Py_RETURN_NONE;
1152 PyDoc_STRVAR(clear_doc, "Remove all elements from this set.");
1154 static PyObject *
1155 set_union(PySetObject *so, PyObject *other)
1157 PySetObject *result;
1159 result = (PySetObject *)set_copy(so);
1160 if (result == NULL)
1161 return NULL;
1162 if ((PyObject *)so == other)
1163 return (PyObject *)result;
1164 if (set_update_internal(result, other) == -1) {
1165 Py_DECREF(result);
1166 return NULL;
1168 return (PyObject *)result;
1171 PyDoc_STRVAR(union_doc,
1172 "Return the union of two sets as a new set.\n\
1174 (i.e. all elements that are in either set.)");
1176 static PyObject *
1177 set_or(PySetObject *so, PyObject *other)
1179 if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
1180 Py_INCREF(Py_NotImplemented);
1181 return Py_NotImplemented;
1183 return set_union(so, other);
1186 static PyObject *
1187 set_ior(PySetObject *so, PyObject *other)
1189 if (!PyAnySet_Check(other)) {
1190 Py_INCREF(Py_NotImplemented);
1191 return Py_NotImplemented;
1193 if (set_update_internal(so, other) == -1)
1194 return NULL;
1195 Py_INCREF(so);
1196 return (PyObject *)so;
1199 static PyObject *
1200 set_intersection(PySetObject *so, PyObject *other)
1202 PySetObject *result;
1203 PyObject *key, *it, *tmp;
1205 if ((PyObject *)so == other)
1206 return set_copy(so);
1208 result = (PySetObject *)make_new_set(Py_TYPE(so), NULL);
1209 if (result == NULL)
1210 return NULL;
1212 if (PyAnySet_Check(other)) {
1213 Py_ssize_t pos = 0;
1214 setentry *entry;
1216 if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
1217 tmp = (PyObject *)so;
1218 so = (PySetObject *)other;
1219 other = tmp;
1222 while (set_next((PySetObject *)other, &pos, &entry)) {
1223 int rv = set_contains_entry(so, entry);
1224 if (rv == -1) {
1225 Py_DECREF(result);
1226 return NULL;
1228 if (rv) {
1229 if (set_add_entry(result, entry) == -1) {
1230 Py_DECREF(result);
1231 return NULL;
1235 return (PyObject *)result;
1238 it = PyObject_GetIter(other);
1239 if (it == NULL) {
1240 Py_DECREF(result);
1241 return NULL;
1244 while ((key = PyIter_Next(it)) != NULL) {
1245 int rv;
1246 setentry entry;
1247 long hash = PyObject_Hash(key);
1249 if (hash == -1) {
1250 Py_DECREF(it);
1251 Py_DECREF(result);
1252 Py_DECREF(key);
1253 return NULL;
1255 entry.hash = hash;
1256 entry.key = key;
1257 rv = set_contains_entry(so, &entry);
1258 if (rv == -1) {
1259 Py_DECREF(it);
1260 Py_DECREF(result);
1261 Py_DECREF(key);
1262 return NULL;
1264 if (rv) {
1265 if (set_add_entry(result, &entry) == -1) {
1266 Py_DECREF(it);
1267 Py_DECREF(result);
1268 Py_DECREF(key);
1269 return NULL;
1272 Py_DECREF(key);
1274 Py_DECREF(it);
1275 if (PyErr_Occurred()) {
1276 Py_DECREF(result);
1277 return NULL;
1279 return (PyObject *)result;
1282 PyDoc_STRVAR(intersection_doc,
1283 "Return the intersection of two sets as a new set.\n\
1285 (i.e. all elements that are in both sets.)");
1287 static PyObject *
1288 set_intersection_update(PySetObject *so, PyObject *other)
1290 PyObject *tmp;
1292 tmp = set_intersection(so, other);
1293 if (tmp == NULL)
1294 return NULL;
1295 set_swap_bodies(so, (PySetObject *)tmp);
1296 Py_DECREF(tmp);
1297 Py_RETURN_NONE;
1300 PyDoc_STRVAR(intersection_update_doc,
1301 "Update a set with the intersection of itself and another.");
1303 static PyObject *
1304 set_and(PySetObject *so, PyObject *other)
1306 if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
1307 Py_INCREF(Py_NotImplemented);
1308 return Py_NotImplemented;
1310 return set_intersection(so, other);
1313 static PyObject *
1314 set_iand(PySetObject *so, PyObject *other)
1316 PyObject *result;
1318 if (!PyAnySet_Check(other)) {
1319 Py_INCREF(Py_NotImplemented);
1320 return Py_NotImplemented;
1322 result = set_intersection_update(so, other);
1323 if (result == NULL)
1324 return NULL;
1325 Py_DECREF(result);
1326 Py_INCREF(so);
1327 return (PyObject *)so;
1330 static PyObject *
1331 set_isdisjoint(PySetObject *so, PyObject *other)
1333 PyObject *key, *it, *tmp;
1335 if ((PyObject *)so == other) {
1336 if (PySet_GET_SIZE(so) == 0)
1337 Py_RETURN_TRUE;
1338 else
1339 Py_RETURN_FALSE;
1342 if (PyAnySet_CheckExact(other)) {
1343 Py_ssize_t pos = 0;
1344 setentry *entry;
1346 if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
1347 tmp = (PyObject *)so;
1348 so = (PySetObject *)other;
1349 other = tmp;
1351 while (set_next((PySetObject *)other, &pos, &entry)) {
1352 int rv = set_contains_entry(so, entry);
1353 if (rv == -1)
1354 return NULL;
1355 if (rv)
1356 Py_RETURN_FALSE;
1358 Py_RETURN_TRUE;
1361 it = PyObject_GetIter(other);
1362 if (it == NULL)
1363 return NULL;
1365 while ((key = PyIter_Next(it)) != NULL) {
1366 int rv;
1367 setentry entry;
1368 long hash = PyObject_Hash(key);
1370 if (hash == -1) {
1371 Py_DECREF(key);
1372 Py_DECREF(it);
1373 return NULL;
1375 entry.hash = hash;
1376 entry.key = key;
1377 rv = set_contains_entry(so, &entry);
1378 Py_DECREF(key);
1379 if (rv == -1) {
1380 Py_DECREF(it);
1381 return NULL;
1383 if (rv) {
1384 Py_DECREF(it);
1385 Py_RETURN_FALSE;
1388 Py_DECREF(it);
1389 if (PyErr_Occurred())
1390 return NULL;
1391 Py_RETURN_TRUE;
1394 PyDoc_STRVAR(isdisjoint_doc,
1395 "Return True if two sets have a null intersection.");
1397 static int
1398 set_difference_update_internal(PySetObject *so, PyObject *other)
1400 if ((PyObject *)so == other)
1401 return set_clear_internal(so);
1403 if (PyAnySet_Check(other)) {
1404 setentry *entry;
1405 Py_ssize_t pos = 0;
1407 while (set_next((PySetObject *)other, &pos, &entry))
1408 if (set_discard_entry(so, entry) == -1)
1409 return -1;
1410 } else {
1411 PyObject *key, *it;
1412 it = PyObject_GetIter(other);
1413 if (it == NULL)
1414 return -1;
1416 while ((key = PyIter_Next(it)) != NULL) {
1417 if (set_discard_key(so, key) == -1) {
1418 Py_DECREF(it);
1419 Py_DECREF(key);
1420 return -1;
1422 Py_DECREF(key);
1424 Py_DECREF(it);
1425 if (PyErr_Occurred())
1426 return -1;
1428 /* If more than 1/5 are dummies, then resize them away. */
1429 if ((so->fill - so->used) * 5 < so->mask)
1430 return 0;
1431 return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
1434 static PyObject *
1435 set_difference_update(PySetObject *so, PyObject *other)
1437 if (set_difference_update_internal(so, other) != -1)
1438 Py_RETURN_NONE;
1439 return NULL;
1442 PyDoc_STRVAR(difference_update_doc,
1443 "Remove all elements of another set from this set.");
1445 static PyObject *
1446 set_difference(PySetObject *so, PyObject *other)
1448 PyObject *result;
1449 setentry *entry;
1450 Py_ssize_t pos = 0;
1452 if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) {
1453 result = set_copy(so);
1454 if (result == NULL)
1455 return NULL;
1456 if (set_difference_update_internal((PySetObject *)result, other) != -1)
1457 return result;
1458 Py_DECREF(result);
1459 return NULL;
1462 result = make_new_set(Py_TYPE(so), NULL);
1463 if (result == NULL)
1464 return NULL;
1466 if (PyDict_CheckExact(other)) {
1467 while (set_next(so, &pos, &entry)) {
1468 setentry entrycopy;
1469 entrycopy.hash = entry->hash;
1470 entrycopy.key = entry->key;
1471 if (!_PyDict_Contains(other, entry->key, entry->hash)) {
1472 if (set_add_entry((PySetObject *)result, &entrycopy) == -1) {
1473 Py_DECREF(result);
1474 return NULL;
1478 return result;
1481 while (set_next(so, &pos, &entry)) {
1482 int rv = set_contains_entry((PySetObject *)other, entry);
1483 if (rv == -1) {
1484 Py_DECREF(result);
1485 return NULL;
1487 if (!rv) {
1488 if (set_add_entry((PySetObject *)result, entry) == -1) {
1489 Py_DECREF(result);
1490 return NULL;
1494 return result;
1497 PyDoc_STRVAR(difference_doc,
1498 "Return the difference of two sets as a new set.\n\
1500 (i.e. all elements that are in this set but not the other.)");
1501 static PyObject *
1502 set_sub(PySetObject *so, PyObject *other)
1504 if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
1505 Py_INCREF(Py_NotImplemented);
1506 return Py_NotImplemented;
1508 return set_difference(so, other);
1511 static PyObject *
1512 set_isub(PySetObject *so, PyObject *other)
1514 PyObject *result;
1516 if (!PyAnySet_Check(other)) {
1517 Py_INCREF(Py_NotImplemented);
1518 return Py_NotImplemented;
1520 result = set_difference_update(so, other);
1521 if (result == NULL)
1522 return NULL;
1523 Py_DECREF(result);
1524 Py_INCREF(so);
1525 return (PyObject *)so;
1528 static PyObject *
1529 set_symmetric_difference_update(PySetObject *so, PyObject *other)
1531 PySetObject *otherset;
1532 PyObject *key;
1533 Py_ssize_t pos = 0;
1534 setentry *entry;
1536 if ((PyObject *)so == other)
1537 return set_clear(so);
1539 if (PyDict_CheckExact(other)) {
1540 PyObject *value;
1541 int rv;
1542 long hash;
1543 while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
1544 setentry an_entry;
1546 an_entry.hash = hash;
1547 an_entry.key = key;
1548 rv = set_discard_entry(so, &an_entry);
1549 if (rv == -1)
1550 return NULL;
1551 if (rv == DISCARD_NOTFOUND) {
1552 if (set_add_entry(so, &an_entry) == -1)
1553 return NULL;
1556 Py_RETURN_NONE;
1559 if (PyAnySet_Check(other)) {
1560 Py_INCREF(other);
1561 otherset = (PySetObject *)other;
1562 } else {
1563 otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
1564 if (otherset == NULL)
1565 return NULL;
1568 while (set_next(otherset, &pos, &entry)) {
1569 int rv = set_discard_entry(so, entry);
1570 if (rv == -1) {
1571 Py_DECREF(otherset);
1572 return NULL;
1574 if (rv == DISCARD_NOTFOUND) {
1575 if (set_add_entry(so, entry) == -1) {
1576 Py_DECREF(otherset);
1577 return NULL;
1581 Py_DECREF(otherset);
1582 Py_RETURN_NONE;
1585 PyDoc_STRVAR(symmetric_difference_update_doc,
1586 "Update a set with the symmetric difference of itself and another.");
1588 static PyObject *
1589 set_symmetric_difference(PySetObject *so, PyObject *other)
1591 PyObject *rv;
1592 PySetObject *otherset;
1594 otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
1595 if (otherset == NULL)
1596 return NULL;
1597 rv = set_symmetric_difference_update(otherset, (PyObject *)so);
1598 if (rv == NULL)
1599 return NULL;
1600 Py_DECREF(rv);
1601 return (PyObject *)otherset;
1604 PyDoc_STRVAR(symmetric_difference_doc,
1605 "Return the symmetric difference of two sets as a new set.\n\
1607 (i.e. all elements that are in exactly one of the sets.)");
1609 static PyObject *
1610 set_xor(PySetObject *so, PyObject *other)
1612 if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
1613 Py_INCREF(Py_NotImplemented);
1614 return Py_NotImplemented;
1616 return set_symmetric_difference(so, other);
1619 static PyObject *
1620 set_ixor(PySetObject *so, PyObject *other)
1622 PyObject *result;
1624 if (!PyAnySet_Check(other)) {
1625 Py_INCREF(Py_NotImplemented);
1626 return Py_NotImplemented;
1628 result = set_symmetric_difference_update(so, other);
1629 if (result == NULL)
1630 return NULL;
1631 Py_DECREF(result);
1632 Py_INCREF(so);
1633 return (PyObject *)so;
1636 static PyObject *
1637 set_issubset(PySetObject *so, PyObject *other)
1639 setentry *entry;
1640 Py_ssize_t pos = 0;
1642 if (!PyAnySet_Check(other)) {
1643 PyObject *tmp, *result;
1644 tmp = make_new_set(&PySet_Type, other);
1645 if (tmp == NULL)
1646 return NULL;
1647 result = set_issubset(so, tmp);
1648 Py_DECREF(tmp);
1649 return result;
1651 if (PySet_GET_SIZE(so) > PySet_GET_SIZE(other))
1652 Py_RETURN_FALSE;
1654 while (set_next(so, &pos, &entry)) {
1655 int rv = set_contains_entry((PySetObject *)other, entry);
1656 if (rv == -1)
1657 return NULL;
1658 if (!rv)
1659 Py_RETURN_FALSE;
1661 Py_RETURN_TRUE;
1664 PyDoc_STRVAR(issubset_doc, "Report whether another set contains this set.");
1666 static PyObject *
1667 set_issuperset(PySetObject *so, PyObject *other)
1669 PyObject *tmp, *result;
1671 if (!PyAnySet_Check(other)) {
1672 tmp = make_new_set(&PySet_Type, other);
1673 if (tmp == NULL)
1674 return NULL;
1675 result = set_issuperset(so, tmp);
1676 Py_DECREF(tmp);
1677 return result;
1679 return set_issubset((PySetObject *)other, (PyObject *)so);
1682 PyDoc_STRVAR(issuperset_doc, "Report whether this set contains another set.");
1684 static PyObject *
1685 set_richcompare(PySetObject *v, PyObject *w, int op)
1687 PyObject *r1, *r2;
1689 if(!PyAnySet_Check(w)) {
1690 if (op == Py_EQ)
1691 Py_RETURN_FALSE;
1692 if (op == Py_NE)
1693 Py_RETURN_TRUE;
1694 PyErr_SetString(PyExc_TypeError, "can only compare to a set");
1695 return NULL;
1697 switch (op) {
1698 case Py_EQ:
1699 if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w))
1700 Py_RETURN_FALSE;
1701 if (v->hash != -1 &&
1702 ((PySetObject *)w)->hash != -1 &&
1703 v->hash != ((PySetObject *)w)->hash)
1704 Py_RETURN_FALSE;
1705 return set_issubset(v, w);
1706 case Py_NE:
1707 r1 = set_richcompare(v, w, Py_EQ);
1708 if (r1 == NULL)
1709 return NULL;
1710 r2 = PyBool_FromLong(PyObject_Not(r1));
1711 Py_DECREF(r1);
1712 return r2;
1713 case Py_LE:
1714 return set_issubset(v, w);
1715 case Py_GE:
1716 return set_issuperset(v, w);
1717 case Py_LT:
1718 if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w))
1719 Py_RETURN_FALSE;
1720 return set_issubset(v, w);
1721 case Py_GT:
1722 if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w))
1723 Py_RETURN_FALSE;
1724 return set_issuperset(v, w);
1726 Py_INCREF(Py_NotImplemented);
1727 return Py_NotImplemented;
1730 static int
1731 set_nocmp(PyObject *self, PyObject *other)
1733 PyErr_SetString(PyExc_TypeError, "cannot compare sets using cmp()");
1734 return -1;
1737 static PyObject *
1738 set_add(PySetObject *so, PyObject *key)
1740 if (set_add_key(so, key) == -1)
1741 return NULL;
1742 Py_RETURN_NONE;
1745 PyDoc_STRVAR(add_doc,
1746 "Add an element to a set.\n\
1748 This has no effect if the element is already present.");
1750 static int
1751 set_contains(PySetObject *so, PyObject *key)
1753 PyObject *tmpkey;
1754 int rv;
1756 rv = set_contains_key(so, key);
1757 if (rv == -1) {
1758 if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
1759 return -1;
1760 PyErr_Clear();
1761 tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
1762 if (tmpkey == NULL)
1763 return -1;
1764 set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
1765 rv = set_contains(so, tmpkey);
1766 set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
1767 Py_DECREF(tmpkey);
1769 return rv;
1772 static PyObject *
1773 set_direct_contains(PySetObject *so, PyObject *key)
1775 long result;
1777 result = set_contains(so, key);
1778 if (result == -1)
1779 return NULL;
1780 return PyBool_FromLong(result);
1783 PyDoc_STRVAR(contains_doc, "x.__contains__(y) <==> y in x.");
1785 static PyObject *
1786 set_remove(PySetObject *so, PyObject *key)
1788 PyObject *tmpkey, *result;
1789 int rv;
1791 rv = set_discard_key(so, key);
1792 if (rv == -1) {
1793 if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
1794 return NULL;
1795 PyErr_Clear();
1796 tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
1797 if (tmpkey == NULL)
1798 return NULL;
1799 set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
1800 result = set_remove(so, tmpkey);
1801 set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
1802 Py_DECREF(tmpkey);
1803 return result;
1804 } else if (rv == DISCARD_NOTFOUND) {
1805 set_key_error(key);
1806 return NULL;
1808 Py_RETURN_NONE;
1811 PyDoc_STRVAR(remove_doc,
1812 "Remove an element from a set; it must be a member.\n\
1814 If the element is not a member, raise a KeyError.");
1816 static PyObject *
1817 set_discard(PySetObject *so, PyObject *key)
1819 PyObject *tmpkey, *result;
1820 int rv;
1822 rv = set_discard_key(so, key);
1823 if (rv == -1) {
1824 if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
1825 return NULL;
1826 PyErr_Clear();
1827 tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
1828 if (tmpkey == NULL)
1829 return NULL;
1830 set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
1831 result = set_discard(so, tmpkey);
1832 set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
1833 Py_DECREF(tmpkey);
1834 return result;
1836 Py_RETURN_NONE;
1839 PyDoc_STRVAR(discard_doc,
1840 "Remove an element from a set if it is a member.\n\
1842 If the element is not a member, do nothing.");
1844 static PyObject *
1845 set_reduce(PySetObject *so)
1847 PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL;
1849 keys = PySequence_List((PyObject *)so);
1850 if (keys == NULL)
1851 goto done;
1852 args = PyTuple_Pack(1, keys);
1853 if (args == NULL)
1854 goto done;
1855 dict = PyObject_GetAttrString((PyObject *)so, "__dict__");
1856 if (dict == NULL) {
1857 PyErr_Clear();
1858 dict = Py_None;
1859 Py_INCREF(dict);
1861 result = PyTuple_Pack(3, Py_TYPE(so), args, dict);
1862 done:
1863 Py_XDECREF(args);
1864 Py_XDECREF(keys);
1865 Py_XDECREF(dict);
1866 return result;
1869 PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
1871 static int
1872 set_init(PySetObject *self, PyObject *args, PyObject *kwds)
1874 PyObject *iterable = NULL;
1876 if (!PyAnySet_Check(self))
1877 return -1;
1878 if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable))
1879 return -1;
1880 set_clear_internal(self);
1881 self->hash = -1;
1882 if (iterable == NULL)
1883 return 0;
1884 return set_update_internal(self, iterable);
1887 static PySequenceMethods set_as_sequence = {
1888 set_len, /* sq_length */
1889 0, /* sq_concat */
1890 0, /* sq_repeat */
1891 0, /* sq_item */
1892 0, /* sq_slice */
1893 0, /* sq_ass_item */
1894 0, /* sq_ass_slice */
1895 (objobjproc)set_contains, /* sq_contains */
1898 /* set object ********************************************************/
1900 #ifdef Py_DEBUG
1901 static PyObject *test_c_api(PySetObject *so);
1903 PyDoc_STRVAR(test_c_api_doc, "Exercises C API. Returns True.\n\
1904 All is well if assertions don't fail.");
1905 #endif
1907 static PyMethodDef set_methods[] = {
1908 {"add", (PyCFunction)set_add, METH_O,
1909 add_doc},
1910 {"clear", (PyCFunction)set_clear, METH_NOARGS,
1911 clear_doc},
1912 {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST,
1913 contains_doc},
1914 {"copy", (PyCFunction)set_copy, METH_NOARGS,
1915 copy_doc},
1916 {"discard", (PyCFunction)set_discard, METH_O,
1917 discard_doc},
1918 {"difference", (PyCFunction)set_difference, METH_O,
1919 difference_doc},
1920 {"difference_update", (PyCFunction)set_difference_update, METH_O,
1921 difference_update_doc},
1922 {"intersection",(PyCFunction)set_intersection, METH_O,
1923 intersection_doc},
1924 {"intersection_update",(PyCFunction)set_intersection_update, METH_O,
1925 intersection_update_doc},
1926 {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O,
1927 isdisjoint_doc},
1928 {"issubset", (PyCFunction)set_issubset, METH_O,
1929 issubset_doc},
1930 {"issuperset", (PyCFunction)set_issuperset, METH_O,
1931 issuperset_doc},
1932 {"pop", (PyCFunction)set_pop, METH_NOARGS,
1933 pop_doc},
1934 {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS,
1935 reduce_doc},
1936 {"remove", (PyCFunction)set_remove, METH_O,
1937 remove_doc},
1938 {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O,
1939 symmetric_difference_doc},
1940 {"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update, METH_O,
1941 symmetric_difference_update_doc},
1942 #ifdef Py_DEBUG
1943 {"test_c_api", (PyCFunction)test_c_api, METH_NOARGS,
1944 test_c_api_doc},
1945 #endif
1946 {"union", (PyCFunction)set_union, METH_O,
1947 union_doc},
1948 {"update", (PyCFunction)set_update, METH_O,
1949 update_doc},
1950 {NULL, NULL} /* sentinel */
1953 static PyNumberMethods set_as_number = {
1954 0, /*nb_add*/
1955 (binaryfunc)set_sub, /*nb_subtract*/
1956 0, /*nb_multiply*/
1957 0, /*nb_divide*/
1958 0, /*nb_remainder*/
1959 0, /*nb_divmod*/
1960 0, /*nb_power*/
1961 0, /*nb_negative*/
1962 0, /*nb_positive*/
1963 0, /*nb_absolute*/
1964 0, /*nb_nonzero*/
1965 0, /*nb_invert*/
1966 0, /*nb_lshift*/
1967 0, /*nb_rshift*/
1968 (binaryfunc)set_and, /*nb_and*/
1969 (binaryfunc)set_xor, /*nb_xor*/
1970 (binaryfunc)set_or, /*nb_or*/
1971 0, /*nb_coerce*/
1972 0, /*nb_int*/
1973 0, /*nb_long*/
1974 0, /*nb_float*/
1975 0, /*nb_oct*/
1976 0, /*nb_hex*/
1977 0, /*nb_inplace_add*/
1978 (binaryfunc)set_isub, /*nb_inplace_subtract*/
1979 0, /*nb_inplace_multiply*/
1980 0, /*nb_inplace_divide*/
1981 0, /*nb_inplace_remainder*/
1982 0, /*nb_inplace_power*/
1983 0, /*nb_inplace_lshift*/
1984 0, /*nb_inplace_rshift*/
1985 (binaryfunc)set_iand, /*nb_inplace_and*/
1986 (binaryfunc)set_ixor, /*nb_inplace_xor*/
1987 (binaryfunc)set_ior, /*nb_inplace_or*/
1990 PyDoc_STRVAR(set_doc,
1991 "set(iterable) --> set object\n\
1993 Build an unordered collection of unique elements.");
1995 PyTypeObject PySet_Type = {
1996 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1997 "set", /* tp_name */
1998 sizeof(PySetObject), /* tp_basicsize */
1999 0, /* tp_itemsize */
2000 /* methods */
2001 (destructor)set_dealloc, /* tp_dealloc */
2002 (printfunc)set_tp_print, /* tp_print */
2003 0, /* tp_getattr */
2004 0, /* tp_setattr */
2005 set_nocmp, /* tp_compare */
2006 (reprfunc)set_repr, /* tp_repr */
2007 &set_as_number, /* tp_as_number */
2008 &set_as_sequence, /* tp_as_sequence */
2009 0, /* tp_as_mapping */
2010 0, /* tp_hash */
2011 0, /* tp_call */
2012 0, /* tp_str */
2013 PyObject_GenericGetAttr, /* tp_getattro */
2014 0, /* tp_setattro */
2015 0, /* tp_as_buffer */
2016 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES |
2017 Py_TPFLAGS_BASETYPE, /* tp_flags */
2018 set_doc, /* tp_doc */
2019 (traverseproc)set_traverse, /* tp_traverse */
2020 (inquiry)set_clear_internal, /* tp_clear */
2021 (richcmpfunc)set_richcompare, /* tp_richcompare */
2022 offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */
2023 (getiterfunc)set_iter, /* tp_iter */
2024 0, /* tp_iternext */
2025 set_methods, /* tp_methods */
2026 0, /* tp_members */
2027 0, /* tp_getset */
2028 0, /* tp_base */
2029 0, /* tp_dict */
2030 0, /* tp_descr_get */
2031 0, /* tp_descr_set */
2032 0, /* tp_dictoffset */
2033 (initproc)set_init, /* tp_init */
2034 PyType_GenericAlloc, /* tp_alloc */
2035 set_new, /* tp_new */
2036 PyObject_GC_Del, /* tp_free */
2039 /* frozenset object ********************************************************/
2042 static PyMethodDef frozenset_methods[] = {
2043 {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST,
2044 contains_doc},
2045 {"copy", (PyCFunction)frozenset_copy, METH_NOARGS,
2046 copy_doc},
2047 {"difference", (PyCFunction)set_difference, METH_O,
2048 difference_doc},
2049 {"intersection",(PyCFunction)set_intersection, METH_O,
2050 intersection_doc},
2051 {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O,
2052 isdisjoint_doc},
2053 {"issubset", (PyCFunction)set_issubset, METH_O,
2054 issubset_doc},
2055 {"issuperset", (PyCFunction)set_issuperset, METH_O,
2056 issuperset_doc},
2057 {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS,
2058 reduce_doc},
2059 {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O,
2060 symmetric_difference_doc},
2061 {"union", (PyCFunction)set_union, METH_O,
2062 union_doc},
2063 {NULL, NULL} /* sentinel */
2066 static PyNumberMethods frozenset_as_number = {
2067 0, /*nb_add*/
2068 (binaryfunc)set_sub, /*nb_subtract*/
2069 0, /*nb_multiply*/
2070 0, /*nb_divide*/
2071 0, /*nb_remainder*/
2072 0, /*nb_divmod*/
2073 0, /*nb_power*/
2074 0, /*nb_negative*/
2075 0, /*nb_positive*/
2076 0, /*nb_absolute*/
2077 0, /*nb_nonzero*/
2078 0, /*nb_invert*/
2079 0, /*nb_lshift*/
2080 0, /*nb_rshift*/
2081 (binaryfunc)set_and, /*nb_and*/
2082 (binaryfunc)set_xor, /*nb_xor*/
2083 (binaryfunc)set_or, /*nb_or*/
2086 PyDoc_STRVAR(frozenset_doc,
2087 "frozenset(iterable) --> frozenset object\n\
2089 Build an immutable unordered collection of unique elements.");
2091 PyTypeObject PyFrozenSet_Type = {
2092 PyVarObject_HEAD_INIT(&PyType_Type, 0)
2093 "frozenset", /* tp_name */
2094 sizeof(PySetObject), /* tp_basicsize */
2095 0, /* tp_itemsize */
2096 /* methods */
2097 (destructor)set_dealloc, /* tp_dealloc */
2098 (printfunc)set_tp_print, /* tp_print */
2099 0, /* tp_getattr */
2100 0, /* tp_setattr */
2101 set_nocmp, /* tp_compare */
2102 (reprfunc)set_repr, /* tp_repr */
2103 &frozenset_as_number, /* tp_as_number */
2104 &set_as_sequence, /* tp_as_sequence */
2105 0, /* tp_as_mapping */
2106 frozenset_hash, /* tp_hash */
2107 0, /* tp_call */
2108 0, /* tp_str */
2109 PyObject_GenericGetAttr, /* tp_getattro */
2110 0, /* tp_setattro */
2111 0, /* tp_as_buffer */
2112 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES |
2113 Py_TPFLAGS_BASETYPE, /* tp_flags */
2114 frozenset_doc, /* tp_doc */
2115 (traverseproc)set_traverse, /* tp_traverse */
2116 (inquiry)set_clear_internal, /* tp_clear */
2117 (richcmpfunc)set_richcompare, /* tp_richcompare */
2118 offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */
2119 (getiterfunc)set_iter, /* tp_iter */
2120 0, /* tp_iternext */
2121 frozenset_methods, /* tp_methods */
2122 0, /* tp_members */
2123 0, /* tp_getset */
2124 0, /* tp_base */
2125 0, /* tp_dict */
2126 0, /* tp_descr_get */
2127 0, /* tp_descr_set */
2128 0, /* tp_dictoffset */
2129 0, /* tp_init */
2130 PyType_GenericAlloc, /* tp_alloc */
2131 frozenset_new, /* tp_new */
2132 PyObject_GC_Del, /* tp_free */
2136 /***** C API functions *************************************************/
2138 PyObject *
2139 PySet_New(PyObject *iterable)
2141 return make_new_set(&PySet_Type, iterable);
2144 PyObject *
2145 PyFrozenSet_New(PyObject *iterable)
2147 return make_new_set(&PyFrozenSet_Type, iterable);
2150 Py_ssize_t
2151 PySet_Size(PyObject *anyset)
2153 if (!PyAnySet_Check(anyset)) {
2154 PyErr_BadInternalCall();
2155 return -1;
2157 return PySet_GET_SIZE(anyset);
2161 PySet_Clear(PyObject *set)
2163 if (!PySet_Check(set)) {
2164 PyErr_BadInternalCall();
2165 return -1;
2167 return set_clear_internal((PySetObject *)set);
2171 PySet_Contains(PyObject *anyset, PyObject *key)
2173 if (!PyAnySet_Check(anyset)) {
2174 PyErr_BadInternalCall();
2175 return -1;
2177 return set_contains_key((PySetObject *)anyset, key);
2181 PySet_Discard(PyObject *set, PyObject *key)
2183 if (!PySet_Check(set)) {
2184 PyErr_BadInternalCall();
2185 return -1;
2187 return set_discard_key((PySetObject *)set, key);
2191 PySet_Add(PyObject *anyset, PyObject *key)
2193 if (!PySet_Check(anyset) &&
2194 (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) {
2195 PyErr_BadInternalCall();
2196 return -1;
2198 return set_add_key((PySetObject *)anyset, key);
2202 _PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **key)
2204 setentry *entry_ptr;
2206 if (!PyAnySet_Check(set)) {
2207 PyErr_BadInternalCall();
2208 return -1;
2210 if (set_next((PySetObject *)set, pos, &entry_ptr) == 0)
2211 return 0;
2212 *key = entry_ptr->key;
2213 return 1;
2217 _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash)
2219 setentry *entry;
2221 if (!PyAnySet_Check(set)) {
2222 PyErr_BadInternalCall();
2223 return -1;
2225 if (set_next((PySetObject *)set, pos, &entry) == 0)
2226 return 0;
2227 *key = entry->key;
2228 *hash = entry->hash;
2229 return 1;
2232 PyObject *
2233 PySet_Pop(PyObject *set)
2235 if (!PySet_Check(set)) {
2236 PyErr_BadInternalCall();
2237 return NULL;
2239 return set_pop((PySetObject *)set);
2243 _PySet_Update(PyObject *set, PyObject *iterable)
2245 if (!PySet_Check(set)) {
2246 PyErr_BadInternalCall();
2247 return -1;
2249 return set_update_internal((PySetObject *)set, iterable);
2252 #ifdef Py_DEBUG
2254 /* Test code to be called with any three element set.
2255 Returns True and original set is restored. */
2257 #define assertRaises(call_return_value, exception) \
2258 do { \
2259 assert(call_return_value); \
2260 assert(PyErr_ExceptionMatches(exception)); \
2261 PyErr_Clear(); \
2262 } while(0)
2264 static PyObject *
2265 test_c_api(PySetObject *so)
2267 Py_ssize_t count;
2268 char *s;
2269 Py_ssize_t i;
2270 PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x;
2271 PyObject *ob = (PyObject *)so;
2273 /* Verify preconditions and exercise type/size checks */
2274 assert(PyAnySet_Check(ob));
2275 assert(PyAnySet_CheckExact(ob));
2276 assert(!PyFrozenSet_CheckExact(ob));
2277 assert(PySet_Size(ob) == 3);
2278 assert(PySet_GET_SIZE(ob) == 3);
2280 /* Raise TypeError for non-iterable constructor arguments */
2281 assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError);
2282 assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError);
2284 /* Raise TypeError for unhashable key */
2285 dup = PySet_New(ob);
2286 assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError);
2287 assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError);
2288 assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError);
2290 /* Exercise successful pop, contains, add, and discard */
2291 elem = PySet_Pop(ob);
2292 assert(PySet_Contains(ob, elem) == 0);
2293 assert(PySet_GET_SIZE(ob) == 2);
2294 assert(PySet_Add(ob, elem) == 0);
2295 assert(PySet_Contains(ob, elem) == 1);
2296 assert(PySet_GET_SIZE(ob) == 3);
2297 assert(PySet_Discard(ob, elem) == 1);
2298 assert(PySet_GET_SIZE(ob) == 2);
2299 assert(PySet_Discard(ob, elem) == 0);
2300 assert(PySet_GET_SIZE(ob) == 2);
2302 /* Exercise clear */
2303 dup2 = PySet_New(dup);
2304 assert(PySet_Clear(dup2) == 0);
2305 assert(PySet_Size(dup2) == 0);
2306 Py_DECREF(dup2);
2308 /* Raise SystemError on clear or update of frozen set */
2309 f = PyFrozenSet_New(dup);
2310 assertRaises(PySet_Clear(f) == -1, PyExc_SystemError);
2311 assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError);
2312 assert(PySet_Add(f, elem) == 0);
2313 Py_INCREF(f);
2314 assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError);
2315 Py_DECREF(f);
2316 Py_DECREF(f);
2318 /* Exercise direct iteration */
2319 i = 0, count = 0;
2320 while (_PySet_Next((PyObject *)dup, &i, &x)) {
2321 s = PyString_AsString(x);
2322 assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c'));
2323 count++;
2325 assert(count == 3);
2327 /* Exercise updates */
2328 dup2 = PySet_New(NULL);
2329 assert(_PySet_Update(dup2, dup) == 0);
2330 assert(PySet_Size(dup2) == 3);
2331 assert(_PySet_Update(dup2, dup) == 0);
2332 assert(PySet_Size(dup2) == 3);
2333 Py_DECREF(dup2);
2335 /* Raise SystemError when self argument is not a set or frozenset. */
2336 t = PyTuple_New(0);
2337 assertRaises(PySet_Size(t) == -1, PyExc_SystemError);
2338 assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError);
2339 Py_DECREF(t);
2341 /* Raise SystemError when self argument is not a set. */
2342 f = PyFrozenSet_New(dup);
2343 assert(PySet_Size(f) == 3);
2344 assert(PyFrozenSet_CheckExact(f));
2345 assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError);
2346 assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError);
2347 Py_DECREF(f);
2349 /* Raise KeyError when popping from an empty set */
2350 assert(PyNumber_InPlaceSubtract(ob, ob) == ob);
2351 Py_DECREF(ob);
2352 assert(PySet_GET_SIZE(ob) == 0);
2353 assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError);
2355 /* Restore the set from the copy using the PyNumber API */
2356 assert(PyNumber_InPlaceOr(ob, dup) == ob);
2357 Py_DECREF(ob);
2359 /* Verify constructors accept NULL arguments */
2360 f = PySet_New(NULL);
2361 assert(f != NULL);
2362 assert(PySet_GET_SIZE(f) == 0);
2363 Py_DECREF(f);
2364 f = PyFrozenSet_New(NULL);
2365 assert(f != NULL);
2366 assert(PyFrozenSet_CheckExact(f));
2367 assert(PySet_GET_SIZE(f) == 0);
2368 Py_DECREF(f);
2370 Py_DECREF(elem);
2371 Py_DECREF(dup);
2372 Py_RETURN_TRUE;
2375 #undef assertRaises
2377 #endif