-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Don't complain about code that catches ImportErrors #676
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
There are tons of variations on this pattern though... Some code might import a 3rd party module in preference of a stdlib one... Maybe there are assignments following the import, or in the except block some variables are set to None, or a flag is set to False, ... |
If you want to be really crazy, it would be nice to support something like this: In
But maybe that's asking a bit much. For my use case, I wrote out a separate |
You can also use |
Yeah, you can always add a stub file even if there is no corresnponding |
Adding 'priority' as this seems to be a very common problem when migrating existing code. We still don't have a clear understanding of how exactly we should fix this, however. |
#1107 will happen first; is more important for now. |
A similar pattern: try:
from foo import bar
except ImportError:
pass
else:
# do something with bar Here mypy will treat |
This seems too difficult to support in a general enough fashion. Using |
Conder this example from @benhoyt's
scandir
(https://github.com/benhoyt/scandir):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 thatos.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:
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:
Should mypy report an error for the above code if no stub or implementation for
scandir
is available?The text was updated successfully, but these errors were encountered: