Skip to main content

A dynamic python base object.

Project description

MObject: A Python Base Object for Nested Property Management and Type-Safe Object Handling

Overview

MObject is an abstract base class designed to provide a robust framework for handling nested properties, translating keys, and managing types efficiently in Python projects. It offers utilities for working with complex object hierarchies, nested key mappings, and type-safe property assignment while supporting serialization to dictionaries. In addition, the base provides features for calculator interfaces.

Naming Convention for Properties

MObject uses a specific naming convention for property annotations to aid in type handling and key translation:

  • _k: Indicates a configuration key.
  • _i: Indicates an input properties.
  • _r: Indicates a result property.

This convention makes it easier to manage and validate properties dynamically while maintaining clear code semantics.

Key Features

  • Nested Property Management: Access and modify nested object properties dynamically using dot-notation.
  • Type-Safe Property Handling: Automatically validate and set properties based on their type annotations.
  • Key Translation: Translate camel-case keys to snake_case for internal use and vice versa for external representation.
  • Serialization: Convert objects to dictionaries, supporting complex types like lists, dictionaries, NumPy arrays, and Enums.
  • Flexible Initialization: Configure initialization using build orders and custom mappings.
  • Enum Management: Seamlessly handle Enums with support for string and integer values.
  • Logging Support: Provides a logging interface to track issues and warnings.

Installation

pip install mobject-klixz

Usage

Defining a Subclass

Create a subclass of MObject to leverage its functionality. Annotate properties using Python's type hints for automatic type inference and validation.

from typing import List, Dict
from enum import Enum

class Status(Enum):
    ACTIVE = 1
    INACTIVE = 0

class MyObject(MObject):
    _name_k: str
    _age_i: int
    _attributes_r: Dict[str, float]
    _status_k: Status

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

Creating an Instance

You can create an instance of your subclass using camelcase keyword arguments:

obj = MyObject(Name="Example", Age=25, Attributes={"height": 5.9}, Status=Status.ACTIVE)

Accessing and Setting Nested Properties

Retrieve and modify nested properties dynamically:

# Get a nested property
nested_value = obj.get_nested_property(["attributes", "height"])

# Set a nested property
obj.set_nested_property(["attributes", "weight"], 70.5)

Serializing to a Dictionary

Convert the object to a dictionary representation:

obj_dict = obj.to_dict()
print(obj_dict)

Translating Keys

MObject automatically translates camel-case keys to snake_case for internal use and vice versa:

# Input keys (external)
print(obj.InputKeys)

# Result keys (external)
print(obj.ResultKeys)

Enum Handling

Set enum values dynamically:

status = MyObject.set_enum("active", Status)
print(status)  # Output: Status.ACTIVE

API Reference

Methods

get_nested_property(obj, props, serializable=False)

Recursively retrieves a nested property from an object.

set_nested_property(obj, props, val, translate=False)

Recursively sets a nested property on an object.

set_enum(val, enum)

Converts a string, integer, or Enum instance into a valid Enum instance.

set(cls, val)

Creates an instance of the class from a dictionary or another instance of the same class.

collect_annotations(cls)

Collects type annotations from the class and its base classes.

to_dict()

Serializes the object into a dictionary, supporting various data types.

Properties

InputKeys

List of translated input keys.

ResultKeys

List of translated result keys.

ClassName

Returns the name of the class.

Logging

The framework uses Python's logging module. You can configure the logger named mobject to control the log level and output format:

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('mobject')

Examples

Example 1: Simple Object

class SimpleObject(MObject):
    value_k: int
    description_i: str

obj = SimpleObject(value=42, description="A simple example.")
print(obj.to_dict())

Example 2: Nested Properties

class NestedObject(MObject):
    metadata_k: Dict[str, Any]

nested = NestedObject(metadata={"info": {"author": "John Doe", "version": 1.0}})
print(nested.get_nested_property(["metadata", "info", "author"]))  # Output: John Doe

Contributing

Contributions are welcome! Please submit issues or pull requests to enhance the functionality or fix bugs.

License

This project is licensed under the MIT License.

Acknowledgments

Special thanks to the Python community for the powerful tools and libraries that make this possible.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mobject_klixz-0.1.1.tar.gz (3.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mobject_klixz-0.1.1-py3-none-any.whl (3.2 kB view details)

Uploaded Python 3

File details

Details for the file mobject_klixz-0.1.1.tar.gz.

File metadata

  • Download URL: mobject_klixz-0.1.1.tar.gz
  • Upload date:
  • Size: 3.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.7

File hashes

Hashes for mobject_klixz-0.1.1.tar.gz
Algorithm Hash digest
SHA256 576761d6c1aaa5fcca35eafa9241e2dcbf0fa38f3506e98f7179cdd5c6781da4
MD5 832a2bfe2dace1e463611dfd08f5ca0f
BLAKE2b-256 14a2ceffc9868aafb8b1ebff2f825eb9344bff1447dd3430b485d817bb0d7221

See more details on using hashes here.

File details

Details for the file mobject_klixz-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: mobject_klixz-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 3.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.7

File hashes

Hashes for mobject_klixz-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b36f64c8a64c7da430e6441372193a4c9ce9480f6c44a4c345a094e0342e787a
MD5 282cfff75819d3396ee4390b6e028de2
BLAKE2b-256 427fabd853223a6bd07f09537b3f2e59fb6db8ba24ae5b0671eb7bb8e42a18ad

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page