typeshed
typeshed copied to clipboard
Tkinter _Image import
This code is only to illustrate the problem:
from mypy.typeshed.stdlib.tkinter import _Image
tk.Button(image=cast(_Image, 3))
The first line raises this Mypy error:
error: Module "mypy.typeshed.stdlib.tkinter" has no attribute "_Image"
And what is _Image? It is not in Tkinter, neither in ttk, it is only in stub, hard to find/understand and i must import it from typeshed.
What is the practical problem? Why do you want to pass image=3 to a button? I guess the image object isn't an integer in your actual code, so what is it instead?
Was only an example to show how difficult is to use, in user code, alias defined in stubs. It is not only an _Image problem. Another example:
def w(img: _ImageSpec):
tk.Button(image=img)
This applies to type aliases in general. If you really need to, you can use something like this:
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from tkinter import _ImageSpec
else:
_ImageSpec = None
Sometimes a better solution is to just get rid of the type alias and use the actual type, like we did with _TkinterSequence. I would be fine with removing _Color = str, _CanvasItemId = int and other similar type aliases, if you want to make a pull request. But this won't really help with _ImageSpec = Union[_Image, str], because _Image is a protocol that isn't available at runtime. See #4766 for why it is needed.
Good to know. It's magic.