In Python, trying to get type hints working for a dictionary. [code] How would I…
- User
In Python, trying to get type hints working for a dictionary.
pythonclass Base: pass class Child1(Base): pass class Child2(Base): pass def fn(c): d = { Child1: child1_handler_fn, Child2: child2_handler_fn, } d[type(c)](c)How would I annotate these types, specifically, the dictionary (mypy)?
- Assistant
In Python, you can use the
Typefrom thetypingmodule to annotate types for classes. Additionally, you can useCallableto annotate function types. The following code snippet shows how you can annotate the types for your dictionary, so that it can passmypytype checking:pythonfrom typing import Type, Callable, Dict class Base: pass class Child1(Base): pass class Child2(Base): pass def child1_handler_fn(c: Child1) -> None: print("Handling Child1") def child2_handler_fn(c: Child2) -> None: print("Handling Child2") def fn(c: Base) -> None: d: Dict[Type[Base], Callable[[Base], None]] = { Child1: child1_handler_fn, Child2: child2_handler_fn, } d[type(c)](c) - User
mypy gives the following typing errors for that snippet -
mypy scratch.py scratch.py:20: error: Dict entry 0 has incompatible type "type[Child1]": "Callable[[Child1], None]"; expected "type[Base]": "Callable[[Base], None]" [dict-item] scratch.py:21: error: Dict entry 1 has incompatible type "type[Child2]": "Callable[[Child2], None]"; expected "type[Base]": "Callable[[Base], None]" [dict-item] Found 2 errors in 1 file (checked 1 source file)
- Assistant
Ah, you're correct. The issue here is that
Type[Base]andCallable[[Base], None]are invariant, meaning that subclasses are not automatically considered compatible.You can use
TypeVarto express the relationship between the keys and values in the dictionary. Here's how to adjust the code to passmypychecks:pythonfrom typing import Type, Callable, Dict, TypeVar T = TypeVar('T', bound=Base) class Base: pass class Child1(Base): pass class Child2(Base): pass def child1_handler_fn(c: Child1) -> None: print("Handling Child1") def child2_handler_fn(c: Child2) -> None: print("Handling Child2") def fn(c: Base) -> None: d: Dict[Type[T], Callable[[T], None]] = { Child1: child1_handler_fn, Child2: child2_handler_fn, } d[type(c)](c) - User
I had tried something similar, that produces the following errors -
scratch.py:3: error: Name "Base" is used before definition [used-before-def] scratch.py:21: error: Type variable "scratch.T" is unbound [valid-type] scratch.py:21: note: (Hint: Use "Generic[T]" or "Protocol[T]" base class to bind "T" inside a class) scratch.py:21: note: (Hint: Use "T" in function signature to bind "T" inside a function) scratch.py:22: error: Dict entry 0 has incompatible type "type[Child1]": "Callable[[Child1], None]"; expected "type[T?]": "Callable[[T], None]" [dict-item] scratch.py:23: error: Dict entry 1 has incompatible type "type[Child2]": "Callable[[Child2], None]"; expected "type[T?]": "Callable[[T], None]" [dict-item] Found 4 errors in 1 file (checked 1 source file)
- Assistant
I apologize for the confusion. You're right; the
TypeVarapproach doesn't directly solve the issue because it fails to establish a link between the key type and the function argument type within the context of a dictionary.You can solve this issue by using
Unionto specify the exact types for the keys and the corresponding handler functions:pythonfrom typing import Type, Callable, Dict, Union class Base: pass class Child1(Base): pass class Child2(Base): pass def child1_handler_fn(c: Child1) -> None: print("Handling Child1") def child2_handler_fn(c: Child2) -> None: print("Handling Child2") def fn(c: Base) -> None: d: Dict[Type[Union[Child1, Child2]], Callable[[Union[Child1, Child2]], None]] = { Child1: child1_handler_fn, Child2: child2_handler_fn, } d[type(c)](c) - User
That produces the following errors -
scratch.py:20: error: Dict entry 0 has incompatible type "type[Child1]": "Callable[[Child1], None]"; expected "type[Child1] | type[Child2]": "Callable[[Child1 | Child2], None]" [dict-item] scratch.py:21: error: Dict entry 1 has incompatible type "type[Child2]": "Callable[[Child2], None]"; expected "type[Child1] | type[Child2]": "Callable[[Child1 | Child2], None]" [dict-item] scratch.py:24: error: Invalid index type "type[Base]" for "dict[type[Child1] | type[Child2], Callable[[Child1 | Child2], None]]"; expected type "type[Child1] | type[Child2]" [index] scratch.py:24: error: Argument 1 has incompatible type "Base"; expected "Child1 | Child2" [arg-type] Found 4 errors in 1 file (checked 1 source file)
- Assistant
I apologize for the oversight. It looks like we're hitting some limitations of Python's type system and
mypy's ability to infer types across keys and values in a dictionary.One potential workaround is to use a less specific type hint for the dictionary, and then to use explicit type checking and casting within the function. For example:
python - User
What a nightmare.
codefrom typing import Type, Callable, Dict, Any, cast class Base: pass class Child1(Base): pass class Child2(Base): pass def child1_handler_fn(c: Child1) -> None: print("Handling Child1") def child2_handler_fn(c: Child2) -> None: print("Handling Child2") def fn(c: Base) -> None: d: Dict[Type[Base], Callable[[Any], None]] = { Child1: child1_handler_fn, Child2: child2_handler_fn, } d[type(c)](c)This works. Thanks.
- Assistant
You're welcome! Yes, dealing with type systems can sometimes be a bit cumbersome due to their limitations. The example you've settled on strikes a balance between type safety and practicality. It allows you to keep the handler functions strongly typed while using a more flexible type for the dictionary itself.
If you have any more questions or run into additional issues, feel free to ask. Happy coding!