📝 typing#

This module provides utilities for typing enhancements:

  • JsonDict, JsonList - Type aliases for JSON data

  • JsonMap, JsonMutMap - Read-only and mutable mapping aliases for JSON data

  • IterAny, CallableAny - Type aliases for iterables and callables

  • ClassInfo - Type alias for what isinstance accepts

  • is_generic_instance() - Runtime equivalent of isinstance() for generic type hints like dict[str, int]

  • is_sequence() - Check if an object supports O(1) __len__ and __getitem__

  • convert_to_serializable() - Recursively convert objects (dataclasses, defaultdicts, …) to JSON-serializable forms

  • @inheritable - Mark a class as meant to be subclassed

  • @overridable - Mark a member as a default implementation that subclasses may replace

  • @hook - Mark a method as a hook the base class calls at a fixed point of its flow

from collections import defaultdict
from dataclasses import dataclass
import stouputils as stp

# isinstance() cannot look inside a dict, is_generic_instance() can
stp.info(stp.is_generic_instance({"lr": 0.1}, dict[str, float]))
stp.info(stp.is_generic_instance({"lr": "high"}, dict[str, float]))

# A list can be indexed, an iterator cannot
stp.info(stp.is_sequence([1, 2]), stp.is_sequence(iter([1, 2])))

# Turn a dataclass holding a defaultdict into plain JSON
@dataclass
class Run:
    name: str
    scores: defaultdict[str, float]

run = Run("baseline", defaultdict(float, accuracy=0.93))
stp.info(stp.json_dump(stp.convert_to_serializable(run)))
Terminal output of the example

aliases#

JsonDict = JsonDict[source]#

A type alias for JSON dictionaries

JsonList = JsonList[source]#

A type alias for JSON lists

JsonMap = JsonMap[source]#

A type alias for JSON mapping

JsonMutMap = JsonMutMap[source]#

A type alias for mutable JSON mapping

IterAny = IterAny[source]#

A type alias for iterable of any type

CallableAny = CallableAny[source]#

A type alias for any callable

ClassInfo = ClassInfo[source]#

A type alias for class information used in isinstance checks, including unions and tuples of classes

extension_points#

Decorators marking how a class is meant to be extended.

inheritable() flags a class designed to be subclassed, overridable() a working default a subclass may replace, and hook() a method called at a fixed point of a flow, whose default does nothing so a subclass can act there. They only set a boolean attribute and never wrap what they decorate, so they cost nothing at call time.

@inheritable
class Trainer:
    def fit(self) -> None:
        self.before_epoch()
        self.train_epoch()

    @hook
    def before_epoch(self) -> None: ...

    @overridable
    def train_epoch(self) -> None:
        ...
INHERITABLE_ATTRIBUTE: str = '__is_inheritable__'[source]#

Attribute set to True on a class decorated with inheritable().

OVERRIDABLE_ATTRIBUTE: str = '__is_overridable__'[source]#

Attribute set to True on the function behind a member decorated with overridable().

HOOK_ATTRIBUTE: str = '__is_hook__'[source]#

Attribute set to True on the function behind a member decorated with hook().

ClassMember = ClassMember[source]#

A type alias for anything defined in a class body that can be decorated

inheritable(cls: T) → T[source]#

Mark a class as meant to be subclassed, sets __is_inheritable__ to True.

Nothing is enforced at runtime: it only tells the reader that subclassing is part of the class contract.

>>> @inheritable
... class Base:
...     pass
>>> Base.__is_inheritable__
True
overridable(member: T) → T[source]#

Mark a member as a default implementation that subclasses may replace, sets __is_overridable__ to True.

Unlike hook(), the default already does the job, and a subclass swaps it for another way of doing it. Nothing is enforced at runtime and the member is not wrapped. Stack it above @property, @classmethod or @staticmethod: the flag lands on the underlying function.

>>> class Base:
...     @overridable
...     def run(self) -> None: ...
...
...     @overridable
...     @property
...     def name(self) -> str: return "base"
...
...     @overridable
...     @classmethod
...     def create(cls) -> None:
...         ...
>>> Base.run.__is_overridable__, Base.name.fget.__is_overridable__, Base.create.__is_overridable__
(True, True, True)
hook(member: T) → T[source]#

