Skip to main content

flextype

flextype makes working with types in Python more flexible. It provides primitives for writing code with conditional dispatch paths for optional dependencies.

Additionally, it extends the idea of dynamic subclass registrations provided by abc.ABCMeta to the instance-level, enabling the definition of types with dynamically defined instance sets. This is useful to define marker types, enabling conditional dispatch of objects to different implementations based on those marker types.

Install

flextype requires Python 3.12 or newer.

pip install flextype
uv add flextype

Quickstart

Lazy Type Checking

lazy_isinstance and lazy_issubclass work like isinstance and issubclass, but type references may be real classes, fully qualified string names, unions, or tuples. String references are resolved through sys.modules and normal attribute lookup, supporting aliases, nested classes and dynamic attributes. The resolver does not import missing modules. Unloaded module references do not match. Resolved references use regular isinstance / issubclass semantics, including virtual subclasses and custom checking hooks, which may also have side effects.

Use "pkg.submodule:Outer.Type" to specify the module boundary explicitly. Resolution waits only for that module; once it is loaded, missing attributes raise AttributeError. Dotted references such as "pkg.submodule.Type" use the longest loaded module prefix, even when a shorter module exposes a different nested attribute. If lookup fails, they wait only when a longer module prefix could still load. Thus "pkg.C" raises if pkg is loaded but lacks C.

Lazy and delayed dispatcher registrations follow the same rules. Once a reference resolves to a class, later imports do not retarget that registration.

from pathlib import Path

from flextype import lazy_isinstance, lazy_issubclass


path = Path("README.md")

assert lazy_isinstance(path, "pathlib.Path")
assert lazy_isinstance(path, (Path, "os.PathLike"))
assert lazy_issubclass(type(path), ("pathlib.Path", str))

flexdispatch

flexdispatch is a lazy alternative to functools.singledispatch. It accepts regular registrations, lazy string registrations, and delayed registrations.

from flextype import flexdispatch


@flexdispatch
def render(value: object) -> str:
    return "object"


@render.register("pathlib.Path")
def render_path(value: object) -> str:
    return f"path: {value}"

String registrations are resolved lazily. In the example above, pathlib.Path is converted into the real class only after a matching value is dispatched.

Delayed registrations are useful when the implementation itself lives in an optional integration module. Register a callback against a lazy type name, then import the module that defines the regular registrations only when that type is first encountered.

# myapp/render.py
from flextype import flexdispatch


@flexdispatch
def render(value: object) -> str:
    return repr(value)


@render.delayed_register("pandas.DataFrame")
def _load_pandas_handlers(seen_type: type) -> None:
    import myapp.pandas_render  # noqa: F401
# myapp/pandas_render.py
import pandas as pd

from myapp.render import render


@render.register(pd.DataFrame)
def render_dataframe(value: pd.DataFrame) -> str:
    return value.to_markdown()

The delayed callback receives the concrete matching type and runs once. After the import, dispatch uses the regular pd.DataFrame registration.

Casting

caster registers conversions using the first positional parameter's annotation and the return annotation. Use it directly or configure its cost and graph:

from flextype.cast import cast, caster


@caster
def stringify(value: int) -> str:
    return str(value)


@caster(cost=1)
def decode(value: bytes | bytearray) -> str:
    return value.decode()


assert cast(4, str) == "4"
assert cast(b"hello", str) == "hello"

to_str = cast(str)
assert to_str(4) == "4"
assert to_str(b"hello") == "hello"

With one positional argument, cast(target) returns a callable accepting a value. It preserves any explicit graph and max_* limits; otherwise, it uses the active graph when the callable is invoked. graph.cast(target) supports the same form.

Explicit types are also supported: caster(int, str, stringify) or @caster((bytes, bytearray), str). Unions and tuples register every source/target combination with the same function. Parameterized types such as list[int] are registered against their runtime origin (list).

All registration forms return the original function unchanged. Registered caster metadata remains available through CasterGraph.get_direct_caster. Costs must be nonnegative and not NaN; positive infinity is allowed.

Use castmethod inside a class to register an instance method. The source is always the defining class; the target is inferred from the return annotation or given explicitly. Cost, graph, unions, tuples, and generic origins work as with caster:

from flextype.cast import cast, castmethod


class Message:
    @castmethod
    def text(self) -> str:
        return "hello"

    @castmethod(bytes, cost=1)
    def encode(self):
        return self.text().encode()


assert cast(Message(), str) == "hello"
assert cast(Message(), bytes) == b"hello"

Registration happens during class creation and preserves normal method binding. castmethod is intended for instance methods in class bodies: decoration outside a class does not register a cast on its own. No source argument is accepted. Inferred annotation names resolve against module globals and the owning class namespace; otherwise, pass locally scoped target types explicitly.

get_caster(source, target, graph=...) returns the best caster without executing it. Like cast, it uses the active graph when graph is omitted and accepts all three max_* limits.

