Error parsing annotation: 'type' object is not subscriptable
Problem Description
I receive the following warning when working with certain tkinter event annotations. In addition, the type hinting is tagged in the html as a string, and has quotes around it.
Warn: Error parsing type annotation tk.Event[tk.Text] for sample.MyText.open_link: 'type' object is not subscriptable (.../lib/python3.10/site-packages/pdoc/doc_types.py:122)
Sample code
from __future__ import annotations
import tkinter as tk
import webbrowser
class MyText(tk.Text):
"""Sample class."""
def open_link(self, event: tk.Event[tk.Text]) -> None:
"""Open the clicked link in a web browser."""
click_position = f"@{event.x},{event.y}"
tag_range = event.widget.tag_nextrange("linkurl", click_position)
webbrowser.open_new_tab(event.widget.get(*tag_range))
def test(self, event: tk.Event) -> None:
"""Test event."""
pass
Steps to reproduce the behavior:
- Save code above as "sample.py"
- Run
pdoc sample.py - Warning appears in output, and type hinting in html is tagged as a literal string (
span class="s1"), rather than a proper name (span class="n").
System Information
pdoc: 14.4.0 Python: 3.10.14 Platform: Linux-5.10.0-18-amd64-x86_64-with-glibc2.31
Notes
mypy version 1.9.0 correctly interprets the above sample code, and the VS Code mypy extension correctly indicates that event.widget is a tk.Text instance, allowing proper syntax highlighting on event.widget.* methods.
Where did you learn about this tk.Event[tk.Text] syntax?
This is not a pdoc bug, this is an issue with tkinter or with the annotation: If you open a Python shell and run tk.Event[tk.Text], you will get the same error. It's only due to from __future__ import annotations that you don't get errors when running your Python program.
I saw it while using VS Code, and the mypy extension.
When hovering over a function, it showed a tooltip with the function signature, and all the parameters with their types. I think it's a feature of the Pylance extension to show the tooltips like this. One of them showed Event[Text]. See screenshot below for an example.
Adding it to my code allowed mypy to type check the inner members of an expression, like event.widget.tag_nextrange(), showing that tag_nextrange() is actually a method for the given widget. Since it didn't cause any issues running my code, I kept it and added it elsewhere. I was already using from __future__ import annotations to get the int | None type hinting functionality.
This is nothing we can fix in pdoc unfortunately, the tkinter folks need to make sure that their type annotations do not raise if evaluated.