Skip to main content

This repository includes typing used in the Swarmauri framework.

Project description

Swarmauri Logo

PyPI - Downloads Hits PyPI - Python Version PyPI - License PyPI - swarmauri-typing


Swarmauri Typing

The Swarmauri Typing Library provides advanced type utilities for Python, enabling more expressive and flexible type annotations. It includes tools for creating intersection and union types dynamically.

Features

  • Intersection Types: Create intersection types that combine multiple classes.
from typing import Type, TypeVar, Union, Any, Annotated, Tuple

T = TypeVar("T")

class IntersectionMetadata:
    def __init__(self, classes: Tuple[Type[T]]):
        self.classes = classes

    def __repr__(self):
        return f"IntersectionMetadata(classes={self.classes!r})"

class Intersection(type):
    def __class_getitem__(cls, classes: Union[Type, Tuple[Type, ...]]) -> type:
        if not isinstance(classes, tuple):
            classes = (classes,)

        common = set(classes[0].__mro__)
        for c in classes[1:]:
            common.intersection_update(c.__mro__)

        ordered_common = [c for c in classes[0].__mro__ if c in common]

        if not ordered_common:
            return Annotated[Any, IntersectionMetadata(classes=(classes))]
        else:
            union_type = Union[tuple(ordered_common)]
            return Annotated[union_type, IntersectionMetadata(classes=(classes))]
  • Union Factory: Dynamically create union types based on a provided function.
from typing import Type, TypeVar, Callable, List, Union, Any, Annotated, get_args, Optional

T = TypeVar("T")

class UnionFactoryMetadata:
    def __init__(self, data: Any, name: Optional[str] = None):
        self.data = data
        self.name = name or self.__class__.__name__

    def __repr__(self):
        return f"UnionFactoryMetadata(name={self.name!r}, data={self.data!r})"

class UnionFactory:
    def __init__(self, bound: Callable[[Type[T]], List[type]], name: str = None, annotation_extenders: List[Any] = None):
        self.name = name or self.__class__.__name__
        self._union_types_getter = bound
        self._annotation_extenders = annotation_extenders or []

    def _add_metadata(self, annotated_type: Any, new_metadata: Any) -> Any:
        if not (hasattr(annotated_type, '__origin__') and annotated_type.__origin__ is Annotated):
            return Annotated[annotated_type, new_metadata]

        args = get_args(annotated_type)
        base_type = args[0]
        old_metadata = args[1:]
        return Annotated[base_type, *old_metadata, new_metadata]

    def __getitem__(self, input_data: Union[Type[T], str]) -> type:
        if isinstance(input_data, str):
            model_name = input_data
        else:
            model_name = input_data.__name__

        union_members = self._union_types_getter(model_name)

        if not union_members:
            final_annotated = Annotated[Any, UnionFactoryMetadata(data=model_name, name=self.name)]
        else:
            union_type = Union[tuple(union_members)]
            final_annotated = Annotated[union_type, UnionFactoryMetadata(data=model_name, name=self.name)]

            for extension in self._annotation_extenders:
                final_annotated = self._add_metadata(final_annotated, extension)

        return final_annotated

Getting Started

To start using the Swarmauri Typing Library, include it as a module in your Python project. Ensure you have Python 3.10 or later installed.

Steps to install via pypi

pip install swarmauri-typing

Usage Example

from swarmauri_typing import Intersection, UnionFactory

# Example of using Intersection
class A: pass
class B: pass

IntersectionType = Intersection[A, B]

# Example of using UnionFactory
def my_types_getter(name: str):
    return [A, B]

union_factory = UnionFactory(my_types_getter)
MyUnion = union_factory["MyModel"]

Contributing

Contributions are welcome! If you'd like to add a new feature, fix a bug, or improve documentation, kindly go through the contributions guidelines first.

Project details


Release history Release notifications | RSS feed

Download files

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

Source Distribution

swarmauri_typing-0.9.3.dev18.tar.gz (8.0 kB view details)

Uploaded Source

Built Distribution

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

swarmauri_typing-0.9.3.dev18-py3-none-any.whl (9.6 kB view details)

Uploaded Python 3

File details

Details for the file swarmauri_typing-0.9.3.dev18.tar.gz.

File metadata

  • Download URL: swarmauri_typing-0.9.3.dev18.tar.gz
  • Upload date:
  • Size: 8.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.12 {"installer":{"name":"uv","version":"0.10.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for swarmauri_typing-0.9.3.dev18.tar.gz
Algorithm Hash digest
SHA256 c7147db801a1c10713160df0322892a7b69449f7a7fe6dd0ee4d9ca52f7ff343
MD5 5c9368ea2f578f8f185b1c11a1676c5a
BLAKE2b-256 d2bcd87a61e599687d607f6b70f767dcd92f9bf96c3c3706c02b3a685a78b297

See more details on using hashes here.

File details

Details for the file swarmauri_typing-0.9.3.dev18-py3-none-any.whl.

File metadata

  • Download URL: swarmauri_typing-0.9.3.dev18-py3-none-any.whl
  • Upload date:
  • Size: 9.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.12 {"installer":{"name":"uv","version":"0.10.12","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for swarmauri_typing-0.9.3.dev18-py3-none-any.whl
Algorithm Hash digest
SHA256 a6c18610d1ba01002d89a87b3178066b38c52def1886f0fac3913cdd2b41e227
MD5 81e797a8e43b67861825277a0d4ebd27
BLAKE2b-256 d88a6a29b51da229d66dbb1aacd7b6b9dafbfeebafcfb53d1891455a6a4749be

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