Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Created April 29, 2024 21:40
Show Gist options
  • Save malcolmgreaves/5e57be024f3bc79b47634a8d6c1f13fb to your computer and use it in GitHub Desktop.
Save malcolmgreaves/5e57be024f3bc79b47634a8d6c1f13fb to your computer and use it in GitHub Desktop.
Check if a value is of a literal type.
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
@malcolmgreaves
Copy link
Author

is_literal(L, 'a')=True
is_literal(L, 'c')=False
Traceback (most recent call last):
  File "/Users/mgreaves/dev/com/nvidia/bionemo/x.py", line 18, in <module>
    print(f"{is_literal(int, 1)=}") # fail
  File "/Users/mgreaves/dev/com/nvidia/bionemo/x.py", line 10, in is_literal
    raise ValueError(f"Expecting literal type, not {literal_type=}")
ValueError: Expecting literal type, not literal_type=<class 'int'>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment