Skip to content

Don't complain about code that catches ImportErrors #676

Closed
@JukkaL

Description

@JukkaL

Conder this example from @benhoyt's scandir (https://github.com/benhoyt/scandir):

# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
    from os import scandir, walk
except ImportError:
    from scandir import scandir, walk

Code like this is pretty common in Python modules that want to be backward compatible with older Python versions.

If mypy doesn't know about the scandir module (which is not in the std lib), mypy will complain about the code (note that os.scandir is Python 3.5 only, and isn't included in mypy stubs quite yet). However, I argue that the code is fine if the try block doesn't generate errors, since the except block will not be reached (unless some module is missing, but mypy assumes that all modules with a stub are available).

Here is a more formal rule:

Don't report errors for an except ImportError block if the corresponding try block only contains import statements and all the imported modules and names in the try block can be resolved.

Another related issue is code that imports a potentially non-existent module in a try block and falls back to a stdlib module in an except block. Not sure whether we should also ignore errors in the try block if the except block has no issues. Contrived example:

try:
    from scandir import scandir, walk
except ImportError:
    from os import scandir, walk

Should mypy report an error for the above code if no stub or implementation for scandir is available?

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions