[Python] mypy complains about a missing optional module

Discussão em 'Python' iniciado por Stack, Novembro 28, 2025.

  1. Stack

    Stack Membro Participativo

    I have a module (let's name it optional_module) that I want to be imported optionally, as it can be either present or absent. Now I do it this simple way:

    try:
    import optional_module

    except ImportError:
    ... # Working around the module

    else:
    ... # Using the module


    But mypy gives an error in case when optional_module is missing:

    main.py:2: error: Cannot find implementation or library stub for module named
    "optional_module" [import-not-found]
    import optional_module
    ^
    main.py:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports


    Yes, I looked at the link proposed by mypy, but it didn't help me to find the answer.

    Of course, I could simply remove this check adding "# type: ignore" after the import line, but it would also suppress all useful checks of the module content in case when it does exist. So it's too rude.

    Is there a more delicate and correct way to make mypy stop worrying and love my conditional import?

    P.S. Here are my mypy configuration flags:

    [mypy]
    disallow_untyped_defs = True
    check_untyped_defs = True
    disallow_any_unimported = True
    warn_return_any = True
    warn_unreachable = True
    warn_redundant_casts = True
    warn_unused_ignores = True
    pretty = True

    Continue reading...

Compartilhe esta Página