sansio_tools package

Submodules

sansio_tools.multihash module

Multihash and multibase support.

This module implements the [multihash](https://github.com/multiformats/multihash) and [multibase](https://github.com/multiformats/multibase) formats, which are used to self-describe content-addressed hashes.

A multihash is the concatenation of three parts:

  1. A varint encoding of the hash function code.

  2. A varint encoding of the digest size (in bytes).

  3. The raw digest produced by the hash function.

Because the function and size are embedded in the value, a multihash can be interpreted without any out-of-band information about which algorithm produced it.

This module provides:

A ready-to-use registry instance with a set of common hash functions is provided at module level.

exception sansio_tools.multihash.BadHashSpecError[source]

Bases: Exception

Raised when a hash specification is malformed.

class sansio_tools.multihash.Digest(function, digest)[source]

Bases: object

A computed hash digest together with the HashFunction that produced it.

digest: bytes
function: HashFunction
to_multihash_base64url()[source]

Output a multihash digest using multibase base64url encoding.

Return type:

str

to_multihash_bytes()[source]

Output a multihash digest as a bytestring.

Return type:

bytes

class sansio_tools.multihash.ExplicitLengthHasher(function, wrapped)[source]

Bases: Hasher

copy()
digest()
Return type:

Digest

digest_bytes()[source]
property digest_size
function: HashFunction
update(data)
update_iter(data)
wrapped: object
class sansio_tools.multihash.HashFunction(name, function_code, digest_size)[source]

Bases: ABC

Describes a hash function.

This is an abstract base class. Subclasses must implement __call__() to return a fresh Hasher for computing digests. A ready-to-use hashlib-backed implementation is provided by HashFunctionHashlib.

Parameters

name: str

User-friendly name.

function_code: int

[Multihash](https://github.com/multiformats/multihash) function code used as a prefix to the multihash.

digest_size: int

Multihash output digest size in bytes, used as the second prefix.

digest_from_bytes(data)[source]

Wrap a raw digest produced by this function into a Digest.

Return type:

Digest

digest_size: int
function_code: int
property multihash_prefix: bytes[source]
name: str
class sansio_tools.multihash.HashFunctionHashlib(name, function_code, digest_size, hashlib_name, hashlib_needs_digest_size)[source]

Bases: HashFunction

A HashFunction backed by a hashlib algorithm.

Inherited parameters are documented on HashFunction.

Additional parameters

hashlib_name: str

Name used to instantiate a hash function using hashlib.new().

hashlib_needs_digest_size: bool

Is the function a variable digest size function (like SHAKE-256)?

digest_from_bytes(data)

Wrap a raw digest produced by this function into a Digest.

Return type:

Digest

digest_size: int
function_code: int
hashlib_name: str
hashlib_needs_digest_size: bool
property multihash_prefix: bytes
name: str
class sansio_tools.multihash.HashFunctionRegistry(hashes=None)[source]

Bases: object

A registry mapping hash function names and (function_code, digest_size) pairs to HashFunction descriptors, and decoding multihash values into Digest objects.

HASHES = (HashFunctionHashlib(name='sha2-256', function_code=18, digest_size=32, hashlib_name='sha256', hashlib_needs_digest_size=False), HashFunctionHashlib(name='sha2-512', function_code=19, digest_size=64, hashlib_name='sha512', hashlib_needs_digest_size=False), HashFunctionHashlib(name='sha3-512', function_code=20, digest_size=64, hashlib_name='sha3_512', hashlib_needs_digest_size=False), HashFunctionHashlib(name='shake256-512', function_code=25, digest_size=64, hashlib_name='shake_256', hashlib_needs_digest_size=True), HashFunctionHashlib(name='blake2s', function_code=45664, digest_size=32, hashlib_name='blake2s', hashlib_needs_digest_size=False), HashFunctionHashlib(name='blake2b', function_code=45632, digest_size=64, hashlib_name='blake2b', hashlib_needs_digest_size=False))
_register(desc)[source]
code_and_size_to_hash: dict[tuple[int, int], HashFunction]
decode(multihash)[source]

Decode a multihash (bytes, or a multibase base64url string) into a Digest.

Raises InvalidHashError if the function code and digest size do not correspond to a registered hash function.

Return type:

Digest

decode_from_code_and_digest(function_code, digest)[source]

Build a Digest directly from a function code and a raw digest.

Return type:

Digest

get_hashfunction(function_code, size)[source]
Return type:

HashFunction

hashes: list = None
name_to_hash: dict[str, HashFunction]
read_from_binary_parser(p)[source]
Return type:

Digest

register(desc)[source]

Register an additional HashFunction at runtime.

class sansio_tools.multihash.Hasher(function, wrapped)[source]

Bases: object

An instantiated hash function. Can be used to hash data via update() or to produce a digest using digest().

copy()[source]
digest()[source]
Return type:

Digest

digest_bytes()[source]
Return type:

bytes

property digest_size
function: HashFunction
update(data)[source]
update_iter(data)[source]
wrapped: object
class sansio_tools.multihash.ImplicitLengthHasher(function, wrapped)[source]

Bases: Hasher

copy()
digest()
Return type:

Digest

digest_bytes()[source]
property digest_size
function: HashFunction
update(data)
update_iter(data)
wrapped: object
exception sansio_tools.multihash.InvalidHashError[source]

Bases: KeyError, BadHashSpecError

Raised when a multihash refers to a hash function that is not registered.

class sansio_tools.multihash.PHasher(hashers, size=0)[source]

Bases: object

A parallel hasher: update several Hasher objects in lockstep with the same data.

copy()[source]
digest()[source]
hashers: dict[Any, Hasher]
size: int = 0
update(data)[source]
sansio_tools.multihash.multibase_decode_base64url(data)[source]

Decode multibase base64url data (the u prefix).

https://github.com/multiformats/multibase

Return type:

bytes

sansio_tools.multihash.multibase_encode_base64url(data)[source]

Encode data as a multibase base64url string (the u prefix).

Return type:

str

sansio_tools.multihash.multihash_varint_encode(n)[source]

Encode a nonnegative integer as an unsigned LEB128 varint (7 bits per byte).

Return type:

bytes

sansio_tools.multihash.read_multihash_raw(p)[source]

Read a complete raw multihash from a BinaryParser.

Returns the (function_code, digest) pair, where digest is the raw digest bytes (not validated against any registered hash function).

Return type:

tuple[int, bytes]

sansio_tools.multihash.read_multihash_raw_header(p)[source]

Read the raw multihash header (the two varint prefixes) from a BinaryParser.

Returns the (function_code, digest_size) pair.

Return type:

tuple[int, int]

sansio_tools.multihash.read_multihash_varint(p)[source]

Read a single unsigned LEB128 varint (at most 9 bytes) from a BinaryParser, as used by the multihash format.

Raises ValueError if the encoding is non-canonical or longer than 9 bytes, and UnexpectedEOFError if the stream ends in the middle of the varint.

Return type:

int

sansio_tools.parser module

class sansio_tools.parser.BinaryParser(generator=None, trailing_data_raises=True)[source]

Bases: Parser[bytes | bytearray | memoryview]

Generator-based binary parser.

Example:

import struct

struc = struct.Struct("!BB")
output = []

def parse_func(p: BinaryParser):
    header = yield from p.read_bytes(4)
    if header != b"ABCD":
        raise ValueError("invalid header")

    record_count = yield from p.read_int(2, "big", False)
    for i in range(record_count):
        x, y = yield from p.read_struct(struc)
        output.append((x, y))

parser = BinaryParser(parse_func)

parser.feed(b"ABCD")
parser.feed(None)  # signal end of stream

print(output)
# [(6, 7), (3, 5)]
_init_queue()[source]
_read_bytes(nbytes)[source]
Return type:

Generator[None, None, bytes | memoryview | bytearray]

_repr_attribs()
advance()

Call advance_one() to progress the parsing until no more progress can be made.

Return type:

None

advance_one()

Return whether any progress was made.

We consider that progress was made if the generator yielded a truthy value or if the queue became smaller.

If no progress was made and eof is True and the generator has not yet exited, then raise UnexpectedEOFError.

Return type:

bool

property buffered_count: int
eof: bool = False
feed(data)

Add data to the internal buffer queue, then call advance() to parse as much as possible.

If data is None, then that’s the end of the input stream so set eof to True.

feed_from_file(file, buffer_size=65536, finish=True)

Feed the full contents of file as an input. If finish is True, then also signal the end of stream.

feed_from_iter(iterator, finish=True)

Feed the contents of iterator until it runs out. If finish is True, then also signal the end of stream.

feed_without_parsing(data)
Return type:

None

property generator_exited
generator_return_value: Any = ['NOT_YET_EXITED']
position: int = 0
queue: SolidQueue[TypeVar(T)]
read_bytes(nbytes)[source]
Return type:

Generator[None, None, bytes]

read_int(nbytes, byteorder, signed)[source]
Return type:

Generator[None, None, int]

read_struct(struct)[source]
Return type:

Generator[None, None, list]

read_variable_length_int_7bit(maximum_length, byteorder, continuation_bit_value, require_canonical)[source]
trailing_data_raises: bool = True
wait(nbytes)[source]
Return type:

Generator[None, None, None]

class sansio_tools.parser.CharacterRanges(codepoints)[source]

Bases: object

Represents a list of character ranges.

Each range is an (start, end) pair of code points, including start but not including end.

property as_regex: str | None

Return a regular expression character class (e.g. [a-z0-9]) that matches zero or more of the characters contained in this CharacterRanges.

as_regex_object
codepoints: tuple[tuple[int, int], ...]
class sansio_tools.parser.Parser(generator=None, trailing_data_raises=True)[source]

Bases: Generic[T]

abstract _init_queue()[source]
_repr_attribs()[source]
advance()[source]

Call advance_one() to progress the parsing until no more progress can be made.

Return type:

None

advance_one()[source]

Return whether any progress was made.

We consider that progress was made if the generator yielded a truthy value or if the queue became smaller.

If no progress was made and eof is True and the generator has not yet exited, then raise UnexpectedEOFError.

Return type:

bool

property buffered_count: int
eof: bool = False
feed(data)[source]

Add data to the internal buffer queue, then call advance() to parse as much as possible.

If data is None, then that’s the end of the input stream so set eof to True.

feed_from_file(file, buffer_size=65536, finish=True)[source]

Feed the full contents of file as an input. If finish is True, then also signal the end of stream.

feed_from_iter(iterator, finish=True)[source]

Feed the contents of iterator until it runs out. If finish is True, then also signal the end of stream.

feed_without_parsing(data)[source]
Return type:

None

property generator_exited
generator_return_value: Any = ['NOT_YET_EXITED']
position: int = 0
queue: SolidQueue[TypeVar(T)]
trailing_data_raises: bool = True
class sansio_tools.parser.StringParser(generator=None, trailing_data_raises=True)[source]

Bases: Parser[str | StringSlice]

Generator-based text parser.

_init_queue()[source]
_repr_attribs()
advance()

Call advance_one() to progress the parsing until no more progress can be made.

Return type:

None

advance_one()

Return whether any progress was made.

We consider that progress was made if the generator yielded a truthy value or if the queue became smaller.

If no progress was made and eof is True and the generator has not yet exited, then raise UnexpectedEOFError.

Return type:

bool

property buffered_count: int
eof: bool = False
feed(data)

Add data to the internal buffer queue, then call advance() to parse as much as possible.

If data is None, then that’s the end of the input stream so set eof to True.

feed_from_file(file, buffer_size=65536, finish=True)

Feed the full contents of file as an input. If finish is True, then also signal the end of stream.

feed_from_iter(iterator, finish=True)

Feed the contents of iterator until it runs out. If finish is True, then also signal the end of stream.

feed_without_parsing(data)
Return type:

None

property generator_exited
generator_return_value: Any = ['NOT_YET_EXITED']
position: int = 0
queue: SolidQueue[TypeVar(T)]
read_character_ranges(allowed, min_length, max_length)[source]

Like read_character_ranges_iter() but it directly returns a tuple of the concatenated strings or a string slice as well as the reason why we stopped reading the string.

Return type:

Generator[None, None, tuple[str | StringSlice, StringStopReason]]

read_character_ranges_iter(allowed, min_length, max_length)[source]

Read strings matching allowed with a total length between min_length and max_length. Raise UnexpectedCharacterError if fewer than min_length matching characters are found before an EOF or a non-matching character.

This generator exits upon EOF, when max_length matching characters have been read, or when a character not matching allowed is encountered. The terminating character (if any) is left in the queue so that the caller can continue parsing from it.

The generator yields strings and StringSlice objects as they are read, yielding None whenever it needs more data. At the end, it returns a single StringStopReason.

If both MAX_LENGTH and FORBIDDEN apply, then MAX_LENGTH is returned. If both MAX_LENGTH and EOF apply, then MAX_LENGTH is returned.

Return type:

Generator[str | StringSlice | None, None, StringStopReason]

trailing_data_raises: bool = True
class sansio_tools.parser.StringStopReason(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

EOF = 2
FORBIDDEN = 3
MAX_LENGTH = 1
exception sansio_tools.parser.TrailingDataError[source]

Bases: ValueError

Raised if there is unparsed data at the end and Parser.trailing_data_raises is false.

exception sansio_tools.parser.UnexpectedCharacterError[source]

Bases: ValueError

Raised by StringParser.read_character_ranges() if fewer than the required number of matching characters are found.

exception sansio_tools.parser.UnexpectedEOFError[source]

Bases: ValueError

Raised if the input stream ends while the parser is expecting more data.

sansio_tools.parser._complain(p)[source]
sansio_tools.parser._regex_escape_char(char)[source]

Escape a single character so it can be safely placed inside a regular expression character class.

Return type:

str

sansio_tools.queue module

class sansio_tools.queue.BytesQueue(iterable=())[source]

Bases: SolidQueue[bytes | memoryview]

_consolidate_left(n)

This function attempts to consolidate exactly n items from the queue into a single object.

Return type:

bool

Pre-conditions:
  • n must be an integer representing the number of items needed for consolidation.

Post-conditions:
  • Returns True if successful, False otherwise.

  • If there are enough items in the queue, they will be consolidated into a single object at the front of the queue with length exactly n.

_consolidate_right(n)

Similar to _consolidate_left() but operates on the back of the queue instead of the front.

Return type:

bool

static _join(to_join)[source]
static _len(array)[source]
Return type:

int

static _split(array, index)[source]
append(array)

Add items at the end of the queue.

Return type:

None

appendleft(array)

Place data back at the front of the queue. This effectively undoes the previous popleft() operation.

Return type:

None

clear()
property contents: T

Consolidate the sequences of items into one sequence, and then return it.

copy()
data: deque[TypeVar(T)]
iter_blocks()
length: int
peek(n)

Get an array of n items from the back, or None if that is not possible. As a side effect, the next popleft_any() call will remove exactly n items.

Return type:

Optional[TypeVar(T)]

peek_any()
Return type:

Optional[TypeVar(T)]

peekleft(n)

Get an array of n items from the front, or None if that is not possible. As a side effect, the next popleft_any() call will remove exactly n items.

Return type:

Optional[TypeVar(T)]

peekleft_any()
Return type:

Optional[TypeVar(T)]

pop(n)

Remove n items from the back of the queue and return them.

Return type:

TypeVar(T)

pop_all_to(queue)

Transfer all items from this queue to the front of another queue.

Return type:

Optional[TypeVar(T)]

pop_any()

Pop a block of items from the back of the queue. Any size may be returned.

Return type:

Optional[TypeVar(T)]

pop_any_to(queue)

Transfer a block of items from the back of this queue to the front of another queue.

Return type:

Optional[TypeVar(T)]

pop_to(n, queue)

Transfer n items from the back of this queue to the front of another queue.

Return type:

None

popleft(n)

Remove n items from the front of the queue and return them.

Return type:

TypeVar(T)

popleft_after(n)

Control flow magic, used as:

with self.popleft_after(num_bytes) as data:
    BODY

If there are less than n data items waiting, then raise NeedMoreItemsError. Otherwise return those items the data variable and execute the code in BODY. If BODY exits without raising an exception, then remove those items from the data items queue.

If n is None, any nonzero number of items may be returned.

Return type:

TypeVar(T)

popleft_all_to(queue)

Transfer all items from this queue to the back of another queue.

Return type:

Optional[TypeVar(T)]

popleft_any()

Pop a block of items from the front of the queue. Any size may be returned.

Return type:

Optional[TypeVar(T)]

popleft_any_to(queue)

Transfer a block of items from the front of this queue to the back of another queue.

Return type:

Optional[TypeVar(T)]

popleft_to(n, queue)

Transfer n items from the front of this queue to the back of another queue.

Return type:

None

swap(queue)

Swap contents with another queue.

Return type:

None

temporary_left()

Control flow magic, used as:

q = SolidQueue(...)
with q.temporary_left() as tmp:
    block1 = q.popleft_to(tmp)
    do_stuff_with(block1)

    block2 = q.popleft_to(tmp)
    do_stuff_with(block2)

At the end of the “with” block, the contents of tmp are transferred to the front of this queue.

Return type:

Iterator[SolidQueue[TypeVar(T)]]

class sansio_tools.queue.FileAdapterFromGeneratorBytes(generator)[source]

Bases: RawIOBase

Use this to turn a generator that yields bytes into a file-like object.

_buffered: bytes | memoryview = b''
property _buffered_count
_checkClosed()
_checkReadable()
_checkSeekable()
_checkWritable()
_generator: Generator[bytes | bytearray | memoryview | None, None, None]
_repr_attribs()[source]
close()[source]

Flush and close the IO object.

This method has no effect if the file is already closed.

closed
fileno()

Return underlying file descriptor if one exists.

Raise OSError if the IO object does not use a file descriptor.

flush()

Flush write buffers, if applicable.

This is not implemented for read-only and non-blocking streams.

isatty()

Return whether this is an ‘interactive’ stream.

Return False if it can’t be determined.

read(size=-1, /)
readable()[source]

Return whether object was opened for reading.

If False, read() will raise OSError.

readall()

Read until EOF, using multiple read() call.

readinto(b)[source]
readline(size=-1, /)

Read and return a line from the stream.

If size is specified, at most size bytes will be read.

The line terminator is always b’n’ for binary files; for text files, the newlines argument to open can be used to select the line terminator(s) recognized.

readlines(hint=-1, /)

Return a list of lines from the stream.

hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.

seek(offset, whence=0, /)

Change the stream position to the given byte offset.

offset

The stream position, relative to ‘whence’.

whence

The relative position to seek from.

The offset is interpreted relative to the position indicated by whence. Values for whence are:

  • os.SEEK_SET or 0 – start of stream (the default); offset should be zero or positive

  • os.SEEK_CUR or 1 – current stream position; offset may be negative

  • os.SEEK_END or 2 – end of stream; offset is usually negative

Return the new absolute position.

seekable()[source]

Return whether object supports random access.

If False, seek(), tell() and truncate() will raise OSError. This method may need to do a test seek().

tell()

Return current stream position.

truncate(size=None, /)

Truncate file to size bytes.

File pointer is left unchanged. Size defaults to the current IO position as reported by tell(). Return the new size.

writable()[source]

Return whether object was opened for writing.

If False, write() will raise OSError.

write()
writelines(lines, /)

Write a list of lines to stream.

Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.

exception sansio_tools.queue.NeedMoreItemsError[source]

Bases: IndexError

class sansio_tools.queue.SolidQueue(iterable=())[source]

Bases: Generic[T], ABC

Abstract class implementing a queue using sequences of items.

This data structure is not thread-safe.

_consolidate_left(n)[source]

This function attempts to consolidate exactly n items from the queue into a single object.

Return type:

bool

Pre-conditions:
  • n must be an integer representing the number of items needed for consolidation.

Post-conditions:
  • Returns True if successful, False otherwise.

  • If there are enough items in the queue, they will be consolidated into a single object at the front of the queue with length exactly n.

_consolidate_right(n)[source]

Similar to _consolidate_left() but operates on the back of the queue instead of the front.

Return type:

bool

abstract _join(to_join)[source]
Return type:

TypeVar(T)

abstract _len(array)[source]
Return type:

int

abstract _split(array, index)[source]
Return type:

tuple[TypeVar(T), TypeVar(T)]

append(array)[source]

Add items at the end of the queue.

Return type:

None

appendleft(array)[source]

Place data back at the front of the queue. This effectively undoes the previous popleft() operation.

Return type:

None

clear()[source]
property contents: T

Consolidate the sequences of items into one sequence, and then return it.

copy()[source]
data: deque[TypeVar(T)]
iter_blocks()[source]
length: int
peek(n)[source]

Get an array of n items from the back, or None if that is not possible. As a side effect, the next popleft_any() call will remove exactly n items.

Return type:

Optional[TypeVar(T)]

peek_any()[source]
Return type:

Optional[TypeVar(T)]

peekleft(n)[source]

Get an array of n items from the front, or None if that is not possible. As a side effect, the next popleft_any() call will remove exactly n items.

Return type:

Optional[TypeVar(T)]

peekleft_any()[source]
Return type:

Optional[TypeVar(T)]

pop(n)[source]

Remove n items from the back of the queue and return them.

Return type:

TypeVar(T)

pop_all_to(queue)[source]

Transfer all items from this queue to the front of another queue.

Return type:

Optional[TypeVar(T)]

pop_any()[source]

Pop a block of items from the back of the queue. Any size may be returned.

Return type:

Optional[TypeVar(T)]

pop_any_to(queue)[source]

Transfer a block of items from the back of this queue to the front of another queue.

Return type:

Optional[TypeVar(T)]

pop_to(n, queue)[source]

Transfer n items from the back of this queue to the front of another queue.

Return type:

None

popleft(n)[source]

Remove n items from the front of the queue and return them.

Return type:

TypeVar(T)

popleft_after(n)[source]

Control flow magic, used as:

with self.popleft_after(num_bytes) as data:
    BODY

If there are less than n data items waiting, then raise NeedMoreItemsError. Otherwise return those items the data variable and execute the code in BODY. If BODY exits without raising an exception, then remove those items from the data items queue.

If n is None, any nonzero number of items may be returned.

Return type:

TypeVar(T)

popleft_all_to(queue)[source]

Transfer all items from this queue to the back of another queue.

Return type:

Optional[TypeVar(T)]

popleft_any()[source]

Pop a block of items from the front of the queue. Any size may be returned.

Return type:

Optional[TypeVar(T)]

popleft_any_to(queue)[source]

Transfer a block of items from the front of this queue to the back of another queue.

Return type:

Optional[TypeVar(T)]

popleft_to(n, queue)[source]

Transfer n items from the front of this queue to the back of another queue.

Return type:

None

swap(queue)[source]

Swap contents with another queue.

Return type:

None

temporary_left()[source]

Control flow magic, used as:

q = SolidQueue(...)
with q.temporary_left() as tmp:
    block1 = q.popleft_to(tmp)
    do_stuff_with(block1)

    block2 = q.popleft_to(tmp)
    do_stuff_with(block2)

At the end of the “with” block, the contents of tmp are transferred to the front of this queue.

Return type:

Iterator[SolidQueue[TypeVar(T)]]

class sansio_tools.queue.StringQueue(iterable=())[source]

Bases: SolidQueue[str | StringSlice]

_consolidate_left(n)

This function attempts to consolidate exactly n items from the queue into a single object.

Return type:

bool

Pre-conditions:
  • n must be an integer representing the number of items needed for consolidation.

Post-conditions:
  • Returns True if successful, False otherwise.

  • If there are enough items in the queue, they will be consolidated into a single object at the front of the queue with length exactly n.

_consolidate_right(n)

Similar to _consolidate_left() but operates on the back of the queue instead of the front.

Return type:

bool

static _join(to_join)[source]
static _len(array)[source]
Return type:

int

static _split(array, index)[source]
append(array)

Add items at the end of the queue.

Return type:

None

appendleft(array)

Place data back at the front of the queue. This effectively undoes the previous popleft() operation.

Return type:

None

clear()
property contents: T

Consolidate the sequences of items into one sequence, and then return it.

copy()
data: deque[TypeVar(T)]
iter_blocks()
length: int
peek(n)

Get an array of n items from the back, or None if that is not possible. As a side effect, the next popleft_any() call will remove exactly n items.

Return type:

Optional[TypeVar(T)]

peek_any()
Return type:

Optional[TypeVar(T)]

peekleft(n)

Get an array of n items from the front, or None if that is not possible. As a side effect, the next popleft_any() call will remove exactly n items.

Return type:

Optional[TypeVar(T)]

peekleft_any()
Return type:

Optional[TypeVar(T)]

pop(n)

Remove n items from the back of the queue and return them.

Return type:

TypeVar(T)

pop_all_to(queue)

Transfer all items from this queue to the front of another queue.

Return type:

Optional[TypeVar(T)]

pop_any()

Pop a block of items from the back of the queue. Any size may be returned.

Return type:

Optional[TypeVar(T)]

pop_any_to(queue)

Transfer a block of items from the back of this queue to the front of another queue.

Return type:

Optional[TypeVar(T)]

pop_to(n, queue)

Transfer n items from the back of this queue to the front of another queue.

Return type:

None

popleft(n)

Remove n items from the front of the queue and return them.

Return type:

TypeVar(T)

popleft_after(n)

Control flow magic, used as:

with self.popleft_after(num_bytes) as data:
    BODY

If there are less than n data items waiting, then raise NeedMoreItemsError. Otherwise return those items the data variable and execute the code in BODY. If BODY exits without raising an exception, then remove those items from the data items queue.

If n is None, any nonzero number of items may be returned.

Return type:

TypeVar(T)

popleft_all_to(queue)

Transfer all items from this queue to the back of another queue.

Return type:

Optional[TypeVar(T)]

popleft_any()

Pop a block of items from the front of the queue. Any size may be returned.

Return type:

Optional[TypeVar(T)]

popleft_any_to(queue)

Transfer a block of items from the front of this queue to the back of another queue.

Return type:

Optional[TypeVar(T)]

popleft_to(n, queue)

Transfer n items from the front of this queue to the back of another queue.

Return type:

None

swap(queue)

Swap contents with another queue.

Return type:

None

temporary_left()

Control flow magic, used as:

q = SolidQueue(...)
with q.temporary_left() as tmp:
    block1 = q.popleft_to(tmp)
    do_stuff_with(block1)

    block2 = q.popleft_to(tmp)
    do_stuff_with(block2)

At the end of the “with” block, the contents of tmp are transferred to the front of this queue.

Return type:

Iterator[SolidQueue[TypeVar(T)]]

class sansio_tools.queue.StringSlice(string, start, stop)[source]

Bases: object

cut(index)[source]
classmethod new(string)[source]
start: int
stop: int
string: str
sansio_tools.queue.atomic(function)[source]

In a future/better version of Python, maybe it will be possible to temporarily disable KeyboardInterrupt and other exceptions. This is currently a no-op.

Module contents