Skip to content

Commit

Permalink
Merge pull request #157 from ocefpaf/drop_py2k
Browse files Browse the repository at this point in the history
drop python 2
  • Loading branch information
trexfeathers authored May 10, 2021
2 parents a3eeaf1 + 5ae181a commit 8243af8
Show file tree
Hide file tree
Showing 17 changed files with 80 additions and 279 deletions.
1 change: 0 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
language: minimal

env:
- PYTHON_VERSION=2.7
- PYTHON_VERSION=3.6
- PYTHON_VERSION=3.7
- PYTHON_VERSION=3.8
Expand Down
56 changes: 14 additions & 42 deletions cf_units/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# (C) British Crown Copyright 2015 - 2019, Met Office
# (C) British Crown Copyright 2015 - 2020, Met Office
#
# This file is part of cf-units.
#
Expand All @@ -25,11 +25,6 @@
"""

from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa

import six

from contextlib import contextmanager
import copy
import os.path
Expand Down Expand Up @@ -630,7 +625,7 @@ def as_unit(unit):
result = unit
else:
result = None
use_cache = isinstance(unit, six.string_types) or unit is None
use_cache = isinstance(unit, (str,)) or unit is None
if use_cache:
result = _CACHE.get(unit)
if result is None:
Expand Down Expand Up @@ -703,8 +698,6 @@ def _ud_value_error(ud_err, message):
message = u'[{status}] {message}'.format(
status=ud_err.status_msg(), message=message)

if six.PY2:
message = message.encode('utf8')
return ValueError(message)


Expand Down Expand Up @@ -829,16 +822,7 @@ def __init__(self, unit, calendar=None):
if unit is None:
unit = ''

if six.PY2:
if not isinstance(unit, six.text_type):
# Cast everything that isn't a unicode object to a str.
unit = str(unit)
if isinstance(unit, str):
# All str in py2 should be treated as ASCII.
encoding = UT_ASCII
else:
unit = str(unit)
unit = unit.strip()
unit = str(unit).strip()

if unit.lower().endswith(' utc'):
unit = unit[:unit.lower().rfind(' utc')]
Expand All @@ -861,20 +845,17 @@ def __init__(self, unit, calendar=None):
unit = _NO_UNIT_STRING
else:
category = _CATEGORY_UDUNIT
if six.PY2 and not isinstance(unit, six.text_type):
str_unit = unit.encode('utf8')
else:
str_unit = unit
str_unit = unit
try:
ut_unit = _ud.parse(_ud_system, unit.encode('utf8'), encoding)
except _ud.UdunitsError as exception:
value_error = _ud_value_error(
exception, u'Failed to parse unit "{}"'.format(str_unit))
six.raise_from(value_error, None)
raise value_error from None
if _OP_SINCE in unit.lower():
if calendar is None:
calendar_ = CALENDAR_GREGORIAN
elif isinstance(calendar, six.string_types):
elif isinstance(calendar, (str,)):
calendar_ = calendar.lower()
if calendar_ in CALENDAR_ALIASES:
calendar_ = CALENDAR_ALIASES[calendar_]
Expand Down Expand Up @@ -1234,10 +1215,7 @@ def format(self, option=None):
encoding_str = _encoding_lookup[encoding]
result = _ud.format(self.ut_unit, bitmask)

if six.PY2 and encoding_str != 'ascii':
result = six.text_type(result.decode(encoding_str))
else:
result = str(result.decode(encoding_str))
result = str(result.decode(encoding_str))
return result

@property
Expand Down Expand Up @@ -1338,15 +1316,15 @@ def offset_by_time(self, origin):
"""

if not isinstance(origin, (float, six.integer_types)):
if not isinstance(origin, (float, (int,))):
raise TypeError('a numeric type for the origin argument is'
' required')
try:
ut_unit = _ud.offset_by_time(self.ut_unit, origin)
except _ud.UdunitsError as exception:
value_error = _ud_value_error(
exception, 'Failed to offset {!r}'.format(self))
six.raise_from(value_error, None)
raise value_error from None
calendar = None
return Unit._new_from_existing_ut(_CATEGORY_UDUNIT, ut_unit, calendar)

Expand Down Expand Up @@ -1416,7 +1394,7 @@ def root(self, root):
value_error = _ud_value_error(
exception,
'Failed to take the root of {!r}'.format(self))
six.raise_from(value_error, None)
raise value_error from None
calendar = None
result = Unit._new_from_existing_ut(
_CATEGORY_UDUNIT, ut_unit, calendar)
Expand Down Expand Up @@ -1457,7 +1435,7 @@ def log(self, base):
exception,
'Failed to calculate logorithmic base '
'of {!r}'.format(self))
six.raise_from(value_err, None)
raise value_err from None
calendar = None
result = Unit._new_from_existing_ut(
_CATEGORY_UDUNIT, ut_unit, calendar)
Expand All @@ -1480,12 +1458,6 @@ def __str__(self):
"""
return self.origin or self.symbol

if six.PY2:
__unicode__ = __str__

def __str__(self):
return unicode(self).encode('utf8') # noqa: F821

def __repr__(self):
"""
Returns a string representation of the unit object.
Expand Down Expand Up @@ -1555,7 +1527,7 @@ def _op_common(self, other, op_func):
value_err = _ud_value_error(
exception,
'Failed to {} {!r} by {!r}'.format(op_label, self, other))
six.raise_from(value_err, None)
raise value_err from None
calendar = None
result = Unit._new_from_existing_ut(
_CATEGORY_UDUNIT, ut_unit, calendar)
Expand Down Expand Up @@ -1707,7 +1679,7 @@ def __pow__(self, power):
value_err = _ud_value_error(
exception,
'Failed to raise the power of {!r}'.format(self))
six.raise_from(value_err, None)
raise value_err from None
result = Unit._new_from_existing_ut(_CATEGORY_UDUNIT, ut_unit)
return result

