
28.07.21 02:42, Ignacio Pickering пише:
Currently type hints for built-in containers are, in my opinion, less succint than required. I suspect it is probably not very difficult for a type checker to interpret something like this for example:
var1: {str: (int, int)} = {"label": (1, 2)} var2: {str} = {"other_label"}
def function(param1: {int: str} = {1: "foo"}, param2: (int, ...) = (1, 2, 3)) -> (int, (str, ...)): return 3, ("foo", "bar")
as equivalent to:
var1: dict[str, tuple[int, int]] = {"label": (1, 2)} var2: set[str] = {"other_label"}
def function(param1: dict[int, str] = (1, "foo"), param2: tuple[int, ...] = (1, 2, 3)) -> tuple[int, tuple[str, ...]]: return 3, ("foo", "bar")
I thought of posting something like this as a mypy feature suggestion, but I suspect the language would need to modify the way type annotations are interpreted for something like it to work (or maybe not?). Basically, inside a type annotation, the objects created by (a, b), [a], {a: b}, {a} would be reinterpreted as the same thing as constructing tuple[a, b], dict[a, b], list[a], set[a]. I have found myself wanting to write things like this a couple of times, so I think this overloaded usage of builtin containters is natural. I actually feel it is so natural it must either have been proposed before (in which case I would love to give the feature my +1) or there is some more or less obvious flaw.
The idea of having different syntax in annotations was rejected multiple times. You should have ability to refactor your code and introduce simple aliases for cumbersome constructions like Mapping[Tuple[int, str], Callable[[str, Tuple[int, str], Iterable[Mapping[str, Tuple[int, str]]]], List[Callable[[str], bool]]] (it is not too far from real world examples). And it includes parameterized types. MyMultiDict = dict[str, list[T]] MyStrMultiDict = MyMultiDict[str] MyIntMultiDict = MyMultiDict[int] Now, with your syntax: MyMultiDict = {str: [T]} MyStrMultiDict = MyMultiDict[str] # returns not what you want MyIntMultiDict = MyMultiDict[int] # KeyError So you would need principally different syntax in annotations and outside of annotations. It will cause issues in refactoring, and equal definitions would look completely unrelated.