Mark a method as a hook, called at a fixed point of a flow, sets __is_hook__ to True.

The caller may be the class itself, or code driving it from outside, such as a trainer calling a model. Unlike overridable(), the default does nothing, or hands its input back unchanged: a subclass adds behaviour at that point. Nothing is enforced at runtime and the member is not wrapped.

>>> class Runner:
...     @hook
...     def before_run(self) -> None: ...
>>> Runner.before_run.__is_hook__
True
set_member_flag(
member: ClassMember,
attribute: str,
) → None[source]#

Set attribute to True on the function behind a class member.

Parameters:

member – Function, property (its getter is flagged), classmethod or staticmethod (their __func__ is flagged)

runtime#

is_generic_instance(
obj: Any,
type_hint: Any,
) → TypeIs[Any][source]#

Runtime equivalent of isinstance() for generic type hints. is_generic_instance(my_dict, dict[str, int]) checks that my_dict is a dictionary with string keys and integer values.

Note

This function is not a perfect replacement for static type checking, and may not cover all edge cases or complex type hints.

Parameters:
  • obj – The object to check.

  • type_hint – The type hint to check against.

Returns:

True if obj matches type_hint, False otherwise.

>>> is_generic_instance(5, int)
True
>>> is_generic_instance("hello", str)
True
>>> is_generic_instance([1, 2, 3], list)
True
>>> is_generic_instance([1, 2, 3], list[int])
True
>>> is_generic_instance([1, 2, 3], list[str])
False
>>> is_generic_instance({"a": 1}, dict[str, int])
True
>>> is_generic_instance({"a": 1}, dict[str, int] | Mapping)
True
>>> is_generic_instance({"a": 1}, dict[str, int] | Mapping | JsonDict)
True
>>> is_generic_instance({"a": 1}, (dict[str, int], Mapping, JsonDict))
True
>>> is_generic_instance([1, 2, 3], dict[str, int])
False
>>> is_generic_instance({"a": 1}, "dict[str, int] | Mapping | JsonDict")
True
matches_generic_alias(
obj: Any,
type_hint: GenericAlias,
) → bool[source]#

The part of is_generic_instance() that handles a parameterized type such as list[int].

The origin type is always checked. Its parameters are checked only for a one-parameter container, against every item, and for a mapping, against every key and value. Any other parameterized type is matched on its origin alone.

>>> matches_generic_alias({"a": 1}, dict[str, int]), matches_generic_alias([1, "x"], list[int])
(True, False)
>>> matches_generic_alias((1, "x"), tuple[int, str])
True
is_sequence(
obj: Any,
) → TypeIs[Sequence[Any]][source]#

Return True if obj supports O(1) __len__ and __getitem__.

Such objects are used as-is without copying their contents into a list. Plain iterators (iter(), generators, …) return False.

>>> is_sequence(range(int(1e15)))
True
>>> is_sequence([1, 2, 3])
True
>>> is_sequence(iter(range(10)))
False
>>> is_sequence((x for x in range(10)))
False
convert_to_serializable(obj: Any) → Any[source]#

Recursively convert objects to JSON-serializable forms.

Objects with a to_dict() or asdict() method are converted to their dictionary representation. Dictionaries and lists are recursively processed.

Can also be used to convert nested structures containing custom objects, such as defaultdict, dataclasses, or other user-defined types.

Parameters:

obj – The object to convert

Returns:

The JSON-serializable version of the object

>>> from typing import defaultdict
>>> my_dict = defaultdict(lambda: defaultdict(int))
>>> my_dict['a']['b'] += 6
>>> my_dict['c']['d'] = 4
>>> my_dict['a']
defaultdict(<class 'int'>, {'b': 6})
>>> my_dict['c']
defaultdict(<class 'int'>, {'d': 4})
>>> convert_to_serializable(my_dict)
{'a': {'b': 6}, 'c': {'d': 4}}
>>> from dataclasses import dataclass
>>> @dataclass
... class Point:
...     x: int
...     y: int
...     some_list: list[int]
>>> convert_to_serializable(Point(3, 4, [1, 2, 3]))
{'x': 3, 'y': 4, 'some_list': [1, 2, 3]}