Skip to content
Advertisement

Stronger type-annotation for a mixed-type mapping

Suppose I have a mapping that maps string -> int, and int -> string in one dictionary. Is there a way to express that with type annotations in a strict way? Currently I can do Dict[Union[str, int], Union[str, int]], but that allows for str -> str, and int -> int, which I do not actually want.

One might try Union[Dict[str, int], Dict[str, int]], but then only one of these is true for the scope it appears in.

Advertisement

Answer

This can be a solution. If you need, you can re-define other methods. You can also do a d=cast(mydict,existing_dict).

JavaScript

How @MisterMiyagi suggest, also a Protocol can work:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement