Created
April 29, 2024 21:40
-
-
Save malcolmgreaves/5e57be024f3bc79b47634a8d6c1f13fb to your computer and use it in GitHub Desktop.
Check if a value is of a literal type.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Any, Literal | |
def is_literal(literal_type: type, value: Any) -> bool: | |
"""Returns True iff the `value` is a variant of the input `literal_type`. False otherwise. | |
Raises a `ValueError` iff the input `literal_type` is not a `typing.Literal`. | |
""" | |
if not hasattr(literal_type, '__origin__') or literal_type.__origin__ != Literal: | |
raise ValueError(f"Expecting literal type, not {literal_type=}") | |
return any(map(lambda variant: value == variant, literal_type.__args__)) | |
if __name__ == "__main__": | |
L = Literal['a','b'] | |
print(f"{is_literal(L, 'a')=}") | |
print(f"{is_literal(L, 'c')=}") | |
print(f"{is_literal(int, 1)=}") # fail |
Author
malcolmgreaves
commented
Apr 29, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment