API Reference

This module implements encoding and decoding of bittorrent’s bencoding.

exception pybencoding.DecodeError[source]

Bases: exceptions.Exception

Describe a decoding error

exception pybencoding.EncodeError[source]

Bases: exceptions.Exception

Describe an encoding error

pybencoding.decode(data)[source]

Decode a bencoded bytes object

Parameters:data (bytes) – A valid bencoded representation of some object.
Returns:The decoded object.
Return type:bytes, int, dict, list
Raises:DecodeError
pybencoding.encode(val)[source]

Encode a value as a bytearray

Parameters:val

The value that is to be encoded. Can be of type dict, list, int, string, bytes. Dicts and lists can only contain those types. Note that dict objects may not contain keys with a type other than bytes or string and that all keys must have a unique bytes encoding. The following is not valid:

{'hello': 1, b'hello': 2}

because:

'hello'.encode() == b'hello'

Besides the aforementioned types, any type that derives from them is also supported with the expectation that they behave in a sane way. If you supply derived types that don’t behave as we expect these types to behave the results are undefined.

Returns:The bencoded representation of val
Return type:bytes
Raises:EncodeError