首页 > 解决方案 > 如何使用一次性泛型创建类型别名?

问题描述

我希望创建一个类型别名,它可以采用别名中实际未使用的泛型。原因是自记录代码,我知道没有类型检查器能够实际检查这一点。这就是我的意思:

from typing import TypeVar, Dict, Any

from dataclasses import dataclass
from dataclasses_json import dataclass_json, DataClassJsonMixin


JSON = Dict[str, Any]  # Good enough json type for this demo
T = TypeVar("T", bound=DataClassJsonMixin)
JSONOf = JSON[T]  # <-- mypy Problem: JSON takes no generic arguments

@dataclass_json   # this just provides to_json/from_json to dataclasses, not important for question
@dataclass
class Person:
    name: str
    age: int

def add_person_to_db(person: JSONOf[Person]):
    # just from reading the signature the user now knows what the input is
    # If I just put JSON as a type, it is unclear
    ...

问题是JSON类型别名没有使用泛型参数,所以无法接收。我需要在别名定义中使用它,而无需实际使用它。我尝试使用PEP-593 Annotated类型执行此操作,但它也不起作用(我可以像下面这样定义它,但它仍然不需要泛型参数):

from typing import Annotated

JSONOf = Annotated[JSON, T]

我需要做类似的事情(这不存在):

from typing import ThrowAwayGeneric

JSONOf = ThrowAwayGeneric[JSON, T]

是否有可能得到类似于类型检查的东西?再说一次:我实际上对检查 json 数据的类型并不感兴趣,我只想提供一个可读的函数签名。Dict[str, Any]如果完全没问题,则在实际类型检查时使用。

那种蛮力方法当然是为每种类型定义一个别名,但这变得乏味,因为有很多这样的类型。

JSONOfPerson = JSON

标签: pythontype-hintingmypypython-typingtype-alias

解决方案


我想出了一些解决方案:

  • JSONOf与另一种采用 Generic 的类型进行联合,以一种永远不会匹配任何东西的方式制作JSON该类型,例如Dict带有可变键的 a:
JSONOf = Union[JSON, Dict[List, T]] # List could be any mutable, including JSON itself
  • 相同的方法,与自定义泛型类结合:
class JSONFrom(Generic[T]): pass  # Name was chosen to look nice on mypy errors
JSONOf = Union[JSON, JSONFrom[T]]

让我们测试一下:

from typing import Generic, TypeVar, Dict, Any, Union

class DataClassJsonMixin: ...
class Person(DataClassJsonMixin): ...
JSON = Dict[str, Any]  # Good enough json type for this demo
T = TypeVar("T", bound=DataClassJsonMixin)

# Solution 1: Union with impossible type that takes a Generic
# JSONOf = Union[JSON, Dict[JSON, T]]

# Solution 2: Union with custom generic class
class JSONFrom(Generic[T]):
    # just a crude failsafe to prohibit instantiation
    # could be improved with __new__, __init_subclasses__, etc
    def __init__(self):
        raise TypeError("Just dont!")

JSONOf = Union[JSON, JSONFrom[T]]

def add_person_to_db(person: JSONOf[Person]):
    print(person)
    try: reveal_type(person)
    except NameError: pass

add_person_to_db({'id': 1234, 'name': 'Someone'})  # Checks
add_person_to_db("Not a JSON")       # Check error by JSON
add_person_to_db(Person())           # Make sure it does not accept Person
try: someone: JSONFrom = JSONFrom()  # Make sure it does not accept JSONFrom
except TypeError as e: print(e)      # Nice try!
$ python3 test.py 
{'id': 1234, 'name': 'Someone'}
Not a JSON
<__main__.Person object at 0x7fa258a7d128>
Just dont!

$ mypy test.py 
test.py:22: note: Revealed type is "Union[builtins.dict[builtins.str, Any], test.JSONFrom[test.Person]]"
test.py:26: error: Argument 1 to "add_person_to_db" has incompatible type "str"; expected "Union[Dict[str, Any], JSONFrom[Person]]"
test.py:27: error: Argument 1 to "add_person_to_db" has incompatible type "Person"; expected "Union[Dict[str, Any], JSONFrom[Person]]"
Found 2 errors in 1 file (checked 1 source file)

推荐阅读