Skip to content

Incorrect type annotations cause AttributeError on import #851

@pranavrajpal

Description

@pranavrajpal

With the following code (using the Pillow library):

from PIL import Image

def test(im: Image):
    print(im.mode)

def run() -> None:
    im = Image.open('test.png')
    test(im)

and the following config file:

[mypy-PIL.*]
ignore_missing_imports = True

mypy shows no errors, but compiling the code with mypyc and trying to run it produces the following traceback:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "bug.py", line 1, in <module>
    from PIL import Image
AttributeError: module 'PIL' has no attribute 'Image'

The problem is that the type annotations in the original code are incorrect, because PIL.Image is a module, and PIL.Image.open is a function that returns a separate PIL.Image.Image object, so the correct type annotations are:

from PIL import Image
from PIL.Image import Image as ImageType

def test(im: ImageType):
    print(im.mode)

def run() -> None:
    im = Image.open('test.png')
    test(im)

which fixes the mypyc error.


There are a couple of possible solutions that I can think of to this:

  1. Get mypy to realize the error in the original code, even when ignore_missing_imports is set, by noticing that a class is being passed in when a module is expected.
  2. Same as (1), but only emit an error if compiling with mypyc.
  3. Ignore any type annotations from untyped libraries when compiling with mypyc.
  4. Insert code into the compiled C extension to check if this happens and print/raise with a nicer error message.

I'd like to work on this, but I don't really know which (if any) of the solutions I mentioned would be the best way to fix this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugpython compatMypyc doesn't match CPython or documented semantics.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions