diff --git a/Lib/_dummy_thread.py b/Lib/_dummy_thread.py index 13b1f26965a..4909d1846a0 100644 --- a/Lib/_dummy_thread.py +++ b/Lib/_dummy_thread.py @@ -7,7 +7,7 @@ Suggested usage is:: try: import _thread - except ImportError: + except ModuleNotFoundError: import _dummy_thread as _thread """ diff --git a/Lib/_osx_support.py b/Lib/_osx_support.py index 8412e45b701..19ee3e2e400 100644 --- a/Lib/_osx_support.py +++ b/Lib/_osx_support.py @@ -62,7 +62,7 @@ def _read_output(commandstring): try: import tempfile fp = tempfile.NamedTemporaryFile() - except ImportError: + except ModuleNotFoundError: fp = open("/tmp/_osx_support.%s"%( os.getpid(),), "w+b") diff --git a/Lib/_pyio.py b/Lib/_pyio.py index 137ebcbd82c..79e6df25e18 100644 --- a/Lib/_pyio.py +++ b/Lib/_pyio.py @@ -9,7 +9,7 @@ import errno # Import _thread instead of threading to reduce startup cost try: from _thread import allocate_lock as Lock -except ImportError: +except ModuleNotFoundError: from _dummy_thread import allocate_lock as Lock import io @@ -1486,7 +1486,7 @@ class TextIOWrapper(TextIOBase): if encoding is None: try: import locale - except ImportError: + except ModuleNotFoundError: # Importing locale may fail if Python is being built encoding = "ascii" else: diff --git a/Lib/_strptime.py b/Lib/_strptime.py index 75209198066..7724d87ddc0 100644 --- a/Lib/_strptime.py +++ b/Lib/_strptime.py @@ -21,7 +21,7 @@ from datetime import (date as datetime_date, timezone as datetime_timezone) try: from _thread import allocate_lock as _thread_allocate_lock -except ImportError: +except ModuleNotFoundError: from _dummy_thread import allocate_lock as _thread_allocate_lock __all__ = [] diff --git a/Lib/bisect.py b/Lib/bisect.py index 4a4d05255e5..7808651a1aa 100644 --- a/Lib/bisect.py +++ b/Lib/bisect.py @@ -88,5 +88,5 @@ def bisect_left(a, x, lo=0, hi=None): # Overwrite above definitions with a fast C implementation try: from _bisect import * -except ImportError: +except ModuleNotFoundError: pass diff --git a/Lib/bz2.py b/Lib/bz2.py index 6e6a2b99487..f42045f2aa6 100644 --- a/Lib/bz2.py +++ b/Lib/bz2.py @@ -14,7 +14,7 @@ import warnings try: from threading import RLock -except ImportError: +except ModuleNotFoundError: from dummy_threading import RLock from _bz2 import BZ2Compressor, BZ2Decompressor diff --git a/Lib/cmd.py b/Lib/cmd.py index 859e91096d8..58ee5f5f41f 100644 --- a/Lib/cmd.py +++ b/Lib/cmd.py @@ -109,7 +109,7 @@ class Cmd: self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind(self.completekey+": complete") - except ImportError: + except ModuleNotFoundError: pass try: if intro is not None: @@ -143,7 +143,7 @@ class Cmd: try: import readline readline.set_completer(self.old_completer) - except ImportError: + except ModuleNotFoundError: pass diff --git a/Lib/code.py b/Lib/code.py index 9020aab7016..a1ac90421ca 100644 --- a/Lib/code.py +++ b/Lib/code.py @@ -293,7 +293,7 @@ def interact(banner=None, readfunc=None, local=None): else: try: import readline - except ImportError: + except ModuleNotFoundError: pass console.interact(banner) diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py index e1a075c7585..a8ad9169811 100644 --- a/Lib/collections/__init__.py +++ b/Lib/collections/__init__.py @@ -395,7 +395,7 @@ def _count_elements(mapping, iterable): try: # Load C helper function if available from _collections import _count_elements -except ImportError: +except ModuleNotFoundError: pass class Counter(dict): diff --git a/Lib/copy.py b/Lib/copy.py index d96201ea98e..2fbffa1f938 100644 --- a/Lib/copy.py +++ b/Lib/copy.py @@ -59,7 +59,7 @@ error = Error # backward compatibility try: from org.python.core import PyStringMap -except ImportError: +except ModuleNotFoundError: PyStringMap = None __all__ = ["Error", "copy", "deepcopy"] diff --git a/Lib/datetime.py b/Lib/datetime.py index bc1486c9195..2883418cc13 100644 --- a/Lib/datetime.py +++ b/Lib/datetime.py @@ -2116,7 +2116,7 @@ _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) try: from _datetime import * -except ImportError: +except ModuleNotFoundError: pass else: # Clean up unused names diff --git a/Lib/decimal.py b/Lib/decimal.py index d39ac1da749..6c3e19e2cbd 100644 --- a/Lib/decimal.py +++ b/Lib/decimal.py @@ -149,7 +149,7 @@ import sys try: from collections import namedtuple as _namedtuple DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent') -except ImportError: +except ModuleNotFoundError: DecimalTuple = lambda *args: args # Rounding @@ -430,7 +430,7 @@ _rounding_modes = (ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_CEILING, try: import threading -except ImportError: +except ModuleNotFoundError: # Python was compiled without threads; create a mock object instead class MockThreading(object): def local(self, sys=sys): @@ -6147,7 +6147,7 @@ del re # don't care too much if locale isn't present. try: import locale as _locale -except ImportError: +except ModuleNotFoundError: pass def _parse_format_specifier(format_spec, _localeconv=None): @@ -6391,7 +6391,7 @@ del sys try: import _decimal -except ImportError: +except ModuleNotFoundError: pass else: s1 = set(dir()) diff --git a/Lib/distutils/archive_util.py b/Lib/distutils/archive_util.py index fcda08e20a2..ba74045dc08 100644 --- a/Lib/distutils/archive_util.py +++ b/Lib/distutils/archive_util.py @@ -9,7 +9,7 @@ import sys try: import zipfile -except ImportError: +except ModuleNotFoundError: zipfile = None diff --git a/Lib/distutils/ccompiler.py b/Lib/distutils/ccompiler.py index 911e84dd3b3..bc183fc5d13 100644 --- a/Lib/distutils/ccompiler.py +++ b/Lib/distutils/ccompiler.py @@ -3,7 +3,7 @@ Contains CCompiler, an abstract base class that defines the interface for the Distutils compiler abstraction model.""" -import sys, os, re +import importlib, sys, os, re from distutils.errors import * from distutils.spawn import spawn from distutils.file_util import move_file @@ -1013,10 +1013,9 @@ def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0): try: module_name = "distutils." + module_name - __import__ (module_name) - module = sys.modules[module_name] + module = importlib.import_module(module_name) klass = vars(module)[class_name] - except ImportError: + except ModuleNotFoundError: raise DistutilsModuleError( "can't compile C/C++ code: unable to load module '%s'" % \ module_name) diff --git a/Lib/distutils/dist.py b/Lib/distutils/dist.py index f7fac08918b..11f6ff8fbce 100644 --- a/Lib/distutils/dist.py +++ b/Lib/distutils/dist.py @@ -4,11 +4,11 @@ Provides the Distribution class, which represents the module distribution being built/installed/distributed. """ -import sys, os, re +import importlib, sys, os, re try: import warnings -except ImportError: +except ModuleNotFoundError: warnings = None from distutils.errors import * @@ -788,9 +788,8 @@ Common commands: (see '--help-commands' for more) klass_name = command try: - __import__ (module_name) - module = sys.modules[module_name] - except ImportError: + module = importlib.import_module(module_name) + except ModuleNotFoundError: continue try: diff --git a/Lib/distutils/msvccompiler.py b/Lib/distutils/msvccompiler.py index 81166569619..9a94b41ad6b 100644 --- a/Lib/distutils/msvccompiler.py +++ b/Lib/distutils/msvccompiler.py @@ -28,7 +28,7 @@ try: RegEnumValue = winreg.EnumValue RegError = winreg.error -except ImportError: +except ModuleNotFoundError: try: import win32api import win32con @@ -39,7 +39,7 @@ except ImportError: RegEnumKey = win32api.RegEnumKey RegEnumValue = win32api.RegEnumValue RegError = win32api.error - except ImportError: + except ModuleNotFoundError: log.info("Warning: Can't read registry to find the " "necessary compiler setting\n" "Make sure that Python modules winreg, " diff --git a/Lib/distutils/util.py b/Lib/distutils/util.py index a2f9544519a..e241f59b946 100644 --- a/Lib/distutils/util.py +++ b/Lib/distutils/util.py @@ -388,7 +388,7 @@ def byte_compile (py_files, try: from tempfile import mkstemp (script_fd, script_name) = mkstemp(".py") - except ImportError: + except ModuleNotFoundError: from tempfile import mktemp (script_fd, script_name) = None, mktemp(".py") log.info("writing byte-compilation script '%s'", script_name) diff --git a/Lib/encodings/__init__.py b/Lib/encodings/__init__.py index 8dd713056ef..10d881dd018 100644 --- a/Lib/encodings/__init__.py +++ b/Lib/encodings/__init__.py @@ -29,11 +29,11 @@ Written by Marc-Andre Lemburg (mal@lemburg.com). """#" import codecs +import importlib from . import aliases _cache = {} _unknown = '--unknown--' -_import_tail = ['*'] _aliases = aliases.aliases class CodecRegistryError(LookupError, SystemError): @@ -94,9 +94,8 @@ def search_function(encoding): try: # Import is absolute to prevent the possibly malicious import of a # module with side-effects that is not in the 'encodings' package. - mod = __import__('encodings.' + modname, fromlist=_import_tail, - level=0) - except ImportError: + mod = importlib.import_module('encodings.' + modname) + except ModuleNotFoundError: pass else: break diff --git a/Lib/ftplib.py b/Lib/ftplib.py index fcd4b148c32..bd24a9e9d2c 100644 --- a/Lib/ftplib.py +++ b/Lib/ftplib.py @@ -667,7 +667,7 @@ class FTP: try: import ssl -except ImportError: +except ModuleNotFoundError: _SSLSocket = None else: _SSLSocket = ssl.SSLSocket diff --git a/Lib/functools.py b/Lib/functools.py index 67af370d016..9403e8e8432 100644 --- a/Lib/functools.py +++ b/Lib/functools.py @@ -15,7 +15,7 @@ __all__ = ['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES', try: from _functools import reduce -except ImportError: +except ModuleNotFoundError: pass from abc import get_cache_token from collections import namedtuple @@ -143,7 +143,7 @@ def cmp_to_key(mycmp): try: from _functools import cmp_to_key -except ImportError: +except ModuleNotFoundError: pass @@ -166,7 +166,7 @@ def partial(func, *args, **keywords): try: from _functools import partial -except ImportError: +except ModuleNotFoundError: pass diff --git a/Lib/getopt.py b/Lib/getopt.py index 3d6ecbddb99..9c59dd771e8 100644 --- a/Lib/getopt.py +++ b/Lib/getopt.py @@ -36,7 +36,7 @@ __all__ = ["GetoptError","error","getopt","gnu_getopt"] import os try: from gettext import gettext as _ -except ImportError: +except ModuleNotFoundError: # Bootstrapping Python: gettext's dependencies not built yet def _(s): return s diff --git a/Lib/getpass.py b/Lib/getpass.py index 6ec6c78824b..ed9bc5901df 100644 --- a/Lib/getpass.py +++ b/Lib/getpass.py @@ -164,7 +164,7 @@ try: except (ImportError, AttributeError): try: import msvcrt - except ImportError: + except ModuleNotFoundError: getpass = fallback_getpass else: getpass = win_getpass diff --git a/Lib/hashlib.py b/Lib/hashlib.py index a1bd8b2de8c..c9ef4c9af3a 100644 --- a/Lib/hashlib.py +++ b/Lib/hashlib.py @@ -98,7 +98,7 @@ def __get_builtin_constructor(name): return _sha3.sha3_384 elif bs == '512': return _sha3.sha3_512 - except ImportError: + except ModuleNotFoundError: pass # no extension module, this hash is unsupported. raise ValueError('unsupported hash type ' + name) @@ -143,7 +143,7 @@ try: __get_hash = __get_openssl_constructor algorithms_available = algorithms_available.union( _hashlib.openssl_md_meth_names) -except ImportError: +except ModuleNotFoundError: new = __py_new __get_hash = __get_builtin_constructor diff --git a/Lib/heapq.py b/Lib/heapq.py index 00b429c2d36..dfe7a48aa7b 100644 --- a/Lib/heapq.py +++ b/Lib/heapq.py @@ -343,7 +343,7 @@ def _siftup_max(heap, pos): # If available, use C implementation try: from _heapq import * -except ImportError: +except ModuleNotFoundError: pass def merge(*iterables): diff --git a/Lib/http/client.py b/Lib/http/client.py index 939615b2fb4..188f4f60fae 100644 --- a/Lib/http/client.py +++ b/Lib/http/client.py @@ -1156,7 +1156,7 @@ class HTTPConnection: try: import ssl -except ImportError: +except ModuleNotFoundError: pass else: class HTTPSConnection(HTTPConnection): diff --git a/Lib/http/cookiejar.py b/Lib/http/cookiejar.py index be828eba698..fd40ee04a74 100644 --- a/Lib/http/cookiejar.py +++ b/Lib/http/cookiejar.py @@ -35,7 +35,7 @@ import time import urllib.parse, urllib.request try: import threading as _threading -except ImportError: +except ModuleNotFoundError: import dummy_threading as _threading import http.client # only for the default HTTP port from calendar import timegm diff --git a/Lib/http/server.py b/Lib/http/server.py index e47e034feb9..48e3f9745aa 100644 --- a/Lib/http/server.py +++ b/Lib/http/server.py @@ -904,7 +904,7 @@ def nobody_uid(): return nobody try: import pwd - except ImportError: + except ModuleNotFoundError: return -1 try: nobody = pwd.getpwnam('nobody')[2] diff --git a/Lib/imaplib.py b/Lib/imaplib.py index c959f12da09..30f51da9b44 100644 --- a/Lib/imaplib.py +++ b/Lib/imaplib.py @@ -29,7 +29,7 @@ from io import DEFAULT_BUFFER_SIZE try: import ssl HAVE_SSL = True -except ImportError: +except ModuleNotFoundError: HAVE_SSL = False __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", diff --git a/Lib/imp.py b/Lib/imp.py index 40869f5ac06..5170b066e4a 100644 --- a/Lib/imp.py +++ b/Lib/imp.py @@ -12,7 +12,7 @@ from _imp import (lock_held, acquire_lock, release_lock, _fix_co_filename) try: from _imp import load_dynamic -except ImportError: +except ModuleNotFoundError: # Platform doesn't support dynamic loading. load_dynamic = None diff --git a/Lib/importlib/__init__.py b/Lib/importlib/__init__.py index d07f02ed746..df893ccb175 100644 --- a/Lib/importlib/__init__.py +++ b/Lib/importlib/__init__.py @@ -14,7 +14,7 @@ import sys try: import _frozen_importlib as _bootstrap -except ImportError: +except ModuleNotFoundError: from . import _bootstrap _bootstrap._setup(sys, _imp) else: diff --git a/Lib/importlib/abc.py b/Lib/importlib/abc.py index 417fe413fb2..cf20e9fe1af 100644 --- a/Lib/importlib/abc.py +++ b/Lib/importlib/abc.py @@ -3,7 +3,7 @@ from . import _bootstrap from . import machinery try: import _frozen_importlib -except ImportError as exc: +except ModuleNotFoundError as exc: if exc.name != '_frozen_importlib': raise _frozen_importlib = None diff --git a/Lib/inspect.py b/Lib/inspect.py index 22b9e845431..378e22f6d6b 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -51,7 +51,7 @@ from collections import namedtuple, OrderedDict # back to hardcording so the dependency is optional try: from dis import COMPILER_FLAG_NAMES as _flag_names -except ImportError: +except ModuleNotFoundError: CO_OPTIMIZED, CO_NEWLOCALS = 0x1, 0x2 CO_VARARGS, CO_VARKEYWORDS = 0x4, 0x8 CO_NESTED, CO_GENERATOR, CO_NOFREE = 0x10, 0x20, 0x40 diff --git a/Lib/json/decoder.py b/Lib/json/decoder.py index da7ef9c8195..4f11354a615 100644 --- a/Lib/json/decoder.py +++ b/Lib/json/decoder.py @@ -5,7 +5,7 @@ import re from json import scanner try: from _json import scanstring as c_scanstring -except ImportError: +except ModuleNotFoundError: c_scanstring = None __all__ = ['JSONDecoder'] diff --git a/Lib/json/encoder.py b/Lib/json/encoder.py index 39b550dbb0b..3fa90bdfef8 100644 --- a/Lib/json/encoder.py +++ b/Lib/json/encoder.py @@ -4,11 +4,11 @@ import re try: from _json import encode_basestring_ascii as c_encode_basestring_ascii -except ImportError: +except ModuleNotFoundError: c_encode_basestring_ascii = None try: from _json import make_encoder as c_make_encoder -except ImportError: +except ModuleNotFoundError: c_make_encoder = None ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]') diff --git a/Lib/json/scanner.py b/Lib/json/scanner.py index 86426cde1a7..761ade3483b 100644 --- a/Lib/json/scanner.py +++ b/Lib/json/scanner.py @@ -3,7 +3,7 @@ import re try: from _json import make_scanner as c_make_scanner -except ImportError: +except ModuleNotFoundError: c_make_scanner = None __all__ = ['make_scanner'] diff --git a/Lib/lib2to3/refactor.py b/Lib/lib2to3/refactor.py index 81003178715..11a353cb99e 100644 --- a/Lib/lib2to3/refactor.py +++ b/Lib/lib2to3/refactor.py @@ -706,7 +706,7 @@ class MultiprocessRefactoringTool(RefactoringTool): items, write, doctests_only) try: import multiprocessing - except ImportError: + except ModuleNotFoundError: raise MultiprocessingUnsupported if self.queue is not None: raise RuntimeError("already doing multiple processes") diff --git a/Lib/locale.py b/Lib/locale.py index d2a885d519f..75ab2abbb4a 100644 --- a/Lib/locale.py +++ b/Lib/locale.py @@ -47,7 +47,7 @@ try: from _locale import * -except ImportError: +except ModuleNotFoundError: # Locale emulation diff --git a/Lib/logging/__init__.py b/Lib/logging/__init__.py index 46298605c45..b4552bfecb8 100644 --- a/Lib/logging/__init__.py +++ b/Lib/logging/__init__.py @@ -37,7 +37,7 @@ __all__ = ['BASIC_FORMAT', 'BufferingFormatter', 'CRITICAL', 'DEBUG', 'ERROR', try: import threading -except ImportError: #pragma: no cover +except ModuleNotFoundError: #pragma: no cover threading = None __author__ = "Vinay Sajip " diff --git a/Lib/logging/config.py b/Lib/logging/config.py index b882a62ab3e..4354dd129da 100644 --- a/Lib/logging/config.py +++ b/Lib/logging/config.py @@ -30,7 +30,7 @@ import io try: import _thread as thread import threading -except ImportError: #pragma: no cover +except ModuleNotFoundError: #pragma: no cover thread = None from socketserver import ThreadingTCPServer, StreamRequestHandler diff --git a/Lib/logging/handlers.py b/Lib/logging/handlers.py index f1ddbb5edae..0a11b8232b4 100644 --- a/Lib/logging/handlers.py +++ b/Lib/logging/handlers.py @@ -29,7 +29,7 @@ from stat import ST_DEV, ST_INO, ST_MTIME import queue try: import threading -except ImportError: #pragma: no cover +except ModuleNotFoundError: #pragma: no cover threading = None # @@ -995,7 +995,7 @@ class NTEventLogHandler(logging.Handler): logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE, logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, } - except ImportError: + except ModuleNotFoundError: print("The Python Win32 extensions for NT (service, event "\ "logging) appear not to be available.") self._welu = None diff --git a/Lib/macpath.py b/Lib/macpath.py index d34f9e944cc..c5af1026f83 100644 --- a/Lib/macpath.py +++ b/Lib/macpath.py @@ -187,7 +187,7 @@ def realpath(path): path = abspath(path) try: import Carbon.File - except ImportError: + except ModuleNotFoundError: return path if not path: return path diff --git a/Lib/mailbox.py b/Lib/mailbox.py index 2049516b2d6..a45b3bf38b9 100644 --- a/Lib/mailbox.py +++ b/Lib/mailbox.py @@ -23,7 +23,7 @@ import io import contextlib try: import fcntl -except ImportError: +except ModuleNotFoundError: fcntl = None __all__ = [ 'Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF', diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py index 5aaa9080873..a5825cdfa46 100644 --- a/Lib/mimetypes.py +++ b/Lib/mimetypes.py @@ -29,7 +29,7 @@ import posixpath import urllib.parse try: import winreg as _winreg -except ImportError: +except ModuleNotFoundError: _winreg = None __all__ = [ diff --git a/Lib/multiprocessing/connection.py b/Lib/multiprocessing/connection.py index 47e21239ce8..40f7a9e594b 100644 --- a/Lib/multiprocessing/connection.py +++ b/Lib/multiprocessing/connection.py @@ -27,7 +27,7 @@ from multiprocessing.forking import ForkingPickler try: import _winapi from _winapi import WAIT_OBJECT_0, WAIT_TIMEOUT, INFINITE -except ImportError: +except ModuleNotFoundError: if sys.platform == 'win32': raise _winapi = None diff --git a/Lib/multiprocessing/forking.py b/Lib/multiprocessing/forking.py index 54c073dc17c..8841e4e9fca 100644 --- a/Lib/multiprocessing/forking.py +++ b/Lib/multiprocessing/forking.py @@ -73,7 +73,7 @@ ForkingPickler.register(type(int.__add__), _reduce_method_descriptor) try: from functools import partial -except ImportError: +except ModuleNotFoundError: pass else: def _reduce_partial(p): diff --git a/Lib/nntplib.py b/Lib/nntplib.py index 01d4303f4da..7f26e1ca6e9 100644 --- a/Lib/nntplib.py +++ b/Lib/nntplib.py @@ -71,7 +71,7 @@ import warnings try: import ssl -except ImportError: +except ModuleNotFoundError: _have_ssl = False else: _have_ssl = True diff --git a/Lib/ntpath.py b/Lib/ntpath.py index d81f7285aee..4dfea3275e2 100644 --- a/Lib/ntpath.py +++ b/Lib/ntpath.py @@ -566,7 +566,7 @@ def normpath(path): try: from nt import _getfullpathname -except ImportError: # not running on Windows - mock up something sensible +except ModuleNotFoundError: # not running on Windows - mock up something sensible def abspath(path): """Return the absolute version of a path.""" if not isabs(path): @@ -659,6 +659,6 @@ try: # This is overkill on Windows - just pass the path to GetFileAttributes # and check the attribute from there. from nt import _isdir as isdir -except ImportError: +except ModuleNotFoundError: # Use genericpath.isdir as imported above. pass diff --git a/Lib/operator.py b/Lib/operator.py index d31a9a45379..c8273cc90e3 100644 --- a/Lib/operator.py +++ b/Lib/operator.py @@ -360,7 +360,7 @@ def ixor(a, b): try: from _operator import * -except ImportError: +except ModuleNotFoundError: pass else: from _operator import __doc__ diff --git a/Lib/optparse.py b/Lib/optparse.py index 37764d317ac..3812258cc33 100644 --- a/Lib/optparse.py +++ b/Lib/optparse.py @@ -87,7 +87,7 @@ def _repr(self): try: from gettext import gettext, ngettext -except ImportError: +except ModuleNotFoundError: def gettext(message): return message diff --git a/Lib/os.py b/Lib/os.py index 96720e41ef8..8f568c7729d 100644 --- a/Lib/os.py +++ b/Lib/os.py @@ -52,13 +52,13 @@ if 'posix' in _names: try: from posix import _exit __all__.append('_exit') - except ImportError: + except ModuleNotFoundError: pass import posixpath as path try: from posix import _have_functions - except ImportError: + except ModuleNotFoundError: pass elif 'nt' in _names: @@ -68,7 +68,7 @@ elif 'nt' in _names: try: from nt import _exit __all__.append('_exit') - except ImportError: + except ModuleNotFoundError: pass import ntpath as path @@ -78,7 +78,7 @@ elif 'nt' in _names: try: from nt import _have_functions - except ImportError: + except ModuleNotFoundError: pass elif 'ce' in _names: @@ -88,7 +88,7 @@ elif 'ce' in _names: try: from ce import _exit __all__.append('_exit') - except ImportError: + except ModuleNotFoundError: pass # We can use the standard Windows path. import ntpath as path @@ -99,11 +99,11 @@ elif 'ce' in _names: try: from ce import _have_functions - except ImportError: + except ModuleNotFoundError: pass else: - raise ImportError('no os specific module found') + raise ModuleNotFoundError('no os specific module found') sys.modules['os.path'] = path from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, diff --git a/Lib/pdb.py b/Lib/pdb.py index e5596e547ec..d964f9875b6 100755 --- a/Lib/pdb.py +++ b/Lib/pdb.py @@ -158,7 +158,7 @@ class Pdb(bdb.Bdb, cmd.Cmd): import readline # remove some common file name delimiters readline.set_completer_delims(' \t\n`@#$%^&*()=+[{]}\\|;:\'",<>?') - except ImportError: + except ModuleNotFoundError: pass self.allow_kbdint = False self.nosigint = nosigint diff --git a/Lib/pickle.py b/Lib/pickle.py index b3b775f4759..5d22fceaf6b 100644 --- a/Lib/pickle.py +++ b/Lib/pickle.py @@ -90,7 +90,7 @@ class _Stop(Exception): # Jython has PyStringMap; it's a dict subclass with string keys try: from org.python.core import PyStringMap -except ImportError: +except ModuleNotFoundError: PyStringMap = None # Pickle opcodes. See pickletools.py for extensive docs. The listing @@ -1296,7 +1296,7 @@ def loads(s, *, fix_imports=True, encoding="ASCII", errors="strict"): # Use the faster _pickle if possible try: from _pickle import * -except ImportError: +except ModuleNotFoundError: Pickler, Unpickler = _Pickler, _Unpickler # Doctest diff --git a/Lib/platform.py b/Lib/platform.py index c54f7687ba5..5951efbbb5e 100755 --- a/Lib/platform.py +++ b/Lib/platform.py @@ -460,7 +460,7 @@ def _win32_getvalue(key,name,default=''): try: # Use win32api if available from win32api import RegQueryValueEx - except ImportError: + except ModuleNotFoundError: # On Python 2.0 and later, emulate using winreg import winreg RegQueryValueEx = winreg.QueryValueEx @@ -503,7 +503,7 @@ def win32_ver(release='',version='',csd='',ptype=''): RegCloseKey, GetVersionEx from win32con import HKEY_LOCAL_MACHINE, VER_PLATFORM_WIN32_NT, \ VER_PLATFORM_WIN32_WINDOWS, VER_NT_WORKSTATION - except ImportError: + except ModuleNotFoundError: # Emulate the win32api module using Python APIs try: sys.getwindowsversion @@ -661,7 +661,7 @@ def _mac_ver_gestalt(): # Check whether the version info module is available try: import _gestalt - except ImportError: + except ModuleNotFoundError: return None # Get the infos sysv, sysa = _mac_ver_lookup(('sysv','sysa')) @@ -697,7 +697,7 @@ def _mac_ver_xml(): try: import plistlib - except ImportError: + except ModuleNotFoundError: return None pl = plistlib.readPlist(fn) @@ -762,7 +762,7 @@ def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')): # Import the needed APIs try: import java.lang - except ImportError: + except ModuleNotFoundError: return release,vendor,vminfo,osinfo vendor = _java_getprop('java.vendor', vendor) @@ -874,7 +874,7 @@ def _node(default=''): """ try: import socket - except ImportError: + except ModuleNotFoundError: # No sockets... return default try: @@ -1138,7 +1138,7 @@ def uname(): # Get processor information try: import vms_lib - except ImportError: + except ModuleNotFoundError: pass else: csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0) diff --git a/Lib/poplib.py b/Lib/poplib.py index 0f12ae2f2ef..5d62ba44e75 100644 --- a/Lib/poplib.py +++ b/Lib/poplib.py @@ -20,7 +20,7 @@ import socket try: import ssl HAVE_SSL = True -except ImportError: +except ModuleNotFoundError: HAVE_SSL = False __all__ = ["POP3","error_proto"] diff --git a/Lib/pstats.py b/Lib/pstats.py index e1ec3557406..5e5dcaecd7b 100644 --- a/Lib/pstats.py +++ b/Lib/pstats.py @@ -528,7 +528,7 @@ if __name__ == '__main__': import cmd try: import readline - except ImportError: + except ModuleNotFoundError: pass class ProfileBrowser(cmd.Cmd): diff --git a/Lib/pty.py b/Lib/pty.py index e841f12f3ed..605aeee5588 100644 --- a/Lib/pty.py +++ b/Lib/pty.py @@ -67,7 +67,7 @@ def slave_open(tty_name): result = os.open(tty_name, os.O_RDWR) try: from fcntl import ioctl, I_PUSH - except ImportError: + except ModuleNotFoundError: return result try: ioctl(result, I_PUSH, "ptem") diff --git a/Lib/pydoc.py b/Lib/pydoc.py index 6a2b44ac412..2e9b6d518fc 100755 --- a/Lib/pydoc.py +++ b/Lib/pydoc.py @@ -1893,7 +1893,7 @@ Here is a list of available topics. Enter any topic name to get more help. def showtopic(self, topic, more_xrefs=''): try: import pydoc_data.topics - except ImportError: + except ModuleNotFoundError: self.output.write(''' Sorry, topic and keyword documentation is not available because the module "pydoc_data.topics" could not be found. @@ -1933,7 +1933,7 @@ module "pydoc_data.topics" could not be found. """ try: import pydoc_data.topics - except ImportError: + except ModuleNotFoundError: return(''' Sorry, topic and keyword documentation is not available because the module "pydoc_data.topics" could not be found. diff --git a/Lib/queue.py b/Lib/queue.py index c3296fe1382..99cb5b9f570 100644 --- a/Lib/queue.py +++ b/Lib/queue.py @@ -2,13 +2,13 @@ try: import threading -except ImportError: +except ModuleNotFoundError: import dummy_threading as threading from collections import deque from heapq import heappush, heappop try: from time import monotonic as time -except ImportError: +except ModuleNotFoundError: from time import time __all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue'] diff --git a/Lib/quopri.py b/Lib/quopri.py index e5bd010d5ba..63afc1db3d6 100755 --- a/Lib/quopri.py +++ b/Lib/quopri.py @@ -13,7 +13,7 @@ EMPTYSTRING = b'' try: from binascii import a2b_qp, b2a_qp -except ImportError: +except ModuleNotFoundError: a2b_qp = None b2a_qp = None diff --git a/Lib/reprlib.py b/Lib/reprlib.py index f8033604da2..81005f15193 100644 --- a/Lib/reprlib.py +++ b/Lib/reprlib.py @@ -6,7 +6,7 @@ import builtins from itertools import islice try: from _thread import get_ident -except ImportError: +except ModuleNotFoundError: from _dummy_thread import get_ident def recursive_repr(fillvalue='...'): diff --git a/Lib/rlcompleter.py b/Lib/rlcompleter.py index d3a443737a5..4de0c88a802 100644 --- a/Lib/rlcompleter.py +++ b/Lib/rlcompleter.py @@ -154,7 +154,7 @@ def get_class_members(klass): try: import readline -except ImportError: +except ModuleNotFoundError: pass else: readline.set_completer(Completer().complete) diff --git a/Lib/sched.py b/Lib/sched.py index 9a82a89688d..14f6fff4e33 100644 --- a/Lib/sched.py +++ b/Lib/sched.py @@ -33,11 +33,11 @@ import heapq from collections import namedtuple try: import threading -except ImportError: +except ModuleNotFoundError: import dummy_threading as threading try: from time import monotonic as _time -except ImportError: +except ModuleNotFoundError: from time import time as _time __all__ = ["scheduler"] diff --git a/Lib/shutil.py b/Lib/shutil.py index 6879d8bbd1a..9d1a466801d 100644 --- a/Lib/shutil.py +++ b/Lib/shutil.py @@ -17,17 +17,17 @@ try: import bz2 del bz2 _BZ2_SUPPORTED = True -except ImportError: +except ModuleNotFoundError: _BZ2_SUPPORTED = False try: from pwd import getpwnam -except ImportError: +except ModuleNotFoundError: getpwnam = None try: from grp import getgrnam -except ImportError: +except ModuleNotFoundError: getgrnam = None __all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2", @@ -668,7 +668,7 @@ def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): # command. try: import zipfile - except ImportError: + except ModuleNotFoundError: zipfile = None if zipfile is None: @@ -858,7 +858,7 @@ def _unpack_zipfile(filename, extract_dir): """ try: import zipfile - except ImportError: + except ModuleNotFoundError: raise ReadError('zlib not supported, cannot unpack this archive.') if not zipfile.is_zipfile(filename): diff --git a/Lib/site.py b/Lib/site.py index 96a4bef71ef..a1f94f7ea1a 100644 --- a/Lib/site.py +++ b/Lib/site.py @@ -469,7 +469,7 @@ def enablerlcompleter(): try: import readline import rlcompleter - except ImportError: + except ModuleNotFoundError: return # Reading the initialization (config) file may not be enough to set a @@ -570,7 +570,7 @@ def execsitecustomize(): """Run custom site specific code, if available.""" try: import sitecustomize - except ImportError: + except ModuleNotFoundError: pass except Exception as err: if os.environ.get("PYTHONVERBOSE"): @@ -586,7 +586,7 @@ def execusercustomize(): """Run custom user specific code, if available.""" try: import usercustomize - except ImportError: + except ModuleNotFoundError: pass except Exception as err: if os.environ.get("PYTHONVERBOSE"): diff --git a/Lib/smtpd.py b/Lib/smtpd.py index f28036a5b4f..457cef64e05 100755 --- a/Lib/smtpd.py +++ b/Lib/smtpd.py @@ -846,7 +846,7 @@ if __name__ == '__main__': if options.setuid: try: import pwd - except ImportError: + except ModuleNotFoundError: print('Cannot import module "pwd"; try running with -n option.', file=sys.stderr) sys.exit(1) nobody = pwd.getpwnam('nobody')[2] diff --git a/Lib/smtplib.py b/Lib/smtplib.py index cc46e4f49f5..e26bfbd4652 100644 --- a/Lib/smtplib.py +++ b/Lib/smtplib.py @@ -171,7 +171,7 @@ def _fix_eols(data): try: import ssl -except ImportError: +except ModuleNotFoundError: _have_ssl = False else: _have_ssl = True diff --git a/Lib/socket.py b/Lib/socket.py index 96f8ed0c7f7..db28b4b35cd 100644 --- a/Lib/socket.py +++ b/Lib/socket.py @@ -51,7 +51,7 @@ import os, sys, io try: import errno -except ImportError: +except ModuleNotFoundError: errno = None EBADF = getattr(errno, 'EBADF', 9) EAGAIN = getattr(errno, 'EAGAIN', 11) diff --git a/Lib/socketserver.py b/Lib/socketserver.py index e9e4e4e4add..a6ee7187207 100644 --- a/Lib/socketserver.py +++ b/Lib/socketserver.py @@ -136,7 +136,7 @@ import os import errno try: import threading -except ImportError: +except ModuleNotFoundError: import dummy_threading as threading __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer", diff --git a/Lib/sqlite3/test/dbapi.py b/Lib/sqlite3/test/dbapi.py index 04649fc5492..b728cb31068 100644 --- a/Lib/sqlite3/test/dbapi.py +++ b/Lib/sqlite3/test/dbapi.py @@ -25,7 +25,7 @@ import unittest import sqlite3 as sqlite try: import threading -except ImportError: +except ModuleNotFoundError: threading = None from test.support import TESTFN, unlink diff --git a/Lib/sqlite3/test/types.py b/Lib/sqlite3/test/types.py index 3b4cb6d1d1a..9a1d4639c88 100644 --- a/Lib/sqlite3/test/types.py +++ b/Lib/sqlite3/test/types.py @@ -26,7 +26,7 @@ import unittest import sqlite3 as sqlite try: import zlib -except ImportError: +except ModuleNotFoundError: zlib = None diff --git a/Lib/sre_compile.py b/Lib/sre_compile.py index ea6e6be96e0..ed84444639a 100644 --- a/Lib/sre_compile.py +++ b/Lib/sre_compile.py @@ -295,7 +295,7 @@ def _mk_bitmap(bits): def _optimize_unicode(charset, fixup): try: import array - except ImportError: + except ModuleNotFoundError: return charset charmap = [0]*65536 negate = 0 diff --git a/Lib/ssl.py b/Lib/ssl.py index d78d96d160e..5177ae7b459 100644 --- a/Lib/ssl.py +++ b/Lib/ssl.py @@ -127,14 +127,14 @@ _PROTOCOL_NAMES = { try: from _ssl import PROTOCOL_SSLv2 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2 -except ImportError: +except ModuleNotFoundError: _SSLv2_IF_EXISTS = None else: _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2" try: from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2 -except ImportError: +except ModuleNotFoundError: pass else: _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1" diff --git a/Lib/subprocess.py b/Lib/subprocess.py index 78907e0e943..553d3c6a47e 100644 --- a/Lib/subprocess.py +++ b/Lib/subprocess.py @@ -353,7 +353,7 @@ import warnings import errno try: from time import monotonic as _time -except ImportError: +except ModuleNotFoundError: from time import time as _time # Exception classes used by this module. diff --git a/Lib/tarfile.py b/Lib/tarfile.py index 06df7df7405..289aefd9d78 100644 --- a/Lib/tarfile.py +++ b/Lib/tarfile.py @@ -50,7 +50,7 @@ import re try: import grp, pwd -except ImportError: +except ModuleNotFoundError: grp = pwd = None # os.symlink on Windows prior to 6.0 raises NotImplementedError @@ -381,7 +381,7 @@ class _Stream: if comptype == "gz": try: import zlib - except ImportError: + except ModuleNotFoundError: raise CompressionError("zlib module is not available") self.zlib = zlib self.crc = zlib.crc32(b"") @@ -394,7 +394,7 @@ class _Stream: elif comptype == "bz2": try: import bz2 - except ImportError: + except ModuleNotFoundError: raise CompressionError("bz2 module is not available") if mode == "r": self.dbuf = b"" @@ -406,7 +406,7 @@ class _Stream: elif comptype == "xz": try: import lzma - except ImportError: + except ModuleNotFoundError: raise CompressionError("lzma module is not available") if mode == "r": self.dbuf = b"" @@ -1654,7 +1654,7 @@ class TarFile(object): try: import bz2 - except ImportError: + except ModuleNotFoundError: raise CompressionError("bz2 module is not available") fileobj = bz2.BZ2File(fileobj or name, mode, @@ -1678,7 +1678,7 @@ class TarFile(object): try: import lzma - except ImportError: + except ModuleNotFoundError: raise CompressionError("lzma module is not available") fileobj = lzma.LZMAFile(fileobj or name, mode, preset=preset) diff --git a/Lib/tempfile.py b/Lib/tempfile.py index 10b6a1b334e..f2c3ccc48bc 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -36,7 +36,7 @@ from random import Random as _Random try: import fcntl as _fcntl -except ImportError: +except ModuleNotFoundError: def _set_cloexec(fd): pass else: @@ -53,7 +53,7 @@ else: try: import _thread -except ImportError: +except ModuleNotFoundError: import _dummy_thread as _thread _allocate_lock = _thread.allocate_lock diff --git a/Lib/threading.py b/Lib/threading.py index 3526894ae0f..90612e5839e 100644 --- a/Lib/threading.py +++ b/Lib/threading.py @@ -6,14 +6,14 @@ import _thread from time import sleep as _sleep try: from time import monotonic as _time -except ImportError: +except ModuleNotFoundError: from time import time as _time from traceback import format_exc as _format_exc from _weakrefset import WeakSet from itertools import islice as _islice try: from _collections import deque as _deque -except ImportError: +except ModuleNotFoundError: from collections import deque as _deque # Note regarding PEP 8 compliant names @@ -922,7 +922,7 @@ _shutdown = _MainThread()._exitfunc try: from _thread import _local as local -except ImportError: +except ModuleNotFoundError: from _threading_local import local diff --git a/Lib/trace.py b/Lib/trace.py index 09fe9ee0e48..dc72b8c6034 100644 --- a/Lib/trace.py +++ b/Lib/trace.py @@ -61,12 +61,12 @@ import pickle from warnings import warn as _warn try: from time import monotonic as _time -except ImportError: +except ModuleNotFoundError: from time import time as _time try: import threading -except ImportError: +except ModuleNotFoundError: _settrace = sys.settrace def _unsettrace(): diff --git a/Lib/urllib/request.py b/Lib/urllib/request.py index 4765a942886..d54b9747fb1 100644 --- a/Lib/urllib/request.py +++ b/Lib/urllib/request.py @@ -110,7 +110,7 @@ from urllib.response import addinfourl, addclosehook # check for SSL try: import ssl -except ImportError: +except ModuleNotFoundError: _have_ssl = False else: _have_ssl = True @@ -2512,7 +2512,7 @@ elif os.name == 'nt': proxies = {} try: import winreg - except ImportError: + except ModuleNotFoundError: # Std module, so should be around - but you never know! return proxies try: @@ -2560,7 +2560,7 @@ elif os.name == 'nt': def proxy_bypass_registry(host): try: import winreg - except ImportError: + except ModuleNotFoundError: # Std modules, so should be around - but you never know! return 0 try: diff --git a/Lib/venv/__init__.py b/Lib/venv/__init__.py index ecdb68e8808..102c8d3f237 100644 --- a/Lib/venv/__init__.py +++ b/Lib/venv/__init__.py @@ -35,7 +35,7 @@ import sys import sysconfig try: import threading -except ImportError: +except ModuleNotFoundError: threading = None logger = logging.getLogger(__name__) diff --git a/Lib/warnings.py b/Lib/warnings.py index b05a08ee83a..38223617c67 100644 --- a/Lib/warnings.py +++ b/Lib/warnings.py @@ -144,8 +144,8 @@ def _getcategory(category): module = category[:i] klass = category[i+1:] try: - m = __import__(module, None, None, [klass]) - except ImportError: + m = __import__(module, fromlist[klass]) + except ModuleNotFoundError: raise _OptionError("invalid module name: %r" % (module,)) try: cat = getattr(m, klass) @@ -362,7 +362,7 @@ try: defaultaction = _defaultaction onceregistry = _onceregistry _warnings_defaults = True -except ImportError: +except ModuleNotFoundError: filters = [] defaultaction = "default" onceregistry = {} diff --git a/Lib/xml/etree/ElementTree.py b/Lib/xml/etree/ElementTree.py index edf25818f13..9c129d829dd 100644 --- a/Lib/xml/etree/ElementTree.py +++ b/Lib/xml/etree/ElementTree.py @@ -1439,13 +1439,13 @@ class XMLParser: def __init__(self, html=0, target=None, encoding=None): try: from xml.parsers import expat - except ImportError: + except ModuleNotFoundError: try: import pyexpat as expat - except ImportError: - raise ImportError( - "No module named expat; use SimpleXMLTreeBuilder instead" - ) + except ModuleNotFoundError: + raise ModuleNotFoundError( + "No module named expat; use SimpleXMLTreeBuilder instead", + name='expat') parser = expat.ParserCreate(encoding, "}") if target is None: target = TreeBuilder() diff --git a/Lib/xml/sax/expatreader.py b/Lib/xml/sax/expatreader.py index a227cdab572..8619747529c 100644 --- a/Lib/xml/sax/expatreader.py +++ b/Lib/xml/sax/expatreader.py @@ -20,7 +20,7 @@ del sys try: from xml.parsers import expat -except ImportError: +except ModuleNotFoundError: raise SAXReaderNotAvailable("expat not supported", None) else: if not hasattr(expat, "ParserCreate"): @@ -30,18 +30,7 @@ from xml.sax import xmlreader, saxutils, handler AttributesImpl = xmlreader.AttributesImpl AttributesNSImpl = xmlreader.AttributesNSImpl -# If we're using a sufficiently recent version of Python, we can use -# weak references to avoid cycles between the parser and content -# handler, otherwise we'll just have to pretend. -try: - import _weakref -except ImportError: - def _mkproxy(o): - return o -else: - import weakref - _mkproxy = weakref.proxy - del weakref, _weakref +import weakref # --- ExpatLocator @@ -52,7 +41,7 @@ class ExpatLocator(xmlreader.Locator): a circular reference between the parser and the content handler. """ def __init__(self, parser): - self._ref = _mkproxy(parser) + self._ref = weakref.proxy(parser) def getColumnNumber(self): parser = self._ref diff --git a/Lib/xmlrpc/client.py b/Lib/xmlrpc/client.py index ff422652e69..55546e47309 100644 --- a/Lib/xmlrpc/client.py +++ b/Lib/xmlrpc/client.py @@ -139,7 +139,7 @@ import errno from io import BytesIO try: import gzip -except ImportError: +except ModuleNotFoundError: gzip = None #python can be built without zlib/gzip support # --------------------------------------------------------------------