diff options
author | Seth Troisi <sethtroisi@google.com> | 2020-01-21 13:46:27 -0800 |
---|---|---|
committer | Seth Troisi <sethtroisi@google.com> | 2020-01-21 13:46:27 -0800 |
commit | 6737f241454688f6ea59a883f6c6e3fe8eff8e8b (patch) | |
tree | c2441245dce49f6bd5ece6fbe4219d8c85655f20 | |
parent | 19b96a1635ee93c487d69ab88ac5ea3a6a14e79e (diff) | |
download | numpy-6737f241454688f6ea59a883f6c6e3fe8eff8e8b.tar.gz |
MAINT: Python2 Cleanups
-rw-r--r-- | numpy/core/code_generators/generate_umath.py | 1 | ||||
-rw-r--r-- | numpy/core/tests/test_memmap.py | 3 | ||||
-rw-r--r-- | numpy/core/tests/test_records.py | 3 | ||||
-rw-r--r-- | numpy/distutils/log.py | 2 | ||||
-rw-r--r-- | numpy/lib/tests/test_io.py | 5 | ||||
-rw-r--r-- | numpy/ma/core.py | 2 | ||||
-rw-r--r-- | numpy/matrixlib/tests/test_interaction.py | 27 | ||||
-rw-r--r-- | numpy/testing/tests/test_utils.py | 18 | ||||
-rw-r--r-- | numpy/tests/test_warnings.py | 2 | ||||
-rw-r--r-- | tools/npy_tempita/__init__.py | 192 |
10 files changed, 66 insertions, 189 deletions
diff --git a/numpy/core/code_generators/generate_umath.py b/numpy/core/code_generators/generate_umath.py index 7599360f5..f9ee7d993 100644 --- a/numpy/core/code_generators/generate_umath.py +++ b/numpy/core/code_generators/generate_umath.py @@ -298,6 +298,7 @@ defdict = { ], TD(O, f='PyNumber_Multiply'), ), +#'divide' : aliased to true_divide in umathmodule.c:initumath 'floor_divide': Ufunc(2, 1, None, # One is only a unit to the right, not the left docstrings.get('numpy.core.umath.floor_divide'), diff --git a/numpy/core/tests/test_memmap.py b/numpy/core/tests/test_memmap.py index bae7a318a..feef80ce8 100644 --- a/numpy/core/tests/test_memmap.py +++ b/numpy/core/tests/test_memmap.py @@ -3,11 +3,11 @@ import os import shutil import mmap import pytest +from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryFile, mktemp, mkdtemp from numpy import ( memmap, sum, average, product, ndarray, isscalar, add, subtract, multiply) -from numpy.compat import Path from numpy import arange, allclose, asarray from numpy.testing import ( @@ -74,7 +74,6 @@ class TestMemmap: del b del fp - @pytest.mark.skipif(Path is None, reason="No pathlib.Path") def test_path(self): tmpname = mktemp('', 'mmap', dir=self.tempdir) fp = memmap(Path(tmpname), dtype=self.dtype, mode='w+', diff --git a/numpy/core/tests/test_records.py b/numpy/core/tests/test_records.py index bf43fedcc..50b3d429b 100644 --- a/numpy/core/tests/test_records.py +++ b/numpy/core/tests/test_records.py @@ -7,10 +7,10 @@ except ImportError: import collections as collections_abc import textwrap from os import path +from pathlib import Path import pytest import numpy as np -from numpy.compat import Path from numpy.testing import ( assert_, assert_equal, assert_array_equal, assert_array_almost_equal, assert_raises, temppath, @@ -319,7 +319,6 @@ class TestFromrecords: assert_equal(rec['f1'], [b'', b'', b'']) -@pytest.mark.skipif(Path is None, reason="No pathlib.Path") class TestPathUsage: # Test that pathlib.Path can be used def test_tofile_fromfile(self): diff --git a/numpy/distutils/log.py b/numpy/distutils/log.py index 79eec00a6..eac517f56 100644 --- a/numpy/distutils/log.py +++ b/numpy/distutils/log.py @@ -1,4 +1,4 @@ -# Colored log, requires Python 2.3 or up. +# Colored log import sys from distutils.log import * from distutils.log import Log as old_Log diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index 2d6f39e40..436cd1d24 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -7,6 +7,7 @@ import warnings import io import re import pytest +from pathlib import Path from tempfile import NamedTemporaryFile from io import BytesIO, StringIO from datetime import datetime @@ -15,7 +16,7 @@ import locale import numpy as np import numpy.ma as ma from numpy.lib._iotools import ConverterError, ConversionWarning -from numpy.compat import asbytes, bytes, Path +from numpy.compat import asbytes, bytes from numpy.ma.testutils import assert_equal from numpy.testing import ( assert_warns, assert_, assert_raises_regex, assert_raises, @@ -362,7 +363,6 @@ class TestSaveTxt: c.seek(0) assert_equal(c.readlines(), [b'1 3\n', b'4 6\n']) - @pytest.mark.skipif(Path is None, reason="No pathlib.Path") def test_multifield_view(self): a = np.ones(1, dtype=[('x', 'i4'), ('y', 'i4'), ('z', 'f4')]) v = a[['x', 'z']] @@ -2339,7 +2339,6 @@ M 33 21.99 assert_equal(test['f2'], 1024) -@pytest.mark.skipif(Path is None, reason="No pathlib.Path") class TestPathUsage: # Test that pathlib.Path can be used def test_loadtxt(self): diff --git a/numpy/ma/core.py b/numpy/ma/core.py index fcbd1d8d0..41c35026d 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -4744,7 +4744,7 @@ class MaskedArray(ndarray): >>> x = np.ma.array([1, 2, 3]) >>> x.ids() - (166691080, 3083169284L) # may vary + (166691080, 3083169284) # may vary """ if self._mask is nomask: diff --git a/numpy/matrixlib/tests/test_interaction.py b/numpy/matrixlib/tests/test_interaction.py index 608416ed7..5154bd621 100644 --- a/numpy/matrixlib/tests/test_interaction.py +++ b/numpy/matrixlib/tests/test_interaction.py @@ -324,24 +324,17 @@ class TestConcatenatorMatrix: def test_array_equal_error_message_matrix(): # 2018-04-29: moved here from testing.tests.test_utils. - try: + with pytest.raises(AssertionError) as exc_info: assert_equal(np.array([1, 2]), np.matrix([1, 2])) - except AssertionError as e: - msg = str(e) - msg2 = msg.replace("shapes (2L,), (1L, 2L)", "shapes (2,), (1, 2)") - msg_reference = textwrap.dedent("""\ - - Arrays are not equal - - (shapes (2,), (1, 2) mismatch) - x: array([1, 2]) - y: matrix([[1, 2]])""") - try: - assert_equal(msg, msg_reference) - except AssertionError: - assert_equal(msg2, msg_reference) - else: - raise AssertionError("Did not raise") + msg = str(exc_info.value) + msg_reference = textwrap.dedent("""\ + + Arrays are not equal + + (shapes (2,), (1, 2) mismatch) + x: array([1, 2]) + y: matrix([[1, 2]])""") + assert_equal(msg, msg_reference) def test_array_almost_equal_matrix(): diff --git a/numpy/testing/tests/test_utils.py b/numpy/testing/tests/test_utils.py index 232ca0e83..913c67fc6 100644 --- a/numpy/testing/tests/test_utils.py +++ b/numpy/testing/tests/test_utils.py @@ -341,24 +341,6 @@ class TestEqual(TestArrayEqual): self._assert_func(x, x) self._test_not_equal(x, y) - def test_error_message(self): - with pytest.raises(AssertionError) as exc_info: - self._assert_func(np.array([1, 2]), np.array([[1, 2]])) - msg = str(exc_info.value) - msg2 = msg.replace("shapes (2L,), (1L, 2L)", "shapes (2,), (1, 2)") - msg_reference = textwrap.dedent("""\ - - Arrays are not equal - - (shapes (2,), (1, 2) mismatch) - x: array([1, 2]) - y: array([[1, 2]])""") - - try: - assert_equal(msg, msg_reference) - except AssertionError: - assert_equal(msg2, msg_reference) - def test_object(self): #gh-12942 import datetime diff --git a/numpy/tests/test_warnings.py b/numpy/tests/test_warnings.py index ff75681dc..c4c206542 100644 --- a/numpy/tests/test_warnings.py +++ b/numpy/tests/test_warnings.py @@ -35,7 +35,7 @@ class FindFuncs(ast.NodeVisitor): if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings': if node.args[0].s == "ignore": raise AssertionError( - "ignore filter should not be used; found in " + "warnings should have an appropriate stacklevel; found in " "{} on line {}".format(self.__filename, node.lineno)) if p.ls[-1] == 'warn' and ( diff --git a/tools/npy_tempita/__init__.py b/tools/npy_tempita/__init__.py index ec4b0d5e7..50a995104 100644 --- a/tools/npy_tempita/__init__.py +++ b/tools/npy_tempita/__init__.py @@ -46,7 +46,7 @@ import os import tokenize from ._looper import looper from .compat3 import ( - PY3, bytes, basestring_, next, is_unicode, coerce_text, iteritems) + bytes, basestring_, next, is_unicode, coerce_text, iteritems) __all__ = ['TemplateError', 'Template', 'sub', 'HTMLTemplate', @@ -155,7 +155,7 @@ class Template: c = f.read() if encoding: c = c.decode(encoding) - elif PY3: + else: c = c.decode('latin-1') return cls(content=c, name=filename, namespace=namespace, default_inherit=default_inherit, get_template=get_template) @@ -318,10 +318,7 @@ class Template: else: arg0 = coerce_text(e_value) e_value.args = (self._add_line_info(arg0, pos),) - if PY3: - raise e_value - else: - exec('raise e_type, e_value, e_traceback') + raise e_value def _exec(self, code, ns, pos): # __traceback_hide__ = True @@ -333,10 +330,7 @@ class Template: e_value.args = (self._add_line_info(e_value.args[0], pos),) else: e_value.args = (self._add_line_info(None, pos),) - if PY3: - raise e_value - else: - exec('raise e_type, e_value, e_traceback') + raise e_value def _repr(self, value, pos): # __traceback_hide__ = True @@ -355,10 +349,7 @@ class Template: except: e_type, e_value, e_traceback = sys.exc_info() e_value.args = (self._add_line_info(e_value.args[0], pos),) - if PY3: - raise e_value - else: - exec('raise e_type, e_value, e_traceback') + raise e_value else: if self._unicode and isinstance(value, bytes): if not self.default_encoding: @@ -628,7 +619,7 @@ class _Empty: return 'Empty' def __unicode__(self): - return '' if PY3 else u'' + return '' def __iter__(self): return iter(()) @@ -645,6 +636,27 @@ del _Empty def lex(s, name=None, trim_whitespace=True, line_offset=0, delimiters=None): + """ + Lex a string into chunks: + + >>> lex('hey') + ['hey'] + >>> lex('hey {{you}}') + ['hey ', ('you', (1, 7))] + >>> lex('hey {{') + Traceback (most recent call last): + ... + tempita.TemplateError: No }} to finish last expression at line 1 column 7 + >>> lex('hey }}') + Traceback (most recent call last): + ... + tempita.TemplateError: }} outside expression at line 1 column 7 + >>> lex('hey {{ {{') + Traceback (most recent call last): + ... + tempita.TemplateError: {{ inside expression at line 1 column 10 + """ + if delimiters is None: delimiters = (Template.default_namespace['start_braces'], Template.default_namespace['end_braces']) @@ -685,48 +697,6 @@ def lex(s, name=None, trim_whitespace=True, line_offset=0, delimiters=None): chunks = trim_lex(chunks) return chunks -lex.__doc__ = """ -Lex a string into chunks: - - >>> lex('hey') - ['hey'] - >>> lex('hey {{you}}') - ['hey ', ('you', (1, 7))] - >>> lex('hey {{') - Traceback (most recent call last): - ... - tempita.TemplateError: No }} to finish last expression at line 1 column 7 - >>> lex('hey }}') - Traceback (most recent call last): - ... - tempita.TemplateError: }} outside expression at line 1 column 7 - >>> lex('hey {{ {{') - Traceback (most recent call last): - ... - tempita.TemplateError: {{ inside expression at line 1 column 10 - -""" if PY3 else """ -Lex a string into chunks: - - >>> lex('hey') - ['hey'] - >>> lex('hey {{you}}') - ['hey ', ('you', (1, 7))] - >>> lex('hey {{') - Traceback (most recent call last): - ... - TemplateError: No }} to finish last expression at line 1 column 7 - >>> lex('hey }}') - Traceback (most recent call last): - ... - TemplateError: }} outside expression at line 1 column 7 - >>> lex('hey {{ {{') - Traceback (most recent call last): - ... - TemplateError: {{ inside expression at line 1 column 10 - -""" - statement_re = re.compile(r'^(?:if |elif |for |def |inherit |default |py:)') single_statements = ['else', 'endif', 'endfor', 'enddef', 'continue', 'break'] trail_whitespace_re = re.compile(r'\n\r?[\t ]*$') @@ -734,6 +704,16 @@ lead_whitespace_re = re.compile(r'^[\t ]*\n') def trim_lex(tokens): + r""" + Takes a lexed set of tokens, and removes whitespace when there is + a directive on a line by itself: + + >>> tokens = lex('{{if x}}\nx\n{{endif}}\ny', trim_whitespace=False) + >>> tokens + [('if x', (1, 3)), '\nx\n', ('endif', (3, 3)), '\ny'] + >>> trim_lex(tokens) + [('if x', (1, 3)), 'x\n', ('endif', (3, 3)), 'y'] + """ last_trim = None for i in range(len(tokens)): current = tokens[i] @@ -781,26 +761,6 @@ def trim_lex(tokens): tokens[i + 1] = next_chunk return tokens -trim_lex.__doc__ = r""" - Takes a lexed set of tokens, and removes whitespace when there is - a directive on a line by itself: - - >>> tokens = lex('{{if x}}\nx\n{{endif}}\ny', trim_whitespace=False) - >>> tokens - [('if x', (1, 3)), '\nx\n', ('endif', (3, 3)), '\ny'] - >>> trim_lex(tokens) - [('if x', (1, 3)), 'x\n', ('endif', (3, 3)), 'y'] - """ if PY3 else r""" - Takes a lexed set of tokens, and removes whitespace when there is - a directive on a line by itself: - - >>> tokens = lex('{{if x}}\nx\n{{endif}}\ny', trim_whitespace=False) - >>> tokens - [('if x', (1, 3)), '\nx\n', ('endif', (3, 3)), '\ny'] - >>> trim_lex(tokens) - [('if x', (1, 3)), 'x\n', ('endif', (3, 3)), 'y'] - """ - def find_position(string, index, last_index, last_pos): """ @@ -815,18 +775,7 @@ def find_position(string, index, last_index, last_pos): def parse(s, name=None, line_offset=0, delimiters=None): - - if delimiters is None: - delimiters = (Template.default_namespace['start_braces'], - Template.default_namespace['end_braces']) - tokens = lex(s, name=name, line_offset=line_offset, delimiters=delimiters) - result = [] - while tokens: - next_chunk, tokens = parse_expr(tokens, name) - result.append(next_chunk) - return result - -parse.__doc__ = r""" + r""" Parses a string into a kind of AST >>> parse('{{x}}') @@ -881,63 +830,18 @@ parse.__doc__ = r""" ... tempita.TemplateError: Multi-line py blocks must start with a newline at line 1 column 3 - """ if PY3 else r""" - Parses a string into a kind of AST - - >>> parse('{{x}}') - [('expr', (1, 3), 'x')] - >>> parse('foo') - ['foo'] - >>> parse('{{if x}}test{{endif}}') - [('cond', (1, 3), ('if', (1, 3), 'x', ['test']))] - >>> parse( - ... 'series->{{for x in y}}x={{x}}{{endfor}}' - ... ) #doctest: +NORMALIZE_WHITESPACE - ['series->', - ('for', (1, 11), ('x',), 'y', ['x=', ('expr', (1, 27), 'x')])] - >>> parse('{{for x, y in z:}}{{continue}}{{endfor}}') - [('for', (1, 3), ('x', 'y'), 'z', [('continue', (1, 21))])] - >>> parse('{{py:x=1}}') - [('py', (1, 3), 'x=1')] - >>> parse( - ... '{{if x}}a{{elif y}}b{{else}}c{{endif}}' - ... ) #doctest: +NORMALIZE_WHITESPACE - [('cond', (1, 3), ('if', (1, 3), 'x', ['a']), - ('elif', (1, 12), 'y', ['b']), ('else', (1, 23), None, ['c']))] - - Some exceptions:: - - >>> parse('{{continue}}') - Traceback (most recent call last): - ... - TemplateError: continue outside of for loop at line 1 column 3 - >>> parse('{{if x}}foo') - Traceback (most recent call last): - ... - TemplateError: No {{endif}} at line 1 column 3 - >>> parse('{{else}}') - Traceback (most recent call last): - ... - TemplateError: else outside of an if block at line 1 column 3 - >>> parse('{{if x}}{{for x in y}}{{endif}}{{endfor}}') - Traceback (most recent call last): - ... - TemplateError: Unexpected endif at line 1 column 25 - >>> parse('{{if}}{{endif}}') - Traceback (most recent call last): - ... - TemplateError: if with no expression at line 1 column 3 - >>> parse('{{for x y}}{{endfor}}') - Traceback (most recent call last): - ... - TemplateError: Bad for (no "in") in 'x y' at line 1 column 3 - >>> parse('{{py:x=1\ny=2}}') #doctest: +NORMALIZE_WHITESPACE - Traceback (most recent call last): - ... - TemplateError: Multi-line py blocks must start - with a newline at line 1 column 3 """ + if delimiters is None: + delimiters = (Template.default_namespace['start_braces'], + Template.default_namespace['end_braces']) + tokens = lex(s, name=name, line_offset=line_offset, delimiters=delimiters) + result = [] + while tokens: + next_chunk, tokens = parse_expr(tokens, name) + result.append(next_chunk) + return result + def parse_expr(tokens, name, context=()): if isinstance(tokens[0], basestring_): |