user3848207
user3848207

Reputation: 4997

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

Upvotes: 4

Views: 1422

Answers (1)

yedpodtrzitko
yedpodtrzitko

Reputation: 9359

you're looking for Literal

from typing import Literal

def func_AB(param1: Literal['A', 'B']):
    ...

Upvotes: 8

Related Questions