Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typing: Define a type that can only be certain strings?

How can I use the typing module, to create a type that can be certain strings?

E.g. let's say I need a type CondOperator, which can be any of these strings:

['=', '>', '<', '>=', '<=', '<>', '!=']

I was hoping for CondOperator = String['=', '>', '<', '>=', '<=', '<>', '!='], but there is no String in typing. So this doesn't work.

How can define such type?

like image 834
Rotareti Avatar asked Mar 07 '23 10:03

Rotareti


1 Answers

Python 3.8 has introduced the Literal type in typing. It's also accessible via the typing_extensions package in previous versions of Python. With Literal, you can define your type as:

from typing import Literal

CondOperator = Literal['=', '>', '<', '>=', '<=', '<>', '!=']

The mypy docs on Literal is a good read.

like image 138
Zecong Hu Avatar answered Mar 24 '23 15:03

Zecong Hu