Skip to content

types

Attributes

TypeAnnotation module-attribute

TypeAnnotation: TypeAlias = type | _GenericAlias | UnionType | GenericAlias

A function parameter's type annotation may be any of the following: 1) type, when declaring any of the built-in Python types 2) typing._GenericAlias, when declaring generic collection types or union types using pre-PEP 585 and pre-PEP 604 syntax (e.g. List[int], Optional[int], or Union[int, None]) 3) types.UnionType, when declaring union types using PEP604 syntax (e.g. int | None) 4) types.GenericAlias, when declaring generic collection types using PEP 585 syntax (e.g. list[int]) types.GenericAlias is a subclass of type, but typing._GenericAlias and types.UnionType are not and must be considered explicitly.

Classes

InspectException

Bases: Exception

Raised when type inspection or parsing fails.

Source code in fgpyo/util/types.py
class InspectException(Exception):  # noqa: N818
    """Raised when type inspection or parsing fails."""

Functions

all_not_none

all_not_none(values: tuple[T | None, ...]) -> TypeGuard[tuple[T, ...]]
all_not_none(values: list[T | None]) -> TypeGuard[list[T]]
all_not_none(values: set[T | None]) -> TypeGuard[set[T]]
all_not_none(values: Sequence[T | None]) -> TypeGuard[Sequence[T]]
all_not_none(values: Collection[T | None]) -> TypeGuard[Collection[T]]
all_not_none(values: Iterable[T | None]) -> bool

Type guard that checks all Optional collection elements are not None.

Parameters:

Name Type Description Default
values Iterable[T | None]

Collection of Optional elements.

required

Returns:

Type Description
bool

True if no elements are None, False otherwise. When True, narrows the collection type from

bool

Container[T | None] to Container[T].

Source code in fgpyo/util/types.py
def all_not_none(values: Iterable[T | None]) -> bool:
    """
    Type guard that checks all Optional collection elements are not None.

    Args:
        values: Collection of Optional elements.

    Returns:
        True if no elements are None, False otherwise. When True, narrows the collection type from
        `Container[T | None]` to `Container[T]`.
    """
    return all(v is not None for v in values)

is_constructible_from_str

is_constructible_from_str(type_: TypeAnnotation) -> TypeGuard[type]

Returns true if the provided type is a class constructible from a single str argument.

Source code in fgpyo/util/types.py
def is_constructible_from_str(type_: TypeAnnotation) -> TypeGuard[type]:
    """Returns true if the provided type is a class constructible from a single str argument."""
    if not isinstance(type_, type):
        return False
    try:
        sig = inspect.signature(type_)
        ((argname, _),) = sig.bind(object()).arguments.items()
    except (TypeError, ValueError):
        return False
    return sig.parameters[argname].annotation is str

is_known_str_constructible

is_known_str_constructible(type_: TypeAnnotation) -> TypeGuard[type]

Returns true if type_ is one of the built-in types known to be constructible from a str.

Complements is_constructible_from_str, which detects str-constructibility via constructor signature inspection. This predicate covers types whose constructors aren't annotated for introspection (e.g. int, str, float) or whose subclasses don't all share an annotation (e.g. PurePath).

Source code in fgpyo/util/types.py
def is_known_str_constructible(type_: TypeAnnotation) -> TypeGuard[type]:
    """
    Returns true if `type_` is one of the built-in types known to be constructible from a str.

    Complements `is_constructible_from_str`, which detects str-constructibility via constructor
    signature inspection. This predicate covers types whose constructors aren't annotated for
    introspection (e.g. `int`, `str`, `float`) or whose subclasses don't all share an annotation
    (e.g. `PurePath`).
    """
    return isinstance(type_, type) and (type_ in (str, int, float) or issubclass(type_, PurePath))

is_list_like

is_list_like(type_: type) -> bool

Returns true if the value is a list or list like object.

Source code in fgpyo/util/types.py
def is_list_like(type_: type) -> bool:
    """Returns true if the value is a list or list like object."""
    return typing.get_origin(type_) in [list, collections.abc.Iterable, collections.abc.Sequence]

make_enum_parser

make_enum_parser(enum: type[EnumType]) -> partial

Makes a parser function for enum classes.

Source code in fgpyo/util/types.py
def make_enum_parser(enum: type[EnumType]) -> partial:
    """Makes a parser function for enum classes."""
    return partial(_make_enum_parser_worker, enum)

make_literal_parser

make_literal_parser(literal: TypeAnnotation, parsers: Iterable[Callable[[str], LiteralType]]) -> partial

Generates a parser function for a literal type object.

Source code in fgpyo/util/types.py
def make_literal_parser(
    literal: TypeAnnotation, parsers: Iterable[Callable[[str], LiteralType]]
) -> partial:
    """Generates a parser function for a literal type object."""
    return partial(_make_literal_parser_worker, literal, parsers)

make_union_parser

make_union_parser(union: TypeAnnotation, parsers: Iterable[Callable[[str], UnionType]]) -> partial

Generates a parser function for a union type object.

Source code in fgpyo/util/types.py
def make_union_parser(
    union: TypeAnnotation, parsers: Iterable[Callable[[str], UnionType]]
) -> partial:
    """Generates a parser function for a union type object."""
    return partial(_make_union_parser_worker, union, parsers)

none_parser

none_parser(value: str) -> Literal[None]

Returns None if the value is 'None', else raises an error.

Source code in fgpyo/util/types.py
def none_parser(value: str) -> Literal[None]:
    """Returns None if the value is 'None', else raises an error."""
    if value == "":
        return None
    raise ValueError(f"NoneType not a valid type for {value}")

parse_bool

parse_bool(string: str) -> bool

Parses strings into bools.

Accounts for the many different text representations of bools that can be used.

Source code in fgpyo/util/types.py
def parse_bool(string: str) -> bool:
    """
    Parses strings into bools.

    Accounts for the many different text representations of bools that can be used.
    """
    if string.lower() in ["t", "true", "1"]:
        return True
    elif string.lower() in ["f", "false", "0"]:
        return False
    else:
        raise ValueError("{} is not a valid boolean string".format(string))