Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string is in string literal type

We use static type checking extensively, but we also need some simple runtime type checking. I'd love to use our static types for that runtime type checking. I've seen typeguard and the other libraries, but I'd prefer to have something simpler.

I've tried below, but assert value in expected_type doesn't make sense. How do I create a simple function that will check if a string is in a Python string literal?

from typing_extensions import Literal

def check_str_in_literal(value: str, expected_type: Literal):
    assert value in expected_type

Gender = Literal["Male", "Female", "Other"]
def print_gender(gender: Gender):
    print(gender)

# Unknown string as it's been retrieved from elsewhere
strRetrievedFromDB = "Male"  # type: ignore

check_str_in_literal(strRetrievedFromDB, Gender)
print_gender(strRetrievedFromDB)
like image 365
pir Avatar asked Jan 24 '26 23:01

pir


1 Answers

Python 3.8 introduced typing.get_args(tp), making this possible:

assert value in get_args(expected_type)
like image 155
Joseph Marinier Avatar answered Jan 27 '26 12:01

Joseph Marinier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!