[Python-Dev] thread-safe generator in standard library
Tim Peters
tim.one at comcast.net
Mon Feb 2 13:57:23 EST 2004
[Jewett, Jim J]
> ...
> The most obvious use case is to generate unique keys
> (as lisp gensym).
Just noting a practical hack that's often sufficient:
import sys
genunique = iter(xrange(sys.maxint)).next
Then each call to genunique() delivers "the next" (short) integer, and it
inherits thread safety from the global interpreter lock.
A similar effect can be gotten via
import itertools
genunique = itertools.count().next
and that also inherits thread safety from the GIL.
A difference is that the xrange spelling stops when it reaches sys.maxint,
but the .count spelling silently wraps around to -sys.maxint-1 then
(undetected overflow at the C level).
More information about the Python-Dev
mailing list