I am looking to create a type alias that can take a generic that is not actually used in the alias. The reason is for self-documenting code, I am aware that no type checker will be able to actually check this. Here is what I mean:
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
...
The problem is that the JSON type alias does not use the generic parameter, so it can not receive it. I would need to use it in the alias definition without actually doing something with it. I tried doing this with the PEP-593 Annotated type, but it does not work either (I can define it like below, but it still does not expect the generic argument):
from typing import Annotated
JSONOf = Annotated[JSON, T]
I would need to do something like (this does not exist):
from typing import ThrowAwayGeneric
JSONOf = ThrowAwayGeneric[JSON, T]
Is it possible to get something similar to type check? Once again: I am not actually interested in type checking the json data, I just want to provide a readable signature of the function. Using Dict[str, Any]
when actually type checking if completely fine.
The kind of brute-force approach would of course be to define an alias for each type, but that becomes tedious as there are many such types.
JSONOfPerson = JSON