Search code examples
pythonsetpython-typing

How to type hint a subset of values from a known set in python


Consider the following set:

s = set(["x", "y", "z"])

How do I create a type hint for a variable that is any subset of the elements in s (short of explicitly creating a Union of every possible subset)?


Solution

  • The closest you can get is annotating the variable as a set whose element type is a literal type:

    from typing import Literal
    
    s2: set[Literal['x', 'y', 'z']] = # whatever
    

    Type checkers will recognize that elements of such a set are one of these values, and they will prohibit adding elements that are not one of these values.

    Type checkers will not recognize any particular subset relation between such a set and s, and they will not allow passing such a set to a function that takes set[str], as such functions could add other strings to the set.