Use graph.get_reachable_casters(source, max_cost=..., max_mro_distance=..., max_chain_length=...) to map reachable registered target types to their best casters. Ranking and inclusive limits are the same as graph.get_caster.

For a quick, unconstrained check, graph.get_reachable_types(source) returns a set of reachable registered target types without ranking or constructing casts. Pass an optional target to stop as soon as a compatible type is found; that target is included on success, but the remaining results may be incomplete.

Registries

ProtocolRegistry is useful for defining marker types: runtime-only semantic categories that objects can opt into without changing their inheritance hierarchy. Unlike regular protocols, these markers can distinguish two objects of the same class. That makes them useful for conditional dispatch based on state, provenance, validation, or other facts that are not captured by the object's structural interface.

from flextype import ProtocolRegistry, flexdispatch


class Verified(ProtocolRegistry, structural_checking=False):
    pass


@flexdispatch
def publish(document: object) -> str:
    return "manual review required"


@publish.register(Verified)
def publish_verified(document: Verified) -> str:
    return "publish immediately"


class Document:
    def __init__(self, title: str) -> None:
        self.title = title


draft = Document("Draft")
release = Document("Release")

Verified.register_instance(release)

assert publish(draft) == "manual review required"
assert publish(release) == "publish immediately"

Use __instancehook__ when membership in a marker type should be dynamic. It is called during isinstance(value, MarkerType) and can classify objects by runtime state, contents, or other predicates instead of explicit registration.

from flextype import ProtocolRegistry, flexdispatch


class IntList(ProtocolRegistry, structural_checking=False):
    @classmethod
    def __instancehook__(cls, instance: object, /) -> bool:
        return isinstance(instance, list) and all(
            isinstance(item, int) for item in instance
        )


@flexdispatch
def summarize(value: object) -> str:
    return "not an int list"


@summarize.register(IntList)
def summarize_int_list(value: list[int]) -> str:
    return f"sum={sum(value)}"


assert summarize([1, 2, 3]) == "sum=6"
assert summarize([1, "2", 3]) == "not an int list"

Return NotImplemented from __instancehook__ to fall back to regular inheritance and explicit register / register_instance checks.

By default, ProtocolRegistry preserves normal protocol structural checks. Pass structural_checking=False when the type should behave as an explicit marker instead: only inheritance, explicit registrations, and __instancehook__ decide whether an object is an instance of the marker type.

ProtocolRegistry is backed by ProtocolRegistryMeta, which extends the ABC registration concept to instance-level registrations. Registry and RegistryMeta expose the same mechanism for non-protocol marker classes, and the metaclasses are exported too when direct metaclass use is the better fit.

Class registries accept the same dotted and module:qualname references as flexdispatch. Available classes are registered immediately; unresolved module references are retried on registration, instance checks without a positive instance-cache hit, and uncached subclass checks. Resolution registers all available references, not just a name matching the class being checked. Protocol registries support pending references only with structural_checking=False; already-loaded string references are eager registrations.

Subclass checks use the normal ABC cache and hook. Consequently, an alias to a class that previously failed a subclass check can remain a cached miss after its module loads, until another uncached check or registration triggers promotion. Prefer canonical class paths for registrations; aliases are only weakly supported. Ordinary lazy_isinstance / lazy_issubclass lookups remain uncached and may use aliases directly.

Development

uv run ruff check
uv run ty check
uv run pytest

Pre-commit hooks are managed with prek:

uv run prek install
uv run prek run --all-files

License

This project is licensed under the Apache License 2.0.

Metadata

Release files for flextype 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flextype 0.3.0
File Size Uploaded Provenance Actions
flextype-0.3.0.tar.gz 34.5 kB With provenance Details for flextype-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for flextype 0.3.0
File Interpreter ABI Platform Actions
flextype-0.3.0-py3-none-any.whl Python 3 none any Details for flextype-0.3.0-py3-none-any.whl

Total release size: 67.7 kB

Release files / flextype-0.3.0.tar.gz

Download URL flextype-0.3.0.tar.gz
Size 34.5 kB
Tags Source
SHA-256 checksum
How to use checksums
2b83852bbe269bc61e51d7cae1f9f3b09b9b32b29659867f17670d9e52d901ec
BLAKE2b-256 checksum
How to use checksums
de37993b3a61a1f6febd183957b27e1f6812b31d05f69031ac5f8aed3ae2c04d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.13

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 20, 2026.

Transparency log

Release files / flextype-0.3.0-py3-none-any.whl

Download URL flextype-0.3.0-py3-none-any.whl
Size 33.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
01e2c6603bbb18ab62cd23ea54c214d521043836a62280e6949868ecbef8e3e8
BLAKE2b-256 checksum
How to use checksums
0b116477ce871bfead7b198d6d6650c5e3bc080009ee20c3a53462a5d3fd479e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.13

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 20, 2026.

Transparency log

Security for flextype 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for flextype-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 20, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page