diff --git a/.travis.yml b/.travis.yml index 6f08335eb5..1ba3fd50a7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,76 +22,59 @@ env: - EXTRA_PIP_FLAGS="--find-links=$EXTRA_WHEELS" - PRE_PIP_FLAGS="--pre $EXTRA_PIP_FLAGS --find-links $PRE_WHEELS" python: - - 3.5 - 3.6 - 3.7 matrix: include: - - python: 3.4 - dist: trusty - sudo: false # Absolute minimum dependencies - - python: 2.7 + - python: 3.5 env: - - DEPENDS="numpy==1.8 setuptools==30.3.0" + - DEPENDS="-r min-requirements.txt setuptools==30.3.0" # Absolute minimum dependencies - - python: 2.7 + - python: 3.5 env: - - DEPENDS="numpy==1.8" + - DEPENDS="-r min-requirements.txt" - CHECK_TYPE="import" # Absolute minimum dependencies plus oldest MPL # Check these against: # nibabel/info.py # doc/source/installation.rst # requirements.txt - - python: 2.7 + - python: 3.5 env: - - DEPENDS="numpy==1.8 matplotlib==1.3.1" + - DEPENDS="-r min-requirements.txt matplotlib==1.3.1" # Minimum pydicom dependency - - python: 2.7 + - python: 3.5 env: - - DEPENDS="numpy==1.8 pydicom==0.9.9 pillow==2.6" + - DEPENDS="-r min-requirements.txt pydicom==0.9.9 pillow==2.6" # pydicom master branch - python: 3.5 env: - DEPENDS="numpy git+https://github.com/pydicom/pydicom.git@master" - # test 2.7 against pre-release builds of everything - - python: 2.7 - env: - - EXTRA_PIP_FLAGS="$PRE_PIP_FLAGS" # test 3.5 against pre-release builds of everything - python: 3.5 env: - EXTRA_PIP_FLAGS="$PRE_PIP_FLAGS" - - python: 2.7 + - python: 3.5 env: - INSTALL_TYPE=sdist - - python: 2.7 + - python: 3.5 env: - INSTALL_TYPE=wheel - - python: 2.7 + - python: 3.5 env: - INSTALL_TYPE=requirements - - python: 2.7 + - python: 3.5 env: - INSTALL_TYPE=archive - - python: 2.7 - env: - - CHECK_TYPE="style" - python: 3.5 env: - CHECK_TYPE="style" # Documentation doctests - - python: 2.7 - env: - - CHECK_TYPE="doc_doctests" - python: 3.5 env: - CHECK_TYPE="doc_doctests" # Run tests with indexed_gzip present - - python: 2.7 - env: - - OPTIONAL_DEPENDS="indexed_gzip" - python: 3.5 env: - OPTIONAL_DEPENDS="indexed_gzip" diff --git a/COPYING b/COPYING index 8511235733..aadf96e90c 100644 --- a/COPYING +++ b/COPYING @@ -218,34 +218,3 @@ the PDDL version 1.0 available at http://opendatacommons.org/licenses/pddl/1.0/ is courtesy of the University of Massachusetts Medical School, also released under the PDDL. - - -Six --------------------- - -In ``nibabel/externals/six.py`` - -Copied from: https://pypi.python.org/packages/source/s/six/six-1.3.0.tar.gz#md5=ec47fe6070a8a64c802363d2c2b1e2ee - -:: - - Copyright (c) 2010-2013 Benjamin Peterson - - Permission is hereby granted, free of charge, to any person obtaining a copy of - this software and associated documentation files (the "Software"), to deal in - the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of - the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS - FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR - COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER - IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - diff --git a/doc/source/installation.rst b/doc/source/installation.rst index c853de9619..2dab695e80 100644 --- a/doc/source/installation.rst +++ b/doc/source/installation.rst @@ -81,14 +81,10 @@ is for you. Requirements ------------ -.. check these against: - nibabel/info.py - requirements.txt - .travis.yml - -* Python_ 2.7, or >= 3.4 -* NumPy_ 1.8 or greater -* Six_ 1.3 or greater +.. check these against setup.cfg + +* Python_ 3.5.1 or greater +* NumPy_ 1.12 or greater * SciPy_ (optional, for full SPM-ANALYZE support) * PyDICOM_ 0.9.9 or greater (optional, for DICOM support) * `Python Imaging Library`_ (optional, for PNG conversion in DICOMFS) diff --git a/doc/source/scripts/make_coord_examples.py b/doc/source/scripts/make_coord_examples.py index 9079cea141..f763b28c28 100644 --- a/doc/source/scripts/make_coord_examples.py +++ b/doc/source/scripts/make_coord_examples.py @@ -15,7 +15,6 @@ * someones_epi.nii.gz (pretend single EPI volume) * someones_anatomy.nii.gz (pretend single subject structural) """ -from __future__ import division, print_function import math diff --git a/doc/tools/build_modref_templates.py b/doc/tools/build_modref_templates.py index 53a8be6ec4..3b988a2135 100755 --- a/doc/tools/build_modref_templates.py +++ b/doc/tools/build_modref_templates.py @@ -1,7 +1,6 @@ #!/usr/bin/env python """Script to auto-generate our API docs. """ -from __future__ import print_function, division # stdlib imports import sys diff --git a/min-requirements.txt b/min-requirements.txt new file mode 100644 index 0000000000..ed4ed75bf2 --- /dev/null +++ b/min-requirements.txt @@ -0,0 +1,2 @@ +# Auto-generated by tools/update_requirements.py +numpy ==1.12 diff --git a/nibabel/affines.py b/nibabel/affines.py index 07154089a1..a7d7a4e9b8 100644 --- a/nibabel/affines.py +++ b/nibabel/affines.py @@ -5,7 +5,7 @@ import numpy as np -from six.moves import reduce +from functools import reduce class AffineError(ValueError): diff --git a/nibabel/arraywriters.py b/nibabel/arraywriters.py index 2bd29e4ca4..fa2d1e4e1c 100644 --- a/nibabel/arraywriters.py +++ b/nibabel/arraywriters.py @@ -28,7 +28,6 @@ def __init__(self, array, out_dtype=None) something else to make sense of conversions between float and int, or between larger ints and smaller. """ -from __future__ import division, absolute_import import warnings diff --git a/nibabel/benchmarks/bench_array_to_file.py b/nibabel/benchmarks/bench_array_to_file.py index 36921a106a..4908848685 100644 --- a/nibabel/benchmarks/bench_array_to_file.py +++ b/nibabel/benchmarks/bench_array_to_file.py @@ -13,7 +13,6 @@ nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_load_save.py """ -from __future__ import division, print_function import sys from io import BytesIO # NOQA diff --git a/nibabel/benchmarks/bench_fileslice.py b/nibabel/benchmarks/bench_fileslice.py index b9568c65a0..764e0390b5 100644 --- a/nibabel/benchmarks/bench_fileslice.py +++ b/nibabel/benchmarks/bench_fileslice.py @@ -11,7 +11,6 @@ nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_fileslice.py """ -from __future__ import division, print_function import sys from timeit import timeit diff --git a/nibabel/benchmarks/bench_finite_range.py b/nibabel/benchmarks/bench_finite_range.py index 5f268eb285..6aa9d9d861 100644 --- a/nibabel/benchmarks/bench_finite_range.py +++ b/nibabel/benchmarks/bench_finite_range.py @@ -13,7 +13,6 @@ nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_finite_range """ -from __future__ import division, print_function import sys diff --git a/nibabel/benchmarks/bench_load_save.py b/nibabel/benchmarks/bench_load_save.py index c2ee68578a..59198eac1a 100644 --- a/nibabel/benchmarks/bench_load_save.py +++ b/nibabel/benchmarks/bench_load_save.py @@ -13,7 +13,6 @@ nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_load_save.py """ -from __future__ import division, print_function import sys diff --git a/nibabel/benchmarks/bench_streamlines.py b/nibabel/benchmarks/bench_streamlines.py index c076657d27..fc1e39f8ad 100644 --- a/nibabel/benchmarks/bench_streamlines.py +++ b/nibabel/benchmarks/bench_streamlines.py @@ -13,11 +13,9 @@ nosetests -s --match '(?:^|[\\b_\\.//-])[Bb]ench' /path/to/bench_streamlines.py """ -from __future__ import division, print_function import numpy as np -from six.moves import zip from nibabel.tmpdirs import InTemporaryDirectory from numpy.testing import assert_array_equal diff --git a/nibabel/benchmarks/butils.py b/nibabel/benchmarks/butils.py index 36e42f270d..bea5872272 100644 --- a/nibabel/benchmarks/butils.py +++ b/nibabel/benchmarks/butils.py @@ -1,6 +1,5 @@ """ Benchmarking utilities """ -from __future__ import print_function, division from .. import get_info diff --git a/nibabel/brikhead.py b/nibabel/brikhead.py index 1a12abfbca..49182ba705 100644 --- a/nibabel/brikhead.py +++ b/nibabel/brikhead.py @@ -27,14 +27,12 @@ am aware) always be >= 1. This permits sub-brick indexing common in AFNI programs (e.g., example4d+orig'[0]'). """ -from __future__ import print_function, division from copy import deepcopy import os import re import numpy as np -from six import string_types from .arrayproxy import ArrayProxy from .fileslice import strided_scalar @@ -204,7 +202,7 @@ def parse_AFNI_header(fobj): [1, 1, 1] """ # edge case for being fed a filename instead of a file object - if isinstance(fobj, string_types): + if isinstance(fobj, str): with open(fobj, 'rt') as src: return parse_AFNI_header(src) # unpack variables in HEAD file diff --git a/nibabel/checkwarns.py b/nibabel/checkwarns.py index deb3f6f009..a5942427b6 100644 --- a/nibabel/checkwarns.py +++ b/nibabel/checkwarns.py @@ -8,7 +8,6 @@ ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Contexts for *with* statement allowing checks for warnings ''' -from __future__ import division, print_function import warnings diff --git a/nibabel/cifti2/cifti2.py b/nibabel/cifti2/cifti2.py index 104c9396cd..1a5307eba5 100644 --- a/nibabel/cifti2/cifti2.py +++ b/nibabel/cifti2/cifti2.py @@ -16,13 +16,8 @@ http://www.nitrc.org/projects/cifti ''' -from __future__ import division, print_function, absolute_import import re -try: - from collections.abc import MutableSequence, MutableMapping, Iterable -except ImportError: - # PY2 compatibility - from collections import MutableSequence, MutableMapping, Iterable +from collections.abc import MutableSequence, MutableMapping, Iterable from collections import OrderedDict from .. import xmlutils as xml from ..filebasedimages import FileBasedHeader diff --git a/nibabel/cifti2/cifti2_axes.py b/nibabel/cifti2/cifti2_axes.py index 30decec3d1..05ab84e6ab 100644 --- a/nibabel/cifti2/cifti2_axes.py +++ b/nibabel/cifti2/cifti2_axes.py @@ -120,7 +120,6 @@ """ import numpy as np from . import cifti2 -from six import string_types, add_metaclass, integer_types from operator import xor import abc @@ -173,8 +172,7 @@ def to_header(axes): return cifti2.Cifti2Header(matrix) -@add_metaclass(abc.ABCMeta) -class Axis(object): +class Axis(abc.ABC): """ Abstract class for any object describing the rows or columns of a CIFTI-2 vector/matrix @@ -289,7 +287,7 @@ def __init__(self, name, voxel=None, vertex=None, affine=None, else: self.vertex = np.asanyarray(vertex, dtype=int) - if isinstance(name, string_types): + if isinstance(name, str): name = [self.to_cifti_brain_structure_name(name)] * self.vertex.size self.name = np.asanyarray(name, dtype='U') @@ -505,7 +503,7 @@ def to_cifti_brain_structure_name(name): """ if name in cifti2.CIFTI_BRAIN_STRUCTURES: return name - if not isinstance(name, string_types): + if not isinstance(name, str): if len(name) == 1: structure = name[0] orientation = 'both' @@ -589,7 +587,7 @@ def volume_shape(self, value): value = tuple(value) if len(value) != 3: raise ValueError("Volume shape should be a tuple of length 3") - if not all(isinstance(v, integer_types) for v in value): + if not all(isinstance(v, int) for v in value): raise ValueError("All elements of the volume shape should be integers") self._volume_shape = value @@ -679,9 +677,9 @@ def __getitem__(self, item): Otherwise returns a new BrainModelAxis """ - if isinstance(item, integer_types): + if isinstance(item, int): return self.get_element(item) - if isinstance(item, string_types): + if isinstance(item, str): raise IndexError("Can not index an Axis with a string (except for ParcelsAxis)") return self.__class__(self.name[item], self.voxel[item], self.vertex[item], self.affine, self.volume_shape, self.nvertices) @@ -914,7 +912,7 @@ def volume_shape(self, value): value = tuple(value) if len(value) != 3: raise ValueError("Volume shape should be a tuple of length 3") - if not all(isinstance(v, integer_types) for v in value): + if not all(isinstance(v, int) for v in value): raise ValueError("All elements of the volume shape should be integers") self._volume_shape = value @@ -989,14 +987,14 @@ def __getitem__(self, item): - `string`: 2-element tuple of (parcel voxels, parcel vertices - other object that can index 1D arrays: new Parcel axis """ - if isinstance(item, string_types): + if isinstance(item, str): idx = np.where(self.name == item)[0] if len(idx) == 0: raise IndexError("Parcel %s not found" % item) if len(idx) > 1: raise IndexError("Multiple parcels with name %s found" % item) return self.voxels[idx[0]], self.vertices[idx[0]] - if isinstance(item, integer_types): + if isinstance(item, int): return self.get_element(item) return self.__class__(self.name[item], self.voxels[item], self.vertices[item], self.affine, self.volume_shape, self.nvertices) @@ -1125,7 +1123,7 @@ def __add__(self, other): ) def __getitem__(self, item): - if isinstance(item, integer_types): + if isinstance(item, int): return self.get_element(item) return self.__class__(self.name[item], self.meta[item]) @@ -1270,7 +1268,7 @@ def __add__(self, other): ) def __getitem__(self, item): - if isinstance(item, integer_types): + if isinstance(item, int): return self.get_element(item) return self.__class__(self.name[item], self.label[item], self.meta[item]) @@ -1437,7 +1435,7 @@ def __getitem__(self, item): nelements = 0 return SeriesAxis(idx_start * self.step + self.start, self.step * step, nelements, self.unit) - elif isinstance(item, integer_types): + elif isinstance(item, int): return self.get_element(item) raise IndexError('SeriesAxis can only be indexed with integers or slices ' 'without breaking the regular structure') diff --git a/nibabel/cifti2/parse_cifti2.py b/nibabel/cifti2/parse_cifti2.py index 608636a446..8c3d40cd56 100644 --- a/nibabel/cifti2/parse_cifti2.py +++ b/nibabel/cifti2/parse_cifti2.py @@ -6,7 +6,6 @@ # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -from __future__ import division, print_function, absolute_import from distutils.version import LooseVersion diff --git a/nibabel/cifti2/tests/test_cifti2io_header.py b/nibabel/cifti2/tests/test_cifti2io_header.py index e4970625a4..3e3cd9c77d 100644 --- a/nibabel/cifti2/tests/test_cifti2io_header.py +++ b/nibabel/cifti2/tests/test_cifti2io_header.py @@ -6,7 +6,6 @@ # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -from __future__ import division, print_function, absolute_import from os.path import join as pjoin, dirname import io diff --git a/nibabel/cmdline/diff.py b/nibabel/cmdline/diff.py index 4b8b69381c..fde72431fb 100755 --- a/nibabel/cmdline/diff.py +++ b/nibabel/cmdline/diff.py @@ -10,7 +10,6 @@ """ Quick summary of the differences among a set of neuroimaging files """ -from __future__ import division, print_function, absolute_import import re import sys diff --git a/nibabel/cmdline/ls.py b/nibabel/cmdline/ls.py index f919700247..68bd6ee8c0 100755 --- a/nibabel/cmdline/ls.py +++ b/nibabel/cmdline/ls.py @@ -10,7 +10,6 @@ """ Output a summary table for neuroimaging files (resolution, dimensionality, etc.) """ -from __future__ import division, print_function, absolute_import import sys from optparse import OptionParser, Option diff --git a/nibabel/cmdline/parrec2nii.py b/nibabel/cmdline/parrec2nii.py index 9bbc303848..0dfa03cac9 100644 --- a/nibabel/cmdline/parrec2nii.py +++ b/nibabel/cmdline/parrec2nii.py @@ -1,6 +1,5 @@ """Code for PAR/REC to NIfTI converter command """ -from __future__ import division, print_function, absolute_import from optparse import OptionParser, Option import numpy as np diff --git a/nibabel/cmdline/tests/test_utils.py b/nibabel/cmdline/tests/test_utils.py index e701925870..199eea5d41 100644 --- a/nibabel/cmdline/tests/test_utils.py +++ b/nibabel/cmdline/tests/test_utils.py @@ -15,7 +15,7 @@ from os.path import (join as pjoin) from nibabel.testing import data_path from collections import OrderedDict -from six import StringIO +from io import StringIO def test_table2string(): diff --git a/nibabel/cmdline/utils.py b/nibabel/cmdline/utils.py index e14c860274..57c0ccc286 100644 --- a/nibabel/cmdline/utils.py +++ b/nibabel/cmdline/utils.py @@ -18,8 +18,6 @@ import numpy as np -from nibabel.py3k import asunicode - verbose_level = 0 @@ -100,7 +98,7 @@ def table2string(table, out=None): string_ += "%%%ds%%s%%%ds " \ % (nspacesl, nspacesr) % ('', item, '') string += string_.rstrip() + '\n' - out.write(asunicode(string)) + out.write(string) if print2string: value = out.getvalue() diff --git a/nibabel/data.py b/nibabel/data.py index 2a53f15f64..6208ebe7d5 100644 --- a/nibabel/data.py +++ b/nibabel/data.py @@ -8,7 +8,7 @@ from os.path import join as pjoin import glob import sys -from six.moves import configparser +import configparser from distutils.version import LooseVersion from .environment import get_nipy_user_dir, get_nipy_system_dir diff --git a/nibabel/dft.py b/nibabel/dft.py index 392856d4c1..7b39d35b81 100644 --- a/nibabel/dft.py +++ b/nibabel/dft.py @@ -10,7 +10,6 @@ """ DICOM filesystem tools """ -from __future__ import division, print_function, absolute_import import os from os.path import join as pjoin @@ -278,9 +277,7 @@ def __exit__(self, type, value, traceback): def _get_subdirs(base_dir, files_dict=None, followlinks=False): dirs = [] - # followlinks keyword not available for python 2.5. - kwargs = {} if not followlinks else {'followlinks': True} - for (dirpath, dirnames, filenames) in os.walk(base_dir, **kwargs): + for (dirpath, dirnames, filenames) in os.walk(base_dir, followlinks=followlinks): abs_dir = os.path.realpath(dirpath) if abs_dir in dirs: raise CachingError('link cycle detected under %s' % base_dir) diff --git a/nibabel/eulerangles.py b/nibabel/eulerangles.py index eac1c046ed..0928cd39d3 100644 --- a/nibabel/eulerangles.py +++ b/nibabel/eulerangles.py @@ -85,7 +85,7 @@ import math -from six.moves import reduce +from functools import reduce import numpy as np diff --git a/nibabel/externals/__init__.py b/nibabel/externals/__init__.py index 4c31772bb5..0eefb918c9 100644 --- a/nibabel/externals/__init__.py +++ b/nibabel/externals/__init__.py @@ -1,5 +1,2 @@ # init for externals package from collections import OrderedDict - -from ..deprecated import ModuleProxy as _ModuleProxy -six = _ModuleProxy('nibabel.externals.six') diff --git a/nibabel/externals/netcdf.py b/nibabel/externals/netcdf.py index e485533cd7..aca62aac80 100644 --- a/nibabel/externals/netcdf.py +++ b/nibabel/externals/netcdf.py @@ -12,7 +12,6 @@ with NetCDF files. """ -from __future__ import division, print_function, absolute_import # TODO: # * properly implement ``_FillValue``. @@ -36,13 +35,11 @@ from mmap import mmap, ACCESS_READ import numpy as np # noqa -from ..py3k import asbytes, asstr +from numpy.compat.py3k import asbytes, asstr from numpy import frombuffer, ndarray, dtype, empty, array, asarray from numpy import little_endian as LITTLE_ENDIAN from functools import reduce -from six import integer_types - ABSENT = b'\x00\x00\x00\x00\x00\x00\x00\x00' ZERO = b'\x00\x00\x00\x00' @@ -480,8 +477,8 @@ def _write_values(self, values): if hasattr(values, 'dtype'): nc_type = REVERSE[values.dtype.char, values.dtype.itemsize] else: - types = [(t, NC_INT) for t in integer_types] - types += [ + types = [ + (int, NC_INT), (float, NC_FLOAT), (str, NC_CHAR), ] diff --git a/nibabel/externals/oset.py b/nibabel/externals/oset.py index 83b1e3e24d..0a29c661c5 100644 --- a/nibabel/externals/oset.py +++ b/nibabel/externals/oset.py @@ -13,13 +13,8 @@ License: BSD-3 """ -from __future__ import absolute_import -try: - from collections.abc import MutableSet -except ImportError: - # PY2 compatibility - from collections import MutableSet +from collections.abc import MutableSet KEY, PREV, NEXT = range(3) diff --git a/nibabel/externals/six.py b/nibabel/externals/six.py deleted file mode 100644 index 77e656cd67..0000000000 --- a/nibabel/externals/six.py +++ /dev/null @@ -1,12 +0,0 @@ -""" Shim allowing some grace time for removal of six.py copy """ -# Remove around version 4.0 -from __future__ import absolute_import - -import warnings - -warnings.warn("We no longer carry a copy of the 'six' package in nibabel; " - "Please import the 'six' package directly", - FutureWarning, - stacklevel=2) - -from six import * # noqa diff --git a/nibabel/externals/tests/test_netcdf.py b/nibabel/externals/tests/test_netcdf.py index 679d9d5ff4..289e6791c1 100644 --- a/nibabel/externals/tests/test_netcdf.py +++ b/nibabel/externals/tests/test_netcdf.py @@ -1,5 +1,4 @@ ''' Tests for netcdf ''' -from __future__ import division, print_function, absolute_import import os from os.path import join as pjoin, dirname diff --git a/nibabel/externals/tests/test_six.py b/nibabel/externals/tests/test_six.py deleted file mode 100644 index 35db2ca851..0000000000 --- a/nibabel/externals/tests/test_six.py +++ /dev/null @@ -1,33 +0,0 @@ -""" Test we are deprecating externals.six import -""" - -import warnings -import types - -from nose.tools import assert_true, assert_equal - -from nibabel.deprecated import ModuleProxy - - -def test_old_namespace(): - with warnings.catch_warnings(record=True) as warns: - # Top level import. - # This import does not trigger an import of the six.py module, because - # it's the proxy object. - from nibabel.externals import six - assert_equal(warns, []) - # If there was a previous import it will be module, otherwise it will be - # a proxy. - previous_import = isinstance(six, types.ModuleType) - if not previous_import: - assert_true(isinstance(six, ModuleProxy)) - shim_BytesIO = six.BytesIO # just to check it works - # There may or may not be a warning raised on accessing the proxy, - # depending on whether the externals.six.py module is already imported - # in this test run. - if not previous_import: - assert_equal(warns.pop(0).category, FutureWarning) - from six import BytesIO - assert_equal(warns, []) - # The import from old module is the same as that from new - assert_true(shim_BytesIO is BytesIO) diff --git a/nibabel/filebasedimages.py b/nibabel/filebasedimages.py index c17701bc2e..64b79550e3 100644 --- a/nibabel/filebasedimages.py +++ b/nibabel/filebasedimages.py @@ -10,7 +10,6 @@ import io from copy import deepcopy -from six import string_types from .fileholders import FileHolder from .filename_parser import (types_filenames, TypesFilenamesError, splitext_addext) @@ -374,7 +373,7 @@ def make_file_map(klass, mapping=None): for key, ext in klass.files_types: file_map[key] = FileHolder() mapval = mapping.get(key, None) - if isinstance(mapval, string_types): + if isinstance(mapval, str): file_map[key].filename = mapval elif hasattr(mapval, 'tell'): file_map[key].fileobj = mapval diff --git a/nibabel/fileslice.py b/nibabel/fileslice.py index e55f48c127..af410a7e22 100644 --- a/nibabel/fileslice.py +++ b/nibabel/fileslice.py @@ -1,12 +1,11 @@ """ Utilities for getting array slices out of file-like objects """ -from __future__ import division import operator from numbers import Integral from mmap import mmap -from six.moves import reduce +from functools import reduce import numpy as np diff --git a/nibabel/fileutils.py b/nibabel/fileutils.py index be9c214616..b88e2f7128 100644 --- a/nibabel/fileutils.py +++ b/nibabel/fileutils.py @@ -23,9 +23,8 @@ def read_zt_byte_strings(fobj, n_strings=1, bufsize=1024): Parameters ---------- f : fileobj - File object to use. Should implement ``read``, returning byte objects - (str in Python 2), and ``seek(n, 1)`` to seek from current file - position. + File object to use. Should implement ``read``, returning byte objects, + and ``seek(n, 1)`` to seek from current file position. n_strings : int, optional Number of byte strings to return bufsize: int, optional diff --git a/nibabel/freesurfer/io.py b/nibabel/freesurfer/io.py index 9dda179d1c..f8d2442662 100644 --- a/nibabel/freesurfer/io.py +++ b/nibabel/freesurfer/io.py @@ -1,6 +1,5 @@ """ Read / write FreeSurfer geometry, morphometry, label, annotation formats """ -from __future__ import division, print_function, absolute_import import warnings import numpy as np @@ -8,7 +7,6 @@ import time from collections import OrderedDict -from six.moves import xrange from ..openers import Opener @@ -357,7 +355,7 @@ def read_annot(filepath, orig_ids=False): to any label and orig_ids=False, its id will be set to -1. ctab : ndarray, shape (n_labels, 5) RGBT + label id colortable array. - names : list of str (python 2), list of bytes (python 3) + names : list of bytes The names of the labels. The length of the list is n_labels. """ with open(filepath, "rb") as fobj: @@ -432,7 +430,7 @@ def _read_annot_ctab_old_format(fobj, n_entries): orig_tab = orig_tab[:-1] names = list() ctab = np.zeros((n_entries, 5), dt) - for i in xrange(n_entries): + for i in range(n_entries): # structure name length + string name_length = np.fromfile(fobj, dt, 1)[0] name = np.fromfile(fobj, "|S%d" % name_length, 1)[0] @@ -483,7 +481,7 @@ def _read_annot_ctab_new_format(fobj, ctab_version): # number of LUT entries present in the file entries_to_read = np.fromfile(fobj, dt, 1)[0] names = list() - for _ in xrange(entries_to_read): + for _ in range(entries_to_read): # index of this entry idx = np.fromfile(fobj, dt, 1)[0] # structure name length + string diff --git a/nibabel/freesurfer/tests/test_io.py b/nibabel/freesurfer/tests/test_io.py index 51fe123025..fc926ee2af 100644 --- a/nibabel/freesurfer/tests/test_io.py +++ b/nibabel/freesurfer/tests/test_io.py @@ -1,4 +1,3 @@ -from __future__ import division, print_function, absolute_import import os from os.path import join as pjoin, isdir import getpass diff --git a/nibabel/gifti/gifti.py b/nibabel/gifti/gifti.py index 22d6449e9a..95b0c4133a 100644 --- a/nibabel/gifti/gifti.py +++ b/nibabel/gifti/gifti.py @@ -11,11 +11,10 @@ The Gifti specification was (at time of writing) available as a PDF download from http://www.nitrc.org/projects/gifti/ """ -from __future__ import division, print_function, absolute_import import sys - import numpy as np +import base64 from .. import xmlutils as xml from ..filebasedimages import SerializableImage @@ -24,11 +23,6 @@ gifti_endian_codes, KIND2FMT) from ..deprecated import deprecate_with_version -# {en,de}codestring in deprecated in Python3, but -# {en,de}codebytes not available in Python2. -# Therefore set the proper functions depending on the Python version. -import base64 - class GiftiMetaData(xml.XmlSerializable): """ A sequence of GiftiNVPairs containing metadata for a gifti data array diff --git a/nibabel/gifti/parse_gifti_fast.py b/nibabel/gifti/parse_gifti_fast.py index f27e0725d6..044a70fede 100644 --- a/nibabel/gifti/parse_gifti_fast.py +++ b/nibabel/gifti/parse_gifti_fast.py @@ -6,7 +6,6 @@ # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -from __future__ import division, print_function, absolute_import import base64 import sys diff --git a/nibabel/gifti/tests/test_gifti.py b/nibabel/gifti/tests/test_gifti.py index f1285d441d..d6367b30c8 100644 --- a/nibabel/gifti/tests/test_gifti.py +++ b/nibabel/gifti/tests/test_gifti.py @@ -7,7 +7,6 @@ import numpy as np import nibabel as nib -from six import string_types from nibabel.gifti import (GiftiImage, GiftiDataArray, GiftiLabel, GiftiLabelTable, GiftiMetaData, GiftiNVPairs, GiftiCoordSystem) @@ -176,11 +175,11 @@ def test_to_xml_open_close_deprecations(): da = GiftiDataArray(np.ones((1,)), 'triangle') with clear_and_catch_warnings() as w: warnings.filterwarnings('always', category=DeprecationWarning) - assert_true(isinstance(da.to_xml_open(), string_types)) + assert_true(isinstance(da.to_xml_open(), str)) assert_equal(len(w), 1) with clear_and_catch_warnings() as w: warnings.filterwarnings('once', category=DeprecationWarning) - assert_true(isinstance(da.to_xml_close(), string_types)) + assert_true(isinstance(da.to_xml_close(), str)) assert_equal(len(w), 1) diff --git a/nibabel/gifti/tests/test_parse_gifti_fast.py b/nibabel/gifti/tests/test_parse_gifti_fast.py index 726779d988..a06180a964 100644 --- a/nibabel/gifti/tests/test_parse_gifti_fast.py +++ b/nibabel/gifti/tests/test_parse_gifti_fast.py @@ -6,7 +6,6 @@ # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -from __future__ import division, print_function, absolute_import from os.path import join as pjoin, dirname import sys diff --git a/nibabel/loadsave.py b/nibabel/loadsave.py index 8c3041e73c..cd1efbe3d7 100644 --- a/nibabel/loadsave.py +++ b/nibabel/loadsave.py @@ -17,7 +17,6 @@ from .filebasedimages import ImageFileError from .imageclasses import all_image_classes from .arrayproxy import is_proxy -from .py3k import FileNotFoundError from .deprecated import deprecate_with_version diff --git a/nibabel/mriutils.py b/nibabel/mriutils.py index 0f27544fae..b0f3f6a86f 100644 --- a/nibabel/mriutils.py +++ b/nibabel/mriutils.py @@ -9,7 +9,6 @@ """ Utilities for calculations related to MRI """ -from __future__ import division __all__ = ['calculate_dwell_time'] diff --git a/nibabel/nicom/dicomreaders.py b/nibabel/nicom/dicomreaders.py index d18a43af96..ad8d9c6b64 100644 --- a/nibabel/nicom/dicomreaders.py +++ b/nibabel/nicom/dicomreaders.py @@ -1,4 +1,3 @@ -from __future__ import division, print_function, absolute_import from os.path import join as pjoin import glob diff --git a/nibabel/nicom/dicomwrappers.py b/nibabel/nicom/dicomwrappers.py index 194227c6cf..ab80b51402 100755 --- a/nibabel/nicom/dicomwrappers.py +++ b/nibabel/nicom/dicomwrappers.py @@ -11,7 +11,6 @@ processing that needs to raise an error, should be in a method, rather than in a property, or property-like thing. """ -from __future__ import division import operator diff --git a/nibabel/nicom/tests/test_csareader.py b/nibabel/nicom/tests/test_csareader.py index 592dd2ba54..a6bf589e90 100644 --- a/nibabel/nicom/tests/test_csareader.py +++ b/nibabel/nicom/tests/test_csareader.py @@ -130,8 +130,6 @@ def test_ice_dims(): @dicom_test -@skipif(sys.version_info < (2,7) and pydicom.__version__ < '1.0', - 'Known issue for python 2.6 and pydicom < 1.0') def test_missing_csa_elem(): # Test that we get None instead of raising an Exception when the file has # the PrivateCreator element for the CSA dict but not the element with the diff --git a/nibabel/nicom/utils.py b/nibabel/nicom/utils.py index 66688b801b..f1d5810775 100644 --- a/nibabel/nicom/utils.py +++ b/nibabel/nicom/utils.py @@ -1,8 +1,7 @@ """ Utilities for working with DICOM datasets """ -from __future__ import division, print_function, absolute_import -from ..py3k import asstr +from numpy.compat.py3k import asstr def find_private_section(dcm_data, group_no, creator): diff --git a/nibabel/nifti1.py b/nibabel/nifti1.py index c2d409e81a..3979f5b96c 100644 --- a/nibabel/nifti1.py +++ b/nibabel/nifti1.py @@ -10,15 +10,13 @@ NIfTI1 format defined at http://nifti.nimh.nih.gov/nifti-1/ ''' -from __future__ import division, print_function import warnings from io import BytesIO -from six import string_types import numpy as np import numpy.linalg as npl +from numpy.compat.py3k import asstr -from .py3k import asstr from .filebasedimages import SerializableImage from .volumeutils import Recoder, make_dt_codes, endian_codes from .spatialimages import HeaderDataError, ImageFileError @@ -1390,7 +1388,7 @@ def set_intent(self, code, params=(), name='', allow_unknown=False): if not known_intent: # We can set intent via an unknown integer code, but can't via an # unknown string label - if not allow_unknown or isinstance(code, string_types): + if not allow_unknown or isinstance(code, str): raise KeyError('Unknown intent code: ' + str(code)) if known_intent: icode = intent_codes.code[code] diff --git a/nibabel/onetime.py b/nibabel/onetime.py index 1f410b9a1e..a036d0d229 100644 --- a/nibabel/onetime.py +++ b/nibabel/onetime.py @@ -19,7 +19,6 @@ [2] Python data model, https://docs.python.org/reference/datamodel.html """ -from __future__ import division, print_function, absolute_import # ----------------------------------------------------------------------------- # Classes and Functions diff --git a/nibabel/openers.py b/nibabel/openers.py index e551404561..e0706c4998 100644 --- a/nibabel/openers.py +++ b/nibabel/openers.py @@ -9,13 +9,8 @@ """ Context manager openers for various fileobject types """ -import sys -if sys.version_info[0] < 3: - from bz2file import BZ2File -else: - from bz2 import BZ2File +from bz2 import BZ2File import gzip -import sys import warnings from os.path import splitext from distutils.version import StrictVersion @@ -43,51 +38,6 @@ HAVE_INDEXED_GZIP = False -# The largest memory chunk that gzip can use for reads -GZIP_MAX_READ_CHUNK = 100 * 1024 * 1024 # 100Mb - - -class BufferedGzipFile(gzip.GzipFile): - """GzipFile able to readinto buffer >= 2**32 bytes. - - This class only differs from gzip.GzipFile - in Python 3.5.0. - - This works around a known issue in Python 3.5. - See https://bugs.python.org/issue25626 - """ - - # This helps avoid defining readinto in Python 2.6, - # where it is undefined on gzip.GzipFile. - # It also helps limit the exposure to this code. - if sys.version_info[:3] == (3, 5, 0): - def __init__(self, fileish, mode='rb', compresslevel=9, - buffer_size=2**32 - 1): - super(BufferedGzipFile, self).__init__(fileish, mode=mode, - compresslevel=compresslevel) - self.buffer_size = buffer_size - - def readinto(self, buf): - """Uses self.buffer_size to do a buffered read.""" - n_bytes = len(buf) - if n_bytes < 2 ** 32: - return super(BufferedGzipFile, self).readinto(buf) - - # This works around a known issue in Python 3.5. - # See https://bugs.python.org/issue25626 - mv = memoryview(buf) - n_read = 0 - max_read = 2 ** 32 - 1 # Max for unsigned 32-bit integer - while (n_read < n_bytes): - n_wanted = min(n_bytes - n_read, max_read) - n_got = super(BufferedGzipFile, self).readinto( - mv[n_read:n_read + n_wanted]) - n_read += n_got - if n_got != n_wanted: - break - return n_read - - def _gzip_open(filename, mode='rb', compresslevel=9, keep_open=False): # use indexed_gzip if possible for faster read access. If keep_open == @@ -96,16 +46,9 @@ def _gzip_open(filename, mode='rb', compresslevel=9, keep_open=False): if HAVE_INDEXED_GZIP and mode == 'rb': gzip_file = IndexedGzipFile(filename, drop_handles=not keep_open) - # Fall-back to built-in GzipFile (wrapped with the BufferedGzipFile class - # defined above) + # Fall-back to built-in GzipFile else: - gzip_file = BufferedGzipFile(filename, mode, compresslevel) - - # Speedup for #209, for versions of python < 3.5. Open gzip files with - # faster reads on large files using a larger read buffer. See - # https://github.com/nipy/nibabel/pull/210 for discussion - if hasattr(gzip_file, 'max_read_chunk'): - gzip_file.max_read_chunk = GZIP_MAX_READ_CHUNK + gzip_file = gzip.GzipFile(filename, mode, compresslevel) return gzip_file diff --git a/nibabel/optpkg.py b/nibabel/optpkg.py index fb0e00179a..d52329f186 100644 --- a/nibabel/optpkg.py +++ b/nibabel/optpkg.py @@ -1,7 +1,6 @@ """ Routines to support optional packages """ import pkgutil from distutils.version import LooseVersion -from six import string_types from .tripwire import TripWire if pkgutil.find_loader('nose'): @@ -12,7 +11,7 @@ def _check_pkg_version(pkg, min_version): # Default version checking function - if isinstance(min_version, string_types): + if isinstance(min_version, str): min_version = LooseVersion(min_version) try: return min_version <= pkg.__version__ diff --git a/nibabel/orientations.py b/nibabel/orientations.py index 9f3bbfed4d..ddea3159d0 100644 --- a/nibabel/orientations.py +++ b/nibabel/orientations.py @@ -8,7 +8,6 @@ ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Utilities for calculating and applying affine orientations ''' -from __future__ import division, print_function, absolute_import import numpy as np import numpy.linalg as npl diff --git a/nibabel/parrec.py b/nibabel/parrec.py index 1dfa998394..8ed9adf2c5 100644 --- a/nibabel/parrec.py +++ b/nibabel/parrec.py @@ -121,7 +121,6 @@ utility via the option "--strict-sort". The dimension info can be exported to a CSV file by adding the option "--volume-info". """ -from __future__ import print_function, division import warnings import numpy as np diff --git a/nibabel/processing.py b/nibabel/processing.py index cf9f60c76c..449e6b41fc 100644 --- a/nibabel/processing.py +++ b/nibabel/processing.py @@ -14,7 +14,6 @@ Smoothing and resampling routines need scipy """ -from __future__ import print_function, division, absolute_import import numpy as np import numpy.linalg as npl diff --git a/nibabel/py3k.py b/nibabel/py3k.py index bd55158d30..02dd1f16e7 100644 --- a/nibabel/py3k.py +++ b/nibabel/py3k.py @@ -1,88 +1,9 @@ -""" -Python 3 compatibility tools. +import warnings -Copied from numpy/compat/py3k. +warnings.warn("We no longer carry a copy of the 'py3k' module in nibabel; " + "Please import from the 'numpy.compat.py3k' module directly. " + "Full removal scheduled for nibabel 4.0.", + FutureWarning, + stacklevel=2) -Please prefer the routines in the six module when possible. - -BSD license -""" - -__all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar', - 'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested', - 'asstr', 'open_latin1', 'StringIO', 'BytesIO'] - -import sys - -if sys.version_info[0] >= 3: - import io - StringIO = io.StringIO - BytesIO = io.BytesIO - bytes = bytes - unicode = str - asunicode = str - - def asbytes(s): - if isinstance(s, bytes): - return s - return s.encode('latin1') - - def asstr(s): - if isinstance(s, str): - return s - return s.decode('latin1') - - def isfileobj(f): - return isinstance(f, io.FileIO) - - def open_latin1(filename, mode='r'): - return open(filename, mode=mode, encoding='iso-8859-1') - strchar = 'U' - ints2bytes = lambda seq: bytes(seq) - ZEROB = bytes([0]) - FileNotFoundError = FileNotFoundError - import builtins -else: - import StringIO - StringIO = BytesIO = StringIO.StringIO - bytes = str - unicode = unicode - asbytes = str - asstr = str - strchar = 'S' - - def isfileobj(f): - return isinstance(f, file) - - def asunicode(s): - if isinstance(s, unicode): - return s - return s.decode('ascii') - - def open_latin1(filename, mode='r'): - return open(filename, mode=mode) - ints2bytes = lambda seq: ''.join(chr(i) for i in seq) - ZEROB = chr(0) - - class FileNotFoundError(IOError): - pass - - import __builtin__ as builtins # noqa - - -def getexception(): - return sys.exc_info()[1] - - -def asbytes_nested(x): - if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)): - return [asbytes_nested(y) for y in x] - else: - return asbytes(x) - - -def asunicode_nested(x): - if hasattr(x, '__iter__') and not isinstance(x, (bytes, unicode)): - return [asunicode_nested(y) for y in x] - else: - return asunicode(x) +from numpy.compat.py3k import * # noqa diff --git a/nibabel/rstutils.py b/nibabel/rstutils.py index 6a330174b1..d0bdb655b0 100644 --- a/nibabel/rstutils.py +++ b/nibabel/rstutils.py @@ -2,7 +2,6 @@ * Make ReST table given array of values """ -from __future__ import division import numpy as np diff --git a/nibabel/streamlines/__init__.py b/nibabel/streamlines/__init__.py index 84d810367e..7f999ca19b 100644 --- a/nibabel/streamlines/__init__.py +++ b/nibabel/streamlines/__init__.py @@ -2,7 +2,6 @@ """ import os import warnings -from six import string_types from .header import Field from .array_sequence import ArraySequence @@ -57,7 +56,7 @@ def detect_format(fileobj): except IOError: pass - if isinstance(fileobj, string_types): + if isinstance(fileobj, str): _, ext = os.path.splitext(fileobj) return FORMATS.get(ext.lower()) diff --git a/nibabel/streamlines/array_sequence.py b/nibabel/streamlines/array_sequence.py index 5e6df6bf26..e86cbb5127 100644 --- a/nibabel/streamlines/array_sequence.py +++ b/nibabel/streamlines/array_sequence.py @@ -1,4 +1,3 @@ -from __future__ import division import numbers from operator import mul diff --git a/nibabel/streamlines/tck.py b/nibabel/streamlines/tck.py index 9b1888ebba..ffcd2e437a 100644 --- a/nibabel/streamlines/tck.py +++ b/nibabel/streamlines/tck.py @@ -3,15 +3,14 @@ TCK format is defined at http://mrtrix.readthedocs.io/en/latest/getting_started/image_data.html?highlight=format#tracks-file-format-tck """ -from __future__ import division import os import warnings import numpy as np +from numpy.compat.py3k import asbytes, asstr from nibabel.openers import Opener -from nibabel.py3k import asbytes, asstr from .array_sequence import ArraySequence from .tractogram_file import TractogramFile diff --git a/nibabel/streamlines/tests/test_streamlines.py b/nibabel/streamlines/tests/test_streamlines.py index 90a18f5acf..2f96e56843 100644 --- a/nibabel/streamlines/tests/test_streamlines.py +++ b/nibabel/streamlines/tests/test_streamlines.py @@ -8,7 +8,7 @@ import nibabel as nib from io import BytesIO from nibabel.tmpdirs import InTemporaryDirectory -from nibabel.py3k import asbytes +from numpy.compat.py3k import asbytes from nibabel.testing import data_path from nibabel.testing import clear_and_catch_warnings diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 0fe83a26d7..888de0bd49 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -10,7 +10,6 @@ from nibabel.testing import clear_and_catch_warnings from nose.tools import assert_equal, assert_raises, assert_true from numpy.testing import assert_array_equal, assert_array_almost_equal -from six.moves import zip from .. import tractogram as module_tractogram from ..tractogram import is_data_dict, is_lazy_dict diff --git a/nibabel/streamlines/tractogram.py b/nibabel/streamlines/tractogram.py index 209ed27c26..11d72ac78a 100644 --- a/nibabel/streamlines/tractogram.py +++ b/nibabel/streamlines/tractogram.py @@ -2,12 +2,7 @@ import numbers import numpy as np from warnings import warn - -try: - from collections.abc import MutableMapping -except ImportError: - # PY2 compatibility - from collections import MutableMapping +from collections.abc import MutableMapping from nibabel.affines import apply_affine diff --git a/nibabel/streamlines/tractogram_file.py b/nibabel/streamlines/tractogram_file.py index d422560280..f8184c8ba9 100644 --- a/nibabel/streamlines/tractogram_file.py +++ b/nibabel/streamlines/tractogram_file.py @@ -1,7 +1,6 @@ """ Define abstract interface for Tractogram file classes """ -from abc import ABCMeta, abstractmethod -from six import with_metaclass +from abc import ABC, abstractmethod from .header import Field @@ -34,7 +33,7 @@ def __init__(self, callable): super(abstractclassmethod, self).__init__(callable) -class TractogramFile(with_metaclass(ABCMeta)): +class TractogramFile(ABC): """ Convenience class to encapsulate tractogram file format. """ def __init__(self, tractogram, header=None): diff --git a/nibabel/streamlines/trk.py b/nibabel/streamlines/trk.py index 805b44edcf..f67ab1509a 100644 --- a/nibabel/streamlines/trk.py +++ b/nibabel/streamlines/trk.py @@ -1,4 +1,3 @@ -from __future__ import division # Definition of trackvis header structure: # http://www.trackvis.org/docs/?subsect=fileformat @@ -9,10 +8,11 @@ import warnings import numpy as np +from numpy.compat.py3k import asstr + import nibabel as nib from nibabel.openers import Opener -from nibabel.py3k import asstr from nibabel.volumeutils import (native_code, swapped_code, endian_codes) from nibabel.orientations import (aff2axcodes, axcodes2ornt) diff --git a/nibabel/testing/__init__.py b/nibabel/testing/__init__.py index 16f2112299..010e4d0ad1 100644 --- a/nibabel/testing/__init__.py +++ b/nibabel/testing/__init__.py @@ -7,7 +7,6 @@ # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Utilities for testing ''' -from __future__ import division, print_function import re import os @@ -30,7 +29,7 @@ except ImportError: pass -from six.moves import zip_longest +from itertools import zip_longest # set path to example data data_path = abspath(pjoin(dirname(__file__), '..', 'tests', 'data')) diff --git a/nibabel/tests/scriptrunner.py b/nibabel/tests/scriptrunner.py index c5b37df80f..33b5e3dcef 100644 --- a/nibabel/tests/scriptrunner.py +++ b/nibabel/tests/scriptrunner.py @@ -18,22 +18,8 @@ from subprocess import Popen, PIPE -try: # Python 2 - string_types = basestring, -except NameError: # Python 3 - string_types = str, - -def _get_package(): - """ Workaround for missing ``__package__`` in Python 3.2 - """ - if '__package__' in globals() and not __package__ is None: - return __package__ - return __name__.split('.', 1)[0] - - -# Same as __package__ for Python 2.6, 2.7 and >= 3.3 -MY_PACKAGE = _get_package() +MY_PACKAGE = __package__ def local_script_dir(script_sdir): @@ -112,12 +98,12 @@ def run_command(self, cmd, check_code=True): ------- returncode : int return code from execution of `cmd` - stdout : bytes (python 3) or str (python 2) + stdout : bytes stdout from `cmd` - stderr : bytes (python 3) or str (python 2) + stderr : bytes stderr from `cmd` """ - if isinstance(cmd, string_types): + if isinstance(cmd, str): cmd = [cmd] else: cmd = list(cmd) diff --git a/nibabel/tests/test_analyze.py b/nibabel/tests/test_analyze.py index 25ee778db9..45a4c00d62 100644 --- a/nibabel/tests/test_analyze.py +++ b/nibabel/tests/test_analyze.py @@ -20,7 +20,7 @@ import numpy as np -from six import BytesIO, StringIO +from io import BytesIO, StringIO from ..spatialimages import (HeaderDataError, HeaderTypeError, supported_np_types) from ..analyze import AnalyzeHeader, AnalyzeImage @@ -698,8 +698,6 @@ class TestAnalyzeImage(tsi.TestSpatialImage, tsi.MmapImageMixin): image_class = AnalyzeImage can_save = True supported_np_types = TestAnalyzeHeader.supported_np_types - # Flag to skip bz2 save tests if they are going to break - bad_bz2 = False def test_supported_types(self): img = self.image_class(np.zeros((2, 3, 4)), np.eye(4)) @@ -794,9 +792,7 @@ def test_big_offset_exts(self): arr = np.arange(24, dtype=np.int16).reshape((2, 3, 4)) aff = np.eye(4) img_ext = img_klass.files_types[0][1] - compressed_exts = ['', '.gz'] - if not self.bad_bz2: - compressed_exts.append('.bz2') + compressed_exts = ['', '.gz', '.bz2'] with InTemporaryDirectory(): for offset in (0, 2048): # Set offset in in-memory image diff --git a/nibabel/tests/test_api_validators.py b/nibabel/tests/test_api_validators.py index affa89d3e3..a7cbb8b555 100644 --- a/nibabel/tests/test_api_validators.py +++ b/nibabel/tests/test_api_validators.py @@ -1,8 +1,5 @@ """ Metaclass and class for validating instance APIs """ -from __future__ import division, print_function, absolute_import - -from six import with_metaclass from nose.tools import assert_equal @@ -33,7 +30,7 @@ def meth(self): return klass -class ValidateAPI(with_metaclass(validator2test)): +class ValidateAPI(metaclass=validator2test): """ A class to validate APIs Your job is twofold: diff --git a/nibabel/tests/test_arrayproxy.py b/nibabel/tests/test_arrayproxy.py index 187d5940df..b1cc081b6d 100644 --- a/nibabel/tests/test_arrayproxy.py +++ b/nibabel/tests/test_arrayproxy.py @@ -8,7 +8,6 @@ ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """ Tests for arrayproxy module """ -from __future__ import division, print_function, absolute_import import warnings import gzip diff --git a/nibabel/tests/test_arraywriters.py b/nibabel/tests/test_arraywriters.py index b4a3a48e93..d5547e875f 100644 --- a/nibabel/tests/test_arraywriters.py +++ b/nibabel/tests/test_arraywriters.py @@ -2,11 +2,8 @@ See docstring of :mod:`nibabel.arraywriters` for API. """ -from __future__ import division, print_function, absolute_import -import sys from platform import python_compiler, machine -from distutils.version import LooseVersion import itertools import numpy as np @@ -34,8 +31,6 @@ IUINT_TYPES = INT_TYPES + UINT_TYPES NUMERIC_TYPES = CFLOAT_TYPES + IUINT_TYPES -NP_VERSION = LooseVersion(np.__version__) - def round_trip(writer, order='F', apply_scale=True): sio = BytesIO() @@ -66,29 +61,14 @@ def test_arraywriters(): assert_array_equal(arr, round_trip(aw)) # Byteswapped should be OK bs_arr = arr.byteswap().newbyteorder('S') - # Except on some numpies for complex256, where the array does not - # equal itself - if not np.all(bs_arr == arr): - assert_true(NP_VERSION <= LooseVersion('1.7.0')) - assert_true(on_powerpc()) - assert_true(type == np.complex256) - else: - bs_aw = klass(bs_arr) - bs_aw_rt = round_trip(bs_aw) - # On Ubuntu 13.04 with python 3.3 __eq__ comparison on - # arrays with complex numbers fails here for some - # reason -- not our fault, and to test correct operation we - # will just compare element by element - if NP_VERSION == '1.7.1' and sys.version_info[:2] == (3, 3): - assert_array_equal_ = lambda x, y: np.all([x_ == y_ for x_, y_ in zip(x, y)]) - else: - assert_array_equal_ = assert_array_equal - # assert against original array because POWER7 was running into - # trouble using the byteswapped array (bs_arr) - assert_array_equal_(arr, bs_aw_rt) - bs_aw2 = klass(bs_arr, arr.dtype) - bs_aw2_rt = round_trip(bs_aw2) - assert_array_equal(arr, bs_aw2_rt) + bs_aw = klass(bs_arr) + bs_aw_rt = round_trip(bs_aw) + # assert against original array because POWER7 was running into + # trouble using the byteswapped array (bs_arr) + assert_array_equal(arr, bs_aw_rt) + bs_aw2 = klass(bs_arr, arr.dtype) + bs_aw2_rt = round_trip(bs_aw2) + assert_array_equal(arr, bs_aw2_rt) # 2D array arr2 = np.reshape(arr, (2, 5)) a2w = klass(arr2) diff --git a/nibabel/tests/test_batteryrunners.py b/nibabel/tests/test_batteryrunners.py index 71cbbba072..1130c2f4cb 100644 --- a/nibabel/tests/test_batteryrunners.py +++ b/nibabel/tests/test_batteryrunners.py @@ -9,7 +9,7 @@ ''' Tests for BatteryRunner and Report objects ''' -from six import StringIO +from io import StringIO import logging diff --git a/nibabel/tests/test_brikhead.py b/nibabel/tests/test_brikhead.py index c1632c06c2..a99e6c41b6 100644 --- a/nibabel/tests/test_brikhead.py +++ b/nibabel/tests/test_brikhead.py @@ -6,7 +6,6 @@ # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -from __future__ import division, print_function, absolute_import from os.path import join as pjoin diff --git a/nibabel/tests/test_data.py b/nibabel/tests/test_data.py index fbb225838d..641d6e55cd 100644 --- a/nibabel/tests/test_data.py +++ b/nibabel/tests/test_data.py @@ -1,7 +1,6 @@ # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ''' Tests for data module ''' -from __future__ import division, print_function, absolute_import import os from os.path import join as pjoin from os import environ as env diff --git a/nibabel/tests/test_diff.py b/nibabel/tests/test_diff.py index 4f99ca145f..754779dbc9 100644 --- a/nibabel/tests/test_diff.py +++ b/nibabel/tests/test_diff.py @@ -2,7 +2,6 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """ Test diff """ -from __future__ import division, print_function, absolute_import from os.path import (dirname, join as pjoin, abspath) import numpy as np diff --git a/nibabel/tests/test_ecat.py b/nibabel/tests/test_ecat.py index 2bfd983c53..9005d32d4f 100644 --- a/nibabel/tests/test_ecat.py +++ b/nibabel/tests/test_ecat.py @@ -6,7 +6,6 @@ # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -from __future__ import division, print_function, absolute_import import os import warnings diff --git a/nibabel/tests/test_ecat_data.py b/nibabel/tests/test_ecat_data.py index dce96646e8..471bc6b93c 100644 --- a/nibabel/tests/test_ecat_data.py +++ b/nibabel/tests/test_ecat_data.py @@ -8,7 +8,6 @@ ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """ Test we can correctly import example ECAT files """ -from __future__ import print_function, absolute_import import os from os.path import join as pjoin diff --git a/nibabel/tests/test_filehandles.py b/nibabel/tests/test_filehandles.py index 365a418890..1533b7c4f8 100644 --- a/nibabel/tests/test_filehandles.py +++ b/nibabel/tests/test_filehandles.py @@ -1,7 +1,6 @@ """ Check that loading an image does not use up filehandles. """ -from __future__ import division, print_function, absolute_import from os.path import join as pjoin import shutil diff --git a/nibabel/tests/test_fileslice.py b/nibabel/tests/test_fileslice.py index e9cfe8e0a4..19735200eb 100644 --- a/nibabel/tests/test_fileslice.py +++ b/nibabel/tests/test_fileslice.py @@ -2,8 +2,6 @@ import sys -PY2 = sys.version_info[0] < 3 - from io import BytesIO from itertools import product from functools import partial @@ -13,9 +11,6 @@ import numpy as np -# np > 1.11 makes double ellipsis illegal in indices -HAVE_NP_GT_1p11 = LooseVersion(np.__version__) > '1.11' - from ..fileslice import (is_fancy, canonical_slicers, fileslice, predict_shape, read_segments, _positive_slice, threshold_heuristic, optimize_slicer, slice2len, @@ -48,7 +43,7 @@ def test_is_fancy(): _check_slice(slice0) _check_slice((slice0,)) # tuple is same # Double ellipsis illegal in np 1.12dev - set up check for that case - maybe_bad = HAVE_NP_GT_1p11 and slice0 is Ellipsis + maybe_bad = slice0 is Ellipsis for slice1 in slices: if maybe_bad and slice1 is Ellipsis: continue @@ -250,9 +245,6 @@ def test_threshold_heuristic(): assert_equal(threshold_heuristic(1, 9, 1, skip_thresh=7), None) assert_equal(threshold_heuristic(1, 9, 2, skip_thresh=16), 'full') assert_equal(threshold_heuristic(1, 9, 2, skip_thresh=15), None) - # long if on Python 2 - if PY2: - assert_equal(threshold_heuristic(long(1), 9, 1, skip_thresh=8), 'full') # full slice, smallest step size assert_equal(threshold_heuristic( slice(0, 9, 1), 9, 2, skip_thresh=2), @@ -515,10 +507,6 @@ def test_optimize_read_slicers(): assert_equal(optimize_read_slicers( (1, 2, 3), (2, 3, 4), 4, _always), ((sn, sn, 3), (1, 2))) - if PY2: # Check we can pass in longs as well - assert_equal(optimize_read_slicers( - (long(1), long(2), long(3)), (2, 3, 4), 4, _always), - ((sn, sn, 3), (1, 2))) def test_slicers2segments(): @@ -540,10 +528,6 @@ def test_slicers2segments(): assert_equal(slicers2segments( (slice(None), slice(None), 2), (10, 6, 4), 7, 4), [[7 + 10 * 6 * 2 * 4, 10 * 6 * 4]]) - if PY2: # Check we can pass longs on Python 2 - assert_equal( - slicers2segments((long(0), long(1), long(2)), (10, 6, 4), 7, 4), - [[7 + 10 * 4 + 10 * 6 * 2 * 4, 4]]) def test_calc_slicedefs(): diff --git a/nibabel/tests/test_floating.py b/nibabel/tests/test_floating.py index 96376270b1..d9401db156 100644 --- a/nibabel/tests/test_floating.py +++ b/nibabel/tests/test_floating.py @@ -2,8 +2,6 @@ """ import sys -PY2 = sys.version_info[0] < 3 - from distutils.version import LooseVersion import numpy as np @@ -110,9 +108,7 @@ def test_check_nmant_nexp(): assert_true(_check_nmant(t, ti['nmant'])) # Test fails for longdouble after blacklisting of OSX powl as of numpy # 1.12 - see https://github.com/numpy/numpy/issues/8307 - if (t != np.longdouble or - sys.platform != 'darwin' or - LooseVersion(np.__version__) < LooseVersion('1.12')): + if t != np.longdouble or sys.platform != 'darwin': assert_true(_check_maxexp(t, ti['maxexp'])) @@ -186,11 +182,6 @@ def test_int_to_float(): i = 2**(nmant + 1) - 1 assert_equal(as_int(int_to_float(i, LD)), i) assert_equal(as_int(int_to_float(-i, LD)), -i) - # Test no error for longs - if PY2: - i = long(i) - assert_equal(as_int(int_to_float(i, LD)), i) - assert_equal(as_int(int_to_float(-i, LD)), -i) # If longdouble can cope with 2**64, test if nmant >= 63: # Check conversion to int; the line below causes an error subtracting diff --git a/nibabel/tests/test_funcs.py b/nibabel/tests/test_funcs.py index 6032c08672..8a2a7918d8 100644 --- a/nibabel/tests/test_funcs.py +++ b/nibabel/tests/test_funcs.py @@ -7,7 +7,6 @@ # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Test for image funcs ''' -from __future__ import division, print_function, absolute_import import numpy as np diff --git a/nibabel/tests/test_helpers.py b/nibabel/tests/test_helpers.py index 7b05a4d666..928b4bd1a3 100644 --- a/nibabel/tests/test_helpers.py +++ b/nibabel/tests/test_helpers.py @@ -31,33 +31,6 @@ def bytesio_round_trip(img): return klass.from_file_map(bytes_map) -def bz2_mio_error(): - """ Return True if writing mat 4 file fails - - Writing an empty string can fail for bz2 objects in python 3.3: - - https://bugs.python.org/issue16828 - - This in turn causes scipy to give this error when trying to write bz2 mat - files. - - This won't cause a problem for scipy releases after Jan 24 2014 because of - commit 98ef522d99 (in scipy) - """ - if not have_scipy: - return True - import scipy.io - - with InTemporaryDirectory(): - with ImageOpener('test.mat.bz2', 'wb') as fobj: - try: - scipy.io.savemat(fobj, {'a': 1}, format='4') - except ValueError: - return True - else: - return False - - def assert_data_similar(arr, params): """ Check data is the same if recorded, otherwise check summaries diff --git a/nibabel/tests/test_image_api.py b/nibabel/tests/test_image_api.py index ac2a2428c4..979b8777f9 100644 --- a/nibabel/tests/test_image_api.py +++ b/nibabel/tests/test_image_api.py @@ -23,12 +23,10 @@ * ``img.in_memory`` is True for an array image, and for a proxy image that is cached, but False otherwise. """ -from __future__ import division, print_function, absolute_import import warnings from functools import partial from itertools import product -from six import string_types import numpy as np @@ -578,7 +576,7 @@ def validate_path_maybe_image(self, imaker, params): assert_true(isinstance(test, bool)) if sniff is not None: assert isinstance(sniff[0], bytes) - assert isinstance(sniff[1], string_types) + assert isinstance(sniff[1], str) class MakeImageAPI(LoadImageAPI): diff --git a/nibabel/tests/test_image_load_save.py b/nibabel/tests/test_image_load_save.py index f7318945e7..7101b6a31b 100644 --- a/nibabel/tests/test_image_load_save.py +++ b/nibabel/tests/test_image_load_save.py @@ -7,7 +7,6 @@ # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Tests for loader function ''' -from __future__ import division, print_function, absolute_import from io import BytesIO import shutil diff --git a/nibabel/tests/test_image_types.py b/nibabel/tests/test_image_types.py index e72ad6bbbc..3ffc65eead 100644 --- a/nibabel/tests/test_image_types.py +++ b/nibabel/tests/test_image_types.py @@ -7,7 +7,6 @@ # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Tests for is_image / may_contain_header functions ''' -from __future__ import division, print_function, absolute_import import copy from os.path import dirname, basename, join as pjoin diff --git a/nibabel/tests/test_loadsave.py b/nibabel/tests/test_loadsave.py index 676c09c121..4c1c703389 100644 --- a/nibabel/tests/test_loadsave.py +++ b/nibabel/tests/test_loadsave.py @@ -1,6 +1,5 @@ """ Testing loadsave module """ -from __future__ import print_function from os.path import dirname, join as pjoin import shutil @@ -22,7 +21,6 @@ from nose.tools import (assert_true, assert_false, assert_raises, assert_equal, assert_not_equal) -from ..py3k import FileNotFoundError data_path = pjoin(dirname(__file__), 'data') diff --git a/nibabel/tests/test_minc1.py b/nibabel/tests/test_minc1.py index 1c150b02d5..50f4955917 100644 --- a/nibabel/tests/test_minc1.py +++ b/nibabel/tests/test_minc1.py @@ -6,7 +6,6 @@ # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -from __future__ import division, print_function, absolute_import from os.path import join as pjoin diff --git a/nibabel/tests/test_minc2.py b/nibabel/tests/test_minc2.py index c4cb9341ca..d456de0eec 100644 --- a/nibabel/tests/test_minc2.py +++ b/nibabel/tests/test_minc2.py @@ -6,7 +6,6 @@ # copyright and license terms. # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## -from __future__ import division, print_function, absolute_import from os.path import join as pjoin diff --git a/nibabel/tests/test_minc2_data.py b/nibabel/tests/test_minc2_data.py index 1ec4999a43..0471f87e7e 100644 --- a/nibabel/tests/test_minc2_data.py +++ b/nibabel/tests/test_minc2_data.py @@ -8,7 +8,6 @@ ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """ Test we can correctly import example MINC2_PATH files """ -from __future__ import print_function, absolute_import import os from os.path import join as pjoin diff --git a/nibabel/tests/test_mriutils.py b/nibabel/tests/test_mriutils.py index 6978d9c253..527afc61ba 100644 --- a/nibabel/tests/test_mriutils.py +++ b/nibabel/tests/test_mriutils.py @@ -8,7 +8,6 @@ ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """ Testing mriutils module """ -from __future__ import division from numpy.testing import (assert_almost_equal, diff --git a/nibabel/tests/test_nifti1.py b/nibabel/tests/test_nifti1.py index 931455e75a..38863e9aa2 100644 --- a/nibabel/tests/test_nifti1.py +++ b/nibabel/tests/test_nifti1.py @@ -7,13 +7,10 @@ # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Tests for nifti reading package ''' -from __future__ import division, print_function, absolute_import import os import warnings import struct -import six - import numpy as np from nibabel import nifti1 as nifti1 @@ -943,16 +940,16 @@ def test_set_sform(self): def test_sqform_code_type(self): # make sure get_s/qform returns codes as integers img = self.image_class(np.zeros((2, 3, 4)), None) - assert isinstance(img.get_sform(coded=True)[1], six.integer_types) - assert isinstance(img.get_qform(coded=True)[1], six.integer_types) + assert isinstance(img.get_sform(coded=True)[1], int) + assert isinstance(img.get_qform(coded=True)[1], int) img.set_sform(None, 3) img.set_qform(None, 3) - assert isinstance(img.get_sform(coded=True)[1], six.integer_types) - assert isinstance(img.get_qform(coded=True)[1], six.integer_types) + assert isinstance(img.get_sform(coded=True)[1], int) + assert isinstance(img.get_qform(coded=True)[1], int) img.set_sform(None, 2.0) img.set_qform(None, 4.0) - assert isinstance(img.get_sform(coded=True)[1], six.integer_types) - assert isinstance(img.get_qform(coded=True)[1], six.integer_types) + assert isinstance(img.get_sform(coded=True)[1], int) + assert isinstance(img.get_qform(coded=True)[1], int) img.set_sform(None, img.get_sform(coded=True)[1]) img.set_qform(None, img.get_qform(coded=True)[1]) diff --git a/nibabel/tests/test_nifti2.py b/nibabel/tests/test_nifti2.py index 8c7afd9ea4..730e30a689 100644 --- a/nibabel/tests/test_nifti2.py +++ b/nibabel/tests/test_nifti2.py @@ -7,7 +7,6 @@ # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Tests for nifti2 reading package ''' -from __future__ import division, print_function, absolute_import import os import numpy as np diff --git a/nibabel/tests/test_openers.py b/nibabel/tests/test_openers.py index 6aeb66aaf7..69704eaeb1 100644 --- a/nibabel/tests/test_openers.py +++ b/nibabel/tests/test_openers.py @@ -13,7 +13,7 @@ from io import BytesIO, UnsupportedOperation from distutils.version import StrictVersion -from ..py3k import asstr, asbytes +from numpy.compat.py3k import asstr, asbytes from ..openers import Opener, ImageOpener, HAVE_INDEXED_GZIP, BZ2File from ..tmpdirs import InTemporaryDirectory from ..volumeutils import BinOpener diff --git a/nibabel/tests/test_optpkg.py b/nibabel/tests/test_optpkg.py index c0930e848a..99f90b5de6 100644 --- a/nibabel/tests/test_optpkg.py +++ b/nibabel/tests/test_optpkg.py @@ -4,6 +4,7 @@ import mock import types import sys +import builtins from distutils.version import LooseVersion from nose import SkipTest @@ -11,7 +12,6 @@ assert_equal) -from nibabel.py3k import builtins from nibabel.optpkg import optional_package from nibabel.tripwire import TripWire, TripWireError diff --git a/nibabel/tests/test_parrec_data.py b/nibabel/tests/test_parrec_data.py index 630e66cab8..1cbd2923e9 100644 --- a/nibabel/tests/test_parrec_data.py +++ b/nibabel/tests/test_parrec_data.py @@ -1,6 +1,5 @@ """ Test we can correctly import example PARREC files """ -from __future__ import print_function, absolute_import from glob import glob from os.path import join as pjoin, basename, splitext, exists diff --git a/nibabel/tests/test_processing.py b/nibabel/tests/test_processing.py index 34b30f14c8..a09bd4cd85 100644 --- a/nibabel/tests/test_processing.py +++ b/nibabel/tests/test_processing.py @@ -8,7 +8,6 @@ ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## """ Testing processing module """ -from __future__ import division, print_function from os.path import dirname, join as pjoin diff --git a/nibabel/tests/test_proxy_api.py b/nibabel/tests/test_proxy_api.py index 7280c5552d..f1a1248c61 100644 --- a/nibabel/tests/test_proxy_api.py +++ b/nibabel/tests/test_proxy_api.py @@ -27,7 +27,6 @@ These last are to allow the proxy to be re-used with different images. """ -from __future__ import division, print_function, absolute_import from os.path import join as pjoin import warnings @@ -36,7 +35,6 @@ import numpy as np -from six import string_types from ..volumeutils import apply_read_scaling from ..analyze import AnalyzeHeader from ..spm99analyze import Spm99AnalyzeHeader @@ -153,7 +151,7 @@ def validate_header_isolated(self, pmaker, params): def validate_fileobj_isolated(self, pmaker, params): # Check file position of read independent of file-like object prox, fio, hdr = pmaker() - if isinstance(fio, string_types): + if isinstance(fio, str): return assert_array_equal(prox, params['arr_out']) fio.read() # move to end of file diff --git a/nibabel/tests/test_rstutils.py b/nibabel/tests/test_rstutils.py index 9fd708ba64..51103c45ca 100644 --- a/nibabel/tests/test_rstutils.py +++ b/nibabel/tests/test_rstutils.py @@ -1,13 +1,10 @@ """ Test printable table """ -from __future__ import division, print_function -import sys import numpy as np from ..rstutils import rst_table -from nose import SkipTest from nose.tools import assert_equal, assert_raises @@ -15,9 +12,6 @@ def test_rst_table(): # Tests for printable table function R, C = 3, 4 cell_values = np.arange(R * C).reshape((R, C)) - if (sys.version_info[:3] == (3, 2, 3) and np.__version__ == '1.6.1'): - raise SkipTest("Known (later fixed) bug in python3.2/numpy " - "treating np.int64 as str") assert_equal(rst_table(cell_values), """+--------+--------+--------+--------+--------+ | | col[0] | col[1] | col[2] | col[3] | diff --git a/nibabel/tests/test_scaling.py b/nibabel/tests/test_scaling.py index d318c9f810..019cc58d1c 100644 --- a/nibabel/tests/test_scaling.py +++ b/nibabel/tests/test_scaling.py @@ -7,7 +7,6 @@ # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Test for scaling / rounding in volumeutils module ''' -from __future__ import division, print_function, absolute_import import numpy as np diff --git a/nibabel/tests/test_scripts.py b/nibabel/tests/test_scripts.py index 2c17c33fd1..99e9c546f0 100644 --- a/nibabel/tests/test_scripts.py +++ b/nibabel/tests/test_scripts.py @@ -4,7 +4,6 @@ Test running scripts """ -from __future__ import division, print_function, absolute_import import sys import os diff --git a/nibabel/tests/test_spm99analyze.py b/nibabel/tests/test_spm99analyze.py index 5ee94e98c2..137d3b0451 100644 --- a/nibabel/tests/test_spm99analyze.py +++ b/nibabel/tests/test_spm99analyze.py @@ -31,7 +31,7 @@ from ..testing import assert_allclose_safely, suppress_warnings from . import test_analyze -from .test_helpers import (bytesio_round_trip, bytesio_filemap, bz2_mio_error) +from .test_helpers import bytesio_round_trip, bytesio_filemap FLOAT_TYPES = np.sctypes['float'] COMPLEX_TYPES = np.sctypes['complex'] @@ -404,8 +404,6 @@ def test_nan2zero_range_ok(self): class TestSpm99AnalyzeImage(test_analyze.TestAnalyzeImage, ImageScalingMixin): # class for testing images image_class = Spm99AnalyzeImage - # Flag to skip bz2 save tests if they are going to break - bad_bz2 = bz2_mio_error() # Decorating the old way, before the team invented @ test_data_hdr_cache = (scipy_skip( diff --git a/nibabel/tests/test_testing.py b/nibabel/tests/test_testing.py index 40d5ebc41e..f770ac4b0e 100644 --- a/nibabel/tests/test_testing.py +++ b/nibabel/tests/test_testing.py @@ -1,6 +1,5 @@ """ Tests for warnings context managers """ -from __future__ import division, print_function, absolute_import import sys import warnings @@ -14,18 +13,6 @@ get_fresh_mod, assert_re_in) -def assert_warn_len_equal(mod, n_in_context): - mod_warns = mod.__warningregistry__ - # Python 3.4 appears to clear any pre-existing warnings of the same type, - # when raising warnings inside a catch_warnings block. So, there is a - # warning generated by the tests within the context manager, but no - # previous warnings. - if 'version' in mod_warns: - assert_equal(len(mod_warns), 2) # including 'version' - else: - assert_equal(len(mod_warns), n_in_context) - - def test_assert_allclose_safely(): # Test the safe version of allclose assert_allclose_safely([1, 1], [1, 1]) diff --git a/nibabel/tests/test_tmpdirs.py b/nibabel/tests/test_tmpdirs.py index 48fa5885a9..1d35b59269 100644 --- a/nibabel/tests/test_tmpdirs.py +++ b/nibabel/tests/test_tmpdirs.py @@ -1,5 +1,4 @@ """ Test tmpdirs module """ -from __future__ import division, print_function, absolute_import from os import getcwd from os.path import realpath, abspath, dirname, isfile diff --git a/nibabel/tests/test_trackvis.py b/nibabel/tests/test_trackvis.py index 96f96a3f44..076e22f74e 100644 --- a/nibabel/tests/test_trackvis.py +++ b/nibabel/tests/test_trackvis.py @@ -1,5 +1,4 @@ ''' Testing trackvis module ''' -from __future__ import division, print_function, absolute_import from functools import partial diff --git a/nibabel/tests/test_volumeutils.py b/nibabel/tests/test_volumeutils.py index fcdc5c2713..6eeb6c6e55 100644 --- a/nibabel/tests/test_volumeutils.py +++ b/nibabel/tests/test_volumeutils.py @@ -7,7 +7,6 @@ # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Test for volumeutils module ''' -from __future__ import division import os from os.path import exists diff --git a/nibabel/tests/test_wrapstruct.py b/nibabel/tests/test_wrapstruct.py index 5e307067ab..45e8c28a52 100644 --- a/nibabel/tests/test_wrapstruct.py +++ b/nibabel/tests/test_wrapstruct.py @@ -26,8 +26,7 @@ import logging import numpy as np -from io import BytesIO -from six import StringIO +from io import BytesIO, StringIO from ..wrapstruct import WrapStructError, WrapStruct, LabeledWrapStruct from ..batteryrunners import Report diff --git a/nibabel/tmpdirs.py b/nibabel/tmpdirs.py index 8c1b704260..2636d8acb7 100644 --- a/nibabel/tmpdirs.py +++ b/nibabel/tmpdirs.py @@ -8,7 +8,6 @@ ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Contexts for *with* statement providing temporary directories ''' -from __future__ import division, print_function, absolute_import import os import shutil from tempfile import template, mkdtemp diff --git a/nibabel/trackvis.py b/nibabel/trackvis.py index 233e10ba79..691ad7b537 100644 --- a/nibabel/trackvis.py +++ b/nibabel/trackvis.py @@ -4,26 +4,20 @@ We will deprecate this, the old interface, in some future release. """ -from __future__ import division, print_function import warnings import struct import itertools import numpy as np import numpy.linalg as npl +from numpy.compat.py3k import asstr -from .py3k import asstr from .volumeutils import (native_code, swapped_code, endian_codes, rec2dict) from .openers import ImageOpener from .orientations import aff2axcodes from .affines import apply_affine from .deprecated import deprecate_with_version -try: - basestring -except NameError: # python 3 - basestring = str - warnings.warn("The trackvis interface has been deprecated and will be removed " "in v4.0; please use the 'nibabel.streamlines' interface.", DeprecationWarning, @@ -326,7 +320,7 @@ def write(fileobj, streamlines, hdr_mapping=None, endianness=None, >>> pts1 = np.random.uniform(size=(10,3)) >>> streamlines = ([(pts0, None, None), (pts1, None, None)]) >>> write(file_obj, streamlines) - >>> _ = file_obj.seek(0) # returns 0 in python 3 + >>> _ = file_obj.seek(0) # returns 0 >>> streams, hdr = read(file_obj) >>> len(streams) 2 @@ -832,15 +826,13 @@ def __init__(self, @classmethod def from_file(klass, file_like, points_space=None): streamlines, header = read(file_like, points_space=points_space) - filename = (file_like if isinstance(file_like, basestring) - else None) + filename = file_like if isinstance(file_like, str) else None return klass(streamlines, header, None, filename, points_space) def to_file(self, file_like): write(file_like, self.streamlines, self.header, self.endianness, points_space=self.points_space) - self.filename = (file_like if isinstance(file_like, basestring) - else None) + self.filename = file_like if isinstance(file_like, str) else None def get_affine(self, atleast_v2=True): """ Get affine from header in object diff --git a/nibabel/viewers.py b/nibabel/viewers.py index 7a0f4d93d7..0cdbdcb815 100644 --- a/nibabel/viewers.py +++ b/nibabel/viewers.py @@ -3,7 +3,6 @@ Includes version of OrthoSlicer3D code originally written by our own Paul Ivanov. """ -from __future__ import division, print_function import numpy as np import weakref diff --git a/nibabel/volumeutils.py b/nibabel/volumeutils.py index 95c7af3e45..2cc083ecb6 100644 --- a/nibabel/volumeutils.py +++ b/nibabel/volumeutils.py @@ -7,7 +7,6 @@ # ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## ''' Utility functions for analyze-like formats ''' -from __future__ import division, print_function import sys import warnings @@ -480,7 +479,7 @@ def array_from_file(shape, in_dtype, infile, offset=0, order='F', mmap=True): >>> from io import BytesIO >>> bio = BytesIO() >>> arr = np.arange(6).reshape(1,2,3) - >>> _ = bio.write(arr.tostring('F')) # outputs int in python3 + >>> _ = bio.write(arr.tostring('F')) # outputs int >>> arr2 = array_from_file((1,2,3), arr.dtype, bio) >>> np.all(arr == arr2) True @@ -610,7 +609,7 @@ def array_to_file(data, fileobj, out_dtype=None, offset=0, >>> array_to_file(data, sio, np.float) >>> sio.getvalue() == data.tostring('F') True - >>> _ = sio.truncate(0); _ = sio.seek(0) # outputs 0 in python 3 + >>> _ = sio.truncate(0); _ = sio.seek(0) # outputs 0 >>> array_to_file(data, sio, np.int16) >>> sio.getvalue() == data.astype(np.int16).tostring() True diff --git a/nisext/py3builder.py b/nisext/py3builder.py index 9435f6c60b..4f82a8cfb2 100644 --- a/nisext/py3builder.py +++ b/nisext/py3builder.py @@ -1,6 +1,5 @@ """ distutils utilities for porting to python 3 within 2-compatible tree """ -from __future__ import division, print_function, absolute_import import sys import re diff --git a/nisext/testers.py b/nisext/testers.py index a80bbd904b..e0ca4a040a 100644 --- a/nisext/testers.py +++ b/nisext/testers.py @@ -29,7 +29,6 @@ ''' -from __future__ import print_function import os import sys diff --git a/nisext/tests/test_testers.py b/nisext/tests/test_testers.py index 336677b48f..08fa70cd1a 100644 --- a/nisext/tests/test_testers.py +++ b/nisext/tests/test_testers.py @@ -1,6 +1,5 @@ """ Tests for testers """ -from __future__ import division, print_function import os from os.path import dirname, pathsep diff --git a/requirements.txt b/requirements.txt index 6299333665..365f19556b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,9 +1,2 @@ -# Minumum requirements -# -# Check these against -# nibabel/info.py -# .travis.yml -# doc/source/installation.rst - -six>=1.3 -numpy>=1.8 +# Auto-generated by tools/update_requirements.py +numpy >=1.12 diff --git a/setup.cfg b/setup.cfg index 69bd84afe7..7ba13660eb 100644 --- a/setup.cfg +++ b/setup.cfg @@ -13,8 +13,6 @@ classifiers = License :: OSI Approved :: MIT License Operating System :: OS Independent Programming Language :: Python - Programming Language :: Python :: 2.7 - Programming Language :: Python :: 3.4 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 @@ -29,12 +27,12 @@ provides = nisext [options] -python_requires = >=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.* +python_requires = >=3.5.1 install_requires = - numpy >=1.8 - six >=1.3 - bz2file ; python_version < "3.0" -tests_require = nose + numpy >=1.12 +tests_require = + nose >=0.10.1 + mock test_suite = nose.collector zip_safe = False packages = find: @@ -47,6 +45,7 @@ doc = sphinx >=0.3 test = nose >=0.10.1 + mock all = %(dicom)s %(doc)s diff --git a/tools/refresh_readme.py b/tools/refresh_readme.py index 59076442c7..577c10bd36 100755 --- a/tools/refresh_readme.py +++ b/tools/refresh_readme.py @@ -3,7 +3,6 @@ Should be run from nibabel root (containing setup.py) """ -from __future__ import print_function import os import runpy diff --git a/tools/update_requirements.py b/tools/update_requirements.py new file mode 100755 index 0000000000..551424994c --- /dev/null +++ b/tools/update_requirements.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +import sys +from configparser import ConfigParser +from pathlib import Path + +if sys.version_info < (3, 6): + print("This script requires Python 3.6 to work correctly") + sys.exit(1) + +repo_root = Path(__file__).parent.parent +setup_cfg = repo_root / "setup.cfg" +reqs = repo_root / "requirements.txt" +min_reqs = repo_root / "min-requirements.txt" + +config = ConfigParser() +config.read(setup_cfg) +requirements = config.get("options", "install_requires").strip().splitlines() + +script_name = Path(__file__).relative_to(repo_root) + +lines = [f"# Auto-generated by {script_name}", ""] + +# Write requirements +lines[1:-1] = requirements +reqs.write_text("\n".join(lines)) + +# Write minimum requirements +lines[1:-1] = [req.replace(">=", "==").replace("~=", "==") for req in requirements] +min_reqs.write_text("\n".join(lines))