Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove py2 things from lib #2752

Merged
merged 5 commits into from
Jun 17, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions package/MDAnalysis/lib/NeighborSearch.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@
This module contains classes that allow neighbor searches directly with
`AtomGroup` objects from `MDAnalysis`.
"""
from __future__ import absolute_import

import numpy as np
from MDAnalysis.lib.distances import capped_distance
from MDAnalysis.lib.util import unique_int_1d
Expand Down
2 changes: 0 additions & 2 deletions package/MDAnalysis/lib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@
================================================================
"""

from __future__ import absolute_import

__all__ = ['log', 'transformations', 'util', 'mdamath', 'distances',
'NeighborSearch', 'formats', 'pkdtree', 'nsgrid']

Expand Down
1 change: 0 additions & 1 deletion package/MDAnalysis/lib/correlations.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@

"""

from __future__ import absolute_import, division
import numpy as np
from copy import deepcopy

Expand Down
14 changes: 4 additions & 10 deletions package/MDAnalysis/lib/distances.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,6 @@
.. autofunction:: augment_coordinates(coordinates, box, r)
.. autofunction:: undo_augment(results, translation, nreal)
"""
from __future__ import division, absolute_import
from six.moves import range
from six import raise_from

import numpy as np
from numpy.lib.utils import deprecate

Expand Down Expand Up @@ -99,12 +95,10 @@ def _run(funcname, args=None, kwargs=None, backend="serial"):
backend = backend.lower()
try:
func = getattr(_distances[backend], funcname)
except KeyError:
raise_from(
ValueError(
"Function {0} not available with backend {1}; try one "
"of: {2}".format(funcname, backend, _distances.keys())),
None)
except KeyError as exc:
IAlibay marked this conversation as resolved.
Show resolved Hide resolved
errmsg = (f"Function {funcname} not available with backend {backend} "
f"try one of: {_distances.keys()}")
IAlibay marked this conversation as resolved.
Show resolved Hide resolved
raise ValueError(errmsg) from exc
return func(*args, **kwargs)

# serial versions are always available (and are typically used within
Expand Down
1 change: 0 additions & 1 deletion package/MDAnalysis/lib/formats/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
from __future__ import absolute_import
from . import libmdaxdr
from . import libdcd

Expand Down
6 changes: 1 addition & 5 deletions package/MDAnalysis/lib/formats/libdcd.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,9 @@ from VMD's `molfile`_ plugin and `catdcd`_.
.. _catdcd: http://www.ks.uiuc.edu/Development/MDTools/catdcd/

"""
from six.moves import range


from os import path
import numpy as np
from collections import namedtuple
import six
import string
import sys

Expand Down Expand Up @@ -497,7 +493,7 @@ cdef class DCDFile:
self.charmm = DCD_HAS_EXTRA_BLOCK | DCD_IS_CHARMM
self.natoms = natoms

if isinstance(remarks, six.string_types):
if isinstance(remarks, str):
try:
remarks = bytearray(remarks, 'ascii')
except UnicodeDecodeError:
Expand Down
2 changes: 0 additions & 2 deletions package/MDAnalysis/lib/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,6 @@
.. autogenerated, see Online Docs

"""
from __future__ import absolute_import

import sys
import logging
import re
Expand Down
2 changes: 0 additions & 2 deletions package/MDAnalysis/lib/mdamath.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@
.. versionchanged: 1.0.0
Unused function :func:`_angle()` has now been removed.
"""
from __future__ import division, absolute_import
from six.moves import zip
import numpy as np

from ..exceptions import NoDataError
Expand Down
2 changes: 0 additions & 2 deletions package/MDAnalysis/lib/pkdtree.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@
boundary conditions.
"""

from __future__ import absolute_import

import itertools
import numpy as np
from scipy.spatial import cKDTree
Expand Down
4 changes: 0 additions & 4 deletions package/MDAnalysis/lib/transformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,10 +188,6 @@
MDAnalysis.lib.transformations
"""

from __future__ import division, absolute_import

from six.moves import range

import sys
import os
import warnings
Expand Down
93 changes: 38 additions & 55 deletions package/MDAnalysis/lib/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,6 @@
underlying stream and ``NamedStream.close(force=True)`` will also
close it.
"""
from __future__ import division, absolute_import
import six
from six.moves import range, map
import sys

