diff options
83 files changed, 158 insertions, 144 deletions
diff --git a/Lib/_dummy_thread.py b/Lib/_dummy_thread.py index 4909d18..13b1f26 100644 --- a/Lib/_dummy_thread.py +++ b/Lib/_dummy_thread.py @@ -7,7 +7,7 @@ Suggested usage is:: try: import _thread - except ModuleNotFoundError: + except ImportError: import _dummy_thread as _thread """ diff --git a/Lib/_osx_support.py b/Lib/_osx_support.py index 19ee3e2..8412e45 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 ModuleNotFoundError: + except ImportError: fp = open("/tmp/_osx_support.%s"%( os.getpid(),), "w+b") diff --git a/Lib/_pyio.py b/Lib/_pyio.py index 79e6df2..137ebcb 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 ModuleNotFoundError: +except ImportError: 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 ModuleNotFoundError: + except ImportError: # Importing locale may fail if Python is being built encoding = "ascii" else: diff --git a/Lib/_strptime.py b/Lib/_strptime.py index 7724d87..7520919 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 ModuleNotFoundError: +except ImportError: from _dummy_thread import allocate_lock as _thread_allocate_lock __all__ = [] diff --git a/Lib/bisect.py b/Lib/bisect.py index 7808651..4a4d052 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 ModuleNotFoundError: +except ImportError: pass @@ -14,7 +14,7 @@ import warnings try: from threading import RLock -except ModuleNotFoundError: +except ImportError: from dummy_threading import RLock from _bz2 import BZ2Compressor, BZ2Decompressor @@ -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 ModuleNotFoundError: + except ImportError: pass try: if intro is not None: @@ -143,7 +143,7 @@ class Cmd: try: import readline readline.set_completer(self.old_completer) - except ModuleNotFoundError: + except ImportError: pass diff --git a/Lib/code.py b/Lib/code.py index a1ac904..9020aab 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 ModuleNotFoundError: + except ImportError: pass console.interact(banner) diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py index a8ad916..e1a075c 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 ModuleNotFoundError: +except ImportError: pass class Counter(dict): diff --git a/Lib/copy.py b/Lib/copy.py index 2fbffa1..d96201e 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 ModuleNotFoundError: +except ImportError: PyStringMap = None __all__ = ["Error", "copy", "deepcopy"] diff --git a/Lib/datetime.py b/Lib/datetime.py index 2883418..bc1486c 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 ModuleNotFoundError: +except ImportError: pass else: # Clean up unused names diff --git a/Lib/decimal.py b/Lib/decimal.py index 6c3e19e..d39ac1d 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 ModuleNotFoundError: +except ImportError: 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 ModuleNotFoundError: +except ImportError: # 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 ModuleNotFoundError: +except ImportError: pass def _parse_format_specifier(format_spec, _localeconv=None): @@ -6391,7 +6391,7 @@ del sys try: import _decimal -except ModuleNotFoundError: +except ImportError: pass else: s1 = set(dir()) diff --git a/Lib/distutils/archive_util.py b/Lib/distutils/archive_util.py index ba74045..fcda08e 100644 --- a/Lib/distutils/archive_util.py +++ b/Lib/distutils/archive_util.py @@ -9,7 +9,7 @@ import sys try: import zipfile -except ModuleNotFoundError: +except ImportError: zipfile = None diff --git a/Lib/distutils/ccompiler.py b/Lib/distutils/ccompiler.py index bc183fc..911e84d 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 importlib, sys, os, re +import sys, os, re from distutils.errors import * from distutils.spawn import spawn from distutils.file_util import move_file @@ -1013,9 +1013,10 @@ def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0): try: module_name = "distutils." + module_name - module = importlib.import_module(module_name) + __import__ (module_name) + module = sys.modules[module_name] klass = vars(module)[class_name] - except ModuleNotFoundError: + except ImportError: 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 11f6ff8..f7fac08 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 importlib, sys, os, re +import sys, os, re try: import warnings -except ModuleNotFoundError: +except ImportError: warnings = None from distutils.errors import * @@ -788,8 +788,9 @@ Common commands: (see '--help-commands' for more) klass_name = command try: - module = importlib.import_module(module_name) - except ModuleNotFoundError: + __import__ (module_name) + module = sys.modules[module_name] + except ImportError: continue try: diff --git a/Lib/distutils/msvccompiler.py b/Lib/distutils/msvccompiler.py index 9a94b41..8116656 100644 --- a/Lib/distutils/msvccompiler.py +++ b/Lib/distutils/msvccompiler.py @@ -28,7 +28,7 @@ try: RegEnumValue = winreg.EnumValue RegError = winreg.error -except ModuleNotFoundError: +except ImportError: try: import win32api import win32con @@ -39,7 +39,7 @@ except ModuleNotFoundError: RegEnumKey = win32api.RegEnumKey RegEnumValue = win32api.RegEnumValue RegError = win32api.error - except ModuleNotFoundError: + except ImportError: 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 257de68..efb3834 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 ModuleNotFoundError: + except ImportError: 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 10d881d..8dd7130 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,8 +94,9 @@ 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 = importlib.import_module('encodings.' + modname) - except ModuleNotFoundError: + mod = __import__('encodings.' + modname, fromlist=_import_tail, + level=0) + except ImportError: pass else: break diff --git a/Lib/ftplib.py b/Lib/ftplib.py index bd24a9e..fcd4b14 100644 --- a/Lib/ftplib.py +++ b/Lib/ftplib.py @@ -667,7 +667,7 @@ class FTP: try: import ssl -except ModuleNotFoundError: +except ImportError: _SSLSocket = None else: _SSLSocket = ssl.SSLSocket diff --git a/Lib/functools.py b/Lib/functools.py index 95c1a41..6aa13a2 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 ModuleNotFoundError: +except ImportError: 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 ModuleNotFoundError: +except ImportError: pass @@ -166,7 +166,7 @@ def partial(func, *args, **keywords): try: from _functools import partial -except ModuleNotFoundError: +except ImportError: pass diff --git a/Lib/getopt.py b/Lib/getopt.py index 9c59dd7..3d6ecbd 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 ModuleNotFoundError: +except ImportError: # Bootstrapping Python: gettext's dependencies not built yet def _(s): return s diff --git a/Lib/getpass.py b/Lib/getpass.py index ed9bc59..6ec6c788 100644 --- a/Lib/getpass.py +++ b/Lib/getpass.py @@ -164,7 +164,7 @@ try: except (ImportError, AttributeError): try: import msvcrt - except ModuleNotFoundError: + except ImportError: getpass = fallback_getpass else: getpass = win_getpass diff --git a/Lib/hashlib.py b/Lib/hashlib.py index c9ef4c9..a1bd8b2 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 ModuleNotFoundError: + except ImportError: 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 ModuleNotFoundError: +except ImportError: new = __py_new __get_hash = __get_builtin_constructor diff --git a/Lib/heapq.py b/Lib/heapq.py index dfe7a48..00b429c 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 ModuleNotFoundError: +except ImportError: pass def merge(*iterables): diff --git a/Lib/http/client.py b/Lib/http/client.py index 188f4f6..939615b 100644 --- a/Lib/http/client.py +++ b/Lib/http/client.py @@ -1156,7 +1156,7 @@ class HTTPConnection: try: import ssl -except ModuleNotFoundError: +except ImportError: pass else: class HTTPSConnection(HTTPConnection): diff --git a/Lib/http/cookiejar.py b/Lib/http/cookiejar.py index fd40ee0..be828eb 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 ModuleNotFoundError: +except ImportError: 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 48e3f97..e47e034 100644 --- a/Lib/http/server.py +++ b/Lib/http/server.py @@ -904,7 +904,7 @@ def nobody_uid(): return nobody try: import pwd - except ModuleNotFoundError: + except ImportError: return -1 try: nobody = pwd.getpwnam('nobody')[2] diff --git a/Lib/imaplib.py b/Lib/imaplib.py index ce32c80..42353bb 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 ModuleNotFoundError: +except ImportError: HAVE_SSL = False __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", @@ -12,7 +12,7 @@ from _imp import (lock_held, acquire_lock, release_lock, _fix_co_filename) try: from _imp import load_dynamic -except ModuleNotFoundError: +except ImportError: # Platform doesn't support dynamic loading. load_dynamic = None diff --git a/Lib/importlib/__init__.py b/Lib/importlib/__init__.py index 83de028..d456c48 100644 --- a/Lib/importlib/__init__.py +++ b/Lib/importlib/__init__.py @@ -15,7 +15,7 @@ import types try: import _frozen_importlib as _bootstrap -except ModuleNotFoundError: +except ImportError: from . import _bootstrap _bootstrap._setup(sys, _imp) else: diff --git a/Lib/importlib/abc.py b/Lib/importlib/abc.py index b53a1a5..082796c 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 ModuleNotFoundError as exc: +except ImportError as exc: if exc.name != '_frozen_importlib': raise _frozen_importlib = None diff --git a/Lib/inspect.py b/Lib/inspect.py index d788525..4a28507 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -50,7 +50,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 ModuleNotFoundError: +except ImportError: 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 4f11354..da7ef9c 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 ModuleNotFoundError: +except ImportError: c_scanstring = None __all__ = ['JSONDecoder'] diff --git a/Lib/json/encoder.py b/Lib/json/encoder.py index 3fa90bd..39b550d 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 ModuleNotFoundError: +except ImportError: c_encode_basestring_ascii = None try: from _json import make_encoder as c_make_encoder -except ModuleNotFoundError: +except ImportError: 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 761ade3..86426cd 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 ModuleNotFoundError: +except ImportError: c_make_scanner = None __all__ = ['make_scanner'] diff --git a/Lib/lib2to3/refactor.py b/Lib/lib2to3/refactor.py index 11a353c..8100317 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 ModuleNotFoundError: + except ImportError: 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 75ab2ab..d2a885d 100644 --- a/Lib/locale.py +++ b/Lib/locale.py @@ -47,7 +47,7 @@ try: from _locale import * -except ModuleNotFoundError: +except ImportError: # Locale emulation diff --git a/Lib/logging/__init__.py b/Lib/logging/__init__.py index b4552bf..4629860 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 ModuleNotFoundError: #pragma: no cover +except ImportError: #pragma: no cover threading = None __author__ = "Vinay Sajip <vinay_sajip@red-dove.com>" diff --git a/Lib/logging/config.py b/Lib/logging/config.py index 4354dd1..b882a62 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 ModuleNotFoundError: #pragma: no cover +except ImportError: #pragma: no cover thread = None from socketserver import ThreadingTCPServer, StreamRequestHandler diff --git a/Lib/logging/handlers.py b/Lib/logging/handlers.py index 0a11b82..f1ddbb5 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 ModuleNotFoundError: #pragma: no cover +except ImportError: #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 ModuleNotFoundError: + except ImportError: 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 c5af102..d34f9e94 100644 --- a/Lib/macpath.py +++ b/Lib/macpath.py @@ -187,7 +187,7 @@ def realpath(path): path = abspath(path) try: import Carbon.File - except ModuleNotFoundError: + except ImportError: return path if not path: return path diff --git a/Lib/mailbox.py b/Lib/mailbox.py index a45b3bf3..2049516 100644 --- a/Lib/mailbox.py +++ b/Lib/mailbox.py @@ -23,7 +23,7 @@ import io import contextlib try: import fcntl -except ModuleNotFoundError: +except ImportError: fcntl = None __all__ = [ 'Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF', diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py index a5825cd..5aaa908 100644 --- a/Lib/mimetypes.py +++ b/Lib/mimetypes.py @@ -29,7 +29,7 @@ import posixpath import urllib.parse try: import winreg as _winreg -except ModuleNotFoundError: +except ImportError: _winreg = None __all__ = [ diff --git a/Lib/multiprocessing/connection.py b/Lib/multiprocessing/connection.py index 55f6ba9..1093d9f 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 ModuleNotFoundError: +except ImportError: if sys.platform == 'win32': raise _winapi = None diff --git a/Lib/multiprocessing/forking.py b/Lib/multiprocessing/forking.py index d06036d..39cfd8d 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 ModuleNotFoundError: +except ImportError: pass else: def _reduce_partial(p): diff --git a/Lib/nntplib.py b/Lib/nntplib.py index 7f26e1c..01d4303 100644 --- a/Lib/nntplib.py +++ b/Lib/nntplib.py @@ -71,7 +71,7 @@ import warnings try: import ssl -except ModuleNotFoundError: +except ImportError: _have_ssl = False else: _have_ssl = True diff --git a/Lib/ntpath.py b/Lib/ntpath.py index 4dfea32..d81f728 100644 --- a/Lib/ntpath.py +++ b/Lib/ntpath.py @@ -566,7 +566,7 @@ def normpath(path): try: from nt import _getfullpathname -except ModuleNotFoundError: # not running on Windows - mock up something sensible +except ImportError: # 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 ModuleNotFoundError: +except ImportError: # Use genericpath.isdir as imported above. pass diff --git a/Lib/operator.py b/Lib/operator.py index c8273cc..d31a9a4 100644 --- a/Lib/operator.py +++ b/Lib/operator.py @@ -360,7 +360,7 @@ def ixor(a, b): try: from _operator import * -except ModuleNotFoundError: +except ImportError: pass else: from _operator import __doc__ diff --git a/Lib/optparse.py b/Lib/optparse.py index 3812258..37764d3 100644 --- a/Lib/optparse.py +++ b/Lib/optparse.py @@ -87,7 +87,7 @@ def _repr(self): try: from gettext import gettext, ngettext -except ModuleNotFoundError: +except ImportError: def gettext(message): return message @@ -52,13 +52,13 @@ if 'posix' in _names: try: from posix import _exit __all__.append('_exit') - except ModuleNotFoundError: + except ImportError: pass import posixpath as path try: from posix import _have_functions - except ModuleNotFoundError: + except ImportError: pass elif 'nt' in _names: @@ -68,7 +68,7 @@ elif 'nt' in _names: try: from nt import _exit __all__.append('_exit') - except ModuleNotFoundError: + except ImportError: pass import ntpath as path @@ -78,7 +78,7 @@ elif 'nt' in _names: try: from nt import _have_functions - except ModuleNotFoundError: + except ImportError: pass elif 'ce' in _names: @@ -88,7 +88,7 @@ elif 'ce' in _names: try: from ce import _exit __all__.append('_exit') - except ModuleNotFoundError: + except ImportError: 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 ModuleNotFoundError: + except ImportError: pass else: - raise ModuleNotFoundError('no os specific module found') + raise ImportError('no os specific module found') sys.modules['os.path'] = path from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, @@ -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 ModuleNotFoundError: + except ImportError: pass self.allow_kbdint = False self.nosigint = nosigint diff --git a/Lib/pickle.py b/Lib/pickle.py index 5d22fce..b3b775f 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 ModuleNotFoundError: +except ImportError: 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 ModuleNotFoundError: +except ImportError: Pickler, Unpickler = _Pickler, _Unpickler # Doctest diff --git a/Lib/platform.py b/Lib/platform.py index 5951efb..c54f768 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 ModuleNotFoundError: + except ImportError: # 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 ModuleNotFoundError: + except ImportError: # 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 ModuleNotFoundError: + except ImportError: return None # Get the infos sysv, sysa = _mac_ver_lookup(('sysv','sysa')) @@ -697,7 +697,7 @@ def _mac_ver_xml(): try: import plistlib - except ModuleNotFoundError: + except ImportError: 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 ModuleNotFoundError: + except ImportError: return release,vendor,vminfo,osinfo vendor = _java_getprop('java.vendor', vendor) @@ -874,7 +874,7 @@ def _node(default=''): """ try: import socket - except ModuleNotFoundError: + except ImportError: # No sockets... return default try: @@ -1138,7 +1138,7 @@ def uname(): # Get processor information try: import vms_lib - except ModuleNotFoundError: + except ImportError: pass else: csid, cpu_number = vms_lib.getsyi('SYI$_CPU',0) diff --git a/Lib/poplib.py b/Lib/poplib.py index 5d62ba4..0f12ae2 100644 --- a/Lib/poplib.py +++ b/Lib/poplib.py @@ -20,7 +20,7 @@ import socket try: import ssl HAVE_SSL = True -except ModuleNotFoundError: +except ImportError: HAVE_SSL = False __all__ = ["POP3","error_proto"] diff --git a/Lib/pstats.py b/Lib/pstats.py index 5e5dcae..e1ec355 100644 --- a/Lib/pstats.py +++ b/Lib/pstats.py @@ -528,7 +528,7 @@ if __name__ == '__main__': import cmd try: import readline - except ModuleNotFoundError: + except ImportError: pass class ProfileBrowser(cmd.Cmd): @@ -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 ModuleNotFoundError: + except ImportError: return result try: ioctl(result, I_PUSH, "ptem") diff --git a/Lib/pydoc.py b/Lib/pydoc.py index 9cc3126..61d5165 100755 --- a/Lib/pydoc.py +++ b/Lib/pydoc.py @@ -1892,7 +1892,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 ModuleNotFoundError: + except ImportError: self.output.write(''' Sorry, topic and keyword documentation is not available because the module "pydoc_data.topics" could not be found. @@ -1932,7 +1932,7 @@ module "pydoc_data.topics" could not be found. """ try: import pydoc_data.topics - except ModuleNotFoundError: + except ImportError: 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 99cb5b9..c3296fe 100644 --- a/Lib/queue.py +++ b/Lib/queue.py @@ -2,13 +2,13 @@ try: import threading -except ModuleNotFoundError: +except ImportError: import dummy_threading as threading from collections import deque from heapq import heappush, heappop try: from time import monotonic as time -except ModuleNotFoundError: +except ImportError: from time import time __all__ = ['Empty', 'Full', 'Queue', 'PriorityQueue', 'LifoQueue'] diff --git a/Lib/quopri.py b/Lib/quopri.py index 63afc1d..e5bd010 100755 --- a/Lib/quopri.py +++ b/Lib/quopri.py @@ -13,7 +13,7 @@ EMPTYSTRING = b'' try: from binascii import a2b_qp, b2a_qp -except ModuleNotFoundError: +except ImportError: a2b_qp = None b2a_qp = None diff --git a/Lib/reprlib.py b/Lib/reprlib.py index 81005f1..f803360 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 ModuleNotFoundError: +except ImportError: from _dummy_thread import get_ident def recursive_repr(fillvalue='...'): diff --git a/Lib/rlcompleter.py b/Lib/rlcompleter.py index 4de0c88..d3a4437 100644 --- a/Lib/rlcompleter.py +++ b/Lib/rlcompleter.py @@ -154,7 +154,7 @@ def get_class_members(klass): try: import readline -except ModuleNotFoundError: +except ImportError: pass else: readline.set_completer(Completer().complete) diff --git a/Lib/sched.py b/Lib/sched.py index 14f6fff..9a82a89 100644 --- a/Lib/sched.py +++ b/Lib/sched.py @@ -33,11 +33,11 @@ import heapq from collections import namedtuple try: import threading -except ModuleNotFoundError: +except ImportError: import dummy_threading as threading try: from time import monotonic as _time -except ModuleNotFoundError: +except ImportError: from time import time as _time __all__ = ["scheduler"] diff --git a/Lib/shutil.py b/Lib/shutil.py index 9d1a466..6879d8b 100644 --- a/Lib/shutil.py +++ b/Lib/shutil.py @@ -17,17 +17,17 @@ try: import bz2 del bz2 _BZ2_SUPPORTED = True -except ModuleNotFoundError: +except ImportError: _BZ2_SUPPORTED = False try: from pwd import getpwnam -except ModuleNotFoundError: +except ImportError: getpwnam = None try: from grp import getgrnam -except ModuleNotFoundError: +except ImportError: 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 ModuleNotFoundError: + except ImportError: zipfile = None if zipfile is None: @@ -858,7 +858,7 @@ def _unpack_zipfile(filename, extract_dir): """ try: import zipfile - except ModuleNotFoundError: + except ImportError: 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 a1f94f7..96a4bef 100644 --- a/Lib/site.py +++ b/Lib/site.py @@ -469,7 +469,7 @@ def enablerlcompleter(): try: import readline import rlcompleter - except ModuleNotFoundError: + except ImportError: 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 ModuleNotFoundError: + except ImportError: 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 ModuleNotFoundError: + except ImportError: pass except Exception as err: if os.environ.get("PYTHONVERBOSE"): diff --git a/Lib/smtpd.py b/Lib/smtpd.py index 457cef6..f28036a 100755 --- a/Lib/smtpd.py +++ b/Lib/smtpd.py @@ -846,7 +846,7 @@ if __name__ == '__main__': if options.setuid: try: import pwd - except ModuleNotFoundError: + except ImportError: 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 80dd468..e1a32ed 100644 --- a/Lib/smtplib.py +++ b/Lib/smtplib.py @@ -171,7 +171,7 @@ def _fix_eols(data): try: import ssl -except ModuleNotFoundError: +except ImportError: _have_ssl = False else: _have_ssl = True diff --git a/Lib/socket.py b/Lib/socket.py index db28b4b..96f8ed0 100644 --- a/Lib/socket.py +++ b/Lib/socket.py @@ -51,7 +51,7 @@ import os, sys, io try: import errno -except ModuleNotFoundError: +except ImportError: errno = None EBADF = getattr(errno, 'EBADF', 9) EAGAIN = getattr(errno, 'EAGAIN', 11) diff --git a/Lib/socketserver.py b/Lib/socketserver.py index a6ee718..e9e4e4e 100644 --- a/Lib/socketserver.py +++ b/Lib/socketserver.py @@ -136,7 +136,7 @@ import os import errno try: import threading -except ModuleNotFoundError: +except ImportError: 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 b728cb3..04649fc 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 ModuleNotFoundError: +except ImportError: threading = None from test.support import TESTFN, unlink diff --git a/Lib/sqlite3/test/types.py b/Lib/sqlite3/test/types.py index 9a1d463..3b4cb6d 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 ModuleNotFoundError: +except ImportError: zlib = None diff --git a/Lib/sre_compile.py b/Lib/sre_compile.py index ed84444..ea6e6be 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 ModuleNotFoundError: + except ImportError: return charset charmap = [0]*65536 negate = 0 @@ -127,14 +127,14 @@ _PROTOCOL_NAMES = { try: from _ssl import PROTOCOL_SSLv2 _SSLv2_IF_EXISTS = PROTOCOL_SSLv2 -except ModuleNotFoundError: +except ImportError: _SSLv2_IF_EXISTS = None else: _PROTOCOL_NAMES[PROTOCOL_SSLv2] = "SSLv2" try: from _ssl import PROTOCOL_TLSv1_1, PROTOCOL_TLSv1_2 -except ModuleNotFoundError: +except ImportError: pass else: _PROTOCOL_NAMES[PROTOCOL_TLSv1_1] = "TLSv1.1" diff --git a/Lib/subprocess.py b/Lib/subprocess.py index f81e676..d299f04 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 ModuleNotFoundError: +except ImportError: from time import time as _time # Exception classes used by this module. diff --git a/Lib/tarfile.py b/Lib/tarfile.py index 289aefd..06df7df 100644 --- a/Lib/tarfile.py +++ b/Lib/tarfile.py @@ -50,7 +50,7 @@ import re try: import grp, pwd -except ModuleNotFoundError: +except ImportError: 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 ModuleNotFoundError: + except ImportError: 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 ModuleNotFoundError: + except ImportError: 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 ModuleNotFoundError: + except ImportError: raise CompressionError("lzma module is not available") if mode == "r": self.dbuf = b"" @@ -1654,7 +1654,7 @@ class TarFile(object): try: import bz2 - except ModuleNotFoundError: + except ImportError: 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 ModuleNotFoundError: + except ImportError: 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 f2c3ccc..10b6a1b 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 ModuleNotFoundError: +except ImportError: def _set_cloexec(fd): pass else: @@ -53,7 +53,7 @@ else: try: import _thread -except ModuleNotFoundError: +except ImportError: import _dummy_thread as _thread _allocate_lock = _thread.allocate_lock diff --git a/Lib/threading.py b/Lib/threading.py index 90612e5..3526894 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 ModuleNotFoundError: +except ImportError: 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 ModuleNotFoundError: +except ImportError: 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 ModuleNotFoundError: +except ImportError: from _threading_local import local diff --git a/Lib/trace.py b/Lib/trace.py index dc72b8c..09fe9ee 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 ModuleNotFoundError: +except ImportError: from time import time as _time try: import threading -except ModuleNotFoundError: +except ImportError: _settrace = sys.settrace def _unsettrace(): diff --git a/Lib/urllib/request.py b/Lib/urllib/request.py index d54b974..4765a94 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 ModuleNotFoundError: +except ImportError: _have_ssl = False else: _have_ssl = True @@ -2512,7 +2512,7 @@ elif os.name == 'nt': proxies = {} try: import winreg - except ModuleNotFoundError: + except ImportError: # 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 ModuleNotFoundError: + except ImportError: # 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 102c8d3..ecdb68e 100644 --- a/Lib/venv/__init__.py +++ b/Lib/venv/__init__.py @@ -35,7 +35,7 @@ import sys import sysconfig try: import threading -except ModuleNotFoundError: +except ImportError: threading = None logger = logging.getLogger(__name__) diff --git a/Lib/warnings.py b/Lib/warnings.py index 3822361..b05a08e 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, fromlist[klass]) - except ModuleNotFoundError: + m = __import__(module, None, None, [klass]) + except ImportError: 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 ModuleNotFoundError: +except ImportError: filters = [] defaultaction = "default" onceregistry = {} diff --git a/Lib/xml/etree/ElementTree.py b/Lib/xml/etree/ElementTree.py index 9c129d8..edf2581 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 ModuleNotFoundError: + except ImportError: try: import pyexpat as expat - except ModuleNotFoundError: - raise ModuleNotFoundError( - "No module named expat; use SimpleXMLTreeBuilder instead", - name='expat') + except ImportError: + raise ImportError( + "No module named expat; use SimpleXMLTreeBuilder instead" + ) 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 8619747..a227cda 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 ModuleNotFoundError: +except ImportError: raise SAXReaderNotAvailable("expat not supported", None) else: if not hasattr(expat, "ParserCreate"): @@ -30,7 +30,18 @@ from xml.sax import xmlreader, saxutils, handler AttributesImpl = xmlreader.AttributesImpl AttributesNSImpl = xmlreader.AttributesNSImpl -import weakref +# 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 # --- ExpatLocator @@ -41,7 +52,7 @@ class ExpatLocator(xmlreader.Locator): a circular reference between the parser and the content handler. """ def __init__(self, parser): - self._ref = weakref.proxy(parser) + self._ref = _mkproxy(parser) def getColumnNumber(self): parser = self._ref diff --git a/Lib/xmlrpc/client.py b/Lib/xmlrpc/client.py index 55546e4..ff42265 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 ModuleNotFoundError: +except ImportError: gzip = None #python can be built without zlib/gzip support # -------------------------------------------------------------------- |