Name
qsize
Synopsis
q
.qsize( )
Returns the number of items that are currently in
q
.
Queue
offers a good example of the idiom
“it’s easier to ask forgiveness
than permission” (EAFP), covered in Chapter 6. Due to multithreading, each non-mutating
method of q
can only be advisory. When
some other thread executes and mutates q
,
things can change between the instant a thread gets the information
and the very next moment, when the thread acts on the information.
Relying on the “look before you
leap” (LBYL) idiom is futile, and fiddling with
locks to try and fix things is a substantial waste of effort. Just
avoid LBYL code such as:
ifq
.empty( ): print "no work to perform" else:x
=q
.get_nowait( )
and instead use the simpler and more robust EAFP approach:
try:x
=q
.get_nowait( ) except Queue.Empty: print "no work to perform"
Get Python in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.