sgkit icon indicating copy to clipboard operation
sgkit copied to clipboard

Add explicit checks for literal types

Open aktech opened this issue 4 years ago • 0 comments

We use Literal types for creating a list of Enum string values to be used in the code base, but we only rely on mypy at the moment for checking the string value passed is a valid literal, which is not ideal since the users of the library may not run mypy on their code to get warned about invalid literal values, see this: https://github.com/pystatgen/sgkit/pull/498#discussion_r614206050 from @eric-czech

It would great to add explicit checks for literal values everywhere in the code and corresponding dev docs should be added for the same.

An example of explicit check:

TargetTypes = Literal["cpu", "gpu"]

def foo(target):
    valid_targets = TargetTypes.__args__  # type: ignore[attr-defined]

    if target not in valid_targets:
        raise ValueError(
            f"Invalid Target, expected one of {valid_targets}, got: {target}"
        )

    ...

cc @eric-czech @ravwojdyla

aktech avatar Apr 23 '21 07:04 aktech