### Install development dependencies with uv Source: https://github.com/apeworx/pyrlp/blob/main/docs/contributing.rst Navigate into the cloned directory and install the development dependencies. The dev dependency group is installed by default, so uv sync is sufficient. Then install the prek hooks. ```sh cd pyrlp uv sync uv run prek install ``` -------------------------------- ### Import rlp and sedes types Source: https://github.com/apeworx/pyrlp/blob/main/docs/quickstart.rst Imports the rlp library and the sedes types used in the quickstart examples: big_endian_int, text, and List. ```python >>> import rlp >>> from rlp.sedes import big_endian_int, text, List ``` -------------------------------- ### Install pyrlp with pip Source: https://github.com/apeworx/pyrlp/blob/main/README.md Install the pyrlp package from PyPI using pip. This is the standard installation command for the rlp library. ```sh python -m pip install rlp ``` -------------------------------- ### Install pyrlp via pip Source: https://github.com/apeworx/pyrlp/blob/main/docs/index.rst Use this command to install the pyrlp package using pip. ```bash python -m pip install pyrlp ``` -------------------------------- ### LazyList usage example Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lazy.md Example of using LazyList with rlp.decode_lazy, showing indexing, length, and slicing. ```python import rlp from rlp.sedes import big_endian_int encoded = rlp.encode([10, 20, 30]) lazy = rlp.decode_lazy(encoded, big_endian_int) lazy[2] # 30 len(lazy) # 3 — forces full decode lazy[:2] # (10, 20) lazy[1:2] # (20,) ``` -------------------------------- ### infer_sedes usage examples Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/codec.md Example usage of rlp.infer_sedes with various object types. Shows the resolved sedes for integers, bytes, booleans, and lists. ```python import rlp from rlp.sedes import big_endian_int, List, binary, boolean rlp.infer_sedes(5) # big_endian_int rlp.infer_sedes(b"x") # binary rlp.infer_sedes(True) # boolean rlp.infer_sedes([1, "a"]) # List([big_endian_int, text]) ``` -------------------------------- ### Basic decode() usage with and without sedes Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/codec.md Shows how to decode RLP bytes to raw Python objects and with a big_endian_int sedes to get an integer. ```python import rlp from rlp.sedes import big_endian_int rlp.decode(b"\x82\x04\xd2") # b'\x04\xd2' rlp.decode(b"\x82\x04\xd2", big_endian_int) # 1234 ``` -------------------------------- ### peek usage example Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lazy.md Demonstrates how to use rlp.peek to extract elements from an RLP-encoded nested list, including nested index access and deserialization with sedes. ```python >>> import rlp >>> rlpdata = rlp.encode([1, 2, [3, [4, 5]]]) >>> rlp.peek(rlpdata, 0, rlp.sedes.big_endian_int) 1 >>> rlp.peek(rlpdata, [2, 0], rlp.sedes.big_endian_int) 3 ``` -------------------------------- ### Composing sedes with List, CountableList, and nesting Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/sedes.md Shows how to compose sedes: a fixed-shape List, a CountableList with max_length, and a nested List. Each example encodes and decodes a value, with the expected output shown in comments. ```python import rlp from rlp.sedes import big_endian_int, text, List, CountableList, boolean # fixed-shape record person = List([text, big_endian_int, boolean]) rlp.decode(rlp.encode(["alice", 30, True], person), person) # ('alice', 30, True) # homogeneous variable-length list addresses = CountableList(text, max_length=100) rlp.decode(rlp.encode(["a", "b"], addresses), addresses) # ('a', 'b') # nesting tree = List([big_endian_int, [big_endian_int, []]]) rlp.decode(rlp.encode([1, [2, []]], tree), tree) # (1, (2, ())) ``` -------------------------------- ### Nest rlp.List sedes objects Source: https://github.com/apeworx/pyrlp/blob/main/docs/tutorial.rst Shows how to nest rlp.List sedes objects. The example defines an inner list of two binary elements and an outer list of three inner lists, then decodes encoded data for both. ```default >>> inner = List([binary, binary]) >>> outer = List([inner, inner, inner]) >>> decode(encode(['asdf', 'fdsa']), inner) (b'asdf', b'fdsa') >>> decode(encode([['a1', 'a2'], ['b1', 'b2'], ['c1', 'c2']]), outer) ((b'a1', b'a2'), (b'b1', b'b2'), (b'c1', b'c2')) ``` -------------------------------- ### Lazy decoding example with big_endian_int Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lazy.md Shows how to lazily decode a list with a sedes, accessing elements on demand. Byte-string roots decode eagerly. ```python import rlp from rlp.sedes import big_endian_int lazy = rlp.decode_lazy(rlp.encode([1, 2, [3]]), big_endian_int) lazy[0] # 1 — only this element is decoded list(lazy) # [1, 2, [3]] — decodes the rest on demand # byte-string roots decode eagerly rlp.decode_lazy(rlp.encode(b"abc")) # b'abc' ``` -------------------------------- ### consume_length_prefix(rlp, start) Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/codec.md Helper function to parse an RLP length prefix. ```APIDOC ## `consume_length_prefix(rlp, start)` ### Description Reads one length prefix at the given position of the RLP string. ### Signature `def consume_length_prefix(rlp, start)` ### Parameters - **rlp** (bytes) - Required - RLP string. - **start** (int) - Required - Position to read the prefix from. ### Return tuple `(prefix, type, length, end)` where `type` is `bytes` (builtin `bytes` class) or `list`, `length` is the payload length in bytes, `end` is the position of the first payload byte. ### Raises - `rlp.DecodingError` for non-canonical encodings: single byte encoded as short string, length prefixes starting with zero bytes, long prefixes used for short items ("Long string prefix used for short string" / "Long list prefix used for short list"). ``` -------------------------------- ### pyproject.toml optional dependency for Rust backend Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/configuration.md Declares the optional `rust-backend` extra in `pyproject.toml` to install the `rusty-rlp` package. This extra is used to select the Rust backend at import time; without it, the pure-Python backend is used. ```toml [project.optional-dependencies] rust-backend = ["rusty-rlp>=0.2.1"] ``` -------------------------------- ### peek error handling example Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lazy.md Shows how to catch IndexError when peeking at an element that is not a list, resulting in the error message 'Too many indices given'. ```python import rlp rlpdata = rlp.encode([1, [2, 3]]) try: rlp.peek(rlpdata, [0, 0]) # element 0 is not a list except IndexError as e: print(e) # 'Too many indices given' ``` -------------------------------- ### LazyList Constructor Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/configuration.md Constructor for the LazyList class. Accepts rlp, start, end, sedes, and **sedes_kwargs parameters. ```APIDOC ## LazyList Constructor ### Description Creates a LazyList instance for lazy deserialization of RLP lists. ### Parameters #### Constructor Parameters - **rlp** (bytes) - Required - RLP string containing the list. - **start** (int) - Required - First payload byte position. - **end** (int) - Required - Last payload byte position. - **sedes** (sedes or None) - Optional - Deserializer applied to each element on access. - **\*\*sedes_kwargs** (any) - Optional - Forwarded to the element deserializer. ### Example ```python LazyList(rlp=b'...', start=0, end=10) LazyList(rlp=b'...', start=0, end=10, sedes=BigEndianInt()) ``` ``` -------------------------------- ### consume_item(rlp, start) Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/codec.md Helper function to parse a single RLP item. ```APIDOC ## `consume_item(rlp, start)` ### Description Convenience combination of `consume_length_prefix` + `consume_payload`. ### Signature `def consume_item(rlp, start)` ### Parameters - **rlp** (bytes) - Required - RLP string. - **start** (int) - Required - Position to start parsing. ### Return tuple `(item, per_item_rlp, end)` as in `consume_payload`. ``` -------------------------------- ### Error handling example Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/boolean.md Demonstrates catching SerializationError when serializing an int (1) and DeserializationError when deserializing b"\x02". The error messages are printed. ```python from rlp.exceptions import DeserializationError, SerializationError from rlp.sedes import boolean try: boolean.serialize(1) # int, not bool except SerializationError as e: print(e) # 'Can only serialize integers' try: boolean.deserialize(b"\x02") # only 0x01 / 0x00 (empty) allowed except DeserializationError as e: print(e) # 'Invalid serialized boolean. Must be either 0x01 or 0x00' ``` -------------------------------- ### rlp.encode basic examples Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/codec.md Basic usage of rlp.encode with strings, lists, and integers. Integers are inferred as big_endian_int. The comments show the expected byte output. ```python import rlp rlp.encode("ethereum") # b'\x88ethereum' rlp.encode([]) # b'\xc0' rlp.encode([b"this", [b"is"]]) # b'\xc9\x84this\xc2\x82is' rlp.encode(1234) # b'\x82\x04\xd2' (int inferred as big_endian_int) ``` -------------------------------- ### Round-trip usage example Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/boolean.md Shows encoding and decoding booleans with the boolean sedes. rlp.encode(True, boolean) returns b'\x01', rlp.encode(False, boolean) returns b'', rlp.decode(b"\x01", boolean) returns True, and rlp.decode(b"", boolean) returns False. ```python import rlp from rlp.sedes import boolean rlp.encode(True, boolean) # b'\x01' rlp.encode(False, boolean) # b'' rlp.decode(b"\x01", boolean) # True rlp.decode(b"", boolean) # False ``` -------------------------------- ### LazyList constructor signature Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lazy.md Exact constructor signature for LazyList. Parameters: rlp (bytes), start (int), end (int), sedes (optional), and sedes_kwargs. ```python def __init__(self, rlp, start, end, sedes=None, **sedes_kwargs): ``` -------------------------------- ### MetaBase class definition (rlp.sedes.serializable) Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/types.md Default metadata object for Serializable subclasses. Subclasses get a generated _meta subclass of MetaBase (or a user-supplied _meta). Fields are None by default; the metaclass enforces constraints and raises TypeError on violations. ```python class MetaBase: fields = None field_names = None field_attrs = None sedes = None ``` -------------------------------- ### Encode and decode unicode string with rlp.sedes.binary Source: https://github.com/apeworx/pyrlp/blob/main/docs/tutorial.rst Encodes and decodes a unicode string using the binary sedes, which uses UTF-8. The example shows the encoded bytes and the decoded byte string, and then prints the decoded string after calling .decode('utf-8'). ```default >>> from rlp.sedes import binary >>> encode(u'Ðapp') b'\x85\xc3\x90app' >>> decode(b'\x85\xc3\x90app', binary) b'\xc3\x90app' >>> print(decode(b'\x85\xc3\x90app', binary).decode('utf-8')) Ðapp ``` -------------------------------- ### Build and test documentation before release Source: https://github.com/apeworx/pyrlp/blob/main/docs/contributing.rst Build the HTML documentation and run doctests to verify the documentation is correct before publishing. ```sh uv run --group docs sphinx-build -W -b html docs docs/_build/html uv run --group docs sphinx-build -W -b doctest docs docs/_build/doctest ``` -------------------------------- ### Instantiate Transaction objects and access attributes Source: https://github.com/apeworx/pyrlp/blob/main/docs/tutorial.rst Shows how to create instances using positional or keyword arguments, and that the amount attribute is accessible. ```python >>> tx1 = Transaction(b'me', b'you', 255) >>> tx2 = Transaction(amount=255, sender=b'you', receiver=b'me') >>> tx1.amount 255 ``` -------------------------------- ### Binary.__init__ Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/binary.md Constructor for the Binary sedes class, allowing configuration of length constraints and empty string allowance. ```APIDOC ## Binary.__init__ ### Description Initializes a Binary sedes with optional minimum and maximum length constraints, and an option to allow empty strings. ### Method Constructor ### Signature ```python def __init__(self, min_length=None, max_length=None, allow_empty=False): ``` ### Parameters - **min_length** (int or None) - Optional - Minimal length in bytes; None means no lower limit (stored as 0). - **max_length** (int or None) - Optional - Maximal length in bytes; None means no upper limit (stored as float("inf")). - **allow_empty** (bool) - Optional - If True, an empty string is valid even when a minimum length would otherwise reject it. ### Returns None ``` -------------------------------- ### Build and test the package before release Source: https://github.com/apeworx/pyrlp/blob/main/docs/contributing.rst Before releasing a new version, build the package and run the core tests. This ensures the package builds correctly and passes the test suite. ```sh git checkout main && git pull uv build uv run --group test pytest tests/core ``` -------------------------------- ### List.__init__(elements=None, strict=True) Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lists.md Constructor for the List sedes class, which represents a fixed-length list of element sedes. ```APIDOC ## List.__init__(elements=None, strict=True) ### Description Initializes a List sedes instance. Nested plain sequences are auto-converted to List instances. ### Parameters - **elements** (list of sedes / nested sequences, or None) - Optional - Element sedes. Non-sedes sequences become nested List(e). Defaults to None. - **strict** (bool) - Optional - If True, (de)serializing lists whose length differs from the sedes length raises; if False, (de)serialization stops when either list runs out of elements. Defaults to True. ### Raises - **TypeError** - If any element is neither a sedes nor a Sequence. ``` -------------------------------- ### consume_payload(rlp, prefix, start, type_, length) Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/codec.md Helper function to read the payload of an RLP item. ```APIDOC ## `consume_payload(rlp, prefix, start, type_, length)` ### Description Reads the payload of one item given its already-parsed prefix. ### Signature `def consume_payload(rlp, prefix, start, type_, length)` ### Parameters - **rlp** (bytes) - Required - RLP string. - **prefix** (bytes) - Required - The prefix bytes consumed for this item. - **start** (int) - Required - Position of the first payload byte. - **type_** (type) - Required - `bytes` or `list`. - **length** (int) - Required - Payload length in bytes. ### Return tuple `(item, per_item_rlp, end)` — the decoded item, a list of RLP encodings of each sub-item (index 0 is the full list's RLP), and the position of the first unprocessed byte. ### Raises - `TypeError("Type must be either list or bytes")` for any other `type_`. - `rlp.DecodingError("List length prefix announced a too small length")` when a list payload overshoots its announced bounds. ``` -------------------------------- ### Text.__init__ constructor Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/text.md Constructor for the Text sedes. min_length and max_length are measured in encoded characters, with None stored as 0 and float("inf") respectively. allow_empty permits empty strings even when a minimum length would reject them. ```python def __init__( self, min_length=None, max_length=None, allow_empty=False, encoding="utf8" ): ``` -------------------------------- ### Serializable.__init__ Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/serializable.md Constructor for Serializable instances. Accepts positional and keyword field values in declaration order. ```APIDOC ## Serializable.__init__ ### Description Initializes a new Serializable instance with field values. Field values are made immutable and stored as read-only properties. ### Method Constructor ### Signature ```python def __init__(self, *args, **kwargs) ``` ### Parameters - **\*args** (any) - Positional field values in declaration order. - **\*\*kwargs** (any) - Keyword field values; mixed positional/keyword is allowed and resolved by field name. ### Raises - `TypeError("Argument count mismatch. expected N - got M - missing ...")` - `TypeError` from `merge_kwargs_to_args`: duplicate argument names, duplicate kwargs, unknown kwargs, missing kwargs. ``` -------------------------------- ### Text.__init__ Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/text.md Constructor for the Text sedes class. Initializes a Text instance with optional minimum/maximum length constraints, empty string allowance, and character encoding. ```APIDOC ## Text.__init__ ### Description Initializes a Text sedes instance with configurable length constraints and character encoding. ### Method Constructor ### Signature ```python def __init__( self, min_length=None, max_length=None, allow_empty=False, encoding="utf8" ): ``` ### Parameters - **min_length** (int or None) - Optional - Minimal length in encoded characters; None means no lower limit (stored as 0). - **max_length** (int or None) - Optional - Maximal length in encoded characters; None means no upper limit (stored as float("inf")). - **allow_empty** (bool) - Optional - If True, empty strings are valid even when a minimum length would otherwise reject them. Default: False. - **encoding** (str) - Optional - Codec name passed to str.encode() / bytes.decode(). Default: "utf8". ``` -------------------------------- ### Binary Constructor Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/configuration.md Constructor for the Binary sedes class. Accepts min_length, max_length, and allow_empty parameters to define byte string constraints. ```APIDOC ## Binary Constructor ### Description Creates a Binary sedes instance for serializing/deserializing byte strings with length constraints. ### Parameters #### Constructor Parameters - **min_length** (int or None) - Optional - Minimal bytes; stored as `0` when `None`. - **max_length** (int or None) - Optional - Maximal bytes; stored as `float("inf")` when `None`. - **allow_empty** (bool) - Optional - Allow empty payload regardless of `min_length`. ### Example ```python Binary() Binary(min_length=1, max_length=32, allow_empty=False) ``` ``` -------------------------------- ### Binary constructor signature Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/binary.md Constructor for `Binary` with optional `min_length`, `max_length`, and `allow_empty` parameters. `None` for length means no limit; `allow_empty` permits empty strings even when a minimum length is set. ```python def __init__(self, min_length=None, max_length=None, allow_empty=False): ``` -------------------------------- ### Decode integer with rlp.sedes.big_endian_int Source: https://github.com/apeworx/pyrlp/blob/main/docs/tutorial.rst Decodes an RLP-encoded integer using the big_endian_int sedes object. The example shows the expected output 1503 for the given input bytes. ```default >>> from rlp.sedes import big_endian_int >>> decode(b'\x82\x05\xdf', big_endian_int) 1503 ``` -------------------------------- ### Encode and decode list with rlp.sedes.List Source: https://github.com/apeworx/pyrlp/blob/main/docs/tutorial.rst Encodes a list of mixed types and decodes it using a List sedes object composed of big_endian_int, binary, and big_endian_int. The example shows the encoded bytes and the decoded tuple. ```default >>> from rlp.sedes import List >>> encode([5, 'fdsa', 0]) b'\xc7\x05\x84fdsa\x80' >>> sedes = List([big_endian_int, binary, big_endian_int]) >>> decode(b'\xc7\x05\x84fdsa\x80', sedes) (5, b'fdsa', 0) ``` -------------------------------- ### Binary.fixed_length Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/binary.md Classmethod to create a Binary sedes with fixed length constraints. ```APIDOC ## Binary.fixed_length ### Description Creates a Binary sedes that accepts exactly the specified length in bytes. ### Method Classmethod ### Signature ```python @classmethod def fixed_length(cls, length, allow_empty=False): ``` ### Parameters - **length** (int) - Required - The exact length in bytes that the sedes will accept. - **allow_empty** (bool) - Optional - If True, an empty string is valid even though it does not match the fixed length. ### Returns - **Binary** - A Binary instance with min_length and max_length set to the given length. ``` -------------------------------- ### rlp.encode error handling for unsupported types Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/codec.md Error handling example: attempting to encode a float raises EncodingError because floats have no sedes. The exception object's obj attribute holds the original value. ```python import rlp from rlp.exceptions import EncodingError try: rlp.encode(3.14) # floats have no sedes except EncodingError as e: print(repr(e)) # EncodingError('Cannot encode object of type float') # e.obj == 3.14 ``` -------------------------------- ### Clone the pyrlp repository Source: https://github.com/apeworx/pyrlp/blob/main/docs/contributing.rst Fork the repository to your GitHub account and clone it to your development machine using SSH. ```sh git clone git@github.com:your-github-username/pyrlp.git ``` -------------------------------- ### Error handling with Binary Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/binary.md Demonstrates catching `SerializationError` and `DeserializationError` when using a fixed-length `Binary` with invalid inputs. ```python from rlp.exceptions import DeserializationError, SerializationError from rlp.sedes import Binary h32 = Binary.fixed_length(32) try: h32.serialize(b"short") except SerializationError as e: print(e) # 'Object has invalid length' try: h32.deserialize(b"short") except DeserializationError as e: print(e) # "has invalid length" try: h32.deserialize("text") # decoded value must be bytes/bytearray except DeserializationError as e: print(e) # "Objects of type str cannot be deserialized" ``` -------------------------------- ### Run all tests with pytest Source: https://github.com/apeworx/pyrlp/blob/main/docs/contributing.rst Run the entire test suite using pytest. ```sh pytest tests ``` -------------------------------- ### CountableList.__init__ Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lists.md Constructor for CountableList. Initializes the sedes with an element sedes and an optional maximum length. ```APIDOC ## CountableList.__init__ ### Description Constructor for CountableList. Initializes the sedes with an element sedes and an optional maximum length. ### Method Constructor ### Signature ```python def __init__(self, element_sedes, max_length=None): ``` ### Parameters - **element_sedes** (sedes) - Required - Applied to every element. - **max_length** (int or None) - Optional - Maximum allowed number of elements. Defaults to None. ``` -------------------------------- ### Text Constructor Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/configuration.md Constructor for the Text sedes class. Accepts min_length, max_length, allow_empty, and encoding parameters to define string constraints. ```APIDOC ## Text Constructor ### Description Creates a Text sedes instance for serializing/deserializing text strings with length and encoding constraints. ### Parameters #### Constructor Parameters - **min_length** (int or None) - Optional - Minimal encoded characters; stored as `0` when `None`. - **max_length** (int or None) - Optional - Maximal encoded characters; stored as `float("inf")` when `None`. - **allow_empty** (bool) - Optional - Allow empty string regardless of `min_length`. - **encoding** (str) - Optional - Codec for `str.encode`/`bytes.decode`. Default: `"utf8"`. ### Example ```python Text() Text(min_length=1, max_length=100, allow_empty=False, encoding="utf8") ``` ``` -------------------------------- ### BigEndianInt.__init__(length=None) Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/big_endian_int.md Constructor for the BigEndianInt sedes class. Initializes a serializer with an optional fixed length for the serialized representation. ```APIDOC ## BigEndianInt.__init__(length=None) ### Description Initializes a BigEndianInt instance. If length is None, serialization uses the shortest possible representation (no leading zeros). If length is an integer, serialization is left-padded with zero bytes to exactly that many bytes. ### Method Constructor ### Signature ```python def __init__(self, length=None): ``` ### Parameters - **length** (int or None) - Optional - Size of the serialized representation in bytes. None means "shortest possible" (no leading zeros). ``` -------------------------------- ### Run prek lint manually Source: https://github.com/apeworx/pyrlp/blob/main/docs/contributing.rst Run the prek tool manually to enforce code style. This runs automatically with every commit, but can be run manually with make lint. ```sh make lint ``` -------------------------------- ### copy method Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/serializable.md Creates a new instance from self, overriding the given fields. Fields not overridden are copy.deepcopy-ed; the combined keyword set is resolved with merge_args_to_kwargs. __copy__/__deepcopy__ delegate to copy(). ```python def copy(self, *args, **kwargs): ``` -------------------------------- ### Text module singleton Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/text.md Module-level singleton instance of Text with default (unbounded, UTF-8) constraints. Used by rlp.infer_sedes for str inputs. ```python text = Text() # rlp/sedes/text.py:77 ``` -------------------------------- ### as_dict method Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/serializable.md Returns a dict mapping field names to values in declaration order. ```python def as_dict(self): ``` -------------------------------- ### rlp.sedes.binary Source: https://github.com/apeworx/pyrlp/blob/main/docs/api.rst A sedes object for binary data of arbitrary length, an instance of rlp.sedes.Binary with default arguments. ```APIDOC ## rlp.sedes.binary ### Description A sedes object for binary data of arbitrary length (an instance of `rlp.sedes.Binary` with default arguments). ### Usage This is a sedes object, not a function. It is used as an argument to RLP encoding/decoding functions. ``` -------------------------------- ### Text round-trip with rlp.encode and rlp.decode Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/text.md Shows round-trip usage with the default text sedes. rlp.encode produces the expected bytes for "ethereum", and rlp.decode reverses it, including handling empty strings. ```python import rlp from rlp.sedes import text rlp.encode("ethereum", text) # b'\x88ethereum' rlp.decode(b"\x88ethereum", text) # 'ethereum' rlp.decode(rlp.encode(""), text) # '' ``` -------------------------------- ### Usage pattern for changesets on a Serializable Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/serializable.md Illustrates the two ways to use a changeset on a Serializable object: via the context manager (with build_changeset) or explicit open()/commit() calls. In both cases commit() returns a new modified instance while leaving the original untouched. Mirrors tests in tests/core/test_serializable.py. ```python import rlp from rlp.sedes import text, big_endian_int class Tx(rlp.Serializable): fields = [ ("from", text), ("to", text), ("amount", big_endian_int), ] tx = Tx("me", "you", 255) # context-manager changeset: modify a copy, commit with tx.build_changeset(amount=1000) as cs: cs.amount = 2000 new_tx = cs.commit() new_tx.amount # 2000 (tx is untouched: 255) # explicit open/close API cs = tx.build_changeset() cs.open() cs.to = "them" result = cs.commit() ``` -------------------------------- ### Serializable.copy Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/serializable.md Creates a new instance from self, overriding given fields. ```APIDOC ## Serializable.copy ### Description Creates a new instance from `self`, overriding the given fields. Fields not overridden are deep-copied. ### Method Method ### Signature ```python def copy(self, *args, **kwargs) ``` ### Parameters - **\*args** (any) - Positional field values to override. - **\*\*kwargs** (any) - Keyword field values to override. ### Return Value - **Serializable** - New instance of the same type. ``` -------------------------------- ### Serializable.serialize Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/serializable.md Classmethod that serializes an instance using the class's meta sedes, wrapping list serialization errors. ```APIDOC ## Serializable.serialize ### Description Serializes an instance with the class's `_meta.sedes` (a `List`), wrapping `ListSerializationError` into `ObjectSerializationError`. ### Method Classmethod ### Signature ```python @classmethod def serialize(cls, obj) ``` ### Parameters - **obj** (Serializable) - The instance to serialize. ### Return Value - **list** - An RLP-serializable sequence (list of field serializations). ### Raises - `ObjectSerializationError` ``` -------------------------------- ### Binary.fixed_length classmethod Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/binary.md Classmethod that creates a `Binary` sedes accepting exactly `length` bytes. Returns a `Binary` instance. ```python @classmethod def fixed_length(cls, length, allow_empty=False): ``` -------------------------------- ### List and CountableList usage Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lists.md Demonstrates defining a fixed-shape list schema, encoding and decoding data, using strict=False for length tolerance, and using CountableList for homogeneous variable-length lists. ```APIDOC ## List and CountableList usage ### Description Demonstrates defining a fixed-shape list schema, encoding and decoding data, using strict=False for length tolerance, and using CountableList for homogeneous variable-length lists. ### Code Example ```python import rlp from rlp.sedes import List, CountableList, big_endian_int, text # strict fixed-shape record rec = List([text, big_endian_int]) rlp.decode(rlp.encode(["alice", 42], rec), rec) # ('alice', 42) rec.serialize(["bob", 7]) # ['bob', b'\x07'] # strict=False tolerates length mismatches loose = List([text], strict=False) loose.deserialize([b"a", b"b"]) # ('a',) — stops at sedes end # homogeneous variable-length list tags = CountableList(text, max_length=3) rlp.decode(rlp.encode(["x", "y"], tags), tags) # ('x', 'y') ``` ``` -------------------------------- ### BaseChangeset — class Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/serializable.md Base class for changesets. Provides methods to open, close, commit, and build RLP representations. ```APIDOC ## BaseChangeset ### Description Base class for changesets. Holds the original Serializable, state, and diff. Provides methods to manage the changeset lifecycle and produce a new instance. ### Class Attributes - `__original__` (Any) - The source `Serializable`. - `__state__` (Any) - Member of `ChangesetState`. - `__diff__` (dict) - Field-name → new value dict, initialized from `changes or {}`. ### Constructor `__init__(self, obj, changes=None)` - Initializes the changeset with the given object and optional changes. ### Methods #### commit() - **Description**: Builds the RLP representation, closes the changeset, and returns the new instance. Does not mutate the original. - **Returns**: A new instance of the original class. #### build_rlp() - **Description**: Constructs `type(self.__original__)(**field_kwargs)` where each field is the diffed value or the original's value. Raises `ValueError("Cannot open Changeset which is not in the OPEN state")` unless state is `OPEN`. - **Raises**: `ValueError` if state is not `OPEN`. #### open() - **Description**: Transitions `INITIALIZED → OPEN`. Raises `ValueError("Cannot open Changeset which is not in the INITIALIZED state")` otherwise. - **Raises**: `ValueError` if state is not `INITIALIZED`. #### close() - **Description**: Transitions `OPEN → CLOSED`. Raises `ValueError("Cannot close Changeset which is not in the OPEN state")` otherwise. - **Raises**: `ValueError` if state is not `OPEN`. #### __enter__() - **Description**: Calls `open()` and returns `self`. Raises `ValueError("Cannot open Changeset which is not in the INITIALIZED state")` if already opened/closed. - **Raises**: `ValueError` if state is not `INITIALIZED`. #### __exit__() - **Description**: Calls `close()` if state is `OPEN`. ### Usage Example ```python # context-manager changeset: modify a copy, commit with tx.build_changeset(amount=1000) as cs: cs.amount = 2000 new_tx = cs.commit() new_tx.amount # 2000 (tx is untouched: 255) # explicit open/close API cs = tx.build_changeset() cs.open() cs.to = "them" result = cs.commit() ``` ``` -------------------------------- ### Encode byte strings and lists with rlp.encode() Source: https://github.com/apeworx/pyrlp/blob/main/docs/tutorial.rst Shows how to encode Python strings and lists (including nested lists) into RLP-encoded bytes using rlp.encode(). The output is shown for each input, including empty strings and empty lists. ```default >>> from rlp import encode >>> encode('ethereum') b'\x88ethereum' >>> encode('') b'\x80' >>> encode('Lorem ipsum dolor sit amet, consetetur sadipscing elitr.') b'\xb88Lorem ipsum dolor sit amet, consetetur sadipscing elitr.' >>> encode([]) b'\xc0' >>> encode(['this', ['is', ('a', ('nested', 'list', []))]]) b'\xd9\x84this\xd3\x82is\xcfa\xcd\x86nested\x84list\xc0' ``` -------------------------------- ### Catch patterns for rlp exceptions Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/exceptions.md Shows how to catch RLPException broadly and access failure attributes on ObjectSerializationError. ```python import rlp # broad catch try: rlp.encode(obj) except rlp.RLPException as e: ... # attribute access on the failure payload from rlp.exceptions import ObjectSerializationError try: Tx.deserialize(rlp_bytes) except ObjectSerializationError as e: print(e.field) # field responsible, or None print(e.list_exception) # underlying ListDeserializationError ``` -------------------------------- ### Module singleton binary Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/binary.md Singleton instance of `Binary` with default unbounded constraints, used by `rlp.infer_sedes` for `bytes`/`bytearray` inputs. ```python binary = Binary() # rlp/sedes/binary.py:67 ``` -------------------------------- ### decode() error handling: strict mode and invalid input Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/codec.md Demonstrates non-strict decoding with trailing bytes, strict mode raising DecodingError, and invalid input type raising DecodingError. ```python import rlp from rlp.exceptions import DecodingError # trailing garbage: strict raises, strict=False returns first item payload = rlp.encode([1, 2]) + b"\xff\xff" rlp.decode(payload, strict=False) # [b'\x01', b'\x02'] try: rlp.decode(payload) except DecodingError as e: print(e) # 'RLP string ends with 2 superfluous bytes' # e.rlp == payload try: rlp.decode("not bytes") except DecodingError as e: print(e) # "Can only decode RLP bytes, got type str" ``` -------------------------------- ### Serializable Constructor Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/configuration.md Constructor for the Serializable class. Accepts field values in declaration order or by name. ```APIDOC ## Serializable Constructor ### Description Creates a Serializable instance with field values provided in declaration order or by name. ### Parameters #### Constructor Parameters - **\*args** (any) - Optional - Field values in declaration order. - **\*\*kwargs** (any) - Optional - Field values by name. ### Example ```python Serializable(value1, value2) Serializable(field1=value1, field2=value2) ``` ``` -------------------------------- ### Serializable.as_dict Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/serializable.md Returns a dictionary mapping field names to values in declaration order. ```APIDOC ## Serializable.as_dict ### Description Returns a dictionary mapping field names to values in declaration order. ### Method Method ### Signature ```python def as_dict(self) ``` ### Return Value - **dict** - Mapping of field name to value, in declaration order. ``` -------------------------------- ### Exception hierarchy diagram Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/exceptions.md Shows the inheritance tree of all exception classes, including their attributes. ```text Exception └── RLPException ├── EncodingError (.obj) ├── DecodingError (.rlp) ├── SerializationError (.obj) │ ├── ListSerializationError (.index, .element_exception) │ └── ObjectSerializationError (.sedes, .list_exception, .field) └── DeserializationError (.serial) ├── ListDeserializationError (.index, .element_exception) └── ObjectDeserializationError (.sedes, .list_exception, .field) ``` -------------------------------- ### Encode and decode a custom Serializable class Tx Source: https://github.com/apeworx/pyrlp/blob/main/docs/quickstart.rst Defines a custom Serializable class with three fields, creates an instance, encodes it, and decodes it back, verifying equality. ```python >>> class Tx(rlp.Serializable): ... fields = [ ... ('from', text), ... ('to', text), ... ('amount', big_endian_int) ... ] ... >>> tx = Tx('me', 'you', 255) >>> rlp.encode(tx) b'\xc9\x82me\x83you\x81\xff' >>> rlp.decode(b'\xc9\x82me\x83you\x81\xff', Tx) == tx True ``` -------------------------------- ### List.serialize method signature Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lists.md Serializes a sequence to a list of serialized elements, decorated with eth_utils.to_list. ```python @to_list def serialize(self, obj): ``` -------------------------------- ### Encode and decode an integer with rlp.encode() and rlp.decode() Source: https://github.com/apeworx/pyrlp/blob/main/docs/tutorial.rst Attempts to encode an integer and then decode it. Encoding works, but decoding returns a byte string because RLP is typeless and loses type information. This demonstrates the need for manual deserialization after decoding. ```default >>> encode(1503) b'\x82\x05\xdf' >>> decode(b'\x82\x05\xdf') b'\x05\xdf' ``` -------------------------------- ### List constructor signature Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lists.md Constructor for the List sedes class, accepting element sedes and a strict flag. ```python def __init__(self, elements=None, strict=True): ``` -------------------------------- ### Module singleton big_endian_int Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/big_endian_int.md Creates the standard minimal big-endian integer sedes instance used by rlp.infer_sedes for non-negative int values. ```python big_endian_int = BigEndianInt() # rlp/sedes/big_endian_int.py:56 ``` -------------------------------- ### Handle ListSerializationError and ListDeserializationError Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lists.md Demonstrates catching ListSerializationError for wrong length and element failures, and ListDeserializationError for wrong length during deserialization. Shows how to access error details like e.index and e.element_exception. ```python from rlp.exceptions import ListSerializationError, ListDeserializationError from rlp.sedes import List, big_endian_int pair = List([big_endian_int, big_endian_int]) try: pair.serialize([1]) # wrong length except ListSerializationError as e: print(e) # 'Serializing list length (1) does not match sedes (2)' try: pair.serialize([1, "x"]) # element 1 fails except ListSerializationError as e: print(e.index) # 1 print(type(e.element_exception).__name__) # SerializationError try: pair.deserialize([b"\x01", b"\x02", b"\x03"]) # wrong length except ListDeserializationError as e: print(e) # 'Deserializing list length (3) does not match sedes (2)' ``` -------------------------------- ### Decode RLP-encoded bytes with rlp.decode() Source: https://github.com/apeworx/pyrlp/blob/main/docs/tutorial.rst Shows how to decode RLP-encoded bytes back into Python objects using rlp.decode(). The output is shown for each input, including empty bytes and nested lists. ```default >>> from rlp import decode >>> decode(b'\x88ethereum') b'ethereum' >>> decode(b'\x80') b'' >>> decode(b'\xc0') [] >>> decode(b'\xd9\x84this\xd3\x82is\xcfa\xcd\x86nested\x84list\xc0') [b'this', [b'is', [b'a', [b'nested', b'list', []]]]] ``` -------------------------------- ### Fixed-length integers and error handling with BigEndianInt Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/big_endian_int.md Demonstrates fixed-length serialization and deserialization, and catches SerializationError for oversized integers and DeserializationError for wrong size. ```python from rlp.exceptions import SerializationError, DeserializationError from rlp.sedes import BigEndianInt u32 = BigEndianInt(4) u32.serialize(1) # b'\x00\x00\x00\x01' u32.deserialize(b"\x00\x00\x00\x01") # 1 try: u32.serialize(2**32) # does not fit in 4 bytes except SerializationError as e: print(e) # 'Integer too large (does not fit in 4 bytes)' try: u32.deserialize(b"\x01") # wrong size except DeserializationError as e: print(e) # 'Invalid serialization (wrong size)' ``` -------------------------------- ### Basic encode/decode round-trip with big_endian_int Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/big_endian_int.md Shows encoding and decoding an integer using the inferred sedes and explicit big_endian_int. Zero serializes to the empty string. ```python import rlp from rlp.sedes import big_endian_int rlp.encode(1234) # b'\x82\x04\xd2' (inferred sedes) rlp.decode(b"\x82\x04\xd2", big_endian_int) # 1234 # zero serializes to the empty string rlp.decode(rlp.encode(0, big_endian_int), big_endian_int) # 0 ``` -------------------------------- ### length_prefix(length, offset) Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/codec.md Helper function to construct the RLP length prefix for an item. ```APIDOC ## `length_prefix(length, offset)` ### Description Constructs the RLP prefix byte(s) for an item of the given length. ### Signature `def length_prefix(length, offset)` ### Parameters - **length** (int) - Required - Length of the item in bytes. - **offset** (int) - Required - `0x80` for raw bytes, `0xc0` for a list. ### Return `bytes` — a 1-byte prefix if `length < 56`, else a long-form prefix with a big-endian length word (up to `256**8` bytes). ### Raises - `ValueError("Length greater than 256**8")` for `length >= LONG_LENGTH` (encode wraps this into `EncodingError`). ``` -------------------------------- ### Module singleton boolean Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/boolean.md The module-level boolean instance is created as Boolean(). It is used by rlp.infer_sedes for bool inputs. ```python boolean = Boolean() # rlp/sedes/boolean.py:32 ``` -------------------------------- ### Serializable constructor Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/serializable.md Constructor inherited from BaseSerializable. Accepts positional field values in declaration order and keyword field values; mixed positional/keyword is allowed and resolved by field name. Raises TypeError on argument count mismatch or duplicate/unknown/missing kwargs. ```python def __init__(self, *args, **kwargs): ``` -------------------------------- ### List.serialize(obj) Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lists.md Serializes a sequence into a list of serialized elements. ```APIDOC ## List.serialize(obj) ### Description Serializes the given sequence `obj` into a list of per-element serialized values. ### Parameters - **obj** (sequence) - Required - Value to serialize. ### Returns - **list** - List of serialized elements. ### Raises - **ListSerializationError** - If `obj` is not a sequence, or if `strict` is True and lengths differ, or if any element sedes raises a SerializationError. ``` -------------------------------- ### List.deserialize method signature Source: https://github.com/apeworx/pyrlp/blob/main/_autodocs/api-reference/lists.md Deserializes a decoded RLP sequence into a tuple, decorated with eth_utils.to_tuple. ```python @to_tuple def deserialize(self, serial): ```