Search code examples
pythonpython-typing

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?


Solution

  • 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.