Skip to content

types

Attributes

TypeAnnotation module-attribute

TypeAnnotation: TypeAlias = Union[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.

Functions

is_constructible_from_str

is_constructible_from_str(type_: type) -> bool

Returns true if the provided type can be constructed from a string

Source code in fgpyo/util/types.py
def is_constructible_from_str(type_: type) -> bool:
    """Returns true if the provided type can be constructed from a string"""
    try:
        sig = inspect.signature(type_)
        ((argname, _),) = sig.bind(object()).arguments.items()
    except TypeError:  # Can be raised by signature() or Signature.bind().
        return False
    except ValueError:
        # Can be raised for classes, if the relevant info is in `__init__`.
        if not isinstance(type_, type):
            raise
    else:
        if sig.parameters[argname].annotation is str:
            return True
    # FIXME
    # if isinstance(type_, type):
    #     # signature() first checks __new__, if it is present.
    #     return _is_constructible_from_str(type_.__init__(object(), type_))
    return False

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: Type[LiteralType], parsers: Iterable[Callable[[str], LiteralType]]) -> partial

Generates a parser function for a literal type object and a set of parsers for the possible parsers to that literal type object

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

make_union_parser

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

Generates a parser function for a union type object and set of parsers for the possible parsers to that union type object

Source code in fgpyo/util/types.py
def make_union_parser(
    union: Type[UnionType], parsers: Iterable[Callable[[str], UnionType]]
) -> partial:
    """Generates a parser function for a union type object and set of parsers for the possible
    parsers to that 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 accounting 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 accounting 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))