Expand Down Expand Up @@ -1854,7 +1826,7 @@ def convert(self, value, other, ctype=FLOAT64, inplace=False):
value_err = _ud_value_error(
exception,
'Failed to convert {!r} to {!r}'.format(self, other))
six.raise_from(value_err, None)
raise value_err from None
if isinstance(result, np.ndarray):
# Can only handle array of np.float32 or np.float64 so
# cast array of ints to array of floats of requested
Expand Down
10 changes: 2 additions & 8 deletions cf_units/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# (C) British Crown Copyright 2010 - 2018, Met Office
# (C) British Crown Copyright 2010 - 2020, Met Office
#
# This file is part of cf-units.
#
Expand All @@ -16,13 +16,7 @@
# along with cf-units. If not, see <http://www.gnu.org/licenses/>.


from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa

try:
import ConfigParser as configparser
except ImportError:
import configparser
import configparser

import os.path
import sys
Expand Down
53 changes: 0 additions & 53 deletions cf_units/conftest.py

This file was deleted.

5 changes: 1 addition & 4 deletions cf_units/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# (C) British Crown Copyright 2010 - 2018, Met Office
# (C) British Crown Copyright 2010 - 2020, Met Office
#
# This file is part of cf-units.
#
Expand All @@ -14,6 +14,3 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with cf-units. If not, see <http://www.gnu.org/licenses/>.

from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# (C) British Crown Copyright 2016 - 2018, Met Office
# (C) British Crown Copyright 2016 - 2020, Met Office
#
# This file is part of cf-units.
#
Expand All @@ -16,9 +16,6 @@
# along with cf-units. If not, see <http://www.gnu.org/licenses/>.
"""Test function :func:`cf_units._num2date_to_nearest_second`."""

from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa

import unittest
import datetime

Expand Down
8 changes: 2 additions & 6 deletions cf_units/tests/integration/test_date2num.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# (C) British Crown Copyright 2016 - 2019, Met Office
# (C) British Crown Copyright 2016 - 2020, Met Office
#
# This file is part of cf-units.
#
Expand All @@ -16,14 +16,10 @@
# along with cf-units. If not, see <http://www.gnu.org/licenses/>.
"""Test function :func:`cf_units.date2num`."""

from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa

import unittest
import datetime

import numpy as np
import six

from cf_units import date2num

Expand Down Expand Up @@ -74,7 +70,7 @@ def test_long_time_interval(self):
unit = 'years since 1970-01-01'
date = datetime.datetime(1970, 1, 1, 0, 0, 5)
exp_emsg = 'interval of "months", "years" .* got "years".'
with six.assertRaisesRegex(self, ValueError, exp_emsg):
with self.assertRaisesRegex(ValueError, exp_emsg):
date2num(date, unit, self.calendar)


Expand Down
56 changes: 1 addition & 55 deletions cf_units/tests/test_coding_standards.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# (C) British Crown Copyright 2013 - 2019, Met Office
# (C) British Crown Copyright 2013 - 2020, Met Office
#
# This file is part of cf-units.
#
Expand All @@ -15,9 +15,6 @@
# You should have received a copy of the GNU Lesser General Public License
# along with cf-units. If not, see <http://www.gnu.org/licenses/>.

from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa

from datetime import datetime
from fnmatch import fnmatch
from glob import glob
Expand Down Expand Up @@ -190,56 +187,5 @@ def test_license_headers(self):
'There were license header failures. See stdout.')


class TestFutureImports(unittest.TestCase):
excluded = ('*/_version.py')

future_imports_pattern = re.compile(
r"^from __future__ import \(absolute_import,\s*division,\s*"
r"print_function(,\s*unicode_literals)?\)$",
flags=re.MULTILINE)

six_import_pattern = re.compile(
r"^from six.moves import \(filter, input, map, range, zip\) # noqa$",
flags=re.MULTILINE)

def test_future_imports(self):
# Tests that every single Python file includes the appropriate
# __future__ import to enforce consistent behaviour.
check_paths = [os.path.dirname(cf_units.__file__)]
if DOCS_DIRS:
check_paths.extend(DOCS_DIRS)

failed = False
for dirpath, _, files in chain.from_iterable(os.walk(path)
for path in check_paths):
for fname in files:
full_fname = os.path.join(dirpath, fname)
if not full_fname.endswith('.py'):
continue
if not os.path.isfile(full_fname):
continue
if any(fnmatch(full_fname, pat) for pat in self.excluded):
continue

with open(full_fname, "r") as fh:
content = fh.read()

if re.search(self.future_imports_pattern, content) is None:
print('The file {} has no valid __future__ imports '
'and has not been excluded from the imports '
'test.'.format(full_fname))
failed = True

if re.search(self.six_import_pattern, content) is None:
print('The file {} has no valid six import '
'and has not been excluded from the imports '
'test.'.format(full_fname))
failed = True

if failed:
raise AssertionError(
'There were __future__ import check failures. See stdout.')


if __name__ == '__main__':
unittest.main()
Loading

0 comments on commit 8243af8

Please sign in to comment.