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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With