[New-bugs-announce] [issue2778] set_swap_bodies is unsafe

Adam Olsen report at bugs.python.org
Wed May 7 04:19:32 CEST 2008

New submission from Adam Olsen <rhamph at gmail.com>:

set_swap_bodies() is used to cheaply create a frozenset from a set,
which is then used for lookups within a set.  It does this by creating a
temporary empty frozenset, swapping its contents with the original set,
doing the lookup using the frozenset, then swapping the contents back
and releasing the temporary frozenset.

Unfortunately, the lookup can invoke arbitrary code, which may examine
the original set and find it empty (until the lookup completes).  The
lookup may also save a reference to the temporary frozenset, which
mutates to being empty after the lookup completes.

The purpose seems to be allowing "someset in someotherset" to
automatically convert someset to a frozenset.  A brief search didn't
reveal a rationale for this, and in fact PEP 218's history section
claims the opposite: "Auto-conversion between mutable and immutable sets
was dropped."  Perhaps this is a forgotten vestige of that?

set_intersection_update uses set_swap_bodies for a different purpose and
it may be safe.  It depends on whether subclasses of set may retain a
reference to the tmp set somehow.

files: brokensetswap.py
messages: 66349
nosy: Rhamphoryncus
severity: normal
status: open
title: set_swap_bodies is unsafe
type: behavior
Added file: http://bugs.python.org/file10204/brokensetswap.py

Tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list