Skip to content

Utility#

octarine.register_converter(t, converter, insert='first') #

Register a converter for a given data type.

PARAMETER DESCRIPTION
t
    Data type the converter is meant to convert. If a function
    it is expected to take a single argument `x` and return
    True if `x` can be converted using `converter` and False
    if not.

TYPE: type | hashable | callable

converter
    Function that converts `x` to pygfx visuals. Must accept
    at least a single argument and return either a single
    visual or a list thereof.

TYPE: callable

insert
    Whether to insert the converter at the beginning or end
    of the list of converters. This is important because when
    looking for a converter for a given type we will use the
    first one that matches.

TYPE: "first" | "last" DEFAULT: 'first'

Source code in octarine/conversion.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def register_converter(t, converter, insert='first'):
    """Register a converter for a given data type.

    Parameters
    ----------
    t :         type | hashable | callable
                Data type the converter is meant to convert. If a function
                it is expected to take a single argument `x` and return
                True if `x` can be converted using `converter` and False
                if not.
    converter : callable
                Function that converts `x` to pygfx visuals. Must accept
                at least a single argument and return either a single
                visual or a list thereof.
    insert :    "first" | "last"
                Whether to insert the converter at the beginning or end
                of the list of converters. This is important because when
                looking for a converter for a given type we will use the
                first one that matches.

    """
    global CONVERTERS
    assert insert in ('first', 'last')

    if not callable(converter):
        raise ValueError("Converter must be callable.")

    if not callable(t) and not is_hashable(t):
        raise ValueError("Type must be hashable or callable.")


    if insert == 'first':
        items = list(CONVERTERS.items())
        items.insert(0, (t, converter))
        CONVERTERS = dict(items)
    else:
        CONVERTERS[t] = converter