Skip to content

_union_types

is_annotated_union(_type)

Determine whether _type is Annotated and its wrapped type is a union.

See https://docs.python.org/3/library/typing.html#typing.Annotated

Source code in src/fractal_task_tools/_union_types.py
31
32
33
34
35
36
37
def is_annotated_union(_type) -> bool:
    """
    Determine whether `_type` is `Annotated` and its wrapped type is a union.

    See https://docs.python.org/3/library/typing.html#typing.Annotated
    """
    return typing.get_origin(_type) is typing.Annotated and is_union(_type.__origin__)

is_tagged(_type)

Determine whether annotations make an Annotated type a tagged union.

Note that this function only gets called after is_annotated_union(_type) returned True.

See https://docs.python.org/3/library/typing.html#typing.Annotated

Source code in src/fractal_task_tools/_union_types.py
40
41
42
43
44
45
46
47
48
49
50
51
52
def is_tagged(_type) -> bool:
    """
    Determine whether annotations make an `Annotated` type a tagged union.

    Note that this function only gets called after `is_annotated_union(_type)`
    returned `True`.

    See https://docs.python.org/3/library/typing.html#typing.Annotated
    """
    return any(
        isinstance(_item, FieldInfo) and _item.discriminator is not None
        for _item in _type.__metadata__
    )

is_union(_type)

Determine whether _type is a union.

Based on https://docs.python.org/3/library/typing.html#typing.Union https://discuss.python.org/t/how-to-check-if-a-type-annotation-represents-an-union/77692/2.

Source code in src/fractal_task_tools/_union_types.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def is_union(_type) -> bool:
    """
    Determine whether `_type` is a union.

    Based on
    https://docs.python.org/3/library/typing.html#typing.Union
    https://discuss.python.org/t/how-to-check-if-a-type-annotation-represents-an-union/77692/2.
    """
    result = typing.get_origin(_type) in _UNION_TYPES
    alternative_result = (
        type(_type) is typing._UnionGenericAlias or type(_type) is types.UnionType
    )
    if result != alternative_result:
        # This is a safety check, which is meant to be unreachable
        raise ValueError(
            f"Could not determine whether {_type} is a union. Please report "
            "this at https://github.com/fractal-analytics-platform/"
            "fractal-task-tools/issues."
        )
    return result