[Python-ideas] set.add could return True or False
andrew.svetlov at gmail.com
Wed Mar 14 18:46:48 CET 2012
You still can get race condition:
# some thread removes a from b before do_c call...
Explicit lock is still required for your case.
On Wed, Mar 14, 2012 at 10:36 AM, Matt Joiner <anacrolix at gmail.com> wrote:
> set.add(x) could return True if x was added to the set, and False if x
> was already in the set.
> Adding an element that is already present often constitutes an error in my code.
> As I understand, set.add is an atomic operation. Having set.add return
> a boolean will also allow EAFP-style code with regard to handling
> duplicates, the long winded form of which is currently:
> if a not in b:
> b.add(a) <-- race condition
> Which can be improved to:
> if b.add(a):
> * Very common code pattern.
> * More concise.
> * Allows interpreter atomicity to be exploited, often removing the
> need for additional locking.
> * Faster because it avoids double contain check, and can avoid locking.
> Python-ideas mailing list
> Python-ideas at python.org
More information about the Python-ideas