Why yet another bencode package in python?
because I need a bencode library:
- Correct, which mean it should fully validate its inputs,
and won't try decode bencode bytes to
str
by default. Bencode doesn't have a utf-8 str type, only bytes, so many decoder try to decode bytes to str and fallback to bytes, this package won't, it parse bencode bytes value as python bytes. - Fast enough, that's why this package is compiled with cython.
- even cross implement, what's why
this package sill have a pure wheel
bencode2-${version}-py3-none-any.whl
pypi.
pip install bencode2
import bencode2
assert bencode2.bdecode(b"d4:spaml1:a1:bee") == {b"spam": [b"a", b"b"]}
# If you want to decode dict with str keys:
# Note: this doesn't work with BitTorrent V2 torrent file.
assert bencode2.bdecode(b"d4:spaml1:a1:bee", str_key=True) == {"spam": [b"a", b"b"]}
assert bencode2.bencode({'hello': 'world'}) == b'd5:hello5:worlde'
bencode have 4 native types, integer, string, array and directory.
This package will decode integer to int
, array to list
and
directory to dict
.
Because bencode string is not defined as utf-8 string, and will contain raw bytes
bencode2 will decode bencode string to python bytes
.
Many python types are supported.
python type | bencode type |
---|---|
bool |
integer 0/1 |
int , enum.IntEnum
|
integer |
str , enum.StrEnum
|
string |
bytes , bytearray ,memoryview
|
string |
list , tuple , NamedTuple
|
array |
dict , OrderedDict
|
directory |
types.MaapingProxy |
directory |
dataclasses | directory |