my_utilities.mixins package¶
Submodules¶
my_utilities.mixins.compact_pydantic_serializer module¶
- class my_utilities.mixins.compact_pydantic_serializer.SerializableMixin(**data)[source]¶
Bases:
BaseModelMixin for Pydantic models that provides compact serialization into dictionaries with numeric keys and the reverse deserialization.
- The main idea:
Field names are sorted alphabetically and replaced with integer indices.
The model is serialized into a dictionary where keys are field indices.
Works recursively for nested models, collections, and enums.
During deserialization, numeric keys are mapped back to field names.
- Supports:
Primitive types (int, str, float, bool, etc.)
Enum types (stored by their .value)
Nested Pydantic models
Collections (list, tuple, set, dict)
Optional/Union and complex nested structures
Example
- class Address(SerializableMixin):
city: str zip_code: int
- class User(SerializableMixin):
name: str age: int address: Address
user = User(name=”Alice”, age=30, address=Address(city=”NY”, zip_code=10001)) compact = user.to_compact_dict() restored = User.from_compact_dict(compact)
- _abc_impl = <_abc._abc_data object>¶
- classmethod _deserialize_arbitrary_dict(data)[source]¶
Deserialize an arbitrary dictionary that may contain nested structures.
All keys are converted to strings; nested collections are processed recursively.
- Parameters:
data (dict[Any, Any]) – Dictionary with arbitrary key-value types
- Returns:
Fully deserialized dictionary with string keys
- Return type:
dict[str, Any]
- classmethod _deserialize_value(value, field_type, field_info=None)[source]¶
Recursively deserialize a value with respect to its annotated field type.
Supports nested models, enums, lists, tuples, sets, and arbitrary dictionaries.
- Parameters:
value (Any) – Serialized value (int, list, dict, etc.)
field_type (Any) – Type annotation of the field
field_info (Any, optional) – Optional Pydantic field metadata
- Returns:
Deserialized value
- Return type:
Any
- classmethod _serialize_arbitrary_dict(data)[source]¶
Serialize an arbitrary dictionary that is not a Pydantic model.
String keys are kept as-is, values are serialized recursively.
- Parameters:
data (dict[str, Any]) – Arbitrary dictionary to serialize
- Returns:
Serialized dictionary with string keys
- Return type:
dict[str, Any]
- classmethod _serialize_model_dict(data, model_class)[source]¶
Serialize a dictionary representing a Pydantic model into numeric-key format.
- Parameters:
data (dict[str, Any]) – Dictionary obtained from
model_dump()model_class (Type[BaseModel]) – Pydantic model class that owns this dictionary
- Returns:
Serialized dictionary where keys are integer indices
- Return type:
dict[int, Any]
- classmethod _serialize_value(value, field_type=None)[source]¶
Recursively serialize any value (model, collection, enum, etc.) into compact form.
- Parameters:
value (Any) – Value to serialize
field_type (Any) – Type annotation used for recursive type-aware serialization
- Returns:
Serialized value
- Return type:
Any
- classmethod from_compact_dict(compact_data)[source]¶
Deserialize a compact dictionary back into a model instance.
- Parameters:
compact_data (dict[int, Any]) – Dictionary obtained from
to_compact_dict()- Returns:
Restored model instance
- Return type:
- Raises:
ValidationError – If deserialized data does not satisfy model constraints
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- to_compact_dict()[source]¶
Serialize the model into a compact dictionary with numeric keys.
Field names are sorted alphabetically and replaced by sequential indices. Values are recursively serialized, including nested models and collections.
- Returns:
Compact serialized representation of the model
- Return type:
dict[int, Any]
my_utilities.mixins.tst_mode module¶
- class my_utilities.mixins.tst_mode.TestModeMixin(*args, **kwargs)[source]¶
Bases:
objectMixin for switching between production and test implementations of methods depending on the IS_TEST_MODE environment variable.
Example:¶
>>> class MyClass(TestModeMixin): >>> dict_tst_mode = {"base_method": "tst_base_method"} >>> >>> def base_method(self): >>> print("PROD") >>> >>> def tst_base_method(self): >>> print("TEST") >>> >>> MyClass().base_method() # PROD >>> os.environ["IS_TEST_MODE"] = "1" >>> MyClass().base_method() # TEST
- __handle_error(msg, error)¶
Handle error when test substitution fails.
If IS_RAISE_TEST_MODE=1 → raises an exception. Otherwise → emits a warning.
- Return type:
None- Parameters:
msg (str)
error (type[Exception])
- __init__(*args, **kwargs)[source]¶
Initialize mixin and patch test methods if test mode is enabled.
Environment variables: - IS_TEST_MODE=1 → activates test mode - IS_RAISE_TEST_MODE=1 → raises exceptions instead of warnings
- Parameters:
args (Any)
kwargs (Any)
- Return type:
None
-
_dict_tst_mode:
dict[str,str] = {}¶
- _patch_test_methods()[source]¶
Replace production methods with test ones if IS_TEST_MODE=1.
For every pair in dict_tst_mode: - Verify both methods exist and are callable. - Ensure both are of the same type (sync/async). - Dynamically replace the base method with its test equivalent.
- Return type:
None
- property dict_tst_mode: dict[str, str]¶
Return mapping of base methods to their test equivalents.
- Parameters:
args (Any)
kwargs (Any)