__docformat__ = "restructuredtext en"
Expand Down Expand Up @@ -438,7 +435,7 @@ def _get_stream(filename, openfunction=open, mode='r'):
# case we have to ignore the error and return None. Second is when openfunction can't open the file because
# either the file isn't there or the permissions don't allow access.
if errno.errorcode[err.errno] in ['ENOENT', 'EACCES']:
six.reraise(*sys.exc_info())
raise sys.exc_info()[0](sys.exc_info()[1]) from err
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure this is the right conversion here, any input would be appreciated

return None
if mode.startswith('r'):
# additional check for reading (eg can we uncompress) --- is this needed?
Expand Down Expand Up @@ -853,11 +850,10 @@ def fileno(self):
"""
try:
return self.stream.fileno()
except AttributeError:
except AttributeError as exc:
# IOBase.fileno does not raise IOError as advertised so we do this here
six.raise_from(
IOError("This NamedStream does not use a file descriptor."),
None)
errmsg = "This NamedStream does not use a file descriptor."
raise IOError(errmsg) from exc

def readline(self):
try:
Expand Down Expand Up @@ -962,11 +958,9 @@ def check_compressed_format(root, ext):
if ext.lower() in ("bz2", "gz"):
try:
root, ext = get_ext(root)
except Exception:
six.raise_from(
TypeError("Cannot determine coordinate format for '{0}.{1}'"
"".format(root, ext)),
None)
except Exception as exc:
errmsg = f"Cannot determine coordinate format for '{root}.{ext}'"
raise TypeError(errmsg) from exc

return ext.upper()

Expand All @@ -989,12 +983,11 @@ def format_from_filename_extension(filename):
"""
try:
root, ext = get_ext(filename)
except Exception:
six.raise_from(TypeError(
"Cannot determine file format for file '{0}'.\n"
" You can set the format explicitly with "
"'Universe(..., format=FORMAT)'.".format(filename)),
None)
except Exception as exc:
errmsg = (f"Cannot determine file format for file '{filename}'.\n"
f" You can set the format explicitly with "
f"'Universe(..., format=FORMAT)'.")
raise TypeError(errmsg) from exc
format = check_compressed_format(root, ext)
return format

Expand Down Expand Up @@ -1030,12 +1023,11 @@ def guess_format(filename):
# perhaps StringIO or open stream
try:
format = format_from_filename_extension(filename.name)
except AttributeError:
except AttributeError as exc:
# format is None so we need to complain:
six.raise_from(
ValueError("guess_format requires an explicit format specifier "
"for stream {0}".format(filename)),
None)
errmsg = (f"guess_format requires an explicit format specifier "
f"for stream {filename}")
raise ValueError(errmsg) from exc
else:
# iterator, list, filename: simple extension checking... something more
# complicated is left for the ambitious.
Expand All @@ -1050,7 +1042,7 @@ def guess_format(filename):
def iterable(obj):
"""Returns ``True`` if `obj` can be iterated over and is *not* a string
nor a :class:`NamedStream`"""
if isinstance(obj, (six.string_types, NamedStream)):
if isinstance(obj, (str, NamedStream)):
return False # avoid iterating over characters of a string

if hasattr(obj, 'next'):
Expand Down Expand Up @@ -1121,12 +1113,10 @@ def read(self, line):
"""Read the entry from `line` and convert to appropriate type."""
try:
return self.convertor(line[self.start:self.stop])
except ValueError:
six.raise_from(
ValueError(
"{0!r}: Failed to read&convert {1!r}".format(
self, line[self.start:self.stop])),
None)
except ValueError as exc:
errmsg = (f"{self}: Failed to read&convert "
f"{line[self.start:self.stop]}")
raise ValueError(errmsg) from exc

def __len__(self):
"""Length of the field in columns (stop - start)"""
Expand Down Expand Up @@ -1359,10 +1349,9 @@ def get_weights(atoms, weights):
if not iterable(weights) and weights == "mass":
try:
weights = atoms.masses
except AttributeError:
six.raise_from(
TypeError("weights='mass' selected but atoms.masses is missing"),
None)
except AttributeError as exc:
errmsg = "weights='mass' selected but atoms.masses is missing"
raise TypeError(errmsg) from exc

