This document is for py-amqp's development version, which can be significantly different from previous releases. Get the stable docs here: 2.2.

amqp.five

Python 2/3 compatibility.

Compatibility implementations of features only available in newer Python versions.

class amqp.five.Counter(**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)]
copy()[source]

Return a shallow copy.

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.

classmethod fromkeys(S[, v]) → New dict with keys from S and values equal to v.[source]

v defaults to None.

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(**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(**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
amqp.five.reload(module) → module

Reload the module. The module must have been successfully imported before.

class amqp.five.UserList(initlist=None)[source]
append(item)[source]

S.append(object) – append object to the end of the sequence

count(value) → integer -- return number of occurrences of value[source]
extend(other)[source]

S.extend(iterable) – extend sequence by appending elements from the iterable

index(value) → integer -- return first index of value.[source]

Raises ValueError if the value is not present.

insert(i, item)[source]

S.insert(index, object) – insert object before index

pop([index]) → item -- remove and return item at index (default last).[source]

Raise IndexError if list is empty or index is out of range.

remove(item)[source]

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()[source]

S.reverse() – reverse IN PLACE

sort(*args, **kwds)[source]
class amqp.five.UserDict(**kwargs)[source]
clear()[source]
copy()[source]
classmethod fromkeys(iterable, value=None)[source]
get(key, failobj=None)[source]
has_key(key)[source]
items()[source]
iteritems()[source]
iterkeys()[source]
itervalues()[source]
keys()[source]
pop(key, *args)[source]
popitem()[source]
setdefault(key, failobj=None)[source]
update(**kwargs)[source]
values()[source]
class amqp.five.Queue(maxsize=0)[source]

Create a queue object with a given maximum size.

If maxsize is <= 0, the queue size is infinite.

empty()[source]

Return True if the queue is empty, False otherwise (not reliable!).

full()[source]

Return True if the queue is full, False otherwise (not reliable!).

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.

qsize()[source]

Return the approximate size of the queue (not reliable!).

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.

exception amqp.five.Empty[source]

Exception raised by Queue.get(block=0)/get_nowait().

exception amqp.five.Full[source]

Exception raised by Queue.put(block=0)/put_nowait().

class amqp.five.LifoQueue(maxsize=0)[source]

Variant of Queue that retrieves most recently added entries first.

amqp.five.array(typecode, *args, **kwargs)[source]

Create array.

amqp.five.zip_longest

alias of itertools.izip_longest

amqp.five.map

alias of itertools.imap

amqp.five.zip

alias of itertools.izip

amqp.five.string

alias of __builtin__.unicode

amqp.five.string_t

alias of __builtin__.basestring

amqp.five.bytes_t

alias of __builtin__.str

amqp.five.bytes_if_py2(s)[source]

Convert str to bytes if running under Python 2.

amqp.five.long_t

alias of __builtin__.long

amqp.five.text_t

alias of __builtin__.unicode

amqp.five.module_name_t

alias of __builtin__.str

amqp.five.range

alias of __builtin__.xrange

amqp.five.items(d)[source]

Return dict items iterator.

amqp.five.keys(d)[source]

Return dict key iterator.

amqp.five.values(d)[source]

Return dict values iterator.

amqp.five.nextfun(it)[source]

Return iterator next method.

amqp.five.reraise(tp, value, tb=None)[source]
class amqp.five.WhateverIO(v=None, *a, **kw)[source]

StringIO that takes bytes or str.

write(data)[source]

Write string to file.

Returns the number of characters written, which is always equal to the length of the string.

amqp.five.with_metaclass(Type, skip_attrs=None)[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 amqp.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

Line endings translated so far.

Only line endings translated during reading are considered.

Subclasses should override.

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.

amqp.five.getfullargspec(fun, _fill=(None, None, None))[source]

For compatibility with Python 3.

amqp.five.format_d(i)[source]

Format number.

amqp.five.monotonic()
amqp.five.buffer_t

alias of __builtin__.buffer

amqp.five.python_2_unicode_compatible(cls)[source]

Class decorator to ensure class is compatible with Python 2.