This document is for Kombu's development version, which can be significantly different from previous releases. Get the stable docs here: 3.0.
Python 2 to Python 3 utilities - kombu.five
¶
Python 2/3 compatibility.
Compatibility implementations of features only available in newer Python versions.
-
class
kombu.five.
Counter
(*args, **kwds)[source]¶ Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values.
>>> c = Counter('abcdeabcdabcaba') # count elements from a string
>>> c.most_common(3) # three most common elements [('a', 5), ('b', 4), ('c', 3)] >>> sorted(c) # list all unique elements ['a', 'b', 'c', 'd', 'e'] >>> ''.join(sorted(c.elements())) # list elements with repetitions 'aaaaabbbbcccdde' >>> sum(c.values()) # total of all counts 15
>>> c['a'] # count of letter 'a' 5 >>> for elem in 'shazam': # update counts from an iterable ... c[elem] += 1 # by adding 1 to each element's count >>> c['a'] # now there are seven 'a' 7 >>> del c['b'] # remove all 'b' >>> c['b'] # now there are zero 'b' 0
>>> d = Counter('simsalabim') # make another counter >>> c.update(d) # add in the second counter >>> c['a'] # now there are nine 'a' 9
>>> c.clear() # empty the counter >>> c Counter()
Note: If a count is set to zero or reduced to zero, it will remain in the counter until the entry is deleted or the counter is cleared:
>>> c = Counter('aaabbc') >>> c['b'] -= 2 # reduce the count of 'b' by two >>> c.most_common() # 'b' is still in, but its count is zero [('a', 3), ('c', 1), ('b', 0)]
-
elements
()[source]¶ Iterator over elements repeating each as many times as its count.
>>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C']
# Knuth’s example for prime factors of 1836: 2**2 * 3**3 * 17**1 >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) >>> product = 1 >>> for factor in prime_factors.elements(): # loop over factors ... product *= factor # and multiply them >>> product 1836
Note, if an element’s count has been set to zero or is a negative number, elements() will ignore it.
-
most_common
(n=None)[source]¶ List the n most common elements and their counts from the most common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3) [('a', 5), ('b', 4), ('c', 3)]
-
subtract
(*args, **kwds)[source]¶ Like dict.update() but subtracts counts instead of replacing them. Counts can be reduced below zero. Both the inputs and outputs are allowed to contain zero and negative counts.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which') >>> c.subtract('witch') # subtract elements from another iterable >>> c.subtract(Counter('watch')) # subtract elements from another counter >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch 0 >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch -1
-
update
(*args, **kwds)[source]¶ Like dict.update() but add counts instead of replacing them.
Source can be an iterable, a dictionary, or another Counter instance.
>>> c = Counter('which') >>> c.update('witch') # add elements from another iterable >>> d = Counter('watch') >>> c.update(d) # add elements from another counter >>> c['h'] # four 'h' in which, witch, and watch 4
-
-
kombu.five.
reload
(module) → module¶ Reload the module. The module must have been successfully imported before.
-
class
kombu.five.
Queue
(maxsize=0)[source]¶ Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
-
get
(block=True, timeout=None)[source]¶ Remove and return an item from the queue.
If optional args ‘block’ is true and ‘timeout’ is None (the default), block if necessary until an item is available. If ‘timeout’ is a non-negative number, it blocks at most ‘timeout’ seconds and raises the Empty exception if no item was available within that time. Otherwise (‘block’ is false), return an item if one is immediately available, else raise the Empty exception (‘timeout’ is ignored in that case).
-
get_nowait
()[source]¶ Remove and return an item from the queue without blocking.
Only get an item if one is immediately available. Otherwise raise the Empty exception.
-
join
()[source]¶ Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all work on it is complete.
When the count of unfinished tasks drops to zero, join() unblocks.
-
put
(item, block=True, timeout=None)[source]¶ Put an item into the queue.
If optional args ‘block’ is true and ‘timeout’ is None (the default), block if necessary until a free slot is available. If ‘timeout’ is a non-negative number, it blocks at most ‘timeout’ seconds and raises the Full exception if no free slot was available within that time. Otherwise (‘block’ is false), put an item on the queue if a free slot is immediately available, else raise the Full exception (‘timeout’ is ignored in that case).
-
put_nowait
(item)[source]¶ Put an item into the queue without blocking.
Only enqueue the item if a free slot is immediately available. Otherwise raise the Full exception.
-
task_done
()[source]¶ Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete.
If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue).
Raises a ValueError if called more times than there were items placed in the queue.
-
-
class
kombu.five.
LifoQueue
(maxsize=0)[source]¶ Variant of Queue that retrieves most recently added entries first.
-
kombu.five.
zip_longest
¶ alias of
izip_longest
-
kombu.five.
map
¶ alias of
imap
-
kombu.five.
zip
¶ alias of
izip
-
kombu.five.
string
¶ alias of
unicode
-
kombu.five.
string_t
¶ alias of
basestring
-
kombu.five.
long_t
¶ alias of
long
-
kombu.five.
text_t
¶ alias of
unicode
-
kombu.five.
range
¶ alias of
xrange
-
kombu.five.
with_metaclass
(Type, skip_attrs=set([u'__dict__', u'__weakref__']))[source]¶ Class decorator to set metaclass.
Works with both Python 2 and Python 3 and it does not add an extra class in the lookup order like
six.with_metaclass
does (that is – it copies the original class instead of using inheritance).
-
class
kombu.five.
StringIO
¶ Text I/O implementation using an in-memory buffer.
The initial_value argument sets the value of object. The newline argument is like the one of TextIOWrapper’s constructor.
-
close
()¶ Close the IO object. Attempting any further operation after the object is closed will raise a ValueError.
This method has no effect if the file is already closed.
-
closed
¶
-
getvalue
()¶ Retrieve the entire contents of the object.
-
line_buffering
¶
-
newlines
¶
-
next
¶
-
read
()¶ Read at most n characters, returned as a string.
If the argument is negative or omitted, read until EOF is reached. Return an empty string at EOF.
-
readable
() → bool. Returns True if the IO object can be read.¶
-
readline
()¶ Read until newline or EOF.
Returns an empty string if EOF is hit immediately.
-
seek
()¶ Change stream position.
- Seek to character offset pos relative to position indicated by whence:
- 0 Start of stream (the default). pos should be >= 0; 1 Current position - pos must be 0; 2 End of stream - pos must be 0.
Returns the new absolute position.
-
seekable
() → bool. Returns True if the IO object can be seeked.¶
-
tell
()¶ Tell the current file position.
-
truncate
()¶ Truncate size to pos.
The pos argument defaults to the current file position, as returned by tell(). The current file position is unchanged. Returns the new absolute position.
-
writable
() → bool. Returns True if the IO object can be written.¶
-
write
()¶ Write string to file.
Returns the number of characters written, which is always equal to the length of the string.
-
-
kombu.five.
monotonic
()¶
-
kombu.five.
buffer_t
¶ alias of
buffer