if iterable(weights):
if len(np.asarray(weights).shape) != 1:
Expand Down Expand Up @@ -1441,12 +1430,10 @@ def convert_aa_code(x):

try:
return d[x.upper()]
except KeyError:
six.raise_from(
ValueError(
"No conversion for {0} found (1 letter -> 3 letter or 3/4 letter -> 1 letter)".format(x)
),
None)
except KeyError as exc:
errmsg = (f"No conversion for {x} found (1 letter -> 3 letter or 3/4 "
f"letter -> 1 letter)")
raise ValueError(errmsg) from exc


#: Regular expression to match and parse a residue-atom selection; will match
Expand Down Expand Up @@ -1695,21 +1682,19 @@ def __getattr__(self, key):
# a.this causes a __getattr__ call for key = 'this'
try:
return dict.__getitem__(self, key)
except KeyError:
six.raise_from(AttributeError('"{}" is not known in the namespace.'
.format(key)), None)
except KeyError as exc:
errmsg = f'"{key}" is not known in the namespace.'
raise AttributeError(errmsg) from exc

def __setattr__(self, key, value):
dict.__setitem__(self, key, value)

def __delattr__(self, key):
try:
dict.__delitem__(self, key)
except KeyError:
six.raise_from(
AttributeError('"{}" is not known in the namespace.'
.format(key)),
None)
except KeyError as exc:
errmsg = f'"{key}" is not known in the namespace.'
raise AttributeError(errmsg) from exc

def __eq__(self, other):
try:
Expand Down Expand Up @@ -2014,12 +1999,10 @@ def _check_coords(coords, argname):
"".format(fname, argname, coords.shape))
try:
coords = coords.astype(np.float32, order='C', copy=enforce_copy)
except ValueError:
six.raise_from(
TypeError(
"{}(): {}.dtype must be convertible to float32,"
" got {}.".format(fname, argname, coords.dtype)),
None)
except ValueError as exc:
errmsg = (f"{fname}(): {argname}.dtype must be convertible to "
f"float32, got {coords.dtype}.")
raise TypeError(errmsg) from exc
return coords, is_single

@wraps(func)
Expand Down
1 change: 0 additions & 1 deletion testsuite/MDAnalysisTests/lib/test_augment.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787

from __future__ import absolute_import
import pytest
import numpy as np
from numpy.testing import assert_almost_equal, assert_equal
Expand Down
2 changes: 0 additions & 2 deletions testsuite/MDAnalysisTests/lib/test_cutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
from __future__ import absolute_import

import pytest
import numpy as np
from numpy.testing import assert_equal
Expand Down
2 changes: 0 additions & 2 deletions testsuite/MDAnalysisTests/lib/test_distances.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#

from __future__ import division, absolute_import
import pytest
import numpy as np
from numpy.testing import assert_equal, assert_almost_equal
Expand Down
2 changes: 0 additions & 2 deletions testsuite/MDAnalysisTests/lib/test_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#

from __future__ import absolute_import
import warnings
import pytest

Expand Down
2 changes: 0 additions & 2 deletions testsuite/MDAnalysisTests/lib/test_neighborsearch.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#

from __future__ import print_function, absolute_import

import pytest
from numpy.testing import assert_equal

Expand Down
2 changes: 0 additions & 2 deletions testsuite/MDAnalysisTests/lib/test_nsgrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#

from __future__ import print_function, absolute_import

import pytest

from numpy.testing import assert_equal, assert_allclose
Expand Down
2 changes: 0 additions & 2 deletions testsuite/MDAnalysisTests/lib/test_pkdtree.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#

from __future__ import print_function, absolute_import

import pytest
import numpy as np
from numpy.testing import assert_equal
Expand Down
5 changes: 1 addition & 4 deletions testsuite/MDAnalysisTests/lib/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
from __future__ import absolute_import, division


from six.moves import range, StringIO
from io import StringIO
import pytest
import os
import warnings
Expand Down