Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use type checking to check that string is of certain values only

Suppose I have a python function def func_AB(param1: str). param1 can only take on values A or B. If it takes on any other string value, an error should appear.

Is it possible to use python type checking to give out error when this happens? Currently, I use assert to check that param1 contains the valid string value.

I am using python 3.8.5

like image 250
user3848207 Avatar asked Oct 26 '25 02:10

user3848207


1 Answers

you're looking for Literal

from typing import Literal

def func_AB(param1: Literal['A', 'B']):
    ...
like image 171
yedpodtrzitko Avatar answered Oct 27 '25 18:10

yedpodtrzitko