diff options
31 files changed, 117 insertions, 371 deletions
diff --git a/benchmarks/benchmarks/bench_indexing.py b/benchmarks/benchmarks/bench_indexing.py index 2bcf7efad..9ee0d1fb5 100644 --- a/benchmarks/benchmarks/bench_indexing.py +++ b/benchmarks/benchmarks/bench_indexing.py @@ -2,7 +2,6 @@ from .common import Benchmark, get_squares_, get_indexes_, get_indexes_rand_ from os.path import join as pjoin import shutil -import sys from numpy import memmap, float32, array import numpy as np from tempfile import mkdtemp @@ -22,10 +21,7 @@ class Indexing(Benchmark): 'indexes_': get_indexes_(), 'indexes_rand_': get_indexes_rand_()} - if sys.version_info[0] >= 3: - code = "def run():\n for a in squares_.values(): a[%s]%s" - else: - code = "def run():\n for a in squares_.itervalues(): a[%s]%s" + code = "def run():\n for a in squares_.values(): a[%s]%s" code = code % (sel, op) exec(code, ns) diff --git a/numpy/core/__init__.py b/numpy/core/__init__.py index 815c61924..c2d53fe3e 100644 --- a/numpy/core/__init__.py +++ b/numpy/core/__init__.py @@ -135,16 +135,11 @@ def _ufunc_reduce(func): return _ufunc_reconstruct, (whichmodule(func, name), name) -import sys -if sys.version_info[0] >= 3: - import copyreg -else: - import copy_reg as copyreg +import copyreg copyreg.pickle(ufunc, _ufunc_reduce, _ufunc_reconstruct) # Unclutter namespace (must keep _ufunc_reconstruct for unpickling) del copyreg -del sys del _ufunc_reduce from numpy._pytesttester import PytestTester diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index 918da4a72..ec7e4261f 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -22,19 +22,12 @@ __docformat__ = 'restructuredtext' # scalars are printed inside an ndarray. Only the latter strs are currently # user-customizable. -import sys import functools import numbers -if sys.version_info[0] >= 3: - try: - from _thread import get_ident - except ImportError: - from _dummy_thread import get_ident -else: - try: - from thread import get_ident - except ImportError: - from dummy_thread import get_ident +try: + from _thread import get_ident +except ImportError: + from _dummy_thread import get_ident import numpy as np from . import numerictypes as _nt diff --git a/numpy/core/code_generators/generate_umath.py b/numpy/core/code_generators/generate_umath.py index f5691d950..7599360f5 100644 --- a/numpy/core/code_generators/generate_umath.py +++ b/numpy/core/code_generators/generate_umath.py @@ -148,12 +148,8 @@ class Ufunc: # String-handling utilities to avoid locale-dependence. import string -if sys.version_info[0] < 3: - UPPER_TABLE = string.maketrans(string.ascii_lowercase, - string.ascii_uppercase) -else: - UPPER_TABLE = bytes.maketrans(bytes(string.ascii_lowercase, "ascii"), - bytes(string.ascii_uppercase, "ascii")) +UPPER_TABLE = bytes.maketrans(bytes(string.ascii_lowercase, "ascii"), + bytes(string.ascii_uppercase, "ascii")) def english_upper(s): """ Apply English case rules to convert ASCII strings to all upper case. @@ -1076,15 +1072,9 @@ def make_ufuncs(funcdict): uf = funcdict[name] mlist = [] docstring = textwrap.dedent(uf.docstring).strip() - if sys.version_info[0] < 3: - docstring = docstring.encode('string-escape') - docstring = docstring.replace(r'"', r'\"') - else: - docstring = docstring.encode('unicode-escape').decode('ascii') - docstring = docstring.replace(r'"', r'\"') - # XXX: I don't understand why the following replace is not - # necessary in the python 2 case. - docstring = docstring.replace(r"'", r"\'") + docstring = docstring.encode('unicode-escape').decode('ascii') + docstring = docstring.replace(r'"', r'\"') + docstring = docstring.replace(r"'", r"\'") # Split the docstring because some compilers (like MS) do not like big # string literal in C code. We split at endlines because textwrap.wrap # do not play well with \n diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py index 4d7781317..1cfdc55c0 100644 --- a/numpy/core/defchararray.py +++ b/numpy/core/defchararray.py @@ -1953,8 +1953,8 @@ class chararray(ndarray): # strings in the new array. itemsize = long(itemsize) - if sys.version_info[0] >= 3 and isinstance(buffer, str): - # On Py3, unicode objects do not have the buffer interface + if isinstance(buffer, str): + # unicode objects do not have the buffer interface filler = buffer buffer = None else: diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 5a1cbe9fc..72c6089b8 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -35,12 +35,6 @@ bitwise_not = invert ufunc = type(sin) newaxis = None -if sys.version_info[0] >= 3: - import builtins -else: - import __builtin__ as builtins - - array_function_dispatch = functools.partial( overrides.array_function_dispatch, module='numpy') diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py index c63ea08c7..c06552c4e 100644 --- a/numpy/core/numerictypes.py +++ b/numpy/core/numerictypes.py @@ -80,7 +80,6 @@ Exported symbols include: """ import types as _types -import sys import numbers import warnings @@ -120,11 +119,8 @@ from ._dtype import _kind_name # we don't export these for import *, but we do want them accessible # as numerictypes.bool, etc. -if sys.version_info[0] >= 3: - from builtins import bool, int, float, complex, object, str - unicode = str -else: - from __builtin__ import bool, int, float, complex, object, unicode, str +from builtins import bool, int, float, complex, object, str +unicode = str # We use this later diff --git a/numpy/core/setup_common.py b/numpy/core/setup_common.py index a947f7a3d..6d8e603a7 100644 --- a/numpy/core/setup_common.py +++ b/numpy/core/setup_common.py @@ -244,9 +244,9 @@ def check_long_double_representation(cmd): # Disable multi-file interprocedural optimization in the Intel compiler on Linux # which generates intermediary object files and prevents checking the # float representation. - elif (sys.platform != "win32" - and cmd.compiler.compiler_type.startswith('intel') - and '-ipo' in cmd.compiler.cc_exe): + elif (sys.platform != "win32" + and cmd.compiler.compiler_type.startswith('intel') + and '-ipo' in cmd.compiler.cc_exe): newcompiler = cmd.compiler.cc_exe.replace(' -ipo', '') cmd.compiler.set_executables( compiler=newcompiler, diff --git a/numpy/distutils/ccompiler.py b/numpy/distutils/ccompiler.py index 35cf9df81..ea7912feb 100644 --- a/numpy/distutils/ccompiler.py +++ b/numpy/distutils/ccompiler.py @@ -271,12 +271,8 @@ def CCompiler_compile(self, sources, output_dir=None, macros=None, if not sources: return [] - # FIXME:RELATIVE_IMPORT - if sys.version_info[0] < 3: - from .fcompiler import FCompiler, is_f_file, has_f90_header - else: - from numpy.distutils.fcompiler import (FCompiler, is_f_file, - has_f90_header) + from numpy.distutils.fcompiler import (FCompiler, is_f_file, + has_f90_header) if isinstance(self, FCompiler): display = [] for fc in ['f77', 'f90', 'fix']: diff --git a/numpy/distutils/cpuinfo.py b/numpy/distutils/cpuinfo.py index efea90113..e066f9888 100644 --- a/numpy/distutils/cpuinfo.py +++ b/numpy/distutils/cpuinfo.py @@ -17,10 +17,7 @@ __all__ = ['cpu'] import sys, re, types import os -if sys.version_info[0] >= 3: - from subprocess import getstatusoutput -else: - from commands import getstatusoutput +from subprocess import getstatusoutput import warnings import platform @@ -484,10 +481,7 @@ class Win32CPUInfo(CPUInfoBase): info = [] try: #XXX: Bad style to use so long `try:...except:...`. Fix it! - if sys.version_info[0] >= 3: - import winreg - else: - import _winreg as winreg + import winreg prgx = re.compile(r"family\s+(?P<FML>\d+)\s+model\s+(?P<MDL>\d+)" r"\s+stepping\s+(?P<STP>\d+)", re.IGNORECASE) diff --git a/numpy/distutils/exec_command.py b/numpy/distutils/exec_command.py index d35b4f898..fb10d2470 100644 --- a/numpy/distutils/exec_command.py +++ b/numpy/distutils/exec_command.py @@ -74,10 +74,6 @@ def filepath_from_subprocess_output(output): # Another historical oddity if output[-1:] == '\n': output = output[:-1] - # stdio uses bytes in python 2, so to avoid issues, we simply - # remove all non-ascii characters - if sys.version_info < (3, 0): - output = output.encode('ascii', errors='replace') return output @@ -89,10 +85,7 @@ def forward_bytes_to_stdout(val): The assumption is that the subprocess call already returned bytes in a suitable encoding. """ - if sys.version_info.major < 3: - # python 2 has binary output anyway - sys.stdout.write(val) - elif hasattr(sys.stdout, 'buffer'): + if hasattr(sys.stdout, 'buffer'): # use the underlying binary output if there is one sys.stdout.buffer.write(val) elif hasattr(sys.stdout, 'encoding'): @@ -305,11 +298,6 @@ def _exec_command(command, use_shell=None, use_tee = None, **env): if text[-1:] == '\n': text = text[:-1] - # stdio uses bytes in python 2, so to avoid issues, we simply - # remove all non-ascii characters - if sys.version_info < (3, 0): - text = text.encode('ascii', errors='replace') - if use_tee and text: print(text) return proc.returncode, text diff --git a/numpy/distutils/fcompiler/gnu.py b/numpy/distutils/fcompiler/gnu.py index 4fc9f33ff..128e54db3 100644 --- a/numpy/distutils/fcompiler/gnu.py +++ b/numpy/distutils/fcompiler/gnu.py @@ -412,8 +412,7 @@ class Gnu95FCompiler(GnuFCompiler): break h.update(block) text = base64.b32encode(h.digest()) - if sys.version_info[0] >= 3: - text = text.decode('ascii') + text = text.decode('ascii') return text.rstrip('=') def _link_wrapper_lib(self, objects, output_dir, extra_dll_dir, diff --git a/numpy/distutils/log.py b/numpy/distutils/log.py index ec1100b1b..79eec00a6 100644 --- a/numpy/distutils/log.py +++ b/numpy/distutils/log.py @@ -4,12 +4,8 @@ from distutils.log import * from distutils.log import Log as old_Log from distutils.log import _global_log -if sys.version_info[0] < 3: - from .misc_util import (red_text, default_text, cyan_text, green_text, - is_sequence, is_string) -else: - from numpy.distutils.misc_util import (red_text, default_text, cyan_text, - green_text, is_sequence, is_string) +from numpy.distutils.misc_util import (red_text, default_text, cyan_text, + green_text, is_sequence, is_string) def _fix_args(args,flag=1): diff --git a/numpy/distutils/mingw32ccompiler.py b/numpy/distutils/mingw32ccompiler.py index e2cd1c19b..475f73718 100644 --- a/numpy/distutils/mingw32ccompiler.py +++ b/numpy/distutils/mingw32ccompiler.py @@ -15,11 +15,7 @@ import textwrap # Overwrite certain distutils.ccompiler functions: import numpy.distutils.ccompiler - -if sys.version_info[0] < 3: - from . import log -else: - from numpy.distutils import log +from numpy.distutils import log # NT stuff # 1. Make sure libpython<version>.a exists for gcc. If not, build it. # 2. Force windows to use gcc (we're struggling with MSVC and g77 support) diff --git a/numpy/distutils/misc_util.py b/numpy/distutils/misc_util.py index eec8d56a3..f9d2be716 100644 --- a/numpy/distutils/misc_util.py +++ b/numpy/distutils/misc_util.py @@ -2242,10 +2242,7 @@ def get_info(pkgname, dirs=None): return info def is_bootstrapping(): - if sys.version_info[0] >= 3: - import builtins - else: - import __builtin__ as builtins + import builtins try: builtins.__NUMPY_SETUP__ diff --git a/numpy/distutils/npy_pkg_config.py b/numpy/distutils/npy_pkg_config.py index 47965b4ae..26a0437fb 100644 --- a/numpy/distutils/npy_pkg_config.py +++ b/numpy/distutils/npy_pkg_config.py @@ -2,10 +2,7 @@ import sys import re import os -if sys.version_info[0] < 3: - from ConfigParser import RawConfigParser -else: - from configparser import RawConfigParser +from configparser import RawConfigParser __all__ = ['FormatError', 'PkgNotFound', 'LibraryInfo', 'VariableSet', 'read_config', 'parse_flags'] diff --git a/numpy/distutils/system_info.py b/numpy/distutils/system_info.py index 6a69fed59..f0641a688 100644 --- a/numpy/distutils/system_info.py +++ b/numpy/distutils/system_info.py @@ -138,12 +138,8 @@ import textwrap from glob import glob from functools import reduce -if sys.version_info[0] < 3: - from ConfigParser import NoOptionError - from ConfigParser import RawConfigParser as ConfigParser -else: - from configparser import NoOptionError - from configparser import RawConfigParser as ConfigParser +from configparser import NoOptionError +from configparser import RawConfigParser as ConfigParser # It seems that some people are importing ConfigParser from here so is # good to keep its class name. Use of RawConfigParser is needed in # order to be able to load path names with percent in them, like @@ -264,32 +260,29 @@ if sys.platform == 'win32': default_include_dirs.extend( os.path.join(library_root, d) for d in _include_dirs) - if sys.version_info >= (3, 3): - # VCpkg is the de-facto package manager on windows for C/C++ - # libraries. If it is on the PATH, then we append its paths here. - # We also don't re-implement shutil.which for Python 2.7 because - # vcpkg doesn't support MSVC 2008. - vcpkg = shutil.which('vcpkg') - if vcpkg: - vcpkg_dir = os.path.dirname(vcpkg) - if platform.architecture() == '32bit': - specifier = 'x86' - else: - specifier = 'x64' - - vcpkg_installed = os.path.join(vcpkg_dir, 'installed') - for vcpkg_root in [ - os.path.join(vcpkg_installed, specifier + '-windows'), - os.path.join(vcpkg_installed, specifier + '-windows-static'), - ]: - add_system_root(vcpkg_root) - - # Conda is another popular package manager that provides libraries - conda = shutil.which('conda') - if conda: - conda_dir = os.path.dirname(conda) - add_system_root(os.path.join(conda_dir, '..', 'Library')) - add_system_root(os.path.join(conda_dir, 'Library')) + # VCpkg is the de-facto package manager on windows for C/C++ + # libraries. If it is on the PATH, then we append its paths here. + vcpkg = shutil.which('vcpkg') + if vcpkg: + vcpkg_dir = os.path.dirname(vcpkg) + if platform.architecture() == '32bit': + specifier = 'x86' + else: + specifier = 'x64' + + vcpkg_installed = os.path.join(vcpkg_dir, 'installed') + for vcpkg_root in [ + os.path.join(vcpkg_installed, specifier + '-windows'), + os.path.join(vcpkg_installed, specifier + '-windows-static'), + ]: + add_system_root(vcpkg_root) + + # Conda is another popular package manager that provides libraries + conda = shutil.which('conda') + if conda: + conda_dir = os.path.dirname(conda) + add_system_root(os.path.join(conda_dir, '..', 'Library')) + add_system_root(os.path.join(conda_dir, 'Library')) else: default_lib_dirs = libpaths(['/usr/local/lib', '/opt/lib', '/usr/lib', @@ -2145,8 +2138,6 @@ class openblas_info(blas_info): extra_args = info['extra_link_args'] except Exception: extra_args = [] - if sys.version_info < (3, 5) and sys.version_info > (3, 0) and c.compiler_type == "msvc": - extra_args.append("/MANIFEST") try: with open(src, 'wt') as f: f.write(s) diff --git a/numpy/distutils/unixccompiler.py b/numpy/distutils/unixccompiler.py index 9a4d3ba52..cf62cb019 100644 --- a/numpy/distutils/unixccompiler.py +++ b/numpy/distutils/unixccompiler.py @@ -8,11 +8,7 @@ from distutils.errors import DistutilsExecError, CompileError from distutils.unixccompiler import * from numpy.distutils.ccompiler import replace_method from numpy.distutils.misc_util import _commandline_dep_string - -if sys.version_info[0] < 3: - from . import log -else: - from numpy.distutils import log +from numpy.distutils import log # Note that UnixCCompiler._compile appeared in Python 2.3 def UnixCCompiler__compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): diff --git a/numpy/lib/_datasource.py b/numpy/lib/_datasource.py index aa793958e..139b8c0ca 100644 --- a/numpy/lib/_datasource.py +++ b/numpy/lib/_datasource.py @@ -70,70 +70,6 @@ def _check_mode(mode, encoding, newline): raise ValueError("Argument 'newline' not supported in binary mode") -def _python2_bz2open(fn, mode, encoding, newline): - """Wrapper to open bz2 in text mode. - - Parameters - ---------- - fn : str - File name - mode : {'r', 'w'} - File mode. Note that bz2 Text files are not supported. - encoding : str - Ignored, text bz2 files not supported in Python2. - newline : str - Ignored, text bz2 files not supported in Python2. - """ - import bz2 - - _check_mode(mode, encoding, newline) - - if "t" in mode: - # BZ2File is missing necessary functions for TextIOWrapper - warnings.warn("Assuming latin1 encoding for bz2 text file in Python2", - RuntimeWarning, stacklevel=5) - mode = mode.replace("t", "") - return bz2.BZ2File(fn, mode) - -def _python2_gzipopen(fn, mode, encoding, newline): - """ Wrapper to open gzip in text mode. - - Parameters - ---------- - fn : str, bytes, file - File path or opened file. - mode : str - File mode. The actual files are opened as binary, but will decoded - using the specified `encoding` and `newline`. - encoding : str - Encoding to be used when reading/writing as text. - newline : str - Newline to be used when reading/writing as text. - - """ - import gzip - # gzip is lacking read1 needed for TextIOWrapper - class GzipWrap(gzip.GzipFile): - def read1(self, n): - return self.read(n) - - _check_mode(mode, encoding, newline) - - gz_mode = mode.replace("t", "") - - if isinstance(fn, (str, bytes)): - binary_file = GzipWrap(fn, gz_mode) - elif hasattr(fn, "read") or hasattr(fn, "write"): - binary_file = GzipWrap(None, gz_mode, fileobj=fn) - else: - raise TypeError("filename must be a str or bytes object, or a file") - - if "t" in mode: - return io.TextIOWrapper(binary_file, encoding, newline=newline) - else: - return binary_file - - # Using a class instead of a module-level dictionary # to reduce the initial 'import numpy' overhead by # deferring the import of lzma, bz2 and gzip until needed @@ -174,19 +110,13 @@ class _FileOpeners: try: import bz2 - if sys.version_info[0] >= 3: - self._file_openers[".bz2"] = bz2.open - else: - self._file_openers[".bz2"] = _python2_bz2open + self._file_openers[".bz2"] = bz2.open except ImportError: pass try: import gzip - if sys.version_info[0] >= 3: - self._file_openers[".gz"] = gzip.open - else: - self._file_openers[".gz"] = _python2_gzipopen + self._file_openers[".gz"] = gzip.open except ImportError: pass @@ -547,14 +477,10 @@ class DataSource: if os.path.exists(path): return True - # We import this here because importing urllib2 is slow and + # We import this here because importing urllib is slow and # a significant fraction of numpy's total import time. - if sys.version_info[0] >= 3: - from urllib.request import urlopen - from urllib.error import URLError - else: - from urllib2 import urlopen - from urllib2 import URLError + from urllib.request import urlopen + from urllib.error import URLError # Test cached url upath = self.abspath(path) diff --git a/numpy/lib/format.py b/numpy/lib/format.py index 15a74518b..114bae287 100644 --- a/numpy/lib/format.py +++ b/numpy/lib/format.py @@ -162,7 +162,6 @@ evolved with time and this document is more current. """ import numpy -import sys import io import warnings from numpy.lib.utils import safe_eval @@ -213,10 +212,7 @@ def magic(major, minor): raise ValueError("major version must be 0 <= major < 256") if minor < 0 or minor > 255: raise ValueError("minor version must be 0 <= minor < 256") - if sys.version_info[0] < 3: - return MAGIC_PREFIX + chr(major) + chr(minor) - else: - return MAGIC_PREFIX + bytes([major, minor]) + return MAGIC_PREFIX + bytes([major, minor]) def read_magic(fp): """ Read the magic string to get the version of the file format. @@ -234,10 +230,7 @@ def read_magic(fp): if magic_str[:-2] != MAGIC_PREFIX: msg = "the magic string is not correct; expected %r, got %r" raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) - if sys.version_info[0] < 3: - major, minor = map(ord, magic_str[-2:]) - else: - major, minor = magic_str[-2:] + major, minor = magic_str[-2:] return major, minor def _has_metadata(dt): @@ -542,10 +535,7 @@ def _filter_header(s): """ import tokenize - if sys.version_info[0] >= 3: - from io import StringIO - else: - from StringIO import StringIO + from io import StringIO tokens = [] last_token_was_number = False @@ -738,12 +728,10 @@ def read_array(fp, allow_pickle=False, pickle_kwargs=None): try: array = pickle.load(fp, **pickle_kwargs) except UnicodeError as err: - if sys.version_info[0] >= 3: - # Friendlier error message - raise UnicodeError("Unpickling a python object failed: %r\n" - "You may need to pass the encoding= option " - "to numpy.load" % (err,)) - raise + # Friendlier error message + raise UnicodeError("Unpickling a python object failed: %r\n" + "You may need to pass the encoding= option " + "to numpy.load" % (err,)) else: if isfileobj(fp): # We can use the fast fromfile() function. diff --git a/numpy/lib/mixins.py b/numpy/lib/mixins.py index d4811b94d..50157069c 100644 --- a/numpy/lib/mixins.py +++ b/numpy/lib/mixins.py @@ -1,6 +1,4 @@ """Mixin classes for custom array types that don't inherit from ndarray.""" -import sys - from numpy.core import umath as um @@ -152,9 +150,7 @@ class NDArrayOperatorsMixin: __mul__, __rmul__, __imul__ = _numeric_methods(um.multiply, 'mul') __matmul__, __rmatmul__, __imatmul__ = _numeric_methods( um.matmul, 'matmul') - if sys.version_info.major < 3: - # Python 3 uses only __truediv__ and __floordiv__ - __div__, __rdiv__, __idiv__ = _numeric_methods(um.divide, 'div') + # Python 3 does not use __div__, __rdiv__, or __idiv__ __truediv__, __rtruediv__, __itruediv__ = _numeric_methods( um.true_divide, 'truediv') __floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods( diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index c47e388c0..29af488d2 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -7,6 +7,7 @@ import warnings import weakref import contextlib from operator import itemgetter, index as opindex +from collections.abc import Mapping import numpy as np from . import format @@ -26,12 +27,6 @@ from numpy.compat import ( pickle, contextlib_nullcontext ) -if sys.version_info[0] >= 3: - from collections.abc import Mapping -else: - from future_builtins import map - from collections import Mapping - @set_module('numpy') def loads(*args, **kwargs): @@ -264,26 +259,25 @@ class NpzFile(Mapping): raise KeyError("%s is not a file in the archive" % key) - if sys.version_info.major == 3: - # deprecate the python 2 dict apis that we supported by accident in - # python 3. We forgot to implement itervalues() at all in earlier - # versions of numpy, so no need to deprecated it here. + # deprecate the python 2 dict apis that we supported by accident in + # python 3. We forgot to implement itervalues() at all in earlier + # versions of numpy, so no need to deprecated it here. - def iteritems(self): - # Numpy 1.15, 2018-02-20 - warnings.warn( - "NpzFile.iteritems is deprecated in python 3, to match the " - "removal of dict.itertems. Use .items() instead.", - DeprecationWarning, stacklevel=2) - return self.items() + def iteritems(self): + # Numpy 1.15, 2018-02-20 + warnings.warn( + "NpzFile.iteritems is deprecated in python 3, to match the " + "removal of dict.itertems. Use .items() instead.", + DeprecationWarning, stacklevel=2) + return self.items() - def iterkeys(self): - # Numpy 1.15, 2018-02-20 - warnings.warn( - "NpzFile.iterkeys is deprecated in python 3, to match the " - "removal of dict.iterkeys. Use .keys() instead.", - DeprecationWarning, stacklevel=2) - return self.keys() + def iterkeys(self): + # Numpy 1.15, 2018-02-20 + warnings.warn( + "NpzFile.iterkeys is deprecated in python 3, to match the " + "removal of dict.iterkeys. Use .keys() instead.", + DeprecationWarning, stacklevel=2) + return self.keys() @set_module('numpy') @@ -412,11 +406,7 @@ def load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, # result can similarly silently corrupt numerical data. raise ValueError("encoding must be 'ASCII', 'latin1', or 'bytes'") - if sys.version_info[0] >= 3: - pickle_kwargs = dict(encoding=encoding, fix_imports=fix_imports) - else: - # Nothing to do on Python 2 - pickle_kwargs = {} + pickle_kwargs = dict(encoding=encoding, fix_imports=fix_imports) # TODO: Use contextlib.ExitStack once we drop Python 2 if hasattr(file, 'read'): @@ -539,16 +529,10 @@ def save(file, arr, allow_pickle=True, fix_imports=True): fid = open(file, "wb") own_fid = True - if sys.version_info[0] >= 3: - pickle_kwargs = dict(fix_imports=fix_imports) - else: - # Nothing to do on Python 2 - pickle_kwargs = None - try: arr = np.asanyarray(arr) format.write_array(fid, arr, allow_pickle=allow_pickle, - pickle_kwargs=pickle_kwargs) + pickle_kwargs=dict(fix_imports=fix_imports)) finally: if own_fid: fid.close() @@ -691,7 +675,7 @@ def savez_compressed(file, *args, **kwds): The ``.npz`` file format is a zipped archive of files named after the variables they contain. The archive is compressed with ``zipfile.ZIP_DEFLATED`` and each file in the archive contains one variable - in ``.npy`` format. For a description of the ``.npy`` format, see + in ``.npy`` format. For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`. @@ -1375,9 +1359,6 @@ def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', open(fname, 'wt').close() fh = np.lib._datasource.open(fname, 'wt', encoding=encoding) own_fh = True - # need to convert str to unicode for text io output - if sys.version_info[0] == 2: - fh = WriteWrap(fh, encoding or 'latin1') elif hasattr(fname, 'write'): # wrap to handle byte output streams fh = WriteWrap(fname, encoding or 'latin1') diff --git a/numpy/lib/recfunctions.py b/numpy/lib/recfunctions.py index 4e62169f4..af4cfa09d 100644 --- a/numpy/lib/recfunctions.py +++ b/numpy/lib/recfunctions.py @@ -5,7 +5,6 @@ Most of these functions were initially implemented by John Hunter for matplotlib. They have been rewritten and extended for convenience. """ -import sys import itertools import numpy as np import numpy.ma as ma @@ -17,9 +16,6 @@ from numpy.lib._iotools import _is_string_like from numpy.compat import basestring from numpy.testing import suppress_warnings -if sys.version_info[0] < 3: - from future_builtins import zip - _check_fill_value = np.ma.core._check_fill_value @@ -333,12 +329,7 @@ def _izip_records(seqarrays, fill_value=None, flatten=True): else: zipfunc = _izip_fields - if sys.version_info[0] >= 3: - zip_longest = itertools.zip_longest - else: - zip_longest = itertools.izip_longest - - for tup in zip_longest(*seqarrays, fillvalue=fill_value): + for tup in itertools.zip_longest(*seqarrays, fillvalue=fill_value): yield tuple(zipfunc(tup)) diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index d41a6e541..152322115 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -871,11 +871,7 @@ def _lookfor_generate_cache(module, import_modules, regenerate): # Local import to speed up numpy's import time. import inspect - if sys.version_info[0] >= 3: - # In Python3 stderr, stdout are text files. - from io import StringIO - else: - from StringIO import StringIO + from io import StringIO if module is None: module = "numpy" diff --git a/numpy/linalg/lapack_lite/clapack_scrub.py b/numpy/linalg/lapack_lite/clapack_scrub.py index 2ddd083ea..531d861cf 100644 --- a/numpy/linalg/lapack_lite/clapack_scrub.py +++ b/numpy/linalg/lapack_lite/clapack_scrub.py @@ -1,15 +1,11 @@ #!/usr/bin/env python import sys, os import re +from io import StringIO + from plex import Scanner, Str, Lexicon, Opt, Bol, State, AnyChar, TEXT, IGNORE from plex.traditional import re as Re -PY2 = sys.version_info < (3, 0) - -if PY2: - from io import BytesIO as UStringIO -else: - from io import StringIO as UStringIO class MyScanner(Scanner): def __init__(self, info, name='<default>'): @@ -25,8 +21,8 @@ def sep_seq(sequence, sep): return pat def runScanner(data, scanner_class, lexicon=None): - info = UStringIO(data) - outfo = UStringIO() + info = StringIO(data) + outfo = StringIO() if lexicon is not None: scanner = scanner_class(lexicon, info) else: @@ -193,7 +189,7 @@ def cleanComments(source): return SourceLines state = SourceLines - for line in UStringIO(source): + for line in StringIO(source): state = state(line) comments.flushTo(lines) return lines.getValue() @@ -221,7 +217,7 @@ def removeHeader(source): return OutOfHeader state = LookingForHeader - for line in UStringIO(source): + for line in StringIO(source): state = state(line) return lines.getValue() @@ -230,7 +226,7 @@ def removeSubroutinePrototypes(source): r'/[*] Subroutine [*]/^\s*(?:(?:inline|static)\s+){0,2}(?!else|typedef|return)\w+\s+\*?\s*(\w+)\s*\([^0]+\)\s*;?' ) lines = LineQueue() - for line in UStringIO(source): + for line in StringIO(source): if not expression.match(line): lines.add(line) @@ -252,7 +248,7 @@ def removeBuiltinFunctions(source): return InBuiltInFunctions state = LookingForBuiltinFunctions - for line in UStringIO(source): + for line in StringIO(source): state = state(line) return lines.getValue() diff --git a/numpy/ma/core.py b/numpy/ma/core.py index 30aef7465..4148e4597 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -20,6 +20,7 @@ Released for unlimited redistribution. """ # pylint: disable-msg=E1002 +import builtins import sys import operator import warnings @@ -27,11 +28,6 @@ import textwrap import re from functools import reduce -if sys.version_info[0] >= 3: - import builtins -else: - import __builtin__ as builtins - import numpy as np import numpy.core.umath as umath import numpy.core.numerictypes as ntypes @@ -6394,10 +6390,6 @@ class MaskedConstant(MaskedArray): def __str__(self): return str(masked_print_option._display) - if sys.version_info.major < 3: - def __unicode__(self): - return unicode(masked_print_option._display) - def __repr__(self): if self is MaskedConstant.__singleton: return 'masked' diff --git a/runtests.py b/runtests.py index d36e5bd39..07b3f6c87 100755 --- a/runtests.py +++ b/runtests.py @@ -53,6 +53,7 @@ else: import sys import os +import builtins # In case we are run from the source directory, we don't want to import the # project from there: @@ -181,7 +182,7 @@ def main(argv): sys.modules['__main__'] = types.ModuleType('__main__') ns = dict(__name__='__main__', __file__=extra_argv[0]) - exec_(script, ns) + exec(script, ns) sys.exit(0) else: import code @@ -479,25 +480,5 @@ def lcov_generate(): print("HTML output generated under build/lcov/") -# -# Python 3 support -# - -if sys.version_info[0] >= 3: - import builtins - exec_ = getattr(builtins, "exec") -else: - def exec_(code, globs=None, locs=None): - """Execute code in a namespace.""" - if globs is None: - frame = sys._getframe(1) - globs = frame.f_globals - if locs is None: - locs = frame.f_locals - del frame - elif locs is None: - locs = globs - exec("""exec code in globs, locs""") - if __name__ == "__main__": main(argv=sys.argv[1:]) diff --git a/tools/changelog.py b/tools/changelog.py index 00ffdd9eb..2a0c4da43 100755 --- a/tools/changelog.py +++ b/tools/changelog.py @@ -36,13 +36,11 @@ From the bash command line with $GITHUB token:: import os import sys import re -import codecs from git import Repo from github import Github -if sys.version_info.major < 3: - UTF8Writer = codecs.getwriter('utf8') - sys.stdout = UTF8Writer(sys.stdout) +if sys.version_info[:2] < (3, 6): + raise RuntimeError("Python version must be >= 3.6") this_repo = Repo(os.path.join(os.path.dirname(__file__), "..")) diff --git a/tools/npy_tempita/__init__.py b/tools/npy_tempita/__init__.py index b84754988..ec4b0d5e7 100644 --- a/tools/npy_tempita/__init__.py +++ b/tools/npy_tempita/__init__.py @@ -317,7 +317,7 @@ class Template: arg0 = e_value.args[0] else: arg0 = coerce_text(e_value) - e_value.args = (self._add_line_info(arg0, pos),) + e_value.args = (self._add_line_info(arg0, pos),) if PY3: raise e_value else: @@ -461,14 +461,11 @@ def html_quote(value, force=True): return '' if not isinstance(value, basestring_): value = coerce_text(value) - if sys.version >= "3" and isinstance(value, bytes): + if isinstance(value, bytes): value = html_escape(value.decode('latin1'), 1) value = value.encode('latin1') else: value = html_escape(value, 1) - if sys.version < "3": - if is_unicode(value): - value = value.encode('ascii', 'xmlcharrefreplace') return value @@ -1286,7 +1283,7 @@ def fill_command(args=None): template_content = sys.stdin.read() template_name = '<stdin>' else: - with open(template_name, 'rb', encoding="latin-1") as f: + with open(template_name, 'rb', encoding="latin-1") as f: template_content = f.read() if options.use_html: TemplateClass = HTMLTemplate @@ -1295,7 +1292,7 @@ def fill_command(args=None): template = TemplateClass(template_content, name=template_name) result = template.substitute(vars) if options.output: - with open(options.output, 'wb') as f: + with open(options.output, 'wb') as f: f.write(result) else: sys.stdout.write(result) diff --git a/tools/npy_tempita/_looper.py b/tools/npy_tempita/_looper.py index 23121fe9e..8a1156678 100644 --- a/tools/npy_tempita/_looper.py +++ b/tools/npy_tempita/_looper.py @@ -61,9 +61,6 @@ class looper_iter: self.pos += 1 return result - if sys.version < "3": - next = __next__ - class loop_pos: @@ -94,9 +91,6 @@ class loop_pos: except IndexError: return None - if sys.version < "3": - next = __next__ - @property def previous(self): if self.pos == 0: diff --git a/tools/refguide_check.py b/tools/refguide_check.py index 3b587b77b..ad3f93c42 100644 --- a/tools/refguide_check.py +++ b/tools/refguide_check.py @@ -195,7 +195,7 @@ def find_names(module, names_dict): names_dict : dict Dictionary which contains module name as key and a set of found function names and directives as value - + Returns ------- None @@ -229,12 +229,12 @@ def find_names(module, names_dict): def get_all_dict(module): """ Return a copy of the __all__ dict with irrelevant items removed. - + Parameters ---------- module : ModuleType The module whose __all__ dict has to be processed - + Returns ------- deprecated : list @@ -242,7 +242,7 @@ def get_all_dict(module): not_deprecated : list List of non callable or non deprecated sub modules others : list - List of remaining types of sub modules + List of remaining types of sub modules """ if hasattr(module, "__all__"): all_dict = copy.deepcopy(module.__all__) @@ -863,7 +863,7 @@ def check_doctests(module, verbose, ns=None, ns : dict Name space of module dots : bool - + doctest_warnings : bool Returns @@ -934,7 +934,7 @@ def check_doctests_testfile(fname, verbose, ns=None, ns : dict Name space - + dots : bool doctest_warnings : bool @@ -978,12 +978,8 @@ def check_doctests_testfile(fname, verbose, ns=None, return results full_name = fname - if sys.version_info.major <= 2: - with open(fname) as f: - text = f.read() - else: - with open(fname, encoding='utf-8') as f: - text = f.read() + with open(fname, encoding='utf-8') as f: + text = f.read() PSEUDOCODE = set(['some_function', 'some_module', 'import example', 'ctypes.CDLL', # likely need compiling, skip it @@ -1116,7 +1112,7 @@ def init_matplotlib(): def main(argv): """ Validates the docstrings of all the pre decided set of - modules for errors and docstring standards. + modules for errors and docstring standards. """ parser = ArgumentParser(usage=__doc__.lstrip()) parser.add_argument("module_names", metavar="SUBMODULES", default=[], |