typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

Tkinter _Image import

Open melassa opened this issue 4 years ago • 4 comments
trafficstars

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.

melassa avatar Oct 22 '21 13:10 melassa

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?

Akuli avatar Oct 22 '21 14:10 Akuli

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)

melassa avatar Oct 22 '21 17:10 melassa

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.

Akuli avatar Oct 22 '21 18:10 Akuli

Good to know. It's magic.

melassa avatar Oct 23 '21 08:10 melassa