Set type of a variable so it's the same as the contents of a set

时间:2019-04-16 22:39:17

标签: python-3.x string set python-typing

I want to be able to, through the python typing module and the python static type checker, set the type of a variable so that it matches the type inside a defined set.

I have looked around for a while now and I can't find a way to reference the original set such that it defines the type of the new variable. I could do something like the following where I just use the same type reference as the one inside the set declaration...

my_set: Set[str] = {"a","b"}
def my_func(in_val:str):
   ...

but it would not be ideal.

Ideally I could do something like the following...

scratch1.py

import typing

my_set: typing.Set[str] = {"a","b","c"}

def my_func(in_val: TypeElement[my_set]):  # Or something like this
    print(in_val)

my_func("a")  # No error when running mypy
my_func(1)  # Error when running mypy
my_func("d")  # Possibly error, if possible, when running mypy

run in terminal

$ mypy scratch1.py
scratch1.py:9: error: Argument 1 to "my_func" has incompatible type "int"; expected "str"

0 个答案:

没有答案