### LazyDictStruct Example: Iterating Through Keys Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Demonstrates how to iterate over the keys of a LazyDictStruct. This example shows creating a struct with multiple fields and then converting the iterator to a list. ```python class MyStruct(LazyDictStruct): field1: str field2: int s = MyStruct(field1="value", field2=42) print(list(iter(s))) ``` -------------------------------- ### LazyDictStruct Example: JIT Decoding with msgspec Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Demonstrates how to use LazyDictStruct with msgspec for Just-In-Time decoding of JSON data. It shows defining a struct with a raw field and a cached property for decoding, then encoding and decoding data. ```python import msgspec from functools import cached_property # Assuming YourGiantJsonObject is defined elsewhere # class YourGiantJsonObject: ... class MyStruct(LazyDictStruct): _myField: msgspec.Raw = msgspec.field(name='myField') @cached_property def myField(self) -> YourGiantJsonObject: '''Decode the raw JSON data into a python object when accessed.''' return msgspec.json.decode(self._myField, type=YourGiantJsonObject) # Encode data into a raw JSON format raw_data = msgspec.json.encode({"myField": "some value"}) # Create an instance of MyStruct with the raw data my_struct = MyStruct(_myField=raw_data) # Access the decoded field value print(my_struct.myField) ``` -------------------------------- ### LazyDictStruct Example: Checking Key Existence Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Illustrates how to check for the presence of a key within a LazyDictStruct instance. It shows that keys with actual values return True, while non-existent keys return False. ```python class MyStruct(LazyDictStruct): field1: str s = MyStruct(field1="value") print('field1' in s) print('field2' in s) ``` -------------------------------- ### DictStruct Example: Accessing Items Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Shows how to retrieve key-value pairs from a DictStruct (base class for LazyDictStruct) using the items() method. The output is a list of tuples, where each tuple contains a field name and its corresponding value. ```python class MyStruct(DictStruct): field1: str field2: int s = MyStruct(field1="value", field2=42) print(list(s.items())) ``` -------------------------------- ### Get the Number of Keys in a DictStruct Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Returns the total number of keys (fields) present in a DictStruct instance. This method provides a simple way to determine the size of the struct. ```python class MyStruct(DictStruct): field1: str field2: int s = MyStruct(field1="value", field2=42) len(s) ``` -------------------------------- ### Get Values from DictStruct Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Returns an iterator over the values of all fields in a DictStruct instance. This method is useful for processing or collecting all the data stored within the struct. ```python class MyStruct(DictStruct): field1: str field2: int s = MyStruct(field1="value", field2=42) list(s.values()) ``` -------------------------------- ### Get Value by Key with Default in DictStruct Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Retrieves the value associated with a given key from a DictStruct. If the key is not found, it returns a specified default value instead of raising an error. This provides a safe way to access potentially missing fields. ```python class MyStruct(DictStruct): field1: str s = MyStruct(field1="value") s.get('field1') s.get('field2', 'default') ``` -------------------------------- ### Get Keys from DictStruct Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Returns an iterator over the field names (keys) of a DictStruct instance. This method allows for easy access to all the attribute names defined within the struct. ```python class MyStruct(DictStruct): field1: str field2: int s = MyStruct(field1="value", field2=42) list(s.keys()) ``` -------------------------------- ### Get Key-Value Pairs from DictStruct Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Returns an iterator yielding tuples of (key, value) pairs for all fields in a DictStruct. This is useful for iterating over both the names and values of the struct's attributes simultaneously. ```python class MyStruct(DictStruct): field1: str field2: int s = MyStruct(field1="value", field2=42) list(s.items()) ``` -------------------------------- ### Get Struct Field Values as Iterator (Python) Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md The values() method returns an iterator over the struct's field values. This method is part of the DictStruct class and requires no external dependencies beyond the library itself. It takes no arguments and returns an iterator yielding values of any type. ```python from dictstruct import DictStruct class MyStruct(DictStruct): field1: str field2: int s = MyStruct(field1="value", field2=42) # Get an iterator for the values values_iterator = s.values() # Convert to a list to see the values print(list(values_iterator)) ``` -------------------------------- ### DictStruct: Basic Usage and Dictionary-like Access (Python) Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Demonstrates how to define a class inheriting from DictStruct and access its fields using both attribute and dictionary-style access. It also shows how unset fields raise appropriate errors. ```python from msgspec import UNSET from dictstruct import DictStruct class MyStruct(DictStruct): field1: str field2: int field3: int = UNSET s = MyStruct(field1="value", field2=42) # Dictionary-like access to keys print(list(s.keys())) # Dictionary-like access to values print(s['field1']) # Accessing an unset field via attribute raises AttributeError try: print(s.field3) except AttributeError as e: print(e) # Accessing an unset field via dictionary access raises KeyError try: print(s['field3']) except KeyError as e: print(e) ``` -------------------------------- ### DictStruct: Dictionary-Style Item Retrieval (Python) Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Explains how to retrieve values from a DictStruct using dictionary-style key access (e.g., s['key']). This method raises a KeyError if the key does not exist in the struct. ```python from dictstruct import DictStruct class MyStruct(DictStruct): field1: str s = MyStruct(field1="value") print(s['field1']) try: print(s['field2']) except KeyError as e: print(e) ``` -------------------------------- ### JSON Decoding and Encoding with msgspec Source: https://context7.com/bobthebuidler/dictstruct/llms.txt Illustrates how to use msgspec to decode JSON data directly into typed DictStruct objects and encode DictStruct objects back into JSON. This leverages msgspec's high performance for serialization and deserialization. ```python import msgspec from msgspec import json from dictstruct import DictStruct class Transaction(DictStruct): tx_hash: str block_number: int value: str gas_used: int # Decode JSON directly into typed struct json_data = b'{"tx_hash": "0xabc123", "block_number": 12345, "value": "1000000", "gas_used": 21000}' tx = json.decode(json_data, type=Transaction) print(tx["tx_hash"]) print(tx.block_number) # Encode struct back to JSON encoded = json.encode(tx) print(encoded) # Works with nested structures class Block(DictStruct): number: int transactions: list[Transaction] block_json = b'{"number": 12345, "transactions": [{"tx_hash": "0xabc", "block_number": 12345, "value": "100", "gas_used": 21000}]}' block = json.decode(block_json, type=Block) print(block["number"]) print(block.transactions[0]["tx_hash"]) ``` -------------------------------- ### DictStruct: Checking for Key Presence (Python) Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Shows how to use the 'in' operator to check if a key exists within a DictStruct instance. It returns True only if the key is present and its value is not UNSET. ```python from dictstruct import DictStruct class MyStruct(DictStruct): field1: str s = MyStruct(field1="value") print('field1' in s) print('field2' in s) ``` -------------------------------- ### LazyDictStruct: JIT Decoding for Large JSON Responses in Python Source: https://context7.com/bobthebuidler/dictstruct/llms.txt Explains LazyDictStruct for Just-In-Time (JIT) decoding of field values, ideal for large JSON responses. Fields are stored in raw format until accessed, improving performance and reducing memory usage. Uses `msgspec.Raw` and `functools.cached_property`. ```python import msgspec from msgspec import Raw, field, json from functools import cached_property from dictstruct import LazyDictStruct # Define a struct with lazy fields (prefixed with underscore) class APIResponse(LazyDictStruct): _data: Raw = field(name="data") _metadata: Raw = field(name="metadata") @cached_property def data(self) -> dict: """Decode only when accessed.""" return json.decode(self._data, type=dict) @cached_property def metadata(self) -> dict: """Decode only when accessed.""" return json.decode(self._metadata, type=dict) # Decode raw JSON response raw_json = b'{"data": {"users": [1, 2, 3]}, "metadata": {"total": 100, "page": 1}}' response = json.decode(raw_json, type=APIResponse) # Fields are decoded only when accessed (JIT) print("data" in response) print(list(response.keys())) # First access triggers decoding print(response.data) print(response["metadata"]) # Subsequent access uses cached value print(response.data) ``` -------------------------------- ### Frozen DictStruct: Immutable and Hashable Structs in Python Source: https://context7.com/bobthebuidler/dictstruct/llms.txt Illustrates creating immutable and hashable structs using DictStruct with the `frozen=True` option. These structs can be used as dictionary keys or in sets. List fields are automatically converted to tuples for hashing. ```python from dictstruct import DictStruct class ImmutableConfig(DictStruct, frozen=True): host: str port: int tags: list # Create immutable instance config = ImmutableConfig(host="localhost", port=8080, tags=["api", "v1"]) # Hashable - can be used in sets or as dict keys config_set = {config} config_dict = {config: "primary"} print(hash(config)) print(config in config_set) # Attempting to modify raises an error try: config["port"] = 9090 except TypeError as e: print(f"Cannot modify: {e}") # Lists are automatically converted to tuples for hashing config2 = ImmutableConfig(host="localhost", port=8080, tags=["api", "v1"]) print(hash(config) == hash(config2)) ``` -------------------------------- ### Iterate Dictionary Items Source: https://context7.com/bobthebuidler/dictstruct/llms.txt Demonstrates how to iterate over key-value pairs in a dictionary-like object. This is a fundamental operation for accessing data stored in dictionaries or dictstruct objects. ```python for key, value in response.items(): print(f"{key}: {value}") ``` -------------------------------- ### DictStruct: Dictionary-Compatible Structs in Python Source: https://context7.com/bobthebuidler/dictstruct/llms.txt Demonstrates using DictStruct, a base class extending msgspec.Struct, to enable dictionary API compatibility. It supports iteration, key/value access, and containment checks. Fields set to UNSET raise AttributeError or KeyError upon access. ```python from dictstruct import DictStruct from msgspec import UNSET # Define a struct with typed fields class User(DictStruct): name: str age: int email: str = UNSET # Optional field # Create an instance user = User(name="Alice", age=30) # Dictionary-style access print(user["name"]) print(user.get("email", "N/A")) # Attribute access print(user.name) print(user.age) # Iteration over keys, values, and items print(list(user.keys())) print(list(user.values())) print(list(user.items())) # Containment check print("name" in user) print("email" in user) # Length print(len(user)) # Boolean check (always True, unlike empty dicts) print(bool(user)) # Mutable structs can be modified user["age"] = 31 print(user.age) # Error handling try: _ = user["email"] except KeyError as e: print(f"KeyError: {e}") try: _ = user.email except AttributeError as e: print(f"AttributeError: {e}") ``` -------------------------------- ### DictStruct: Handling Unset Attributes (Python) Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Demonstrates the behavior of accessing an attribute that has been explicitly set to UNSET. This will raise an AttributeError, indicating the attribute is not considered present. ```python from msgspec import UNSET from dictstruct import DictStruct class MyStruct(DictStruct): field1: str = UNSET s = MyStruct() try: print(s.field1) except AttributeError as e: print(e) ``` -------------------------------- ### Implement Hashing for Frozen DictStructs Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Provides a custom hash function for frozen DictStruct instances. It attempts to hash fields directly and converts lists to tuples if a TypeError occurs, ensuring hashability for complex structures. Raises TypeError if the struct is not frozen. ```python class MyStruct(DictStruct, frozen=True): field1: str field2: list s = MyStruct(field1="value", field2=[1, 2, 3]) hash(s) ``` -------------------------------- ### Check if DictStruct is Hashable (Frozen) Source: https://context7.com/bobthebuidler/dictstruct/llms.txt Shows how to check if a DictStruct instance is hashable, which is true when it's frozen (immutable). Hashability allows instances to be used as dictionary keys or in sets. ```python print(isinstance(hash(response), int)) ``` -------------------------------- ### values() Method Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Returns an iterator over the struct’s field values. This method is useful for iterating through all the data stored within a DictStruct object. ```APIDOC ## values() ### Description Returns an iterator over the struct’s field values. ### Method N/A (This is a method of a Python class, not an HTTP endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example ```python class MyStruct(DictStruct): field1: str field2: int s = MyStruct(field1="value", field2=42) list(s.values()) ``` ### Response #### Success Response - **Iterator** (*Iterator*[*Any*]) - An iterator yielding the values of the struct's fields. #### Response Example ```python ['value', 42] ``` ``` -------------------------------- ### DictStruct: Boolean Evaluation (Python) Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Illustrates that a DictStruct object, unlike a standard dictionary, always evaluates to True in a boolean context, as it represents a defined structure. ```python from dictstruct import DictStruct class MyStruct(DictStruct): pass struct_instance = MyStruct() print(bool(struct_instance)) ``` -------------------------------- ### Iterate Through DictStruct Keys Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Allows iteration over the keys (field names) of a DictStruct instance. This method returns an iterator yielding strings representing the struct's keys. Useful for processing all fields of a struct. ```python class MyStruct(DictStruct): field1: str field2: int s = MyStruct(field1="value", field2=42) list(iter(s)) ``` -------------------------------- ### Set Item in DictStruct Source: https://github.com/bobthebuidler/dictstruct/blob/master/docs/index.md Allows setting the value of an attribute within a DictStruct instance using dictionary-like key assignment. Raises an AttributeError if the instance is frozen, preventing modification of immutable structs. ```python class MyStruct(DictStruct): field1: str s = MyStruct("some value") s["field1"] = "new value" class MyFrozenStruct(DictStruct, frozen=True): field1: str s = MyFrozenStruct("some value") s["field1"] = "new value" ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.