diff options
Diffstat (limited to 'numpy')
364 files changed, 1515 insertions, 485 deletions
diff --git a/numpy/__init__.py b/numpy/__init__.py index 8a09d2fec..03e2afe6e 100644 --- a/numpy/__init__.py +++ b/numpy/__init__.py @@ -104,6 +104,7 @@ available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``. Exceptions to this rule are documented. """ +from __future__ import division # We first need to detect if we're being called as part of the numpy setup # procedure itself in a reliable manner. diff --git a/numpy/_import_tools.py b/numpy/_import_tools.py index c0a901a8d..ecf29975b 100644 --- a/numpy/_import_tools.py +++ b/numpy/_import_tools.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import sys @@ -66,9 +68,9 @@ class PackageLoader(object): break else: try: - exec 'import %s.info as info' % (package_name) + exec('import %s.info as info' % (package_name)) info_modules[package_name] = info - except ImportError, msg: + except ImportError as msg: self.warn('No scipy-style subpackage %r found in %s. '\ 'Ignoring: %s'\ % (package_name,':'.join(self.parent_path), msg)) @@ -87,7 +89,7 @@ class PackageLoader(object): open(info_file,filedescriptor[1]), info_file, filedescriptor) - except Exception,msg: + except Exception as msg: self.error(msg) info_module = None @@ -207,7 +209,7 @@ class PackageLoader(object): if symbols is None: symbols = eval('dir(%s)' % (package_name), frame.f_globals,frame.f_locals) - symbols = filter(lambda s:not s.startswith('_'),symbols) + symbols = [s for s in symbols if not s.startswith('_')] else: symbols = [symbol] @@ -241,7 +243,7 @@ class PackageLoader(object): frame = self.parent_frame try: exec (cmdstr, frame.f_globals,frame.f_locals) - except Exception,msg: + except Exception as msg: self.error('%s -> failed: %s' % (cmdstr,msg)) return True else: diff --git a/numpy/add_newdocs.py b/numpy/add_newdocs.py index 26711f177..b6ace230f 100644 --- a/numpy/add_newdocs.py +++ b/numpy/add_newdocs.py @@ -1,10 +1,14 @@ -# This is only meant to add docs to objects defined in C-extension modules. -# The purpose is to allow easier editing of the docstrings without -# requiring a re-compile. +""" +This is only meant to add docs to objects defined in C-extension modules. +The purpose is to allow easier editing of the docstrings without +requiring a re-compile. -# NOTE: Many of the methods of ndarray have corresponding functions. -# If you update these docstrings, please keep also the ones in -# core/fromnumeric.py, core/defmatrix.py up-to-date. +NOTE: Many of the methods of ndarray have corresponding functions. + If you update these docstrings, please keep also the ones in + core/fromnumeric.py, core/defmatrix.py up-to-date. + +""" +from __future__ import division from numpy.lib import add_newdoc @@ -4460,6 +4464,15 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('view', (same shape, dtype, etc.) This does not cause a reinterpretation of the memory. + For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of + bytes per entry than the previous dtype (for example, converting a + regular array to a structured array), then the behavior of the view + cannot be predicted just from the superficial appearance of ``a`` (shown + by ``print(a)``). It also depends on exactly how ``a`` is stored in + memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus + defined as a slice or transpose, etc., the view may give different + results. + Examples -------- @@ -4501,6 +4514,22 @@ add_newdoc('numpy.core.multiarray', 'ndarray', ('view', >>> z[0] (9, 10) + Views that change the dtype size (bytes per entry) should normally be + avoided on arrays defined by slices, transposes, fortran-ordering, etc.: + + >>> x = np.array([[1,2,3],[4,5,6]], dtype=np.int16) + >>> y = x[:, 0:2] + >>> y + array([[1, 2], + [4, 5]], dtype=int16) + >>> y.view(dtype=[('width', np.int16), ('length', np.int16)]) + Traceback (most recent call last): + File "<stdin>", line 1, in <module> + ValueError: new type not compatible with array. + >>> z = y.copy() + >>> z.view(dtype=[('width', np.int16), ('length', np.int16)]) + array([[(1, 2)], + [(4, 5)]], dtype=[('width', '<i2'), ('length', '<i2')]) """)) diff --git a/numpy/build_utils/__init__.py b/numpy/build_utils/__init__.py index e69de29bb..b06eaf1a4 100644 --- a/numpy/build_utils/__init__.py +++ b/numpy/build_utils/__init__.py @@ -0,0 +1 @@ +from __future__ import division diff --git a/numpy/build_utils/common.py b/numpy/build_utils/common.py index ee93fc404..031a24583 100644 --- a/numpy/build_utils/common.py +++ b/numpy/build_utils/common.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys import copy import binascii diff --git a/numpy/build_utils/waf.py b/numpy/build_utils/waf.py index 4ef71327c..ee28c0ee6 100644 --- a/numpy/build_utils/waf.py +++ b/numpy/build_utils/waf.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import re @@ -166,7 +168,7 @@ int main () try: conf.run_c_code(**kw) - except conf.errors.ConfigurationError, e: + except conf.errors.ConfigurationError as e: conf.end_msg("failed !") if waflib.Logs.verbose > 1: raise diff --git a/numpy/compat/__init__.py b/numpy/compat/__init__.py index 9b4261616..930be5a90 100644 --- a/numpy/compat/__init__.py +++ b/numpy/compat/__init__.py @@ -8,6 +8,8 @@ extensions, which may be included for the following reasons: * we may only need a small subset of the copied library/module """ +from __future__ import division + import _inspect import py3k from _inspect import getargspec, formatargspec diff --git a/numpy/compat/_inspect.py b/numpy/compat/_inspect.py index 612d1e147..cb9717ced 100644 --- a/numpy/compat/_inspect.py +++ b/numpy/compat/_inspect.py @@ -3,7 +3,9 @@ We use this instead of upstream because upstream inspect is slow to import, and significanly contributes to numpy import times. Importing this copy has almost no overhead. + """ +from __future__ import division import types @@ -125,11 +127,11 @@ def getargspec(func): """ if ismethod(func): - func = func.im_func + func = func.__func__ if not isfunction(func): raise TypeError('arg is not a Python function') - args, varargs, varkw = getargs(func.func_code) - return args, varargs, varkw, func.func_defaults + args, varargs, varkw = getargs(func.__code__) + return args, varargs, varkw, func.__defaults__ def getargvalues(frame): """Get information about arguments passed into a particular frame. @@ -209,8 +211,8 @@ if __name__ == '__main__': def foo(x, y, z=None): return None - print inspect.getargs(foo.func_code) - print getargs(foo.func_code) + print inspect.getargs(foo.__code__) + print getargs(foo.__code__) print inspect.getargspec(foo) print getargspec(foo) diff --git a/numpy/compat/py3k.py b/numpy/compat/py3k.py index 0a03929be..594acc1e0 100644 --- a/numpy/compat/py3k.py +++ b/numpy/compat/py3k.py @@ -2,6 +2,7 @@ Python 3 compatibility tools. """ +from __future__ import division __all__ = ['bytes', 'asbytes', 'isfileobj', 'getexception', 'strchar', 'unicode', 'asunicode', 'asbytes_nested', 'asunicode_nested', diff --git a/numpy/compat/setup.py b/numpy/compat/setup.py index 4e0781085..3de064650 100644 --- a/numpy/compat/setup.py +++ b/numpy/compat/setup.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import division + def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration diff --git a/numpy/core/__init__.py b/numpy/core/__init__.py index 5d1599111..011e356b2 100644 --- a/numpy/core/__init__.py +++ b/numpy/core/__init__.py @@ -1,3 +1,4 @@ +from __future__ import division from info import __doc__ from numpy.version import version as __version__ diff --git a/numpy/core/_internal.py b/numpy/core/_internal.py index 686b773f2..7ba28f993 100644 --- a/numpy/core/_internal.py +++ b/numpy/core/_internal.py @@ -1,5 +1,10 @@ -#A place for code to be called from C-code -# that implements more complicated stuff. +""" +A place for code to be called from core C-code. + +Some things are more easily handled Python. + +""" +from __future__ import division import re import sys diff --git a/numpy/core/_methods.py b/numpy/core/_methods.py index d3c150ac8..a7f9ccd44 100644 --- a/numpy/core/_methods.py +++ b/numpy/core/_methods.py @@ -1,5 +1,9 @@ -# Array methods which are called by the both the C-code for the method -# and the Python code for the NumPy-namespace function +""" +Array methods which are called by the both the C-code for the method +and the Python code for the NumPy-namespace function + +""" +from __future__ import division from numpy.core import multiarray as mu from numpy.core import umath as um diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index f3add4463..fa91a4799 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -1,7 +1,10 @@ """Array printing function $Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $ + """ +from __future__ import division + __all__ = ["array2string", "set_printoptions", "get_printoptions"] __docformat__ = 'restructuredtext' diff --git a/numpy/core/bscript b/numpy/core/bscript index d24b7732c..3d9b84018 100644 --- a/numpy/core/bscript +++ b/numpy/core/bscript @@ -90,6 +90,19 @@ def write_numpy_config(conf): onode = conf.bldnode.make_node(node.path_from(conf.srcnode)).change_ext("") onode.write(cnt) +def write_numpy_inifiles(conf): + subst_dict = dict([("@sep@", os.path.sep), ("@pkgname@", "numpy.core")]) + for inifile in ["mlib.ini.in", "npymath.ini.in"]: + node = conf.path.find_node(inifile) + cnt = node.read() + for k, v in subst_dict.items(): + cnt = cnt.replace(k, v) + assert node is not None + outfile = os.path.join("lib", "npy-pkg-config", inifile) + onode = conf.bldnode.make_node(node.path_from(conf.srcnode).replace( + inifile, outfile)).change_ext("") + onode.write(cnt) + def type_checks(conf): header_name = "Python.h" features = "c pyext" @@ -298,6 +311,8 @@ def post_configure(context): write_numpy_config(conf) + write_numpy_inifiles(conf) + conf.env.INCLUDES = [".", "include", "include/numpy"] # FIXME: Should be handled in bento context @@ -357,6 +372,7 @@ def process_multiarray_api_generator(self): self.bld.register_outputs("numpy_gen_headers", "multiarray", [output for output in tsk.outputs if output.suffix() == ".h"], target_dir="$sitedir/numpy/core/include/numpy") + return tsk @waflib.TaskGen.feature("ufunc_api_gen") @@ -402,6 +418,14 @@ from os.path import join as pjoin def pre_build(context): bld = context.waf_context + context.register_category("numpy_gen_inifiles") + inifile_mlib = context.local_node.declare(os.path.join( + "lib", "npy-pkg-config", "mlib.ini")) + inifile_npymath = context.local_node.declare(os.path.join( + "lib", "npy-pkg-config", "npymath.ini")) + context.register_outputs("numpy_gen_inifiles", "numpyconfig", + [inifile_mlib, inifile_npymath]) + context.register_category("numpy_gen_headers") numpyconfig_h = context.local_node.declare(os.path.join("include", "numpy", "_numpyconfig.h")) diff --git a/numpy/core/code_generators/__init__.py b/numpy/core/code_generators/__init__.py index e69de29bb..b06eaf1a4 100644 --- a/numpy/core/code_generators/__init__.py +++ b/numpy/core/code_generators/__init__.py @@ -0,0 +1 @@ +from __future__ import division diff --git a/numpy/core/code_generators/cversions.py b/numpy/core/code_generators/cversions.py index 036e923ec..161dae8d9 100644 --- a/numpy/core/code_generators/cversions.py +++ b/numpy/core/code_generators/cversions.py @@ -1,10 +1,16 @@ -"""Simple script to compute the api hash of the current API as defined by -numpy_api_order and ufunc_api_order.""" -from os.path import join, dirname +"""Simple script to compute the api hash of the current API. + +The API has is defined by numpy_api_order and ufunc_api_order. + +""" +from __future__ import division + +from os.path import dirname from genapi import fullapi_hash import numpy_api + if __name__ == '__main__': curdir = dirname(__file__) print fullapi_hash(numpy_api.full_api) diff --git a/numpy/core/code_generators/cversions.txt b/numpy/core/code_generators/cversions.txt index 7d3b43d3b..5de3d5dc2 100644 --- a/numpy/core/code_generators/cversions.txt +++ b/numpy/core/code_generators/cversions.txt @@ -1,4 +1,6 @@ -# hash below were defined from numpy_api_order.txt and ufunc_api_order.txt +# Hash below were defined from numpy_api_order.txt and ufunc_api_order.txt +# When adding a new version here for a new minor release, also add the same +# version as NPY_x_y_API_VERSION in numpyconfig.h 0x00000001 = 603580d224763e58c5e7147f804dc0f5 0x00000002 = 8ecb29306758515ae69749c803a75da1 0x00000003 = bf22c0d05b31625d2a7015988d61ce5a diff --git a/numpy/core/code_generators/genapi.py b/numpy/core/code_generators/genapi.py index 32b0972a7..426f4e05e 100644 --- a/numpy/core/code_generators/genapi.py +++ b/numpy/core/code_generators/genapi.py @@ -4,7 +4,10 @@ Get API information encoded in C files. See ``find_function`` for how functions should be formatted, and ``read_order`` for how the order of the functions should be specified. + """ +from __future__ import division + import sys, os, re try: import hashlib diff --git a/numpy/core/code_generators/generate_numpy_api.py b/numpy/core/code_generators/generate_numpy_api.py index 7cd4b9f6a..6a9fde238 100644 --- a/numpy/core/code_generators/generate_numpy_api.py +++ b/numpy/core/code_generators/generate_numpy_api.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import genapi @@ -221,8 +223,8 @@ def do_generate_api(targets, sources): multiarray_api_dict[name] = TypeApi(name, index, 'PyTypeObject', api_name) if len(multiarray_api_dict) != len(multiarray_api_index): - raise AssertionError, "Multiarray API size mismatch %d %d" % \ - (len(multiarray_api_dict), len(multiarray_api_index)) + raise AssertionError("Multiarray API size mismatch %d %d" % + (len(multiarray_api_dict), len(multiarray_api_index))) extension_list = [] for name, index in genapi.order_dict(multiarray_api_index): diff --git a/numpy/core/code_generators/generate_ufunc_api.py b/numpy/core/code_generators/generate_ufunc_api.py index e10b9cd38..862d46e34 100644 --- a/numpy/core/code_generators/generate_ufunc_api.py +++ b/numpy/core/code_generators/generate_ufunc_api.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import genapi diff --git a/numpy/core/code_generators/generate_umath.py b/numpy/core/code_generators/generate_umath.py index 2d8e4360e..6dd3d4876 100644 --- a/numpy/core/code_generators/generate_umath.py +++ b/numpy/core/code_generators/generate_umath.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import re import struct diff --git a/numpy/core/code_generators/numpy_api.py b/numpy/core/code_generators/numpy_api.py index 16278f1a2..4a9c747ea 100644 --- a/numpy/core/code_generators/numpy_api.py +++ b/numpy/core/code_generators/numpy_api.py @@ -10,7 +10,9 @@ needs to be updated. When adding a function, make sure to use the next integer not used as an index (in case you use an existing index or jump, the build will stop and raise an exception, so it should hopefully not get unnoticed). + """ +from __future__ import division multiarray_global_vars = { 'NPY_NUMUSERTYPES': 7, diff --git a/numpy/core/code_generators/ufunc_docstrings.py b/numpy/core/code_generators/ufunc_docstrings.py index b8f11e543..8e175160e 100644 --- a/numpy/core/code_generators/ufunc_docstrings.py +++ b/numpy/core/code_generators/ufunc_docstrings.py @@ -1,13 +1,15 @@ -# Docstrings for generated ufuncs -# -# The syntax is designed to look like the function add_newdoc is being -# called from numpy.lib, but in this file add_newdoc puts the docstrings -# in a dictionary. This dictionary is used in -# numpy/core/code_generators/generate_umath.py to generate the docstrings -# for the ufuncs in numpy.core at the C level when the ufuncs are created -# at compile time. - - +""" +Docstrings for generated ufuncs + +The syntax is designed to look like the function add_newdoc is being +called from numpy.lib, but in this file add_newdoc puts the docstrings +in a dictionary. This dictionary is used in +numpy/core/code_generators/generate_umath.py to generate the docstrings +for the ufuncs in numpy.core at the C level when the ufuncs are created +at compile time. + +""" +from __future__ import division docdict = {} diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py index 1f4b3bef8..c85d95c49 100644 --- a/numpy/core/defchararray.py +++ b/numpy/core/defchararray.py @@ -15,6 +15,7 @@ available in your version of Python. The preferred alias for `defchararray` is `numpy.char`. """ +from __future__ import division import sys from numerictypes import string_, unicode_, integer, object_, bool_, character diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index 7596e3707..9ca56ce27 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -1,4 +1,8 @@ -# Module containing non-deprecated functions borrowed from Numeric. +"""Module containing non-deprecated functions borrowed from Numeric. + +""" +from __future__ import division + __docformat__ = "restructuredtext en" # functions that are now methods diff --git a/numpy/core/function_base.py b/numpy/core/function_base.py index 82b524604..fa6732077 100644 --- a/numpy/core/function_base.py +++ b/numpy/core/function_base.py @@ -1,3 +1,5 @@ +from __future__ import division + __all__ = ['logspace', 'linspace'] import numeric as _nx diff --git a/numpy/core/getlimits.py b/numpy/core/getlimits.py index 4754975e2..7b94346c7 100644 --- a/numpy/core/getlimits.py +++ b/numpy/core/getlimits.py @@ -1,5 +1,7 @@ -""" Machine limits for Float32 and Float64 and (long double) if available... +"""Machine limits for Float32 and Float64 and (long double) if available... + """ +from __future__ import division __all__ = ['finfo','iinfo'] diff --git a/numpy/core/include/numpy/numpyconfig.h b/numpy/core/include/numpy/numpyconfig.h index 702d9952f..5ca171f21 100644 --- a/numpy/core/include/numpy/numpyconfig.h +++ b/numpy/core/include/numpy/numpyconfig.h @@ -29,5 +29,6 @@ * #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION */ #define NPY_1_7_API_VERSION 0x00000007 +#define NPY_1_8_API_VERSION 0x00000008 #endif diff --git a/numpy/core/info.py b/numpy/core/info.py index 561e171b0..f56b2d395 100644 --- a/numpy/core/info.py +++ b/numpy/core/info.py @@ -1,4 +1,4 @@ -__doc__ = """Defines a multi-dimensional array and useful procedures for Numerical computation. +"""Defines a multi-dimensional array and useful procedures for Numerical computation. Functions @@ -81,6 +81,7 @@ More Functions: arccosh arcsinh arctanh """ +from __future__ import division depends = ['testing'] global_symbols = ['*'] diff --git a/numpy/core/machar.py b/numpy/core/machar.py index ea9174017..b7e64290e 100644 --- a/numpy/core/machar.py +++ b/numpy/core/machar.py @@ -1,9 +1,11 @@ """ Machine arithmetics - determine the parameters of the floating-point arithmetic system -""" -# Author: Pearu Peterson, September 2003 +Author: Pearu Peterson, September 2003 + +""" +from __future__ import division __all__ = ['MachAr'] diff --git a/numpy/core/memmap.py b/numpy/core/memmap.py index f068c7b6c..5107e9b28 100644 --- a/numpy/core/memmap.py +++ b/numpy/core/memmap.py @@ -1,3 +1,5 @@ +from __future__ import division + __all__ = ['memmap'] import warnings diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 521001575..a114e4bb5 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -1,3 +1,5 @@ +from __future__ import division + __all__ = ['newaxis', 'ndarray', 'flatiter', 'nditer', 'nested_iters', 'ufunc', 'arange', 'array', 'zeros', 'count_nonzero', 'empty', 'broadcast', 'dtype', 'fromstring', 'fromfile', @@ -29,6 +31,7 @@ import umath from umath import * import numerictypes from numerictypes import * +import collections if sys.version_info[0] < 3: @@ -81,6 +84,10 @@ def zeros_like(a, dtype=None, order='K', subok=True): 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. + subok : bool, optional. + If True, then the newly created array will use the sub-class + type of 'a', otherwise it will be a base-class array. Defaults + to True. Returns ------- @@ -167,6 +174,10 @@ def ones_like(a, dtype=None, order='K', subok=True): 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous, 'C' otherwise. 'K' means match the layout of `a` as closely as possible. + subok : bool, optional. + If True, then the newly created array will use the sub-class + type of 'a', otherwise it will be a base-class array. Defaults + to True. Returns ------- @@ -2437,8 +2448,8 @@ def seterrcall(func): {'over': 'log', 'divide': 'log', 'invalid': 'log', 'under': 'log'} """ - if func is not None and not callable(func): - if not hasattr(func, 'write') or not callable(func.write): + if func is not None and not isinstance(func, collections.Callable): + if not hasattr(func, 'write') or not isinstance(func.write, collections.Callable): raise ValueError("Only callable can be used as callback") pyvals = umath.geterrobj() old = geterrcall() diff --git a/numpy/core/numerictypes.py b/numpy/core/numerictypes.py index e39eb2232..b069b5426 100644 --- a/numpy/core/numerictypes.py +++ b/numpy/core/numerictypes.py @@ -80,6 +80,7 @@ Exported symbols include: \\-> object_ (not used much) (kind=O) """ +from __future__ import division # we add more at the bottom __all__ = ['sctypeDict', 'sctypeNA', 'typeDict', 'typeNA', 'sctypes', diff --git a/numpy/core/records.py b/numpy/core/records.py index 964b4a54e..ff5d98d3a 100644 --- a/numpy/core/records.py +++ b/numpy/core/records.py @@ -34,6 +34,8 @@ Record arrays allow us to access fields as properties:: array([ 2., 2.]) """ +from __future__ import division + # All of the functions allow formats to be a dtype __all__ = ['record', 'recarray', 'format_parser'] @@ -436,7 +438,7 @@ class recarray(ndarray): fielddict = ndarray.__getattribute__(self, 'dtype').fields or {} if attr not in fielddict: exctype, value = sys.exc_info()[:2] - raise exctype, value + raise exctype(value) else: fielddict = ndarray.__getattribute__(self, 'dtype').fields or {} if attr not in fielddict: diff --git a/numpy/core/setup.py b/numpy/core/setup.py index 6a8b0fc38..8c43f97c0 100644 --- a/numpy/core/setup.py +++ b/numpy/core/setup.py @@ -1,3 +1,5 @@ +from __future__ import division + import imp import os import sys diff --git a/numpy/core/setup_common.py b/numpy/core/setup_common.py index 1674333ca..1afc71085 100644 --- a/numpy/core/setup_common.py +++ b/numpy/core/setup_common.py @@ -1,3 +1,5 @@ +from __future__ import division + # Code common to build tools import sys from os.path import join diff --git a/numpy/core/shape_base.py b/numpy/core/shape_base.py index 261379077..4d5439249 100644 --- a/numpy/core/shape_base.py +++ b/numpy/core/shape_base.py @@ -1,3 +1,5 @@ +from __future__ import division + __all__ = ['atleast_1d','atleast_2d','atleast_3d','vstack','hstack'] import numeric as _nx diff --git a/numpy/core/src/multiarray/item_selection.c b/numpy/core/src/multiarray/item_selection.c index 7c8041cf1..4adecf193 100644 --- a/numpy/core/src/multiarray/item_selection.c +++ b/numpy/core/src/multiarray/item_selection.c @@ -31,10 +31,11 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, PyArray_Descr *dtype; PyArray_FastTakeFunc *func; PyArrayObject *obj = NULL, *self, *indices; - npy_intp nd, i, j, n, m, max_item, tmp, chunk, nelem; + npy_intp nd, i, j, n, m, k, max_item, tmp, chunk, itemsize, nelem; npy_intp shape[NPY_MAXDIMS]; - char *src, *dest; + char *src, *dest, *tmp_src; int err; + npy_bool needs_refcounting; indices = NULL; self = (PyArrayObject *)PyArray_CheckAxis(self0, &axis, @@ -110,9 +111,18 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, max_item = PyArray_DIMS(self)[axis]; nelem = chunk; - chunk = chunk * PyArray_DESCR(obj)->elsize; + itemsize = PyArray_ITEMSIZE(obj); + chunk = chunk * itemsize; src = PyArray_DATA(self); dest = PyArray_DATA(obj); + needs_refcounting = PyDataType_REFCHK(PyArray_DESCR(self)); + + if ((max_item == 0) && (PyArray_SIZE(obj) != 0)) { + /* Index error, since that is the usual error for raise mode */ + PyErr_SetString(PyExc_IndexError, + "cannot do a non-empty take from an empty axes."); + goto fail; + } func = PyArray_DESCR(self)->f->fasttake; if (func == NULL) { @@ -124,8 +134,20 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, if (check_and_adjust_index(&tmp, max_item, axis) < 0) { goto fail; } - memmove(dest, src + tmp*chunk, chunk); - dest += chunk; + tmp_src = src + tmp * chunk; + if (needs_refcounting) { + for (k=0; k < nelem; k++) { + PyArray_Item_INCREF(tmp_src, PyArray_DESCR(self)); + PyArray_Item_XDECREF(dest, PyArray_DESCR(self)); + memmove(dest, tmp_src, itemsize); + dest += itemsize; + tmp_src += itemsize; + } + } + else { + memmove(dest, tmp_src, chunk); + dest += chunk; + } } src += chunk*max_item; } @@ -144,8 +166,20 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, tmp -= max_item; } } - memmove(dest, src + tmp*chunk, chunk); - dest += chunk; + tmp_src = src + tmp * chunk; + if (needs_refcounting) { + for (k=0; k < nelem; k++) { + PyArray_Item_INCREF(tmp_src, PyArray_DESCR(self)); + PyArray_Item_XDECREF(dest, PyArray_DESCR(self)); + memmove(dest, tmp_src, itemsize); + dest += itemsize; + tmp_src += itemsize; + } + } + else { + memmove(dest, tmp_src, chunk); + dest += chunk; + } } src += chunk*max_item; } @@ -160,8 +194,20 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, else if (tmp >= max_item) { tmp = max_item - 1; } - memmove(dest, src+tmp*chunk, chunk); - dest += chunk; + tmp_src = src + tmp * chunk; + if (needs_refcounting) { + for (k=0; k < nelem; k++) { + PyArray_Item_INCREF(tmp_src, PyArray_DESCR(self)); + PyArray_Item_XDECREF(dest, PyArray_DESCR(self)); + memmove(dest, tmp_src, itemsize); + dest += itemsize; + tmp_src += itemsize; + } + } + else { + memmove(dest, tmp_src, chunk); + dest += chunk; + } } src += chunk*max_item; } @@ -176,7 +222,6 @@ PyArray_TakeFrom(PyArrayObject *self0, PyObject *indices0, int axis, } } - PyArray_INCREF(obj); Py_XDECREF(indices); Py_XDECREF(self); if (out != NULL && out != obj) { diff --git a/numpy/core/src/multiarray/methods.c b/numpy/core/src/multiarray/methods.c index 7f0e3861b..c81f4b1a8 100644 --- a/numpy/core/src/multiarray/methods.c +++ b/numpy/core/src/multiarray/methods.c @@ -633,6 +633,7 @@ array_toscalar(PyArrayObject *self, PyObject *args) else { PyErr_SetString(PyExc_ValueError, "can only convert an array of size 1 to a Python scalar"); + return NULL; } } /* Special case of C-order flat indexing... :| */ @@ -1847,10 +1848,11 @@ array_cumprod(PyArrayObject *self, PyObject *args, PyObject *kwds) static PyObject * array_dot(PyArrayObject *self, PyObject *args, PyObject *kwds) { - PyObject *b; + PyObject *fname, *ret, *b, *out = NULL; static PyObject *numpycore = NULL; + char * kwords[] = {"b", "out", NULL }; - if (!PyArg_ParseTuple(args, "O", &b)) { + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwords, &b, &out)) { return NULL; } @@ -1862,8 +1864,13 @@ array_dot(PyArrayObject *self, PyObject *args, PyObject *kwds) return NULL; } } - - return PyObject_CallMethod(numpycore, "dot", "OO", self, b); + fname = PyUString_FromString("dot"); + if (out == NULL) { + ret = PyObject_CallMethodObjArgs(numpycore, fname, self, b, NULL); + } + ret = PyObject_CallMethodObjArgs(numpycore, fname, self, b, out, NULL); + Py_DECREF(fname); + return ret; } @@ -2222,7 +2229,7 @@ NPY_NO_EXPORT PyMethodDef array_methods[] = { METH_VARARGS | METH_KEYWORDS, NULL}, {"dot", (PyCFunction)array_dot, - METH_VARARGS, NULL}, + METH_VARARGS | METH_KEYWORDS, NULL}, {"fill", (PyCFunction)array_fill, METH_VARARGS, NULL}, diff --git a/numpy/core/src/multiarray/nditer_pywrap.c b/numpy/core/src/multiarray/nditer_pywrap.c index fd88cdbc7..4621491a3 100644 --- a/numpy/core/src/multiarray/nditer_pywrap.c +++ b/numpy/core/src/multiarray/nditer_pywrap.c @@ -786,7 +786,7 @@ npyiter_init(NewNpyArrayIterObject *self, PyObject *args, PyObject *kwds) if (itershape.len > 0) { if (oa_ndim == 0) { oa_ndim = itershape.len; - memset(op_axes, 0, sizeof(op_axes[0])*oa_ndim); + memset(op_axes, 0, sizeof(op_axes[0]) * nop); } else if (oa_ndim != itershape.len) { PyErr_SetString(PyExc_ValueError, diff --git a/numpy/core/src/multiarray/shape.c b/numpy/core/src/multiarray/shape.c index 97ddb2e61..4223e49f6 100644 --- a/numpy/core/src/multiarray/shape.c +++ b/numpy/core/src/multiarray/shape.c @@ -355,10 +355,14 @@ _attempt_nocopy_reshape(PyArrayObject *self, int newnd, npy_intp* newdims, int oldnd; npy_intp olddims[NPY_MAXDIMS]; npy_intp oldstrides[NPY_MAXDIMS]; - npy_intp np, op; + npy_intp np, op, last_stride; int oi, oj, ok, ni, nj, nk; oldnd = 0; + /* + * Remove axes with dimension 1 from the old array. They have no effect + * but would need special cases since their strides do not matter. + */ for (oi = 0; oi < PyArray_NDIM(self); oi++) { if (PyArray_DIMS(self)[oi]!= 1) { olddims[oldnd] = PyArray_DIMS(self)[oi]; @@ -390,27 +394,31 @@ _attempt_nocopy_reshape(PyArrayObject *self, int newnd, npy_intp* newdims, /* different total sizes; no hope */ return 0; } - /* the current code does not handle 0-sized arrays, so give up */ + if (np == 0) { + /* the current code does not handle 0-sized arrays, so give up */ return 0; } + /* oi to oj and ni to nj give the axis ranges currently worked with */ oi = 0; oj = 1; ni = 0; nj = 1; - while(ni < newnd && oi < oldnd) { + while (ni < newnd && oi < oldnd) { np = newdims[ni]; op = olddims[oi]; while (np != op) { if (np < op) { + /* Misses trailing 1s, these are handled later */ np *= newdims[nj++]; } else { op *= olddims[oj++]; } } + /* Check whether the original axes can be combined */ for (ok = oi; ok < oj - 1; ok++) { if (is_f_order) { if (oldstrides[ok+1] != olddims[ok]*oldstrides[ok]) { @@ -427,6 +435,7 @@ _attempt_nocopy_reshape(PyArrayObject *self, int newnd, npy_intp* newdims, } } + /* Calculate new strides for all axes currently worked with */ if (is_f_order) { newstrides[ni] = oldstrides[oi]; for (nk = ni + 1; nk < nj; nk++) { @@ -445,6 +454,22 @@ _attempt_nocopy_reshape(PyArrayObject *self, int newnd, npy_intp* newdims, } /* + * Set strides corresponding to trailing 1s of the new shape. + */ + if (ni >= 1) { + last_stride = newstrides[ni - 1]; + } + else { + last_stride = PyArray_ITEMSIZE(self); + } + if (is_f_order) { + last_stride *= newdims[ni - 1]; + } + for (nk = ni; nk < newnd; nk++) { + newstrides[nk] = last_stride; + } + + /* fprintf(stderr, "success: _attempt_nocopy_reshape ("); for (oi=0; oi<oldnd; oi++) fprintf(stderr, "(%d,%d), ", olddims[oi], oldstrides[oi]); diff --git a/numpy/core/src/multiarray/testcalcs.py b/numpy/core/src/multiarray/testcalcs.py index 8cb440820..78a875406 100644 --- a/numpy/core/src/multiarray/testcalcs.py +++ b/numpy/core/src/multiarray/testcalcs.py @@ -1,3 +1,5 @@ +from __future__ import division + from scipy import weave class YMD(object): diff --git a/numpy/core/src/umath/ufunc_object.c b/numpy/core/src/umath/ufunc_object.c index 2712f0474..124185bfd 100644 --- a/numpy/core/src/umath/ufunc_object.c +++ b/numpy/core/src/umath/ufunc_object.c @@ -71,6 +71,12 @@ static int _does_loop_use_arrays(void *data); +static int +assign_reduce_identity_zero(PyArrayObject *result); + +static int +assign_reduce_identity_one(PyArrayObject *result); + /* * fpstatus is the ufunc_formatted hardware status * errmask is the handling mask specified by the user. @@ -1643,7 +1649,7 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, PyArrayObject **op) { int nin, nout; - int i, idim, nop; + int i, j, idim, nop; char *ufunc_name; int retval = -1, subok = 1; int needs_api = 0; @@ -1651,11 +1657,12 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, PyArray_Descr *dtypes[NPY_MAXARGS]; /* Use remapped axes for generalized ufunc */ - int broadcast_ndim, op_ndim; + int broadcast_ndim, iter_ndim; int op_axes_arrays[NPY_MAXARGS][NPY_MAXDIMS]; int *op_axes[NPY_MAXARGS]; npy_uint32 op_flags[NPY_MAXARGS]; + npy_intp iter_shape[NPY_MAXARGS]; NpyIter *iter = NULL; @@ -1673,7 +1680,9 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, npy_intp *inner_strides = NULL; npy_intp *inner_strides_tmp, *ax_strides_tmp[NPY_MAXDIMS]; - int core_dim_ixs_size, *core_dim_ixs; + /* The sizes of the core dimensions (# entries is ufunc->core_num_dim_ix) */ + npy_intp *core_dim_sizes = inner_dimensions + 1; + int core_dim_ixs_size; /* The __array_prepare__ function to call for each output */ PyObject *arr_prep[NPY_MAXARGS]; @@ -1719,7 +1728,11 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, goto fail; } - /* Figure out the number of dimensions needed by the iterator */ + /* + * Figure out the number of iteration dimensions, which + * is the broadcast result of all the input non-core + * dimensions. + */ broadcast_ndim = 0; for (i = 0; i < nin; ++i) { int n = PyArray_NDIM(op[i]) - ufunc->core_num_dims[i]; @@ -1727,8 +1740,18 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, broadcast_ndim = n; } } - op_ndim = broadcast_ndim + ufunc->core_num_dim_ix; - if (op_ndim > NPY_MAXDIMS) { + + /* + * Figure out the number of iterator creation dimensions, + * which is the broadcast dimensions + all the core dimensions of + * the outputs, so that the iterator can allocate those output + * dimensions following the rules of order='F', for example. + */ + iter_ndim = broadcast_ndim; + for (i = nin; i < nop; ++i) { + iter_ndim += ufunc->core_num_dims[i]; + } + if (iter_ndim > NPY_MAXDIMS) { PyErr_Format(PyExc_ValueError, "too many dimensions for generalized ufunc %s", ufunc_name); @@ -1736,9 +1759,76 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, goto fail; } + /* + * Validate the core dimensions of all the operands, + * and collect all of the labeled core dimension sizes + * into the array 'core_dim_sizes'. Initialize them to + * 1, for example in the case where the operand broadcasts + * to a core dimension, it won't be visited. + */ + for (i = 0; i < ufunc->core_num_dim_ix; ++i) { + core_dim_sizes[i] = 1; + } + for (i = 0; i < nop; ++i) { + if (op[i] != NULL) { + int dim_offset = ufunc->core_offsets[i]; + int num_dims = ufunc->core_num_dims[i]; + int core_start_dim = PyArray_NDIM(op[i]) - num_dims; + /* Make sure any output operand has enough dimensions */ + if (i >= nin && core_start_dim < 0) { + PyErr_Format(PyExc_ValueError, + "%s: Output operand %d does not have enough dimensions " + "(has %d, gufunc core with signature %s " + "requires %d)", + ufunc_name, i - nin, PyArray_NDIM(op[i]), + ufunc->core_signature, num_dims); + retval = -1; + goto fail; + } + + /* + * Make sure each core dimension matches all other core + * dimensions with the same label + * + * NOTE: For input operands, core_start_dim may be negative. + * In that case, the operand is being broadcast onto + * core dimensions. For example, a scalar will broadcast + * to fit any core signature. + */ + if (core_start_dim >= 0) { + idim = 0; + } else { + idim = -core_start_dim; + } + for (; idim < num_dims; ++idim) { + int core_dim_index = ufunc->core_dim_ixs[dim_offset + idim]; + npy_intp op_dim_size = + PyArray_SHAPE(op[i])[core_start_dim + idim]; + if (core_dim_sizes[core_dim_index] == 1) { + core_dim_sizes[core_dim_index] = op_dim_size; + } else if ((i >= nin || op_dim_size != 1) && + core_dim_sizes[core_dim_index] != op_dim_size) { + PyErr_Format(PyExc_ValueError, + "%s: Operand %d has a mismatch in its core " + "dimension %d, with gufunc signature %s " + "(size %d is different from %d)", + ufunc_name, i, idim, ufunc->core_signature, + op_dim_size, core_dim_sizes[core_dim_index]); + retval = -1; + goto fail; + } + } + } + } + + /* Fill in the initial part of 'iter_shape' */ + for (idim = 0; idim < broadcast_ndim; ++idim) { + iter_shape[idim] = -1; + } + /* Fill in op_axes for all the operands */ + j = broadcast_ndim; core_dim_ixs_size = 0; - core_dim_ixs = ufunc->core_dim_ixs; for (i = 0; i < nop; ++i) { int n; if (op[i]) { @@ -1760,22 +1850,27 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, op_axes_arrays[i][idim] = -1; } } - /* Use the signature information for the rest */ - for (idim = broadcast_ndim; idim < op_ndim; ++idim) { + + /* Any output core dimensions shape should be ignored */ + for (idim = broadcast_ndim; idim < iter_ndim; ++idim) { op_axes_arrays[i][idim] = -1; } - for (idim = 0; idim < ufunc->core_num_dims[i]; ++idim) { - if (n + idim >= 0) { - op_axes_arrays[i][broadcast_ndim + core_dim_ixs[idim]] = - n + idim; - } - else { - op_axes_arrays[i][broadcast_ndim + core_dim_ixs[idim]] = -1; + + /* Except for when it belongs to this output */ + if (i >= nin) { + int dim_offset = ufunc->core_offsets[i]; + int num_dims = ufunc->core_num_dims[i]; + /* Fill in 'iter_shape' and 'op_axes' for this output */ + for (idim = 0; idim < num_dims; ++idim) { + iter_shape[j] = core_dim_sizes[ + ufunc->core_dim_ixs[dim_offset + idim]]; + op_axes_arrays[i][j] = n + idim; + ++j; } } - core_dim_ixs_size += ufunc->core_num_dims[i]; - core_dim_ixs += ufunc->core_num_dims[i]; + op_axes[i] = op_axes_arrays[i]; + core_dim_ixs_size += ufunc->core_num_dims[i]; } /* Get the buffersize, errormask, and error object globals */ @@ -1881,12 +1976,26 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, NPY_ITER_NO_BROADCAST; } + /* + * If there are no iteration dimensions, create a fake one + * so that the scalar edge case works right. + */ + if (iter_ndim == 0) { + iter_ndim = 1; + iter_shape[0] = 1; + for (i = 0; i < nop; ++i) { + op_axes[i][0] = -1; + } + } + /* Create the iterator */ iter = NpyIter_AdvancedNew(nop, op, NPY_ITER_MULTI_INDEX| NPY_ITER_REFS_OK| - NPY_ITER_REDUCE_OK, + NPY_ITER_REDUCE_OK| + NPY_ITER_ZEROSIZE_OK, order, NPY_UNSAFE_CASTING, op_flags, - dtypes, op_ndim, op_axes, NULL, 0); + dtypes, iter_ndim, + op_axes, iter_shape, 0); if (iter == NULL) { retval = -1; goto fail; @@ -1906,37 +2015,38 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, */ inner_strides = (npy_intp *)PyArray_malloc( NPY_SIZEOF_INTP * (nop+core_dim_ixs_size)); - /* The strides after the first nop match core_dim_ixs */ - core_dim_ixs = ufunc->core_dim_ixs; - inner_strides_tmp = inner_strides + nop; - for (idim = 0; idim < ufunc->core_num_dim_ix; ++idim) { - ax_strides_tmp[idim] = NpyIter_GetAxisStrideArray(iter, - broadcast_ndim+idim); - if (ax_strides_tmp[idim] == NULL) { - retval = -1; - goto fail; - } - } + /* Copy the strides after the first nop */ + idim = nop; for (i = 0; i < nop; ++i) { - for (idim = 0; idim < ufunc->core_num_dims[i]; ++idim) { - inner_strides_tmp[idim] = ax_strides_tmp[core_dim_ixs[idim]][i]; + int dim_offset = ufunc->core_offsets[i]; + int num_dims = ufunc->core_num_dims[i]; + int core_start_dim = PyArray_NDIM(op[i]) - num_dims; + /* + * Need to use the arrays in the iterator, not op, because + * a copy with a different-sized type may have been made. + */ + PyArrayObject *arr = NpyIter_GetOperandArray(iter)[i]; + npy_intp *shape = PyArray_SHAPE(arr); + npy_intp *strides = PyArray_STRIDES(arr); + for (j = 0; j < num_dims; ++j) { + if (core_start_dim + j >= 0) { + /* + * Force the stride to zero when the shape is 1, sot + * that the broadcasting works right. + */ + if (shape[core_start_dim + j] != 1) { + inner_strides[idim++] = strides[core_start_dim + j]; + } else { + inner_strides[idim++] = 0; + } + } else { + inner_strides[idim++] = 0; + } } - - core_dim_ixs += ufunc->core_num_dims[i]; - inner_strides_tmp += ufunc->core_num_dims[i]; - } - - /* Set up the inner dimensions array */ - if (NpyIter_GetShape(iter, inner_dimensions) != NPY_SUCCEED) { - retval = -1; - goto fail; } - /* Move the core dimensions to start at the second element */ - memmove(&inner_dimensions[1], &inner_dimensions[broadcast_ndim], - NPY_SIZEOF_INTP * ufunc->core_num_dim_ix); - /* Remove all the core dimensions from the iterator */ - for (i = 0; i < ufunc->core_num_dim_ix; ++i) { + /* Remove all the core output dimensions from the iterator */ + for (i = broadcast_ndim; i < iter_ndim; ++i) { if (NpyIter_RemoveAxis(iter, broadcast_ndim) != NPY_SUCCEED) { retval = -1; goto fail; @@ -1971,8 +2081,8 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, NPY_UF_DBG_PRINT("Executing inner loop\n"); - /* Do the ufunc loop */ if (NpyIter_GetIterSize(iter) != 0) { + /* Do the ufunc loop */ NpyIter_IterNextFunc *iternext; char **dataptr; npy_intp *count_ptr; @@ -1991,6 +2101,36 @@ PyUFunc_GeneralizedFunction(PyUFuncObject *ufunc, inner_dimensions[0] = *count_ptr; innerloop(dataptr, inner_dimensions, inner_strides, innerloopdata); } while (iternext(iter)); + } else { + /** + * For each output operand, check if it has non-zero size, + * and assign the identity if it does. For example, a dot + * product of two zero-length arrays will be a scalar, + * which has size one. + */ + for (i = nin; i < nop; ++i) { + if (PyArray_SIZE(op[i]) != 0) { + switch (ufunc->identity) { + case PyUFunc_Zero: + assign_reduce_identity_zero(op[i]); + break; + case PyUFunc_One: + assign_reduce_identity_one(op[i]); + break; + case PyUFunc_None: + case PyUFunc_ReorderableNone: + PyErr_Format(PyExc_ValueError, + "ufunc %s ", + ufunc_name); + goto fail; + default: + PyErr_Format(PyExc_ValueError, + "ufunc %s has an invalid identity for reduction", + ufunc_name); + goto fail; + } + } + } } /* Check whether any errors occurred during the loop */ @@ -2433,13 +2573,13 @@ reduce_type_resolver(PyUFuncObject *ufunc, PyArrayObject *arr, } static int -assign_reduce_identity_zero(PyArrayObject *result, void *data) +assign_reduce_identity_zero(PyArrayObject *result) { return PyArray_FillWithScalar(result, PyArrayScalar_False); } static int -assign_reduce_identity_one(PyArrayObject *result, void *data) +assign_reduce_identity_one(PyArrayObject *result) { return PyArray_FillWithScalar(result, PyArrayScalar_True); } diff --git a/numpy/core/tests/test_api.py b/numpy/core/tests/test_api.py index df26dd07a..484b6afbd 100644 --- a/numpy/core/tests/test_api.py +++ b/numpy/core/tests/test_api.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys import numpy as np diff --git a/numpy/core/tests/test_arrayprint.py b/numpy/core/tests/test_arrayprint.py index 2a2a97336..a61aa5161 100644 --- a/numpy/core/tests/test_arrayprint.py +++ b/numpy/core/tests/test_arrayprint.py @@ -1,5 +1,7 @@ #!/usr/bin/python # -*- coding: utf-8 -*- +from __future__ import division + import sys import numpy as np from numpy.testing import * diff --git a/numpy/core/tests/test_blasdot.py b/numpy/core/tests/test_blasdot.py index 3795def66..ec80840c5 100644 --- a/numpy/core/tests/test_blasdot.py +++ b/numpy/core/tests/test_blasdot.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy as np import sys from numpy.core import zeros, float64 diff --git a/numpy/core/tests/test_datetime.py b/numpy/core/tests/test_datetime.py index f4a1ee617..03ee20b09 100644 --- a/numpy/core/tests/test_datetime.py +++ b/numpy/core/tests/test_datetime.py @@ -1,3 +1,5 @@ +from __future__ import division + import os, pickle import numpy import numpy as np diff --git a/numpy/core/tests/test_defchararray.py b/numpy/core/tests/test_defchararray.py index 85bb623a4..ed928bce1 100644 --- a/numpy/core/tests/test_defchararray.py +++ b/numpy/core/tests/test_defchararray.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * from numpy.core import * import numpy as np diff --git a/numpy/core/tests/test_deprecations.py b/numpy/core/tests/test_deprecations.py index 71e724a69..c7cc9d413 100644 --- a/numpy/core/tests/test_deprecations.py +++ b/numpy/core/tests/test_deprecations.py @@ -1,7 +1,10 @@ """ Tests related to deprecation warnings. Also a convenient place to document how deprecations should eventually be turned into errors. + """ +from __future__ import division + import sys import warnings from nose.plugins.skip import SkipTest diff --git a/numpy/core/tests/test_dtype.py b/numpy/core/tests/test_dtype.py index f0b0cdc06..a08cf4851 100644 --- a/numpy/core/tests/test_dtype.py +++ b/numpy/core/tests/test_dtype.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys import numpy as np from numpy.testing import * diff --git a/numpy/core/tests/test_einsum.py b/numpy/core/tests/test_einsum.py index fb7ceb0db..4fba533db 100644 --- a/numpy/core/tests/test_einsum.py +++ b/numpy/core/tests/test_einsum.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys from decimal import Decimal diff --git a/numpy/core/tests/test_errstate.py b/numpy/core/tests/test_errstate.py index cfba6d8b4..c7c5a13ce 100644 --- a/numpy/core/tests/test_errstate.py +++ b/numpy/core/tests/test_errstate.py @@ -1,3 +1,5 @@ +from __future__ import division + import platform import numpy as np diff --git a/numpy/core/tests/test_function_base.py b/numpy/core/tests/test_function_base.py index f1a08d9d5..914ffbb14 100644 --- a/numpy/core/tests/test_function_base.py +++ b/numpy/core/tests/test_function_base.py @@ -1,3 +1,4 @@ +from __future__ import division from numpy.testing import * from numpy import logspace, linspace diff --git a/numpy/core/tests/test_getlimits.py b/numpy/core/tests/test_getlimits.py index 8cbc79cf9..5d5d9bc44 100644 --- a/numpy/core/tests/test_getlimits.py +++ b/numpy/core/tests/test_getlimits.py @@ -1,5 +1,7 @@ """ Test functions for limits module. + """ +from __future__ import division from numpy.testing import * diff --git a/numpy/core/tests/test_half.py b/numpy/core/tests/test_half.py index 31a206e1c..ed1b3e5dd 100644 --- a/numpy/core/tests/test_half.py +++ b/numpy/core/tests/test_half.py @@ -1,3 +1,5 @@ +from __future__ import division + import platform import numpy as np @@ -9,7 +11,7 @@ from numpy.testing import TestCase, run_module_suite, assert_, assert_equal, \ def assert_raises_fpe(strmatch, callable, *args, **kwargs): try: callable(*args, **kwargs) - except FloatingPointError, exc: + except FloatingPointError as exc: assert_(str(exc).find(strmatch) >= 0, "Did not raise floating point %s error" % strmatch) else: diff --git a/numpy/core/tests/test_indexerrors.py b/numpy/core/tests/test_indexerrors.py index af10df9b3..2d74d2ef3 100644 --- a/numpy/core/tests/test_indexerrors.py +++ b/numpy/core/tests/test_indexerrors.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy as np from numpy.testing import TestCase, run_module_suite, assert_raises, assert_equal, assert_ import sys @@ -10,6 +12,8 @@ class TestIndexErrors(TestCase): x = np.empty((2, 3, 0, 4)) assert_raises(IndexError, x.take, [0], axis=2) assert_raises(IndexError, x.take, [1], axis=2) + assert_raises(IndexError, x.take, [0], axis=2, mode='wrap') + assert_raises(IndexError, x.take, [0], axis=2, mode='clip') def test_take_from_object(self): # Check exception taking from object array @@ -21,6 +25,8 @@ class TestIndexErrors(TestCase): assert_raises(IndexError, d.take, [1], axis=1) assert_raises(IndexError, d.take, [0], axis=1) assert_raises(IndexError, d.take, [0]) + assert_raises(IndexError, d.take, [0], mode='wrap') + assert_raises(IndexError, d.take, [0], mode='clip') def test_multiindex_exceptions(self): a = np.empty(5, dtype=object) diff --git a/numpy/core/tests/test_indexing.py b/numpy/core/tests/test_indexing.py index da19d2a2a..6b8b7b8a8 100644 --- a/numpy/core/tests/test_indexing.py +++ b/numpy/core/tests/test_indexing.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy as np from numpy.compat import asbytes from numpy.testing import * diff --git a/numpy/core/tests/test_item_selection.py b/numpy/core/tests/test_item_selection.py index f35e04c4f..6da27175b 100644 --- a/numpy/core/tests/test_item_selection.py +++ b/numpy/core/tests/test_item_selection.py @@ -1,43 +1,65 @@ +from __future__ import division + import numpy as np from numpy.testing import * import sys, warnings -def test_take(): - a = [[1, 2], [3, 4]] - a_str = [['1','2'],['3','4']] - modes = ['raise', 'wrap', 'clip'] - indices = [-1, 4] - index_arrays = [np.empty(0, dtype=np.intp), - np.empty(tuple(), dtype=np.intp), - np.empty((1,1), dtype=np.intp)] - real_indices = {} - real_indices['raise'] = {-1:1, 4:IndexError} - real_indices['wrap'] = {-1:1, 4:0} - real_indices['clip'] = {-1:0, 4:1} - # Currently all types but object, use the same function generation. - # So it should not be necessary to test all, but the code does support it. - types = np.int, np.object - for t in types: - ta = np.array(a if issubclass(t, np.number) else a_str, dtype=t) - tresult = list(ta.T.copy()) - for index_array in index_arrays: - if index_array.size != 0: - tresult[0].shape = (2,) + index_array.shape - tresult[1].shape = (2,) + index_array.shape - for mode in modes: - for index in indices: - real_index = real_indices[mode][index] - if real_index is IndexError and index_array.size != 0: - index_array.put(0, index) - assert_raises(IndexError, ta.take, index_array, - mode=mode, axis=1) - elif index_array.size != 0: - index_array.put(0, index) - res = ta.take(index_array, mode=mode, axis=1) - assert_array_equal(res, tresult[real_index]) - else: - res = ta.take(index_array, mode=mode, axis=1) - assert_(res.shape == (2,) + index_array.shape) + +class TestTake(TestCase): + def test_simple(self): + a = [[1, 2], [3, 4]] + a_str = [[b'1', b'2'],[b'3', b'4']] + modes = ['raise', 'wrap', 'clip'] + indices = [-1, 4] + index_arrays = [np.empty(0, dtype=np.intp), + np.empty(tuple(), dtype=np.intp), + np.empty((1,1), dtype=np.intp)] + real_indices = {} + real_indices['raise'] = {-1:1, 4:IndexError} + real_indices['wrap'] = {-1:1, 4:0} + real_indices['clip'] = {-1:0, 4:1} + # Currently all types but object, use the same function generation. + # So it should not be necessary to test all. However test also a non + # refcounted struct on top of object. + types = np.int, np.object, np.dtype([('', 'i', 2)]) + for t in types: + # ta works, even if the array may be odd if buffer interface is used + ta = np.array(a if np.issubdtype(t, np.number) else a_str, dtype=t) + tresult = list(ta.T.copy()) + for index_array in index_arrays: + if index_array.size != 0: + tresult[0].shape = (2,) + index_array.shape + tresult[1].shape = (2,) + index_array.shape + for mode in modes: + for index in indices: + real_index = real_indices[mode][index] + if real_index is IndexError and index_array.size != 0: + index_array.put(0, index) + assert_raises(IndexError, ta.take, index_array, + mode=mode, axis=1) + elif index_array.size != 0: + index_array.put(0, index) + res = ta.take(index_array, mode=mode, axis=1) + assert_array_equal(res, tresult[real_index]) + else: + res = ta.take(index_array, mode=mode, axis=1) + assert_(res.shape == (2,) + index_array.shape) + + + def test_refcounting(self): + objects = [object() for i in xrange(10)] + for mode in ('raise', 'clip', 'wrap'): + a = np.array(objects) + b = np.array([2, 2, 4, 5, 3, 5]) + a.take(b, out=a[:6]) + del a + assert_(all(sys.getrefcount(o) == 3 for o in objects)) + # not contiguous, example: + a = np.array(objects * 2)[::2] + a.take(b, out=a[:6]) + del a + assert_(all(sys.getrefcount(o) == 3 for o in objects)) + if __name__ == "__main__": run_module_suite() diff --git a/numpy/core/tests/test_machar.py b/numpy/core/tests/test_machar.py index 4175ceeac..1d2c42110 100644 --- a/numpy/core/tests/test_machar.py +++ b/numpy/core/tests/test_machar.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * from numpy.core.machar import MachAr @@ -21,7 +23,7 @@ class TestMachAr(TestCase): try: try: self._run_machar_highprec() - except FloatingPointError, e: + except FloatingPointError as e: self.fail("Caught %s exception, should not have been raised." % e) finally: seterr(**serrstate) diff --git a/numpy/core/tests/test_memmap.py b/numpy/core/tests/test_memmap.py index ea9d0616d..5daeaa279 100644 --- a/numpy/core/tests/test_memmap.py +++ b/numpy/core/tests/test_memmap.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys from tempfile import NamedTemporaryFile, mktemp import os diff --git a/numpy/core/tests/test_multiarray.py b/numpy/core/tests/test_multiarray.py index 319147970..25cc8ced8 100644 --- a/numpy/core/tests/test_multiarray.py +++ b/numpy/core/tests/test_multiarray.py @@ -1,3 +1,5 @@ +from __future__ import division + import tempfile import sys import os @@ -902,6 +904,16 @@ class TestMethods(TestCase): assert_equal(np.dot(a, b), a.dot(b)) assert_equal(np.dot(np.dot(a, b), c), a.dot(b).dot(c)) + # test passing in an output array + c = np.zeros_like(a) + a.dot(b,c) + assert_equal(c, np.dot(a,b)) + + # test keyword args + c = np.zeros_like(a) + a.dot(b=b,out=c) + assert_equal(c, np.dot(a,b)) + def test_diagonal(self): a = np.arange(12).reshape((3, 4)) assert_equal(a.diagonal(), [0, 5, 10]) diff --git a/numpy/core/tests/test_multiarray_assignment.py b/numpy/core/tests/test_multiarray_assignment.py index 29ddcf906..555de8c4a 100644 --- a/numpy/core/tests/test_multiarray_assignment.py +++ b/numpy/core/tests/test_multiarray_assignment.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy as np from numpy.testing import TestCase diff --git a/numpy/core/tests/test_nditer.py b/numpy/core/tests/test_nditer.py index 4abe5e2ff..d537e4921 100644 --- a/numpy/core/tests/test_nditer.py +++ b/numpy/core/tests/test_nditer.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy as np from numpy import array, arange, nditer, all from numpy.compat import asbytes @@ -598,6 +600,8 @@ def test_iter_itershape(): [['readonly'], ['writeonly','allocate']], op_axes=[[0,1,None], None], itershape=(-1,1,4)) + # Test bug that for no op_axes but itershape, they are NULLed correctly + i = np.nditer([np.ones(2), None, None], itershape=(2,)) def test_iter_broadcasting_errors(): # Check that errors are thrown for bad broadcasting shapes @@ -632,7 +636,7 @@ def test_iter_broadcasting_errors(): [], [['readonly'], ['readonly'], ['writeonly','no_broadcast']]) assert_(False, 'Should have raised a broadcast error') - except ValueError, e: + except ValueError as e: msg = str(e) # The message should contain the shape of the 3rd operand assert_(msg.find('(2,3)') >= 0, @@ -647,7 +651,7 @@ def test_iter_broadcasting_errors(): op_axes=[[0,1], [0,np.newaxis]], itershape=(4,3)) assert_(False, 'Should have raised a broadcast error') - except ValueError, e: + except ValueError as e: msg = str(e) # The message should contain "shape->remappedshape" for each operand assert_(msg.find('(2,3)->(2,3)') >= 0, @@ -664,7 +668,7 @@ def test_iter_broadcasting_errors(): [], [['writeonly','no_broadcast'], ['readonly']]) assert_(False, 'Should have raised a broadcast error') - except ValueError, e: + except ValueError as e: msg = str(e) # The message should contain the shape of the bad operand assert_(msg.find('(2,1,1)') >= 0, diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py index b6a9c5157..6d0ca4efc 100644 --- a/numpy/core/tests/test_numeric.py +++ b/numpy/core/tests/test_numeric.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys import platform from decimal import Decimal @@ -269,7 +271,7 @@ class TestFloatExceptions(TestCase): flop(x, y) assert_(False, "Type %s did not raise fpe error '%s'." % (ftype, fpeerr)) - except FloatingPointError, exc: + except FloatingPointError as exc: assert_(str(exc).find(fpeerr) >= 0, "Type %s raised wrong fpe error '%s'." % (ftype, exc)) diff --git a/numpy/core/tests/test_numerictypes.py b/numpy/core/tests/test_numerictypes.py index 98a6e07aa..f00aee453 100644 --- a/numpy/core/tests/test_numerictypes.py +++ b/numpy/core/tests/test_numerictypes.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys from numpy.testing import * from numpy.compat import asbytes, asunicode diff --git a/numpy/core/tests/test_print.py b/numpy/core/tests/test_print.py index d40275ef4..3b9025d10 100644 --- a/numpy/core/tests/test_print.py +++ b/numpy/core/tests/test_print.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy as np from numpy.testing import * import nose @@ -225,7 +227,7 @@ def test_scalar_format(): try: assert_equal(fmat.format(val), fmat.format(valtype(val)), "failed with val %s, type %s" % (val, valtype)) - except ValueError, e: + except ValueError as e: assert_(False, "format raised exception (fmt='%s', val=%s, type=%s, exc='%s')" % (fmat, repr(val), repr(valtype), str(e))) diff --git a/numpy/core/tests/test_records.py b/numpy/core/tests/test_records.py index 87c661938..5c7cba936 100644 --- a/numpy/core/tests/test_records.py +++ b/numpy/core/tests/test_records.py @@ -1,9 +1,12 @@ +from __future__ import division + from os import path import numpy as np from numpy.testing import * from numpy.compat import asbytes, asunicode import warnings +import collections class TestFromrecords(TestCase): @@ -94,7 +97,7 @@ class TestFromrecords(TestCase): assert_array_equal(ra['shape'], [['A', 'B', 'C']]) ra.field = 5 assert_array_equal(ra['field'], [[5, 5, 5]]) - assert_(callable(ra.field)) + assert_(isinstance(ra.field, collections.Callable)) def test_fromrecords_with_explicit_dtype(self): a = np.rec.fromrecords([(1, 'a'), (2, 'bbb')], diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py index 1cf2e6e85..95df4a113 100644 --- a/numpy/core/tests/test_regression.py +++ b/numpy/core/tests/test_regression.py @@ -1,3 +1,5 @@ +from __future__ import division + import pickle import sys import platform @@ -545,6 +547,15 @@ class TestRegression(TestCase): a = np.ones((0,2)) a.shape = (-1,2) + def test_reshape_trailing_ones_strides(self): + # Github issue gh-2949, bad strides for trailing ones of new shape + a = np.zeros(12, dtype=np.int32)[::2] # not contiguous + strides_c = (16, 8, 8, 8) + strides_f = (8, 24, 48, 48) + assert_equal(a.reshape(3, 2, 1, 1).strides, strides_c) + assert_equal(a.reshape(3, 2, 1, 1, order='F').strides, strides_f) + assert_equal(np.array(0, dtype=np.int32).reshape(1,1).strides, (4,4)) + def test_repeat_discont(self, level=rlevel): """Ticket #352""" a = np.arange(12).reshape(4,3)[:,2] @@ -626,6 +637,17 @@ class TestRegression(TestCase): np.take(x,[0,2],axis=1,out=b) assert_array_equal(a,b) + def test_take_object_fail(self): + # Issue gh-3001 + d = 123. + a = np.array([d, 1], dtype=object) + ref_d = sys.getrefcount(d) + try: + a.take([0, 100]) + except IndexError: + pass + assert_(ref_d == sys.getrefcount(d)) + def test_array_str_64bit(self, level=rlevel): """Ticket #501""" s = np.array([1, np.nan],dtype=np.float64) @@ -1068,6 +1090,11 @@ class TestRegression(TestCase): assert_( a[0].tolist() == b[0]) assert_( a[1].tolist() == b[1]) + def test_nonscalar_item_method(self): + # Make sure that .item() fails graciously when it should + a = np.arange(5) + assert_raises(ValueError, a.item) + def test_char_array_creation(self, level=rlevel): a = np.array('123', dtype='c') b = np.array(asbytes_nested(['1','2','3'])) @@ -1180,10 +1207,10 @@ class TestRegression(TestCase): good = 'Maximum allowed dimension exceeded' try: np.empty(sz) - except ValueError, e: + except ValueError as e: if not str(e) == good: self.fail("Got msg '%s', expected '%s'" % (e, good)) - except Exception, e: + except Exception as e: self.fail("Got exception of type %s instead of ValueError" % type(e)) def test_huge_arange(self): @@ -1194,10 +1221,10 @@ class TestRegression(TestCase): try: a = np.arange(sz) self.assertTrue(np.size == sz) - except ValueError, e: + except ValueError as e: if not str(e) == good: self.fail("Got msg '%s', expected '%s'" % (e, good)) - except Exception, e: + except Exception as e: self.fail("Got exception of type %s instead of ValueError" % type(e)) def test_fromiter_bytes(self): @@ -1407,7 +1434,7 @@ class TestRegression(TestCase): c = a.astype(y) try: np.dot(b, c) - except TypeError, e: + except TypeError as e: failures.append((x, y)) if failures: raise AssertionError("Failures: %r" % failures) diff --git a/numpy/core/tests/test_scalarmath.py b/numpy/core/tests/test_scalarmath.py index 24b5eae24..03b90af79 100644 --- a/numpy/core/tests/test_scalarmath.py +++ b/numpy/core/tests/test_scalarmath.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys from numpy.testing import * import numpy as np diff --git a/numpy/core/tests/test_scalarprint.py b/numpy/core/tests/test_scalarprint.py index 3bed7e62a..3f791e12d 100644 --- a/numpy/core/tests/test_scalarprint.py +++ b/numpy/core/tests/test_scalarprint.py @@ -2,6 +2,7 @@ """ Test printing of scalar types. """ +from __future__ import division import numpy as np from numpy.testing import TestCase, assert_, run_module_suite diff --git a/numpy/core/tests/test_shape_base.py b/numpy/core/tests/test_shape_base.py index b02ee84a5..ccfb18ef7 100644 --- a/numpy/core/tests/test_shape_base.py +++ b/numpy/core/tests/test_shape_base.py @@ -1,3 +1,5 @@ +from __future__ import division + import warnings import numpy as np from numpy.testing import (TestCase, assert_, assert_raises, assert_array_equal, diff --git a/numpy/core/tests/test_ufunc.py b/numpy/core/tests/test_ufunc.py index 57fd66892..a0fbb4bba 100644 --- a/numpy/core/tests/test_ufunc.py +++ b/numpy/core/tests/test_ufunc.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys import numpy as np @@ -314,6 +316,8 @@ class TestUfunc(TestCase): def test_inner1d(self): a = np.arange(6).reshape((2,3)) assert_array_equal(umt.inner1d(a,a), np.sum(a*a,axis=-1)) + a = np.arange(6) + assert_array_equal(umt.inner1d(a,a), np.sum(a*a)) def test_broadcast(self): msg = "broadcast" @@ -423,6 +427,13 @@ class TestUfunc(TestCase): w = np.arange(300,324).reshape((2,3,4)) assert_array_equal(umt.innerwt(a,b,w), np.sum(a*b*w,axis=-1)) + def test_innerwt_empty(self): + """Test generalized ufunc with zero-sized operands""" + a = np.array([], dtype='f8') + b = np.array([], dtype='f8') + w = np.array([], dtype='f8') + assert_array_equal(umt.innerwt(a,b,w), np.sum(a*b*w,axis=-1)) + def test_matrix_multiply(self): self.compare_matrix_multiply_results(np.long) self.compare_matrix_multiply_results(np.double) diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py index bd281e000..78aa32234 100644 --- a/numpy/core/tests/test_umath.py +++ b/numpy/core/tests/test_umath.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys import platform diff --git a/numpy/core/tests/test_umath_complex.py b/numpy/core/tests/test_umath_complex.py index dfc5f2525..9500056bc 100644 --- a/numpy/core/tests/test_umath_complex.py +++ b/numpy/core/tests/test_umath_complex.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys import platform diff --git a/numpy/core/tests/test_unicode.py b/numpy/core/tests/test_unicode.py index 5bcf464bc..8941f8e82 100644 --- a/numpy/core/tests/test_unicode.py +++ b/numpy/core/tests/test_unicode.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys from numpy.testing import * diff --git a/numpy/ctypeslib.py b/numpy/ctypeslib.py index c11900947..e111fdb83 100644 --- a/numpy/ctypeslib.py +++ b/numpy/ctypeslib.py @@ -49,6 +49,8 @@ Then, we're ready to call ``foo_func``: >>> _lib.foo_func(out, len(out)) #doctest: +SKIP """ +from __future__ import division + __all__ = ['load_library', 'ndpointer', 'test', 'ctypes_load_library', 'c_intp', 'as_ctypes', 'as_array'] @@ -126,7 +128,7 @@ else: try: libpath = os.path.join(libdir, ln) return ctypes.cdll[libpath] - except OSError, e: + except OSError as e: exc = e raise exc diff --git a/numpy/distutils/__init__.py b/numpy/distutils/__init__.py index cdc5d45b6..5b68de74f 100644 --- a/numpy/distutils/__init__.py +++ b/numpy/distutils/__init__.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys if sys.version_info[0] < 3: diff --git a/numpy/distutils/__version__.py b/numpy/distutils/__version__.py index 06077f79c..c9af8cdb1 100644 --- a/numpy/distutils/__version__.py +++ b/numpy/distutils/__version__.py @@ -1,3 +1,5 @@ +from __future__ import division + major = 0 minor = 4 micro = 0 diff --git a/numpy/distutils/ccompiler.py b/numpy/distutils/ccompiler.py index e3b88af08..4478154f8 100644 --- a/numpy/distutils/ccompiler.py +++ b/numpy/distutils/ccompiler.py @@ -1,3 +1,5 @@ +from __future__ import division + import re import os import sys diff --git a/numpy/distutils/command/__init__.py b/numpy/distutils/command/__init__.py index f8f0884da..09fe78d22 100644 --- a/numpy/distutils/command/__init__.py +++ b/numpy/distutils/command/__init__.py @@ -1,7 +1,17 @@ """distutils.command Package containing implementation of all the standard Distutils -commands.""" +commands. + +""" +from __future__ import division + +def test_na_writable_attributes_deletion(): + a = np.NA(2) + attr = ['payload', 'dtype'] + for s in attr: + assert_raises(AttributeError, delattr, a, s) + __revision__ = "$Id: __init__.py,v 1.3 2005/05/16 11:08:49 pearu Exp $" diff --git a/numpy/distutils/command/autodist.py b/numpy/distutils/command/autodist.py index fe40119ef..2e31fe22a 100644 --- a/numpy/distutils/command/autodist.py +++ b/numpy/distutils/command/autodist.py @@ -1,4 +1,8 @@ -"""This module implements additional tests ala autoconf which can be useful.""" +"""This module implements additional tests ala autoconf which can be useful. + +""" +from __future__ import division + # We put them here since they could be easily reused outside numpy.distutils diff --git a/numpy/distutils/command/bdist_rpm.py b/numpy/distutils/command/bdist_rpm.py index 60e9b5752..302c6fdd2 100644 --- a/numpy/distutils/command/bdist_rpm.py +++ b/numpy/distutils/command/bdist_rpm.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import sys if 'setuptools' in sys.modules: diff --git a/numpy/distutils/command/build.py b/numpy/distutils/command/build.py index 5d986570c..239cafe1e 100644 --- a/numpy/distutils/command/build.py +++ b/numpy/distutils/command/build.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import sys from distutils.command.build import build as old_build diff --git a/numpy/distutils/command/build_clib.py b/numpy/distutils/command/build_clib.py index d9cfca73e..99144d7b5 100644 --- a/numpy/distutils/command/build_clib.py +++ b/numpy/distutils/command/build_clib.py @@ -1,5 +1,6 @@ """ Modified version of build_clib that handles fortran source files. """ +from __future__ import division import os from glob import glob diff --git a/numpy/distutils/command/build_ext.py b/numpy/distutils/command/build_ext.py index 3a552897c..2245661a5 100644 --- a/numpy/distutils/command/build_ext.py +++ b/numpy/distutils/command/build_ext.py @@ -1,5 +1,7 @@ """ Modified version of build_ext that handles fortran source files. + """ +from __future__ import division import os import sys diff --git a/numpy/distutils/command/build_py.py b/numpy/distutils/command/build_py.py index 4c02e4136..e8c7b8f83 100644 --- a/numpy/distutils/command/build_py.py +++ b/numpy/distutils/command/build_py.py @@ -1,3 +1,4 @@ +from __future__ import division from distutils.command.build_py import build_py as old_build_py from numpy.distutils.misc_util import is_string @@ -21,7 +22,7 @@ class build_py(old_build_py): def find_modules(self): old_py_modules = self.py_modules[:] - new_py_modules = filter(is_string, self.py_modules) + new_py_modules = [_m for _m in self.py_modules if is_string(_m)] self.py_modules[:] = new_py_modules modules = old_build_py.find_modules(self) self.py_modules[:] = old_py_modules diff --git a/numpy/distutils/command/build_scripts.py b/numpy/distutils/command/build_scripts.py index 99134f202..1a3d26d58 100644 --- a/numpy/distutils/command/build_scripts.py +++ b/numpy/distutils/command/build_scripts.py @@ -1,5 +1,7 @@ """ Modified version of build_scripts that handles building scripts from functions. + """ +from __future__ import division from distutils.command.build_scripts import build_scripts as old_build_scripts from numpy.distutils import log diff --git a/numpy/distutils/command/build_src.py b/numpy/distutils/command/build_src.py index 7bf3b43ce..a9e66e6f4 100644 --- a/numpy/distutils/command/build_src.py +++ b/numpy/distutils/command/build_src.py @@ -1,5 +1,6 @@ """ Build swig, f2py, pyrex sources. """ +from __future__ import division import os import re @@ -186,10 +187,10 @@ class build_src(build_ext.build_ext): build_dir = self.get_package_dir('.'.join(d.split(os.sep))) else: build_dir = os.path.join(self.build_src,d) - funcs = filter(lambda f:hasattr(f, '__call__'), files) - files = filter(lambda f:not hasattr(f, '__call__'), files) + funcs = [f for f in files if hasattr(f, '__call__')] + files = [f for f in files if not hasattr(f, '__call__')] for f in funcs: - if f.func_code.co_argcount==1: + if f.__code__.co_argcount==1: s = f(build_dir) else: s = f() diff --git a/numpy/distutils/command/config.py b/numpy/distutils/command/config.py index 85a86990f..3417fac44 100644 --- a/numpy/distutils/command/config.py +++ b/numpy/distutils/command/config.py @@ -2,6 +2,7 @@ # try_compile call. try_run works but is untested for most of Fortran # compilers (they must define linker_exe first). # Pearu Peterson +from __future__ import division import os, signal import warnings diff --git a/numpy/distutils/command/config_compiler.py b/numpy/distutils/command/config_compiler.py index e7fee94df..6894b4552 100644 --- a/numpy/distutils/command/config_compiler.py +++ b/numpy/distutils/command/config_compiler.py @@ -1,3 +1,5 @@ +from __future__ import division + from distutils.core import Command from numpy.distutils import log diff --git a/numpy/distutils/command/develop.py b/numpy/distutils/command/develop.py index 167706671..8328effcf 100644 --- a/numpy/distutils/command/develop.py +++ b/numpy/distutils/command/develop.py @@ -1,7 +1,9 @@ """ Override the develop command from setuptools so we can ensure that our generated files (from build_src or build_scripts) are properly converted to real files with filenames. + """ +from __future__ import division from setuptools.command.develop import develop as old_develop diff --git a/numpy/distutils/command/egg_info.py b/numpy/distutils/command/egg_info.py index 687faf080..33c64b0e4 100644 --- a/numpy/distutils/command/egg_info.py +++ b/numpy/distutils/command/egg_info.py @@ -1,3 +1,5 @@ +from __future__ import division + from setuptools.command.egg_info import egg_info as _egg_info class egg_info(_egg_info): diff --git a/numpy/distutils/command/install.py b/numpy/distutils/command/install.py index ad3cc507d..ea898ade9 100644 --- a/numpy/distutils/command/install.py +++ b/numpy/distutils/command/install.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys if 'setuptools' in sys.modules: import setuptools.command.install as old_install_mod diff --git a/numpy/distutils/command/install_clib.py b/numpy/distutils/command/install_clib.py index 638d4beac..8845cedab 100644 --- a/numpy/distutils/command/install_clib.py +++ b/numpy/distutils/command/install_clib.py @@ -1,3 +1,5 @@ +from __future__ import division + import os from distutils.core import Command from distutils.ccompiler import new_compiler diff --git a/numpy/distutils/command/install_data.py b/numpy/distutils/command/install_data.py index 0a2e68ae1..d99d656db 100644 --- a/numpy/distutils/command/install_data.py +++ b/numpy/distutils/command/install_data.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys have_setuptools = ('setuptools' in sys.modules) diff --git a/numpy/distutils/command/install_headers.py b/numpy/distutils/command/install_headers.py index 58ace1064..548c3c643 100644 --- a/numpy/distutils/command/install_headers.py +++ b/numpy/distutils/command/install_headers.py @@ -1,3 +1,5 @@ +from __future__ import division + import os from distutils.command.install_headers import install_headers as old_install_headers diff --git a/numpy/distutils/command/sdist.py b/numpy/distutils/command/sdist.py index 62fce9574..3e07f7a01 100644 --- a/numpy/distutils/command/sdist.py +++ b/numpy/distutils/command/sdist.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys if 'setuptools' in sys.modules: from setuptools.command.sdist import sdist as old_sdist diff --git a/numpy/distutils/compat.py b/numpy/distutils/compat.py index 1c37dc2b9..55b9627d5 100644 --- a/numpy/distutils/compat.py +++ b/numpy/distutils/compat.py @@ -1,6 +1,9 @@ """Small modules to cope with python 2 vs 3 incompatibilities inside numpy.distutils + """ +from __future__ import division + import sys def get_exception(): diff --git a/numpy/distutils/conv_template.py b/numpy/distutils/conv_template.py index 368cdd457..61200e0c1 100644 --- a/numpy/distutils/conv_template.py +++ b/numpy/distutils/conv_template.py @@ -78,6 +78,8 @@ Example: 3, 3, jim """ +from __future__ import division + __all__ = ['process_str', 'process_file'] diff --git a/numpy/distutils/core.py b/numpy/distutils/core.py index 535b5ed52..092ea4442 100644 --- a/numpy/distutils/core.py +++ b/numpy/distutils/core.py @@ -1,3 +1,4 @@ +from __future__ import division import sys from distutils.core import * diff --git a/numpy/distutils/cpuinfo.py b/numpy/distutils/cpuinfo.py index a9b2af108..86a18993a 100644 --- a/numpy/distutils/cpuinfo.py +++ b/numpy/distutils/cpuinfo.py @@ -10,7 +10,9 @@ this distribution for specifics. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. Pearu Peterson + """ +from __future__ import division __all__ = ['cpu'] @@ -516,7 +518,7 @@ class Win32CPUInfo(CPUInfoBase): info[-1]["Model"]=int(srch.group("MDL")) info[-1]["Stepping"]=int(srch.group("STP")) except: - print(sys.exc_value,'(ignoring)') + print(sys.exc_info()[1],'(ignoring)') self.__class__.info = info def _not_impl(self): pass diff --git a/numpy/distutils/environment.py b/numpy/distutils/environment.py index 7d3ae56ae..015815cbe 100644 --- a/numpy/distutils/environment.py +++ b/numpy/distutils/environment.py @@ -1,3 +1,5 @@ +from __future__ import division + import os from distutils.dist import Distribution diff --git a/numpy/distutils/exec_command.py b/numpy/distutils/exec_command.py index 7657b8735..f05b56429 100644 --- a/numpy/distutils/exec_command.py +++ b/numpy/distutils/exec_command.py @@ -44,6 +44,7 @@ Known bugs: - Tests, that send messages to stderr, fail when executed from MSYS prompt because the messages are lost at some point. """ +from __future__ import division __all__ = ['exec_command','find_executable'] diff --git a/numpy/distutils/extension.py b/numpy/distutils/extension.py index 2fc29f6d5..95213644f 100644 --- a/numpy/distutils/extension.py +++ b/numpy/distutils/extension.py @@ -4,7 +4,9 @@ Provides the Extension class, used to describe C/C++ extension modules in setup scripts. Overridden to support f2py. + """ +from __future__ import division __revision__ = "$Id: extension.py,v 1.1 2005/04/09 19:29:34 pearu Exp $" diff --git a/numpy/distutils/fcompiler/__init__.py b/numpy/distutils/fcompiler/__init__.py index 6f92af96c..70093e037 100644 --- a/numpy/distutils/fcompiler/__init__.py +++ b/numpy/distutils/fcompiler/__init__.py @@ -11,7 +11,9 @@ file, like 'gcc', that is executed, and should be a string. In contrast, should be a list. But note that FCompiler.executables is actually a dictionary of commands. + """ +from __future__ import division __all__ = ['FCompiler','new_fcompiler','show_fcompilers', 'dummy_fortran_file'] diff --git a/numpy/distutils/fcompiler/absoft.py b/numpy/distutils/fcompiler/absoft.py index e36f0ff78..7c06d70a3 100644 --- a/numpy/distutils/fcompiler/absoft.py +++ b/numpy/distutils/fcompiler/absoft.py @@ -5,6 +5,7 @@ # Notes: # - when using -g77 then use -DUNDERSCORE_G77 to compile f2py # generated extension modules (works for f2py v2.45.241_1936 and up) +from __future__ import division import os diff --git a/numpy/distutils/fcompiler/compaq.py b/numpy/distutils/fcompiler/compaq.py index a00d8bdb8..d67c1f24e 100644 --- a/numpy/distutils/fcompiler/compaq.py +++ b/numpy/distutils/fcompiler/compaq.py @@ -1,5 +1,6 @@ #http://www.compaq.com/fortran/docs/ +from __future__ import division import os import sys diff --git a/numpy/distutils/fcompiler/g95.py b/numpy/distutils/fcompiler/g95.py index 9352a0b7b..478f48f3e 100644 --- a/numpy/distutils/fcompiler/g95.py +++ b/numpy/distutils/fcompiler/g95.py @@ -1,4 +1,5 @@ # http://g95.sourceforge.net/ +from __future__ import division from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/gnu.py b/numpy/distutils/fcompiler/gnu.py index bb832991f..a2e613d0c 100644 --- a/numpy/distutils/fcompiler/gnu.py +++ b/numpy/distutils/fcompiler/gnu.py @@ -1,3 +1,5 @@ +from __future__ import division + import re import os import sys diff --git a/numpy/distutils/fcompiler/hpux.py b/numpy/distutils/fcompiler/hpux.py index 866920ee5..44bfbe1c2 100644 --- a/numpy/distutils/fcompiler/hpux.py +++ b/numpy/distutils/fcompiler/hpux.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.distutils.fcompiler import FCompiler compilers = ['HPUXFCompiler'] diff --git a/numpy/distutils/fcompiler/ibm.py b/numpy/distutils/fcompiler/ibm.py index 113134bbd..70373c0b0 100644 --- a/numpy/distutils/fcompiler/ibm.py +++ b/numpy/distutils/fcompiler/ibm.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import re import sys diff --git a/numpy/distutils/fcompiler/intel.py b/numpy/distutils/fcompiler/intel.py index 281bbe0cb..53ea7af05 100644 --- a/numpy/distutils/fcompiler/intel.py +++ b/numpy/distutils/fcompiler/intel.py @@ -1,4 +1,5 @@ # http://developer.intel.com/software/products/compilers/flin/ +from __future__ import division import sys diff --git a/numpy/distutils/fcompiler/lahey.py b/numpy/distutils/fcompiler/lahey.py index cf2950624..06c4c6f56 100644 --- a/numpy/distutils/fcompiler/lahey.py +++ b/numpy/distutils/fcompiler/lahey.py @@ -1,3 +1,5 @@ +from __future__ import division + import os from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/mips.py b/numpy/distutils/fcompiler/mips.py index 3c2e9ac84..6cd2fdfac 100644 --- a/numpy/distutils/fcompiler/mips.py +++ b/numpy/distutils/fcompiler/mips.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/nag.py b/numpy/distutils/fcompiler/nag.py index 4aca48450..11253c4be 100644 --- a/numpy/distutils/fcompiler/nag.py +++ b/numpy/distutils/fcompiler/nag.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/none.py b/numpy/distutils/fcompiler/none.py index 526b42d49..e99c2ab35 100644 --- a/numpy/distutils/fcompiler/none.py +++ b/numpy/distutils/fcompiler/none.py @@ -1,3 +1,4 @@ +from __future__ import division from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/pathf95.py b/numpy/distutils/fcompiler/pathf95.py index 29881f4cf..c9bd58c62 100644 --- a/numpy/distutils/fcompiler/pathf95.py +++ b/numpy/distutils/fcompiler/pathf95.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.distutils.fcompiler import FCompiler compilers = ['PathScaleFCompiler'] diff --git a/numpy/distutils/fcompiler/pg.py b/numpy/distutils/fcompiler/pg.py index 6ea3c03d6..e0f5e0d44 100644 --- a/numpy/distutils/fcompiler/pg.py +++ b/numpy/distutils/fcompiler/pg.py @@ -1,5 +1,5 @@ - # http://www.pgroup.com +from __future__ import division from numpy.distutils.fcompiler import FCompiler from sys import platform diff --git a/numpy/distutils/fcompiler/sun.py b/numpy/distutils/fcompiler/sun.py index 85e2c3377..7deeac29a 100644 --- a/numpy/distutils/fcompiler/sun.py +++ b/numpy/distutils/fcompiler/sun.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.distutils.ccompiler import simple_version_match from numpy.distutils.fcompiler import FCompiler diff --git a/numpy/distutils/fcompiler/vast.py b/numpy/distutils/fcompiler/vast.py index a7b99ce73..bddc1be91 100644 --- a/numpy/distutils/fcompiler/vast.py +++ b/numpy/distutils/fcompiler/vast.py @@ -1,3 +1,5 @@ +from __future__ import division + import os from numpy.distutils.fcompiler.gnu import GnuFCompiler diff --git a/numpy/distutils/from_template.py b/numpy/distutils/from_template.py index 413f0721d..1bb7a0a27 100644 --- a/numpy/distutils/from_template.py +++ b/numpy/distutils/from_template.py @@ -45,6 +45,7 @@ process_file(filename) <ctypereal=float,double,\\0,\\1> """ +from __future__ import division __all__ = ['process_str','process_file'] diff --git a/numpy/distutils/info.py b/numpy/distutils/info.py index 3d27a8092..4d8b847bd 100644 --- a/numpy/distutils/info.py +++ b/numpy/distutils/info.py @@ -1,5 +1,6 @@ """ Enhanced distutils with Fortran compilers support and more. """ +from __future__ import division postpone_import = True diff --git a/numpy/distutils/intelccompiler.py b/numpy/distutils/intelccompiler.py index 9cff858ce..8c3af0957 100644 --- a/numpy/distutils/intelccompiler.py +++ b/numpy/distutils/intelccompiler.py @@ -1,3 +1,5 @@ +from __future__ import division + from distutils.unixccompiler import UnixCCompiler from numpy.distutils.exec_command import find_executable diff --git a/numpy/distutils/interactive.py b/numpy/distutils/interactive.py index e3dba04eb..a75d5a7e8 100644 --- a/numpy/distutils/interactive.py +++ b/numpy/distutils/interactive.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import sys from pprint import pformat @@ -87,7 +89,7 @@ def interactive_sys_argv(argv): import atexit atexit.register(readline.write_history_file, histfile) except AttributeError: pass - except Exception, msg: + except Exception as msg: print msg task_dict = {'i':show_information, @@ -178,7 +180,7 @@ def interactive_sys_argv(argv): print '-'*68 try: task_func(argv,readline) - except Exception,msg: + except Exception as msg: print 'Failed running task %s: %s' % (task,msg) break print '-'*68 diff --git a/numpy/distutils/lib2def.py b/numpy/distutils/lib2def.py index a486b13bd..0e98e17ef 100644 --- a/numpy/distutils/lib2def.py +++ b/numpy/distutils/lib2def.py @@ -1,3 +1,5 @@ +from __future__ import division + import re import sys import os diff --git a/numpy/distutils/line_endings.py b/numpy/distutils/line_endings.py index 4e6c1f38e..f18850716 100644 --- a/numpy/distutils/line_endings.py +++ b/numpy/distutils/line_endings.py @@ -1,5 +1,7 @@ """ Functions for converting from DOS to UNIX line endings + """ +from __future__ import division import sys, re, os diff --git a/numpy/distutils/log.py b/numpy/distutils/log.py index fe44bb443..a3f4cb9ff 100644 --- a/numpy/distutils/log.py +++ b/numpy/distutils/log.py @@ -1,4 +1,5 @@ # Colored log, requires Python 2.3 or up. +from __future__ import division import sys from distutils.log import * diff --git a/numpy/distutils/mingw32ccompiler.py b/numpy/distutils/mingw32ccompiler.py index ed9801ceb..10e3608ef 100644 --- a/numpy/distutils/mingw32ccompiler.py +++ b/numpy/distutils/mingw32ccompiler.py @@ -7,6 +7,7 @@ Support code for building Python extensions on Windows. # 3. Force windows to use g77 """ +from __future__ import division import os import subprocess @@ -199,10 +200,7 @@ class Mingw32CCompiler(distutils.cygwinccompiler.CygwinCCompiler): func = distutils.cygwinccompiler.CygwinCCompiler.link else: func = UnixCCompiler.link - if sys.version_info[0] >= 3: - func(*args[:func.__code__.co_argcount]) - else: - func(*args[:func.im_func.func_code.co_argcount]) + func(*args[:func.__code__.co_argcount]) return def object_filenames (self, diff --git a/numpy/distutils/misc_util.py b/numpy/distutils/misc_util.py index 3a9eb3b13..c22aacb9a 100644 --- a/numpy/distutils/misc_util.py +++ b/numpy/distutils/misc_util.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import re import sys @@ -555,7 +557,7 @@ def general_source_directories_files(top_path): def get_ext_source_files(ext): # Get sources and any include files in the same directory. filenames = [] - sources = filter(is_string, ext.sources) + sources = [_m for _m in ext.sources if is_string(_m)] filenames.extend(sources) filenames.extend(get_dependencies(sources)) for d in ext.depends: @@ -566,13 +568,13 @@ def get_ext_source_files(ext): return filenames def get_script_files(scripts): - scripts = filter(is_string, scripts) + scripts = [_m for _m in scripts if is_string(_m)] return scripts def get_lib_source_files(lib): filenames = [] sources = lib[1].get('sources',[]) - sources = filter(is_string, sources) + sources = [_m for _m in sources if is_string(_m)] filenames.extend(sources) filenames.extend(get_dependencies(sources)) depends = lib[1].get('depends',[]) @@ -808,7 +810,7 @@ class Configuration(object): caller_level = 1): l = subpackage_name.split('.') subpackage_path = njoin([self.local_path]+l) - dirs = filter(os.path.isdir,glob.glob(subpackage_path)) + dirs = [_m for _m in glob.glob(subpackage_path) if os.path.isdir(_m)] config_list = [] for d in dirs: if not os.path.isfile(njoin(d,'__init__.py')): @@ -850,7 +852,7 @@ class Configuration(object): pn = dot_join(*([parent_name] + subpackage_name.split('.')[:-1])) args = (pn,) def fix_args_py2(args): - if setup_module.configuration.func_code.co_argcount > 1: + if setup_module.configuration.__code__.co_argcount > 1: args = args + (self.top_path,) return args def fix_args_py3(args): diff --git a/numpy/distutils/npy_pkg_config.py b/numpy/distutils/npy_pkg_config.py index 4f64623ed..6f3072885 100644 --- a/numpy/distutils/npy_pkg_config.py +++ b/numpy/distutils/npy_pkg_config.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys if sys.version_info[0] < 3: from ConfigParser import SafeConfigParser, NoOptionError @@ -238,11 +240,11 @@ def parse_meta(config): d[name] = value for k in ['name', 'description', 'version']: - if not d.has_key(k): + if not k in d: raise FormatError("Option %s (section [meta]) is mandatory, " "but not found" % k) - if not d.has_key('requires'): + if not 'requires' in d: d['requires'] = [] return d @@ -313,7 +315,7 @@ def _read_config_imp(filenames, dirs=None): # Update var dict for variables not in 'top' config file for k, v in nvars.items(): - if not vars.has_key(k): + if not k in vars: vars[k] = v # Update sec dict @@ -328,7 +330,7 @@ def _read_config_imp(filenames, dirs=None): # FIXME: document this. If pkgname is defined in the variables section, and # there is no pkgdir variable defined, pkgdir is automatically defined to # the path of pkgname. This requires the package to be imported to work - if not vars.has_key("pkgdir") and vars.has_key("pkgname"): + if not 'pkgdir' in vars and "pkgname" in vars: pkgname = vars["pkgname"] if not pkgname in sys.modules: raise ValueError("You should import %s to get information on %s" % diff --git a/numpy/distutils/numpy_distribution.py b/numpy/distutils/numpy_distribution.py index ea8182659..276f81398 100644 --- a/numpy/distutils/numpy_distribution.py +++ b/numpy/distutils/numpy_distribution.py @@ -1,4 +1,6 @@ # XXX: Handle setuptools ? +from __future__ import division + from distutils.core import Distribution # This class is used because we add new files (sconscripts, and so on) with the diff --git a/numpy/distutils/pathccompiler.py b/numpy/distutils/pathccompiler.py index 48051810e..2e5b76a53 100644 --- a/numpy/distutils/pathccompiler.py +++ b/numpy/distutils/pathccompiler.py @@ -1,3 +1,5 @@ +from __future__ import division + from distutils.unixccompiler import UnixCCompiler class PathScaleCCompiler(UnixCCompiler): diff --git a/numpy/distutils/setup.py b/numpy/distutils/setup.py index afc1fadd2..1d29d706c 100644 --- a/numpy/distutils/setup.py +++ b/numpy/distutils/setup.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +from __future__ import division def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration diff --git a/numpy/distutils/system_info.py b/numpy/distutils/system_info.py index 4dd3d4b6b..68a9ba5a9 100644 --- a/numpy/distutils/system_info.py +++ b/numpy/distutils/system_info.py @@ -108,7 +108,9 @@ terms of the NumPy (BSD style) license. See LICENSE.txt that came with this distribution for specifics. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + """ +from __future__ import division import sys import os @@ -232,9 +234,9 @@ if os.path.join(sys.prefix, 'lib') not in default_lib_dirs: default_include_dirs.append(os.path.join(sys.prefix, 'include')) default_src_dirs.append(os.path.join(sys.prefix, 'src')) -default_lib_dirs = filter(os.path.isdir, default_lib_dirs) -default_include_dirs = filter(os.path.isdir, default_include_dirs) -default_src_dirs = filter(os.path.isdir, default_src_dirs) +default_lib_dirs = [_m for _m in default_lib_dirs if os.path.isdir(_m)] +default_include_dirs = [_m for _m in default_include_dirs if os.path.isdir(_m)] +default_src_dirs = [_m for _m in default_src_dirs if os.path.isdir(_m)] so_ext = get_shared_lib_extension() @@ -1667,7 +1669,7 @@ class _numpy_info(system_info): ## (self.modulename.upper()+'_VERSION_HEX', ## hex(vstr2hex(module.__version__))), ## ) -## except Exception,msg: +## except Exception as msg: ## print msg dict_append(info, define_macros=macros) include_dirs = self.get_include_dirs() diff --git a/numpy/distutils/tests/f2py_ext/__init__.py b/numpy/distutils/tests/f2py_ext/__init__.py index e69de29bb..b06eaf1a4 100644 --- a/numpy/distutils/tests/f2py_ext/__init__.py +++ b/numpy/distutils/tests/f2py_ext/__init__.py @@ -0,0 +1 @@ +from __future__ import division diff --git a/numpy/distutils/tests/f2py_ext/setup.py b/numpy/distutils/tests/f2py_ext/setup.py index e3dfddb74..edaa22287 100644 --- a/numpy/distutils/tests/f2py_ext/setup.py +++ b/numpy/distutils/tests/f2py_ext/setup.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import division + def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('f2py_ext',parent_package,top_path) diff --git a/numpy/distutils/tests/f2py_ext/tests/test_fib2.py b/numpy/distutils/tests/f2py_ext/tests/test_fib2.py index 027f455de..696ee41d8 100644 --- a/numpy/distutils/tests/f2py_ext/tests/test_fib2.py +++ b/numpy/distutils/tests/f2py_ext/tests/test_fib2.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys from numpy.testing import * from f2py_ext import fib2 diff --git a/numpy/distutils/tests/f2py_f90_ext/__init__.py b/numpy/distutils/tests/f2py_f90_ext/__init__.py index e69de29bb..b06eaf1a4 100644 --- a/numpy/distutils/tests/f2py_f90_ext/__init__.py +++ b/numpy/distutils/tests/f2py_f90_ext/__init__.py @@ -0,0 +1 @@ +from __future__ import division diff --git a/numpy/distutils/tests/f2py_f90_ext/setup.py b/numpy/distutils/tests/f2py_f90_ext/setup.py index ee56cc3a6..0a6bea989 100644 --- a/numpy/distutils/tests/f2py_f90_ext/setup.py +++ b/numpy/distutils/tests/f2py_f90_ext/setup.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import division + def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('f2py_f90_ext',parent_package,top_path) diff --git a/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py b/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py index 1543051dc..3fa7b3730 100644 --- a/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py +++ b/numpy/distutils/tests/f2py_f90_ext/tests/test_foo.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys from numpy.testing import * from f2py_f90_ext import foo diff --git a/numpy/distutils/tests/gen_ext/__init__.py b/numpy/distutils/tests/gen_ext/__init__.py index e69de29bb..b06eaf1a4 100644 --- a/numpy/distutils/tests/gen_ext/__init__.py +++ b/numpy/distutils/tests/gen_ext/__init__.py @@ -0,0 +1 @@ +from __future__ import division diff --git a/numpy/distutils/tests/gen_ext/setup.py b/numpy/distutils/tests/gen_ext/setup.py index bf029062c..cbf135dc1 100644 --- a/numpy/distutils/tests/gen_ext/setup.py +++ b/numpy/distutils/tests/gen_ext/setup.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +from __future__ import division fib3_f = ''' C FILE: FIB3.F diff --git a/numpy/distutils/tests/gen_ext/tests/test_fib3.py b/numpy/distutils/tests/gen_ext/tests/test_fib3.py index 8a9a443a5..3fa72036e 100644 --- a/numpy/distutils/tests/gen_ext/tests/test_fib3.py +++ b/numpy/distutils/tests/gen_ext/tests/test_fib3.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys from numpy.testing import * from gen_ext import fib3 diff --git a/numpy/distutils/tests/pyrex_ext/__init__.py b/numpy/distutils/tests/pyrex_ext/__init__.py index e69de29bb..b06eaf1a4 100644 --- a/numpy/distutils/tests/pyrex_ext/__init__.py +++ b/numpy/distutils/tests/pyrex_ext/__init__.py @@ -0,0 +1 @@ +from __future__ import division diff --git a/numpy/distutils/tests/pyrex_ext/setup.py b/numpy/distutils/tests/pyrex_ext/setup.py index 5b348b916..287ec5e3b 100644 --- a/numpy/distutils/tests/pyrex_ext/setup.py +++ b/numpy/distutils/tests/pyrex_ext/setup.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import division + def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('pyrex_ext',parent_package,top_path) diff --git a/numpy/distutils/tests/pyrex_ext/tests/test_primes.py b/numpy/distutils/tests/pyrex_ext/tests/test_primes.py index eb2c91da7..96f73c426 100644 --- a/numpy/distutils/tests/pyrex_ext/tests/test_primes.py +++ b/numpy/distutils/tests/pyrex_ext/tests/test_primes.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys from numpy.testing import * from pyrex_ext.primes import primes diff --git a/numpy/distutils/tests/setup.py b/numpy/distutils/tests/setup.py index 89d73800e..c472e1788 100644 --- a/numpy/distutils/tests/setup.py +++ b/numpy/distutils/tests/setup.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import division + def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('testnumpydistutils',parent_package,top_path) diff --git a/numpy/distutils/tests/swig_ext/__init__.py b/numpy/distutils/tests/swig_ext/__init__.py index e69de29bb..b06eaf1a4 100644 --- a/numpy/distutils/tests/swig_ext/__init__.py +++ b/numpy/distutils/tests/swig_ext/__init__.py @@ -0,0 +1 @@ +from __future__ import division diff --git a/numpy/distutils/tests/swig_ext/setup.py b/numpy/distutils/tests/swig_ext/setup.py index 7f0dbe627..99b688985 100644 --- a/numpy/distutils/tests/swig_ext/setup.py +++ b/numpy/distutils/tests/swig_ext/setup.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import division + def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('swig_ext',parent_package,top_path) diff --git a/numpy/distutils/tests/swig_ext/tests/test_example.py b/numpy/distutils/tests/swig_ext/tests/test_example.py index 9afc01cb2..5a4765fa7 100644 --- a/numpy/distutils/tests/swig_ext/tests/test_example.py +++ b/numpy/distutils/tests/swig_ext/tests/test_example.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys from numpy.testing import * from swig_ext import example diff --git a/numpy/distutils/tests/swig_ext/tests/test_example2.py b/numpy/distutils/tests/swig_ext/tests/test_example2.py index 42d1fcbcd..c3c4727c0 100644 --- a/numpy/distutils/tests/swig_ext/tests/test_example2.py +++ b/numpy/distutils/tests/swig_ext/tests/test_example2.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys from numpy.testing import * from swig_ext import example2 diff --git a/numpy/distutils/tests/test_fcompiler_gnu.py b/numpy/distutils/tests/test_fcompiler_gnu.py index 6a36fb160..d3b38db23 100644 --- a/numpy/distutils/tests/test_fcompiler_gnu.py +++ b/numpy/distutils/tests/test_fcompiler_gnu.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * import numpy.distutils.fcompiler diff --git a/numpy/distutils/tests/test_fcompiler_intel.py b/numpy/distutils/tests/test_fcompiler_intel.py index ad03daeea..4ebf1a0c0 100644 --- a/numpy/distutils/tests/test_fcompiler_intel.py +++ b/numpy/distutils/tests/test_fcompiler_intel.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * import numpy.distutils.fcompiler diff --git a/numpy/distutils/tests/test_misc_util.py b/numpy/distutils/tests/test_misc_util.py index 448800b68..57fde8899 100644 --- a/numpy/distutils/tests/test_misc_util.py +++ b/numpy/distutils/tests/test_misc_util.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +from __future__ import division from numpy.testing import * from numpy.distutils.misc_util import appendpath, minrelpath, gpaths, rel_path diff --git a/numpy/distutils/tests/test_npy_pkg_config.py b/numpy/distutils/tests/test_npy_pkg_config.py index 6122e303b..d3568eb6b 100644 --- a/numpy/distutils/tests/test_npy_pkg_config.py +++ b/numpy/distutils/tests/test_npy_pkg_config.py @@ -1,3 +1,5 @@ +from __future__ import division + import os from tempfile import mkstemp diff --git a/numpy/distutils/unixccompiler.py b/numpy/distutils/unixccompiler.py index dfc5a676f..837ce5092 100644 --- a/numpy/distutils/unixccompiler.py +++ b/numpy/distutils/unixccompiler.py @@ -1,6 +1,8 @@ """ unixccompiler - can handle very long argument lists for ar. + """ +from __future__ import division import os diff --git a/numpy/doc/__init__.py b/numpy/doc/__init__.py index 6589b5492..19b3d87db 100644 --- a/numpy/doc/__init__.py +++ b/numpy/doc/__init__.py @@ -1,3 +1,5 @@ +from __future__ import division + import os ref_dir = os.path.join(os.path.dirname(__file__)) diff --git a/numpy/doc/basics.py b/numpy/doc/basics.py index 1d0f183e3..d50388282 100644 --- a/numpy/doc/basics.py +++ b/numpy/doc/basics.py @@ -136,3 +136,5 @@ value is inside an array or not. NumPy scalars also have many of the same methods arrays do. """ +from __future__ import division + diff --git a/numpy/doc/broadcasting.py b/numpy/doc/broadcasting.py index 7b6179663..be6cde0bd 100644 --- a/numpy/doc/broadcasting.py +++ b/numpy/doc/broadcasting.py @@ -175,3 +175,5 @@ See `this article <http://www.scipy.org/EricsBroadcastingDoc>`_ for illustrations of broadcasting concepts. """ +from __future__ import division + diff --git a/numpy/doc/byteswapping.py b/numpy/doc/byteswapping.py index 23e7d7f6e..395c858ed 100644 --- a/numpy/doc/byteswapping.py +++ b/numpy/doc/byteswapping.py @@ -1,4 +1,4 @@ -''' +""" ============================= Byteswapping and byte order @@ -134,4 +134,6 @@ the previous operations: >>> swapped_end_arr.tostring() == big_end_str False -''' +""" +from __future__ import division + diff --git a/numpy/doc/constants.py b/numpy/doc/constants.py index 722147dd8..10f41a7ba 100644 --- a/numpy/doc/constants.py +++ b/numpy/doc/constants.py @@ -10,6 +10,8 @@ Numpy includes several constants: # # Note: the docstring is autogenerated. # +from __future__ import division + import textwrap, re # Maintain same format as in numpy.add_newdocs diff --git a/numpy/doc/creation.py b/numpy/doc/creation.py index 9a204e252..f14b163e6 100644 --- a/numpy/doc/creation.py +++ b/numpy/doc/creation.py @@ -141,3 +141,5 @@ random values, and some utility functions to generate special matrices (e.g. diagonal). """ +from __future__ import division + diff --git a/numpy/doc/glossary.py b/numpy/doc/glossary.py index 883100491..35adfc820 100644 --- a/numpy/doc/glossary.py +++ b/numpy/doc/glossary.py @@ -415,3 +415,5 @@ Glossary and f2py (which wraps Fortran). """ +from __future__ import division + diff --git a/numpy/doc/howtofind.py b/numpy/doc/howtofind.py index 29ad05318..8e6793c48 100644 --- a/numpy/doc/howtofind.py +++ b/numpy/doc/howtofind.py @@ -7,3 +7,5 @@ How to Find Stuff How to find things in NumPy. """ +from __future__ import division + diff --git a/numpy/doc/indexing.py b/numpy/doc/indexing.py index 99def8889..84f300dcd 100644 --- a/numpy/doc/indexing.py +++ b/numpy/doc/indexing.py @@ -405,3 +405,5 @@ converted to an array as a list would be. As an example: :: 40 """ +from __future__ import division + diff --git a/numpy/doc/internals.py b/numpy/doc/internals.py index a74429368..d7b6d3c93 100644 --- a/numpy/doc/internals.py +++ b/numpy/doc/internals.py @@ -160,3 +160,5 @@ when accessing elements of an array. Granted, it goes against the grain, but it is more in line with Python semantics and the natural order of the data. """ +from __future__ import division + diff --git a/numpy/doc/io.py b/numpy/doc/io.py index 3cde40bd0..4ee4c7c2f 100644 --- a/numpy/doc/io.py +++ b/numpy/doc/io.py @@ -7,3 +7,5 @@ Array I/O Placeholder for array I/O documentation. """ +from __future__ import division + diff --git a/numpy/doc/jargon.py b/numpy/doc/jargon.py index e13ff5686..3bf4d5070 100644 --- a/numpy/doc/jargon.py +++ b/numpy/doc/jargon.py @@ -7,3 +7,5 @@ Jargon Placeholder for computer science, engineering and other jargon. """ +from __future__ import division + diff --git a/numpy/doc/methods_vs_functions.py b/numpy/doc/methods_vs_functions.py index 22eadccf7..902ec54d0 100644 --- a/numpy/doc/methods_vs_functions.py +++ b/numpy/doc/methods_vs_functions.py @@ -7,3 +7,5 @@ Methods vs. Functions Placeholder for Methods vs. Functions documentation. """ +from __future__ import division + diff --git a/numpy/doc/misc.py b/numpy/doc/misc.py index 8fa3f8a31..9195ebb5a 100644 --- a/numpy/doc/misc.py +++ b/numpy/doc/misc.py @@ -226,3 +226,5 @@ Interfacing to C++: 5) SIP (used mainly in PyQT) """ +from __future__ import division + diff --git a/numpy/doc/performance.py b/numpy/doc/performance.py index 1429e232f..711dd3153 100644 --- a/numpy/doc/performance.py +++ b/numpy/doc/performance.py @@ -7,3 +7,5 @@ Performance Placeholder for Improving Performance documentation. """ +from __future__ import division + diff --git a/numpy/doc/structured_arrays.py b/numpy/doc/structured_arrays.py index af777efa4..eeb8a949f 100644 --- a/numpy/doc/structured_arrays.py +++ b/numpy/doc/structured_arrays.py @@ -221,3 +221,5 @@ You can find some more information on recarrays and structured arrays <http://www.scipy.org/Cookbook/Recarray>`_. """ +from __future__ import division + diff --git a/numpy/doc/subclassing.py b/numpy/doc/subclassing.py index de0338060..19bdd425f 100644 --- a/numpy/doc/subclassing.py +++ b/numpy/doc/subclassing.py @@ -557,3 +557,5 @@ how this can work, have a look at the ``memmap`` class in """ +from __future__ import division + diff --git a/numpy/doc/ufuncs.py b/numpy/doc/ufuncs.py index e85b47763..d566ee98a 100644 --- a/numpy/doc/ufuncs.py +++ b/numpy/doc/ufuncs.py @@ -135,3 +135,5 @@ results in an error. There are two alternatives: a convenient way to apply these operators. """ +from __future__ import division + diff --git a/numpy/dual.py b/numpy/dual.py index 4aa01cd30..15b175b92 100644 --- a/numpy/dual.py +++ b/numpy/dual.py @@ -10,6 +10,8 @@ Numpy. .. _Scipy : http://www.scipy.org """ +from __future__ import division + # This module should be used for functions both in numpy and scipy if # you want to use the numpy version if available but the scipy version # otherwise. diff --git a/numpy/f2py/__init__.py b/numpy/f2py/__init__.py index 220cb3d87..12add2153 100644 --- a/numpy/f2py/__init__.py +++ b/numpy/f2py/__init__.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +from __future__ import division __all__ = ['run_main','compile','f2py_testing'] diff --git a/numpy/f2py/__version__.py b/numpy/f2py/__version__.py index 104c2e1a8..2f842c89d 100644 --- a/numpy/f2py/__version__.py +++ b/numpy/f2py/__version__.py @@ -1,3 +1,5 @@ +from __future__ import division + major = 2 try: diff --git a/numpy/f2py/auxfuncs.py b/numpy/f2py/auxfuncs.py index a12d92b7e..0f68953ad 100644 --- a/numpy/f2py/auxfuncs.py +++ b/numpy/f2py/auxfuncs.py @@ -12,7 +12,10 @@ terms of the NumPy (BSD style) LICENSE. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/07/24 19:01:55 $ Pearu Peterson + """ +from __future__ import division + __version__ = "$Revision: 1.65 $"[10:-1] import __version__ @@ -447,7 +450,7 @@ class throw_error: self.mess = mess def __call__(self,var): mess = '\n\n var = %s\n Message: %s\n' % (var,self.mess) - raise F2PYError,mess + raise F2PYError(mess) def l_and(*f): l,l2='lambda v',[] diff --git a/numpy/f2py/capi_maps.py b/numpy/f2py/capi_maps.py index dd8277aaf..d82b2c3f5 100644 --- a/numpy/f2py/capi_maps.py +++ b/numpy/f2py/capi_maps.py @@ -9,7 +9,9 @@ terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/05/06 10:57:33 $ Pearu Peterson + """ +from __future__ import division __version__ = "$Revision: 1.60 $"[10:-1] @@ -192,7 +194,7 @@ if os.path.isfile('.f2py_f2cmap'): else: errmess("\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n"%(k,k1,d[k][k1],d[k][k1],c2py_map.keys())) outmess('Succesfully applied user defined changes from .f2py_f2cmap\n') - except Exception, msg: + except Exception as msg: errmess('Failed to apply user defined changes from .f2py_f2cmap: %s. Skipping.\n' % (msg)) cformat_map={'double':'%g', 'float':'%g', diff --git a/numpy/f2py/cb_rules.py b/numpy/f2py/cb_rules.py index 8e8320bfd..05404add2 100644 --- a/numpy/f2py/cb_rules.py +++ b/numpy/f2py/cb_rules.py @@ -11,7 +11,9 @@ terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/07/20 11:27:58 $ Pearu Peterson + """ +from __future__ import division __version__ = "$Revision: 1.53 $"[10:-1] diff --git a/numpy/f2py/cfuncs.py b/numpy/f2py/cfuncs.py index 72ee4f7a4..ccadd94e3 100644 --- a/numpy/f2py/cfuncs.py +++ b/numpy/f2py/cfuncs.py @@ -12,7 +12,9 @@ terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/05/06 11:42:34 $ Pearu Peterson + """ +from __future__ import division __version__ = "$Revision: 1.75 $"[10:-1] diff --git a/numpy/f2py/common_rules.py b/numpy/f2py/common_rules.py index 3295676ef..db7a6ee6d 100644 --- a/numpy/f2py/common_rules.py +++ b/numpy/f2py/common_rules.py @@ -11,7 +11,9 @@ terms of the NumPy License NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/05/06 10:57:33 $ Pearu Peterson + """ +from __future__ import division __version__ = "$Revision: 1.19 $"[10:-1] diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py index 5d664e399..76e113a67 100755 --- a/numpy/f2py/crackfortran.py +++ b/numpy/f2py/crackfortran.py @@ -1,7 +1,6 @@ #!/usr/bin/env python """ crackfortran --- read fortran (77,90) code and extract declaration information. - Usage is explained in the comment block below. Copyright 1999-2004 Pearu Peterson all rights reserved, Pearu Peterson <pearu@ioc.ee> @@ -11,138 +10,141 @@ terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/09/27 07:13:49 $ Pearu Peterson + + +Usage of crackfortran: +====================== +Command line keys: -quiet,-verbose,-fix,-f77,-f90,-show,-h <pyffilename> + -m <module name for f77 routines>,--ignore-contains +Functions: crackfortran, crack2fortran +The following Fortran statements/constructions are supported +(or will be if needed): + block data,byte,call,character,common,complex,contains,data, + dimension,double complex,double precision,end,external,function, + implicit,integer,intent,interface,intrinsic, + logical,module,optional,parameter,private,public, + program,real,(sequence?),subroutine,type,use,virtual, + include,pythonmodule +Note: 'virtual' is mapped to 'dimension'. +Note: 'implicit integer (z) static (z)' is 'implicit static (z)' (this is minor bug). +Note: code after 'contains' will be ignored until its scope ends. +Note: 'common' statement is extended: dimensions are moved to variable definitions +Note: f2py directive: <commentchar>f2py<line> is read as <line> +Note: pythonmodule is introduced to represent Python module + +Usage: + `postlist=crackfortran(files,funcs)` + `postlist` contains declaration information read from the list of files `files`. + `crack2fortran(postlist)` returns a fortran code to be saved to pyf-file + + `postlist` has the following structure: + *** it is a list of dictionaries containing `blocks': + B = {'block','body','vars','parent_block'[,'name','prefix','args','result', + 'implicit','externals','interfaced','common','sortvars', + 'commonvars','note']} + B['block'] = 'interface' | 'function' | 'subroutine' | 'module' | + 'program' | 'block data' | 'type' | 'pythonmodule' + B['body'] --- list containing `subblocks' with the same structure as `blocks' + B['parent_block'] --- dictionary of a parent block: + C['body'][<index>]['parent_block'] is C + B['vars'] --- dictionary of variable definitions + B['sortvars'] --- dictionary of variable definitions sorted by dependence (independent first) + B['name'] --- name of the block (not if B['block']=='interface') + B['prefix'] --- prefix string (only if B['block']=='function') + B['args'] --- list of argument names if B['block']== 'function' | 'subroutine' + B['result'] --- name of the return value (only if B['block']=='function') + B['implicit'] --- dictionary {'a':<variable definition>,'b':...} | None + B['externals'] --- list of variables being external + B['interfaced'] --- list of variables being external and defined + B['common'] --- dictionary of common blocks (list of objects) + B['commonvars'] --- list of variables used in common blocks (dimensions are moved to variable definitions) + B['from'] --- string showing the 'parents' of the current block + B['use'] --- dictionary of modules used in current block: + {<modulename>:{['only':<0|1>],['map':{<local_name1>:<use_name1>,...}]}} + B['note'] --- list of LaTeX comments on the block + B['f2pyenhancements'] --- optional dictionary + {'threadsafe':'','fortranname':<name>, + 'callstatement':<C-expr>|<multi-line block>, + 'callprotoargument':<C-expr-list>, + 'usercode':<multi-line block>|<list of multi-line blocks>, + 'pymethoddef:<multi-line block>' + } + B['entry'] --- dictionary {entryname:argslist,..} + B['varnames'] --- list of variable names given in the order of reading the + Fortran code, useful for derived types. + B['saved_interface'] --- a string of scanned routine signature, defines explicit interface + *** Variable definition is a dictionary + D = B['vars'][<variable name>] = + {'typespec'[,'attrspec','kindselector','charselector','=','typename']} + D['typespec'] = 'byte' | 'character' | 'complex' | 'double complex' | + 'double precision' | 'integer' | 'logical' | 'real' | 'type' + D['attrspec'] --- list of attributes (e.g. 'dimension(<arrayspec>)', + 'external','intent(in|out|inout|hide|c|callback|cache|aligned4|aligned8|aligned16)', + 'optional','required', etc) + K = D['kindselector'] = {['*','kind']} (only if D['typespec'] = + 'complex' | 'integer' | 'logical' | 'real' ) + C = D['charselector'] = {['*','len','kind']} + (only if D['typespec']=='character') + D['='] --- initialization expression string + D['typename'] --- name of the type if D['typespec']=='type' + D['dimension'] --- list of dimension bounds + D['intent'] --- list of intent specifications + D['depend'] --- list of variable names on which current variable depends on + D['check'] --- list of C-expressions; if C-expr returns zero, exception is raised + D['note'] --- list of LaTeX comments on the variable + *** Meaning of kind/char selectors (few examples): + D['typespec>']*K['*'] + D['typespec'](kind=K['kind']) + character*C['*'] + character(len=C['len'],kind=C['kind']) + (see also fortran type declaration statement formats below) + +Fortran 90 type declaration statement format (F77 is subset of F90) +==================================================================== +(Main source: IBM XL Fortran 5.1 Language Reference Manual) +type declaration = <typespec> [[<attrspec>]::] <entitydecl> +<typespec> = byte | + character[<charselector>] | + complex[<kindselector>] | + double complex | + double precision | + integer[<kindselector>] | + logical[<kindselector>] | + real[<kindselector>] | + type(<typename>) +<charselector> = * <charlen> | + ([len=]<len>[,[kind=]<kind>]) | + (kind=<kind>[,len=<len>]) +<kindselector> = * <intlen> | + ([kind=]<kind>) +<attrspec> = comma separated list of attributes. + Only the following attributes are used in + building up the interface: + external + (parameter --- affects '=' key) + optional + intent + Other attributes are ignored. +<intentspec> = in | out | inout +<arrayspec> = comma separated list of dimension bounds. +<entitydecl> = <name> [[*<charlen>][(<arrayspec>)] | [(<arrayspec>)]*<charlen>] + [/<init_expr>/ | =<init_expr>] [,<entitydecl>] + +In addition, the following attributes are used: check,depend,note + +TODO: + * Apply 'parameter' attribute (e.g. 'integer parameter :: i=2' 'real x(i)' + -> 'real x(2)') + The above may be solved by creating appropriate preprocessor program, for example. + """ +from __future__ import division + __version__ = "$Revision: 1.177 $"[10:-1] import platform import __version__ f2py_version = __version__.version -""" - Usage of crackfortran: - ====================== - Command line keys: -quiet,-verbose,-fix,-f77,-f90,-show,-h <pyffilename> - -m <module name for f77 routines>,--ignore-contains - Functions: crackfortran, crack2fortran - The following Fortran statements/constructions are supported - (or will be if needed): - block data,byte,call,character,common,complex,contains,data, - dimension,double complex,double precision,end,external,function, - implicit,integer,intent,interface,intrinsic, - logical,module,optional,parameter,private,public, - program,real,(sequence?),subroutine,type,use,virtual, - include,pythonmodule - Note: 'virtual' is mapped to 'dimension'. - Note: 'implicit integer (z) static (z)' is 'implicit static (z)' (this is minor bug). - Note: code after 'contains' will be ignored until its scope ends. - Note: 'common' statement is extended: dimensions are moved to variable definitions - Note: f2py directive: <commentchar>f2py<line> is read as <line> - Note: pythonmodule is introduced to represent Python module - - Usage: - `postlist=crackfortran(files,funcs)` - `postlist` contains declaration information read from the list of files `files`. - `crack2fortran(postlist)` returns a fortran code to be saved to pyf-file - - `postlist` has the following structure: - *** it is a list of dictionaries containing `blocks': - B = {'block','body','vars','parent_block'[,'name','prefix','args','result', - 'implicit','externals','interfaced','common','sortvars', - 'commonvars','note']} - B['block'] = 'interface' | 'function' | 'subroutine' | 'module' | - 'program' | 'block data' | 'type' | 'pythonmodule' - B['body'] --- list containing `subblocks' with the same structure as `blocks' - B['parent_block'] --- dictionary of a parent block: - C['body'][<index>]['parent_block'] is C - B['vars'] --- dictionary of variable definitions - B['sortvars'] --- dictionary of variable definitions sorted by dependence (independent first) - B['name'] --- name of the block (not if B['block']=='interface') - B['prefix'] --- prefix string (only if B['block']=='function') - B['args'] --- list of argument names if B['block']== 'function' | 'subroutine' - B['result'] --- name of the return value (only if B['block']=='function') - B['implicit'] --- dictionary {'a':<variable definition>,'b':...} | None - B['externals'] --- list of variables being external - B['interfaced'] --- list of variables being external and defined - B['common'] --- dictionary of common blocks (list of objects) - B['commonvars'] --- list of variables used in common blocks (dimensions are moved to variable definitions) - B['from'] --- string showing the 'parents' of the current block - B['use'] --- dictionary of modules used in current block: - {<modulename>:{['only':<0|1>],['map':{<local_name1>:<use_name1>,...}]}} - B['note'] --- list of LaTeX comments on the block - B['f2pyenhancements'] --- optional dictionary - {'threadsafe':'','fortranname':<name>, - 'callstatement':<C-expr>|<multi-line block>, - 'callprotoargument':<C-expr-list>, - 'usercode':<multi-line block>|<list of multi-line blocks>, - 'pymethoddef:<multi-line block>' - } - B['entry'] --- dictionary {entryname:argslist,..} - B['varnames'] --- list of variable names given in the order of reading the - Fortran code, useful for derived types. - B['saved_interface'] --- a string of scanned routine signature, defines explicit interface - *** Variable definition is a dictionary - D = B['vars'][<variable name>] = - {'typespec'[,'attrspec','kindselector','charselector','=','typename']} - D['typespec'] = 'byte' | 'character' | 'complex' | 'double complex' | - 'double precision' | 'integer' | 'logical' | 'real' | 'type' - D['attrspec'] --- list of attributes (e.g. 'dimension(<arrayspec>)', - 'external','intent(in|out|inout|hide|c|callback|cache|aligned4|aligned8|aligned16)', - 'optional','required', etc) - K = D['kindselector'] = {['*','kind']} (only if D['typespec'] = - 'complex' | 'integer' | 'logical' | 'real' ) - C = D['charselector'] = {['*','len','kind']} - (only if D['typespec']=='character') - D['='] --- initialization expression string - D['typename'] --- name of the type if D['typespec']=='type' - D['dimension'] --- list of dimension bounds - D['intent'] --- list of intent specifications - D['depend'] --- list of variable names on which current variable depends on - D['check'] --- list of C-expressions; if C-expr returns zero, exception is raised - D['note'] --- list of LaTeX comments on the variable - *** Meaning of kind/char selectors (few examples): - D['typespec>']*K['*'] - D['typespec'](kind=K['kind']) - character*C['*'] - character(len=C['len'],kind=C['kind']) - (see also fortran type declaration statement formats below) - - Fortran 90 type declaration statement format (F77 is subset of F90) -==================================================================== - (Main source: IBM XL Fortran 5.1 Language Reference Manual) - type declaration = <typespec> [[<attrspec>]::] <entitydecl> - <typespec> = byte | - character[<charselector>] | - complex[<kindselector>] | - double complex | - double precision | - integer[<kindselector>] | - logical[<kindselector>] | - real[<kindselector>] | - type(<typename>) - <charselector> = * <charlen> | - ([len=]<len>[,[kind=]<kind>]) | - (kind=<kind>[,len=<len>]) - <kindselector> = * <intlen> | - ([kind=]<kind>) - <attrspec> = comma separated list of attributes. - Only the following attributes are used in - building up the interface: - external - (parameter --- affects '=' key) - optional - intent - Other attributes are ignored. - <intentspec> = in | out | inout - <arrayspec> = comma separated list of dimension bounds. - <entitydecl> = <name> [[*<charlen>][(<arrayspec>)] | [(<arrayspec>)]*<charlen>] - [/<init_expr>/ | =<init_expr>] [,<entitydecl>] - - In addition, the following attributes are used: check,depend,note - - TODO: - * Apply 'parameter' attribute (e.g. 'integer parameter :: i=2' 'real x(i)' - -> 'real x(2)') - The above may be solved by creating appropriate preprocessor program, for example. -""" # import sys import string @@ -993,7 +995,7 @@ def analyzeline(m,case,line): replace(',','+1j*(') try: v = eval(initexpr,{},params) - except (SyntaxError,NameError,TypeError),msg: + except (SyntaxError,NameError,TypeError) as msg: errmess('analyzeline: Failed to evaluate %r. Ignoring: %s\n'\ % (initexpr, msg)) continue @@ -2034,7 +2036,7 @@ def get_parameters(vars, global_params={}): l = markoutercomma(v[1:-1]).split('@,@') try: params[n] = eval(v,g_params,params) - except Exception,msg: + except Exception as msg: params[n] = v #print params outmess('get_parameters: got "%s" on %s\n' % (msg,`v`)) @@ -2062,7 +2064,7 @@ def _eval_scalar(value,params): value = str(eval(value,{},params)) except (NameError, SyntaxError): return value - except Exception,msg: + except Exception as msg: errmess('"%s" in evaluating %r '\ '(available names: %s)\n' \ % (msg,value,params.keys())) @@ -2805,7 +2807,7 @@ if __name__ == "__main__": try: open(l).close() files.append(l) - except IOError,detail: + except IOError as detail: errmess('IOError: %s\n'%str(detail)) else: funcs.append(l) diff --git a/numpy/f2py/diagnose.py b/numpy/f2py/diagnose.py index 3b517a5c9..e7759b6dd 100644 --- a/numpy/f2py/diagnose.py +++ b/numpy/f2py/diagnose.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +from __future__ import division import os import sys @@ -29,14 +30,14 @@ def run(): import numpy has_newnumpy = 1 except ImportError: - print 'Failed to import new numpy:', sys.exc_value + print 'Failed to import new numpy:', sys.exc_info()[1] has_newnumpy = 0 try: from numpy.f2py import f2py2e has_f2py2e = 1 except ImportError: - print 'Failed to import f2py2e:',sys.exc_value + print 'Failed to import f2py2e:',sys.exc_info()[1] has_f2py2e = 0 try: @@ -47,14 +48,14 @@ def run(): import numpy_distutils has_numpy_distutils = 1 except ImportError: - print 'Failed to import numpy_distutils:',sys.exc_value + print 'Failed to import numpy_distutils:',sys.exc_info()[1] has_numpy_distutils = 0 if has_newnumpy: try: print 'Found new numpy version %r in %s' % \ (numpy.__version__, numpy.__file__) - except Exception,msg: + except Exception as msg: print 'error:', msg print '------' @@ -62,7 +63,7 @@ def run(): try: print 'Found f2py2e version %r in %s' % \ (f2py2e.__version__.version,f2py2e.__file__) - except Exception,msg: + except Exception as msg: print 'error:',msg print '------' @@ -77,7 +78,7 @@ def run(): numpy_distutils.numpy_distutils_version.numpy_distutils_version, numpy_distutils.__file__) print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg print '------' try: @@ -91,10 +92,10 @@ def run(): for compiler_class in build_flib.all_compilers: compiler_class(verbose=1).is_available() print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg,'(ignore it, build_flib is obsolute for numpy.distutils 0.2.2 and up)' print '------' try: @@ -110,10 +111,10 @@ def run(): print 'Checking availability of supported Fortran compilers:' fcompiler.show_fcompilers() print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg print '------' try: @@ -128,7 +129,7 @@ def run(): from numpy_distutils.command.cpuinfo import cpuinfo print 'ok' print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg,'(ignore it)' print 'Importing numpy_distutils.cpuinfo ...', from numpy_distutils.cpuinfo import cpuinfo @@ -140,7 +141,7 @@ def run(): if name[0]=='_' and name[1]!='_' and getattr(cpu,name[1:])(): print name[1:], print '------' - except Exception,msg: + except Exception as msg: print 'error:',msg print '------' os.chdir(_path) diff --git a/numpy/f2py/doc/collectinput.py b/numpy/f2py/doc/collectinput.py index 2e6c6c96b..5e98c8350 100755 --- a/numpy/f2py/doc/collectinput.py +++ b/numpy/f2py/doc/collectinput.py @@ -17,7 +17,9 @@ Usage: collectinput <infile> <outfile> collectinput <infile> # <outfile>=inputless_<infile> collectinput # in and out are stdin and stdout + """ +from __future__ import division __version__ = "0.0" diff --git a/numpy/f2py/docs/pytest.py b/numpy/f2py/docs/pytest.py index abd3487df..b49dc764a 100644 --- a/numpy/f2py/docs/pytest.py +++ b/numpy/f2py/docs/pytest.py @@ -1,3 +1,5 @@ +from __future__ import division + #File: pytest.py import Numeric def foo(a): diff --git a/numpy/f2py/docs/usersguide/setup_example.py b/numpy/f2py/docs/usersguide/setup_example.py index e5f5e8441..911dc3324 100644 --- a/numpy/f2py/docs/usersguide/setup_example.py +++ b/numpy/f2py/docs/usersguide/setup_example.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import division + # File: setup_example.py from numpy_distutils.core import Extension diff --git a/numpy/f2py/f2py2e.py b/numpy/f2py/f2py2e.py index 4e6d2587f..235fcb75a 100755 --- a/numpy/f2py/f2py2e.py +++ b/numpy/f2py/f2py2e.py @@ -12,7 +12,9 @@ terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/05/06 08:31:19 $ Pearu Peterson + """ +from __future__ import division import __version__ f2py_version = __version__.version @@ -235,7 +237,7 @@ def scaninputline(inputline): try: open(l).close() files.append(l) - except IOError,detail: + except IOError as detail: errmess('IOError: %s. Skipping file "%s".\n'%(str(detail),l)) elif f==-1: skipfuncs.append(l) elif f==0: onlyfuncs.append(l) @@ -430,13 +432,15 @@ def run_compile(): remove_build_dir = 1 build_dir = os.path.join(tempfile.mktemp()) - sysinfo_flags = filter(re.compile(r'[-][-]link[-]').match,sys.argv[1:]) - sys.argv = filter(lambda a,flags=sysinfo_flags:a not in flags,sys.argv) + _reg1 = re.compile(r'[-][-]link[-]') + sysinfo_flags = [_m for _m in sys.argv[1:] if _reg1.match(_m)] + sys.argv = [_m for _m in sys.argv if _m not in sysinfo_flags] if sysinfo_flags: sysinfo_flags = [f[7:] for f in sysinfo_flags] - f2py_flags = filter(re.compile(r'[-][-]((no[-]|)(wrap[-]functions|lower)|debug[-]capi|quiet)|[-]include').match,sys.argv[1:]) - sys.argv = filter(lambda a,flags=f2py_flags:a not in flags,sys.argv) + _reg2 = re.compile(r'[-][-]((no[-]|)(wrap[-]functions|lower)|debug[-]capi|quiet)|[-]include') + f2py_flags = [_m for _m in sys.argv[1:] if _reg2.match(_m)] + sys.argv = [_m for _m in sys.argv if _m not in f2py_flags] f2py_flags2 = [] fl = 0 for a in sys.argv[1:]: @@ -450,12 +454,13 @@ def run_compile(): f2py_flags2.append(':') f2py_flags.extend(f2py_flags2) - sys.argv = filter(lambda a,flags=f2py_flags2:a not in flags,sys.argv) - - flib_flags = filter(re.compile(r'[-][-]((f(90)?compiler([-]exec|)|compiler)=|help[-]compiler)').match,sys.argv[1:]) - sys.argv = filter(lambda a,flags=flib_flags:a not in flags,sys.argv) - fc_flags = filter(re.compile(r'[-][-]((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help[-]fcompiler))').match,sys.argv[1:]) - sys.argv = filter(lambda a,flags=fc_flags:a not in flags,sys.argv) + sys.argv = [_m for _m in sys.argv if _m not in f2py_flags2] + _reg3 = re.compile(r'[-][-]((f(90)?compiler([-]exec|)|compiler)=|help[-]compiler)') + flib_flags = [_m for _m in sys.argv[1:] if _reg3.match(_m)] + sys.argv = [_m for _m in sys.argv if _m not in flib_flags] + _reg4 = re.compile(r'[-][-]((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help[-]fcompiler))') + fc_flags = [_m for _m in sys.argv[1:] if _reg4.match(_m)] + sys.argv = [_m for _m in sys.argv if _m not in fc_flags] if 1: del_list = [] @@ -481,8 +486,11 @@ def run_compile(): i = flib_flags.index(s) del flib_flags[i] assert len(flib_flags)<=2,`flib_flags` - setup_flags = filter(re.compile(r'[-][-](verbose)').match,sys.argv[1:]) - sys.argv = filter(lambda a,flags=setup_flags:a not in flags,sys.argv) + + _reg5 = re.compile(r'[-][-](verbose)') + setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)] + sys.argv = [_m for _m in sys.argv if _m not in setup_flags] + if '--quiet' in f2py_flags: setup_flags.append('--quiet') diff --git a/numpy/f2py/f2py_testing.py b/numpy/f2py/f2py_testing.py index 0c78f3594..73eb2caed 100644 --- a/numpy/f2py/f2py_testing.py +++ b/numpy/f2py/f2py_testing.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys import re diff --git a/numpy/f2py/f90mod_rules.py b/numpy/f2py/f90mod_rules.py index e4a4b0e96..3a80eb8f4 100644 --- a/numpy/f2py/f90mod_rules.py +++ b/numpy/f2py/f90mod_rules.py @@ -11,7 +11,9 @@ terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/02/03 19:30:23 $ Pearu Peterson + """ +from __future__ import division __version__ = "$Revision: 1.27 $"[10:-1] diff --git a/numpy/f2py/func2subr.py b/numpy/f2py/func2subr.py index f746108ad..eb72c76c9 100644 --- a/numpy/f2py/func2subr.py +++ b/numpy/f2py/func2subr.py @@ -11,7 +11,9 @@ terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2004/11/26 11:13:06 $ Pearu Peterson + """ +from __future__ import division __version__ = "$Revision: 1.16 $"[10:-1] diff --git a/numpy/f2py/info.py b/numpy/f2py/info.py index 8beaba228..b976fb2ea 100644 --- a/numpy/f2py/info.py +++ b/numpy/f2py/info.py @@ -1,5 +1,6 @@ """Fortran to Python Interface Generator. """ +from __future__ import division postpone_import = True diff --git a/numpy/f2py/rules.py b/numpy/f2py/rules.py index 982f8e5b3..b04f54e16 100644 --- a/numpy/f2py/rules.py +++ b/numpy/f2py/rules.py @@ -39,8 +39,7 @@ wrapper_function(args) cleanup_a return buildvalue -""" -""" + Copyright 1999,2000 Pearu Peterson all rights reserved, Pearu Peterson <pearu@ioc.ee> Permission to use, modify, and distribute this software is given under the @@ -49,7 +48,9 @@ terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/08/30 08:58:42 $ Pearu Peterson + """ +from __future__ import division __version__ = "$Revision: 1.129 $"[10:-1] diff --git a/numpy/f2py/setup.py b/numpy/f2py/setup.py index 37aab191c..43de25225 100644 --- a/numpy/f2py/setup.py +++ b/numpy/f2py/setup.py @@ -14,7 +14,9 @@ NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Revision: 1.32 $ $Date: 2005/01/30 17:22:14 $ Pearu Peterson + """ +from __future__ import division __version__ = "$Id: setup.py,v 1.32 2005/01/30 17:22:14 pearu Exp $" diff --git a/numpy/f2py/src/fortranobject.h b/numpy/f2py/src/fortranobject.h index 283021aa1..07e810ff9 100644 --- a/numpy/f2py/src/fortranobject.h +++ b/numpy/f2py/src/fortranobject.h @@ -9,7 +9,7 @@ extern "C" { #ifdef FORTRANOBJECT_C #define NO_IMPORT_ARRAY #endif -#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API +#define PY_ARRAY_UNIQUE_SYMBOL _npy_f2py_ARRAY_API #include "numpy/arrayobject.h" /* diff --git a/numpy/f2py/tests/test_array_from_pyobj.py b/numpy/f2py/tests/test_array_from_pyobj.py index be85a308a..ff8c16cd1 100644 --- a/numpy/f2py/tests/test_array_from_pyobj.py +++ b/numpy/f2py/tests/test_array_from_pyobj.py @@ -1,3 +1,5 @@ +from __future__ import division + import unittest import os import sys @@ -297,7 +299,7 @@ class _test_shared_memory: try: a = self.array([2],intent.in_.inout,self.num2seq) - except TypeError,msg: + except TypeError as msg: if not str(msg).startswith('failed to initialize intent(inout|inplace|cache) array'): raise else: @@ -313,7 +315,7 @@ class _test_shared_memory: shape = (len(self.num23seq),len(self.num23seq[0])) try: a = self.array(shape,intent.in_.inout,obj) - except ValueError,msg: + except ValueError as msg: if not str(msg).startswith('failed to initialize intent(inout) array'): raise else: @@ -398,7 +400,7 @@ class _test_shared_memory: try: a = self.array(shape,intent.in_.cache,obj[::-1]) - except ValueError,msg: + except ValueError as msg: if not str(msg).startswith('failed to initialize intent(cache) array'): raise else: @@ -411,7 +413,7 @@ class _test_shared_memory: shape = (len(self.num2seq),) try: a = self.array(shape,intent.in_.cache,obj) - except ValueError,msg: + except ValueError as msg: if not str(msg).startswith('failed to initialize intent(cache) array'): raise else: @@ -429,7 +431,7 @@ class _test_shared_memory: shape = (-1,3) try: a = self.array(shape,intent.cache.hide,None) - except ValueError,msg: + except ValueError as msg: if not str(msg).startswith('failed to create intent(cache|hide)|optional array'): raise else: @@ -456,7 +458,7 @@ class _test_shared_memory: shape = (-1,3) try: a = self.array(shape,intent.hide,None) - except ValueError,msg: + except ValueError as msg: if not str(msg).startswith('failed to create intent(cache|hide)|optional array'): raise else: @@ -530,14 +532,14 @@ class _test_shared_memory: for t in Type._type_names: - exec '''\ + exec('''\ class test_%s_gen(unittest.TestCase, _test_shared_memory ): def setUp(self): self.type = Type(%r) array = lambda self,dims,intent,obj: Array(Type(%r),dims,intent,obj) -''' % (t,t,t) +''' % (t,t,t)) if __name__ == "__main__": setup() diff --git a/numpy/f2py/tests/test_assumed_shape.py b/numpy/f2py/tests/test_assumed_shape.py index e501b13c3..728c034ec 100644 --- a/numpy/f2py/tests/test_assumed_shape.py +++ b/numpy/f2py/tests/test_assumed_shape.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import math diff --git a/numpy/f2py/tests/test_callback.py b/numpy/f2py/tests/test_callback.py index 5e0cda242..f903fbcb4 100644 --- a/numpy/f2py/tests/test_callback.py +++ b/numpy/f2py/tests/test_callback.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * from numpy import array import math diff --git a/numpy/f2py/tests/test_kind.py b/numpy/f2py/tests/test_kind.py index a6d485a88..56a747096 100644 --- a/numpy/f2py/tests/test_kind.py +++ b/numpy/f2py/tests/test_kind.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import math diff --git a/numpy/f2py/tests/test_mixed.py b/numpy/f2py/tests/test_mixed.py index f786f38dd..dc29d2b5d 100644 --- a/numpy/f2py/tests/test_mixed.py +++ b/numpy/f2py/tests/test_mixed.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import math diff --git a/numpy/f2py/tests/test_return_character.py b/numpy/f2py/tests/test_return_character.py index 67c542688..fd8355ac3 100644 --- a/numpy/f2py/tests/test_return_character.py +++ b/numpy/f2py/tests/test_return_character.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * from numpy import array from numpy.compat import asbytes diff --git a/numpy/f2py/tests/test_return_complex.py b/numpy/f2py/tests/test_return_complex.py index f8c6d226a..4cdc03993 100644 --- a/numpy/f2py/tests/test_return_complex.py +++ b/numpy/f2py/tests/test_return_complex.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * from numpy import array import util diff --git a/numpy/f2py/tests/test_return_integer.py b/numpy/f2py/tests/test_return_integer.py index e1b3a37aa..a1af6b932 100644 --- a/numpy/f2py/tests/test_return_integer.py +++ b/numpy/f2py/tests/test_return_integer.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * from numpy import array import util diff --git a/numpy/f2py/tests/test_return_logical.py b/numpy/f2py/tests/test_return_logical.py index 059b843dc..1c8dce532 100644 --- a/numpy/f2py/tests/test_return_logical.py +++ b/numpy/f2py/tests/test_return_logical.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * from numpy import array import util diff --git a/numpy/f2py/tests/test_return_real.py b/numpy/f2py/tests/test_return_real.py index 5dc12708e..943a4972d 100644 --- a/numpy/f2py/tests/test_return_real.py +++ b/numpy/f2py/tests/test_return_real.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * from numpy import array import math diff --git a/numpy/f2py/tests/test_size.py b/numpy/f2py/tests/test_size.py index a548e9885..72443b4f6 100644 --- a/numpy/f2py/tests/test_size.py +++ b/numpy/f2py/tests/test_size.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import math diff --git a/numpy/f2py/tests/util.py b/numpy/f2py/tests/util.py index a5816b96f..0584ae188 100644 --- a/numpy/f2py/tests/util.py +++ b/numpy/f2py/tests/util.py @@ -5,6 +5,7 @@ Utility functions for - detecting if compilers are present """ +from __future__ import division import os import sys @@ -71,7 +72,7 @@ def _memoize(func): if key not in memo: try: memo[key] = func(*a, **kw) - except Exception, e: + except Exception as e: memo[key] = e raise ret = memo[key] diff --git a/numpy/f2py/use_rules.py b/numpy/f2py/use_rules.py index 021d08601..e47dfc6e5 100644 --- a/numpy/f2py/use_rules.py +++ b/numpy/f2py/use_rules.py @@ -13,7 +13,9 @@ terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2000/09/10 12:35:43 $ Pearu Peterson + """ +from __future__ import division __version__ = "$Revision: 1.3 $"[10:-1] diff --git a/numpy/fft/__init__.py b/numpy/fft/__init__.py index 324e39f4d..6cfa535fb 100644 --- a/numpy/fft/__init__.py +++ b/numpy/fft/__init__.py @@ -1,3 +1,5 @@ +from __future__ import division + # To get sub-modules from info import __doc__ diff --git a/numpy/fft/fftpack.py b/numpy/fft/fftpack.py index 2f8982d3c..54d071884 100644 --- a/numpy/fft/fftpack.py +++ b/numpy/fft/fftpack.py @@ -30,6 +30,8 @@ The underlying code for these functions is an f2c-translated and modified version of the FFTPACK routines. """ +from __future__ import division + __all__ = ['fft','ifft', 'rfft', 'irfft', 'hfft', 'ihfft', 'rfftn', 'irfftn', 'rfft2', 'irfft2', 'fft2', 'ifft2', 'fftn', 'ifftn'] diff --git a/numpy/fft/helper.py b/numpy/fft/helper.py index 796ac4c53..763d6684b 100644 --- a/numpy/fft/helper.py +++ b/numpy/fft/helper.py @@ -1,6 +1,9 @@ """ Discrete Fourier Transforms - helper.py + """ +from __future__ import division + # Created by Pearu Peterson, September 2002 __all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq'] diff --git a/numpy/fft/info.py b/numpy/fft/info.py index 7bd2f0e92..1289f3b4c 100644 --- a/numpy/fft/info.py +++ b/numpy/fft/info.py @@ -174,5 +174,6 @@ Examples For examples, see the various functions. """ +from __future__ import division depends = ['core'] diff --git a/numpy/fft/setup.py b/numpy/fft/setup.py index 6acad7c9a..cf0e6bb58 100644 --- a/numpy/fft/setup.py +++ b/numpy/fft/setup.py @@ -1,3 +1,4 @@ +from __future__ import division def configuration(parent_package='',top_path=None): diff --git a/numpy/fft/tests/test_helper.py b/numpy/fft/tests/test_helper.py index 77e34f1ec..b20e6ddc3 100644 --- a/numpy/fft/tests/test_helper.py +++ b/numpy/fft/tests/test_helper.py @@ -1,6 +1,8 @@ #!/usr/bin/env python -# Copied from fftpack.helper by Pearu Peterson, October 2005 -""" Test functions for fftpack.helper module +"""Test functions for fftpack.helper module + +Copied from fftpack.helper by Pearu Peterson, October 2005 + """ from __future__ import division diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py index 17557605d..5679a2dc8 100644 --- a/numpy/lib/__init__.py +++ b/numpy/lib/__init__.py @@ -1,3 +1,5 @@ +from __future__ import division + from info import __doc__ from numpy.version import version as __version__ diff --git a/numpy/lib/_datasource.py b/numpy/lib/_datasource.py index 390c56d36..d5424e8d3 100644 --- a/numpy/lib/_datasource.py +++ b/numpy/lib/_datasource.py @@ -31,6 +31,7 @@ Example:: >>> fp.close() """ +from __future__ import division __docformat__ = "restructuredtext en" diff --git a/numpy/lib/_iotools.py b/numpy/lib/_iotools.py index 2f2a4bc57..aa3744204 100644 --- a/numpy/lib/_iotools.py +++ b/numpy/lib/_iotools.py @@ -1,4 +1,8 @@ -"""A collection of functions designed to help I/O with ascii files.""" +"""A collection of functions designed to help I/O with ascii files. + +""" +from __future__ import division + __docformat__ = "restructuredtext en" import sys diff --git a/numpy/lib/arraypad.py b/numpy/lib/arraypad.py index 6212ac7f3..e6ebd97e4 100644 --- a/numpy/lib/arraypad.py +++ b/numpy/lib/arraypad.py @@ -1,7 +1,9 @@ """ The arraypad module contains a group of functions to pad values onto the edges of an n-dimensional array. + """ +from __future__ import division import numpy as np diff --git a/numpy/lib/arraysetops.py b/numpy/lib/arraysetops.py index ae14970e2..61bb81721 100644 --- a/numpy/lib/arraysetops.py +++ b/numpy/lib/arraysetops.py @@ -22,7 +22,10 @@ thus calls to argsort(). To do: Optionally return indices analogously to unique for all functions. :Author: Robert Cimrman + """ +from __future__ import division + __all__ = ['ediff1d', 'intersect1d', 'setxor1d', 'union1d', 'setdiff1d', 'unique', 'in1d'] diff --git a/numpy/lib/arrayterator.py b/numpy/lib/arrayterator.py index 2df05e514..6f6953a22 100644 --- a/numpy/lib/arrayterator.py +++ b/numpy/lib/arrayterator.py @@ -7,7 +7,6 @@ an array object, and when iterated it will return sub-arrays with at most a user-specified number of elements. """ - from __future__ import division from operator import mul diff --git a/numpy/lib/financial.py b/numpy/lib/financial.py index 599a36198..5887a9224 100644 --- a/numpy/lib/financial.py +++ b/numpy/lib/financial.py @@ -1,10 +1,15 @@ -# Some simple financial calculations -# patterned after spreadsheet computations. +"""Some simple financial calculations + +patterned after spreadsheet computations. + +There is some complexity in each function +so that the functions behave like ufuncs with +broadcasting and being able to be called with scalars +or arrays (or other sequences). + +""" +from __future__ import division -# There is some complexity in each function -# so that the functions behave like ufuncs with -# broadcasting and being able to be called with scalars -# or arrays (or other sequences). import numpy as np __all__ = ['fv', 'pmt', 'nper', 'ipmt', 'ppmt', 'pv', 'rate', diff --git a/numpy/lib/format.py b/numpy/lib/format.py index 1e508f3e5..9a558f40c 100644 --- a/numpy/lib/format.py +++ b/numpy/lib/format.py @@ -134,6 +134,7 @@ The ``.npy`` format, including reasons for creating it and a comparison of alternatives, is described fully in the "npy-format" NEP. """ +from __future__ import division import cPickle @@ -334,7 +335,7 @@ def read_array_header_1_0(fp): # "descr" : dtype.descr try: d = safe_eval(header) - except SyntaxError, e: + except SyntaxError as e: msg = "Cannot parse header: %r\nException: %r" raise ValueError(msg % (header, e)) if not isinstance(d, dict): @@ -356,7 +357,7 @@ def read_array_header_1_0(fp): raise ValueError(msg % (d['fortran_order'],)) try: dtype = numpy.dtype(d['descr']) - except TypeError, e: + except TypeError as e: msg = "descr is not a valid dtype descriptor: %r" raise ValueError(msg % (d['descr'],)) diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py index 320a8ec6c..cd79dd67f 100644 --- a/numpy/lib/function_base.py +++ b/numpy/lib/function_base.py @@ -1,3 +1,5 @@ +from __future__ import division + __docformat__ = "restructuredtext en" __all__ = ['select', 'piecewise', 'trim_zeros', 'copy', 'iterable', 'percentile', 'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', @@ -30,6 +32,7 @@ from arraysetops import setdiff1d from utils import deprecate from _compiled_base import add_newdoc_ufunc import numpy as np +import collections def iterable(y): @@ -707,7 +710,7 @@ def piecewise(x, condlist, funclist, *args, **kw): y = zeros(x.shape, x.dtype) for k in range(n): item = funclist[k] - if not callable(item): + if not isinstance(item, collections.Callable): y[condlist[k]] = item else: vals = x[condlist[k]] @@ -3053,7 +3056,7 @@ def percentile(a, q, axis=None, out=None, overwrite_input=False): [ 3, 2, 1]]) >>> np.percentile(a, 50) 3.5 - >>> np.percentile(a, 0.5, axis=0) + >>> np.percentile(a, 50, axis=0) array([ 6.5, 4.5, 2.5]) >>> np.percentile(a, 50, axis=1) array([ 7., 2.]) @@ -3239,7 +3242,7 @@ def add_newdoc(place, obj, doc): """ try: new = {} - exec 'from %s import %s' % (place, obj) in new + exec('from %s import %s' % (place, obj), new) if isinstance(doc, str): add_docstring(new[obj], doc.strip()) elif isinstance(doc, tuple): diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py index 15a1a559d..9c58bf747 100644 --- a/numpy/lib/index_tricks.py +++ b/numpy/lib/index_tricks.py @@ -1,3 +1,5 @@ +from __future__ import division + __all__ = ['ravel_multi_index', 'unravel_index', 'mgrid', diff --git a/numpy/lib/info.py b/numpy/lib/info.py index 4a781a2ca..1a2154951 100644 --- a/numpy/lib/info.py +++ b/numpy/lib/info.py @@ -145,6 +145,7 @@ setdiff1d Set difference of 1D arrays with unique elements. ================ =================== """ +from __future__ import division depends = ['core','testing'] global_symbols = ['*'] diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py index b63003f80..ca410a24a 100644 --- a/numpy/lib/npyio.py +++ b/numpy/lib/npyio.py @@ -1,3 +1,5 @@ +from __future__ import division + __all__ = ['savetxt', 'loadtxt', 'genfromtxt', 'ndfromtxt', 'mafromtxt', 'recfromtxt', 'recfromcsv', 'load', 'loads', 'save', 'savez', 'savez_compressed', 'packbits', 'unpackbits', 'fromregex', 'DataSource'] diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py index fad06f4df..de83016e9 100644 --- a/numpy/lib/polynomial.py +++ b/numpy/lib/polynomial.py @@ -1,6 +1,8 @@ """ Functions to operate on polynomials. + """ +from __future__ import division __all__ = ['poly', 'roots', 'polyint', 'polyder', 'polyadd', 'polysub', 'polymul', 'polydiv', 'polyval', 'poly1d', @@ -564,9 +566,9 @@ def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): if w is not None: w = NX.asarray(w) + 0.0 if w.ndim != 1: - raise TypeError, "expected a 1-d array for weights" + raise TypeError("expected a 1-d array for weights") if w.shape[0] != y.shape[0] : - raise TypeError, "expected w and y to have the same length" + raise TypeError("expected w and y to have the same length") lhs *= w[:, NX.newaxis] if rhs.ndim == 2: rhs *= w[:, NX.newaxis] diff --git a/numpy/lib/recfunctions.py b/numpy/lib/recfunctions.py index 0127df9f9..c72cf2059 100644 --- a/numpy/lib/recfunctions.py +++ b/numpy/lib/recfunctions.py @@ -4,8 +4,8 @@ Collection of utilities to manipulate structured arrays. Most of these functions were initially implemented by John Hunter for matplotlib. They have been rewritten and extended for convenience. - """ +from __future__ import division import sys import itertools diff --git a/numpy/lib/scimath.py b/numpy/lib/scimath.py index 48ed1dc25..00fc4bccd 100644 --- a/numpy/lib/scimath.py +++ b/numpy/lib/scimath.py @@ -15,6 +15,7 @@ Similarly, `sqrt`, other base logarithms, `power` and trig functions are correctly handled. See their respective docstrings for specific examples. """ +from __future__ import division __all__ = ['sqrt', 'log', 'log2', 'logn','log10', 'power', 'arccos', 'arcsin', 'arctanh'] diff --git a/numpy/lib/setup.py b/numpy/lib/setup.py index e85fdb517..e69c8c4fa 100644 --- a/numpy/lib/setup.py +++ b/numpy/lib/setup.py @@ -1,3 +1,5 @@ +from __future__ import division + from os.path import join def configuration(parent_package='',top_path=None): diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py index aefc81c2b..575f6149d 100644 --- a/numpy/lib/shape_base.py +++ b/numpy/lib/shape_base.py @@ -1,3 +1,5 @@ +from __future__ import division + __all__ = ['column_stack','row_stack', 'dstack','array_split','split','hsplit', 'vsplit','dsplit','apply_over_axes','expand_dims', 'apply_along_axis', 'kron', 'tile', 'get_array_wrap'] diff --git a/numpy/lib/stride_tricks.py b/numpy/lib/stride_tricks.py index 7358be222..b82537024 100644 --- a/numpy/lib/stride_tricks.py +++ b/numpy/lib/stride_tricks.py @@ -5,6 +5,8 @@ An explanation of strides can be found in the "ndarray.rst" file in the NumPy reference guide. """ +from __future__ import division + import numpy as np __all__ = ['broadcast_arrays'] diff --git a/numpy/lib/tests/test__datasource.py b/numpy/lib/tests/test__datasource.py index ed5af516f..f025b947e 100644 --- a/numpy/lib/tests/test__datasource.py +++ b/numpy/lib/tests/test__datasource.py @@ -1,3 +1,5 @@ +from __future__ import division + import os from tempfile import mkdtemp, mkstemp, NamedTemporaryFile from shutil import rmtree @@ -92,7 +94,7 @@ class TestDataSourceOpen(TestCase): self.assertRaises(IOError, self.ds.open, url) try: self.ds.open(url) - except IOError, e: + except IOError as e: # Regression test for bug fixed in r4342. assert_(e.errno is None) diff --git a/numpy/lib/tests/test__iotools.py b/numpy/lib/tests/test__iotools.py index a0f1546e2..6416b6d7a 100644 --- a/numpy/lib/tests/test__iotools.py +++ b/numpy/lib/tests/test__iotools.py @@ -1,4 +1,7 @@ +from __future__ import division + import sys + if sys.version_info[0] >= 3: from io import BytesIO def StringIO(s=""): diff --git a/numpy/lib/tests/test_arraypad.py b/numpy/lib/tests/test_arraypad.py index 01cb5be4c..e70c06aeb 100644 --- a/numpy/lib/tests/test_arraypad.py +++ b/numpy/lib/tests/test_arraypad.py @@ -1,6 +1,7 @@ -''' -Tests for the pad functions. -''' +"""Tests for the pad functions. + +""" +from __future__ import division from numpy.testing import TestCase, run_module_suite, assert_array_equal from numpy.testing import assert_raises, assert_array_almost_equal diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py index 5f4f10c76..cab7a86b1 100644 --- a/numpy/lib/tests/test_arraysetops.py +++ b/numpy/lib/tests/test_arraysetops.py @@ -1,6 +1,7 @@ -""" Test functions for 1D array set operations. +"""Test functions for 1D array set operations. """ +from __future__ import division from numpy.testing import * import numpy as np diff --git a/numpy/lib/tests/test_arrayterator.py b/numpy/lib/tests/test_arrayterator.py index c1c59ba31..5064ab496 100644 --- a/numpy/lib/tests/test_arrayterator.py +++ b/numpy/lib/tests/test_arrayterator.py @@ -1,3 +1,5 @@ +from __future__ import division + from operator import mul import numpy as np diff --git a/numpy/lib/tests/test_financial.py b/numpy/lib/tests/test_financial.py index 5fe976143..e06c50ef6 100644 --- a/numpy/lib/tests/test_financial.py +++ b/numpy/lib/tests/test_financial.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * import numpy as np diff --git a/numpy/lib/tests/test_format.py b/numpy/lib/tests/test_format.py index 213d69760..320cef3d2 100644 --- a/numpy/lib/tests/test_format.py +++ b/numpy/lib/tests/test_format.py @@ -1,3 +1,5 @@ +from __future__ import division + r''' Test the .npy file format. Set up: diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py index 49544b22b..25c498312 100644 --- a/numpy/lib/tests/test_function_base.py +++ b/numpy/lib/tests/test_function_base.py @@ -1,3 +1,5 @@ +from __future__ import division + import warnings import numpy as np from numpy.testing import ( diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py index a6e65ef56..2b42fdc2c 100644 --- a/numpy/lib/tests/test_index_tricks.py +++ b/numpy/lib/tests/test_index_tricks.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * import numpy as np from numpy import ( array, ones, r_, mgrid, unravel_index, zeros, where, diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index f8caeedb6..f1088ebb5 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys import gzip import os @@ -151,7 +153,7 @@ class TestSavezLoad(RoundtripTest, TestCase): arr = np.random.randn(500, 500) try: np.savez(tmp, arr=arr) - except OSError, err: + except OSError as err: error_list.append(err) finally: os.remove(tmp) @@ -207,7 +209,7 @@ class TestSavezLoad(RoundtripTest, TestCase): for i in range(1, 1025): try: np.load(tmp)["data"] - except Exception, e: + except Exception as e: raise AssertionError("Failed to load data from a file: %s" % e) finally: os.remove(tmp) diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py index 3c69cb93b..fc2b49c81 100644 --- a/numpy/lib/tests/test_polynomial.py +++ b/numpy/lib/tests/test_polynomial.py @@ -1,4 +1,6 @@ -""" +from __future__ import division + +''' >>> p = np.poly1d([1.,2,3]) >>> p poly1d([ 1., 2., 3.]) @@ -74,8 +76,8 @@ poly1d([ 2.]) >>> np.polydiv(np.poly1d([1,0,-1]), np.poly1d([1,1])) (poly1d([ 1., -1.]), poly1d([ 0.])) -""" +''' from numpy.testing import * import numpy as np diff --git a/numpy/lib/tests/test_recfunctions.py b/numpy/lib/tests/test_recfunctions.py index 3d2d1e983..6a0ad1609 100644 --- a/numpy/lib/tests/test_recfunctions.py +++ b/numpy/lib/tests/test_recfunctions.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys import numpy as np diff --git a/numpy/lib/tests/test_regression.py b/numpy/lib/tests/test_regression.py index 270da73e3..e0a3a424d 100644 --- a/numpy/lib/tests/test_regression.py +++ b/numpy/lib/tests/test_regression.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * from numpy.testing.utils import _assert_valid_refcount import numpy as np diff --git a/numpy/lib/tests/test_shape_base.py b/numpy/lib/tests/test_shape_base.py index 56178e8af..70c4d33ac 100644 --- a/numpy/lib/tests/test_shape_base.py +++ b/numpy/lib/tests/test_shape_base.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * from numpy.lib import * from numpy.core import * diff --git a/numpy/lib/tests/test_stride_tricks.py b/numpy/lib/tests/test_stride_tricks.py index 814f2d614..0ac1c279b 100644 --- a/numpy/lib/tests/test_stride_tricks.py +++ b/numpy/lib/tests/test_stride_tricks.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy as np from numpy.testing import * from numpy.lib.stride_tricks import broadcast_arrays diff --git a/numpy/lib/tests/test_twodim_base.py b/numpy/lib/tests/test_twodim_base.py index 7e7900090..702f9a6f5 100644 --- a/numpy/lib/tests/test_twodim_base.py +++ b/numpy/lib/tests/test_twodim_base.py @@ -1,6 +1,7 @@ -""" Test functions for matrix module +"""Test functions for matrix module """ +from __future__ import division from numpy.testing import * diff --git a/numpy/lib/tests/test_type_check.py b/numpy/lib/tests/test_type_check.py index 0f8927614..c4f4a6299 100644 --- a/numpy/lib/tests/test_type_check.py +++ b/numpy/lib/tests/test_type_check.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * from numpy.lib import * from numpy.core import * diff --git a/numpy/lib/tests/test_ufunclike.py b/numpy/lib/tests/test_ufunclike.py index 29b47f257..0f688b021 100644 --- a/numpy/lib/tests/test_ufunclike.py +++ b/numpy/lib/tests/test_ufunclike.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * import numpy.core as nx import numpy.lib.ufunclike as ufl diff --git a/numpy/lib/tests/test_utils.py b/numpy/lib/tests/test_utils.py index 80f90f04b..534806ff2 100644 --- a/numpy/lib/tests/test_utils.py +++ b/numpy/lib/tests/test_utils.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * import numpy.lib.utils as utils from numpy.lib import deprecate diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py index ce147965c..92df5306d 100644 --- a/numpy/lib/twodim_base.py +++ b/numpy/lib/twodim_base.py @@ -1,6 +1,7 @@ """ Basic functions for manipulating 2d arrays """ +from __future__ import division __all__ = ['diag','diagflat','eye','fliplr','flipud','rot90','tri','triu', 'tril','vander','histogram2d','mask_indices', diff --git a/numpy/lib/type_check.py b/numpy/lib/type_check.py index e22d63156..895c4d406 100644 --- a/numpy/lib/type_check.py +++ b/numpy/lib/type_check.py @@ -1,4 +1,7 @@ -## Automatically adapted for numpy Sep 19, 2005 by convertcode.py +"""Automatically adapted for numpy Sep 19, 2005 by convertcode.py + +""" +from __future__ import division __all__ = ['iscomplexobj','isrealobj','imag','iscomplex', 'isreal','nan_to_num','real','real_if_close', diff --git a/numpy/lib/ufunclike.py b/numpy/lib/ufunclike.py index b51365f41..8b85ef770 100644 --- a/numpy/lib/ufunclike.py +++ b/numpy/lib/ufunclike.py @@ -1,7 +1,10 @@ """ Module of functions that are like ufuncs in acting on arrays and optionally storing results in an output array. + """ +from __future__ import division + __all__ = ['fix', 'isneginf', 'isposinf'] import numpy.core.numeric as nx diff --git a/numpy/lib/user_array.py b/numpy/lib/user_array.py index 01b0b1c19..51ab10520 100644 --- a/numpy/lib/user_array.py +++ b/numpy/lib/user_array.py @@ -2,7 +2,9 @@ Standard container-class for easy multiple-inheritance. Try to inherit from the ndarray instead of using this class as this is not complete. + """ +from __future__ import division from numpy.core import array, asarray, absolute, add, subtract, multiply, \ divide, remainder, power, left_shift, right_shift, bitwise_and, \ diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index dc6c16767..2e70bfd15 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import sys import types @@ -86,8 +88,8 @@ if sys.version_info < (2, 4): # Can't set __name__ in 2.3 import new def _set_function_name(func, name): - func = new.function(func.func_code, func.func_globals, - name, func.func_defaults, func.func_closure) + func = new.function(func.__code__, func.__globals__, + name, func.__defaults__, func.__closure__) return func else: def _set_function_name(func, name): @@ -122,7 +124,7 @@ class _Deprecate(object): import warnings if old_name is None: try: - old_name = func.func_name + old_name = func.__name__ except AttributeError: old_name = func.__name__ if new_name is None: @@ -541,7 +543,7 @@ def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): print >> output, "\n *** Total of %d references found. ***" % numfound elif inspect.isfunction(object): - name = object.func_name + name = object.__name__ arguments = inspect.formatargspec(*inspect.getargspec(object)) if len(name+arguments) > maxwidth: @@ -557,7 +559,7 @@ def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): arguments = "()" try: if hasattr(object, '__init__'): - arguments = inspect.formatargspec(*inspect.getargspec(object.__init__.im_func)) + arguments = inspect.formatargspec(*inspect.getargspec(object.__init__.__func__)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] @@ -593,7 +595,7 @@ def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): print >> output, "Instance of class: ", object.__class__.__name__ print >> output if hasattr(object, '__call__'): - arguments = inspect.formatargspec(*inspect.getargspec(object.__call__.im_func)) + arguments = inspect.formatargspec(*inspect.getargspec(object.__call__.__func__)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] @@ -621,7 +623,7 @@ def info(object=None,maxwidth=76,output=sys.stdout,toplevel='numpy'): elif inspect.ismethod(object): name = object.__name__ - arguments = inspect.formatargspec(*inspect.getargspec(object.im_func)) + arguments = inspect.formatargspec(*inspect.getargspec(object.__func__)) arglist = arguments.split(', ') if len(arglist) > 1: arglist[1] = "("+arglist[1] @@ -1154,11 +1156,11 @@ def safe_eval(source): walker = SafeEval() try: ast = compiler.parse(source, mode="eval") - except SyntaxError, err: + except SyntaxError as err: raise try: return walker.visit(ast) - except SyntaxError, err: + except SyntaxError as err: raise #----------------------------------------------------------------------------- diff --git a/numpy/linalg/__init__.py b/numpy/linalg/__init__.py index a74a31950..ed281abee 100644 --- a/numpy/linalg/__init__.py +++ b/numpy/linalg/__init__.py @@ -42,6 +42,8 @@ LinAlgError Indicates a failed linear algebra operation =============== ========================================================== """ +from __future__ import division + # To get sub-modules from info import __doc__ diff --git a/numpy/linalg/info.py b/numpy/linalg/info.py index 235822dfa..45b91db18 100644 --- a/numpy/linalg/info.py +++ b/numpy/linalg/info.py @@ -32,5 +32,6 @@ Exceptions: - LinAlgError Indicates a failed linear algebra operation """ +from __future__ import division depends = ['core'] diff --git a/numpy/linalg/lapack_lite/clapack_scrub.py b/numpy/linalg/lapack_lite/clapack_scrub.py index 1b26c23e4..10ee543b9 100644 --- a/numpy/linalg/lapack_lite/clapack_scrub.py +++ b/numpy/linalg/lapack_lite/clapack_scrub.py @@ -1,4 +1,5 @@ #!/usr/bin/env python2.4 +from __future__ import division import sys, os from cStringIO import StringIO diff --git a/numpy/linalg/lapack_lite/fortran.py b/numpy/linalg/lapack_lite/fortran.py index 7be986a8e..6fff72312 100644 --- a/numpy/linalg/lapack_lite/fortran.py +++ b/numpy/linalg/lapack_lite/fortran.py @@ -1,3 +1,5 @@ +from __future__ import division + import re import itertools diff --git a/numpy/linalg/lapack_lite/make_lite.py b/numpy/linalg/lapack_lite/make_lite.py index e857866e1..1fea7c049 100755 --- a/numpy/linalg/lapack_lite/make_lite.py +++ b/numpy/linalg/lapack_lite/make_lite.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +from __future__ import division import sys, os import fortran diff --git a/numpy/linalg/linalg.py b/numpy/linalg/linalg.py index a4afb6b6a..167e733fd 100644 --- a/numpy/linalg/linalg.py +++ b/numpy/linalg/linalg.py @@ -8,6 +8,8 @@ version only accesses the following LAPACK functions: dgesv, zgesv, dgeev, zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr. """ +from __future__ import division + __all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv', 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'slogdet', 'det', diff --git a/numpy/linalg/setup.py b/numpy/linalg/setup.py index 1fb7a3acd..40e9c0dec 100644 --- a/numpy/linalg/setup.py +++ b/numpy/linalg/setup.py @@ -1,3 +1,4 @@ +from __future__ import division import sys diff --git a/numpy/linalg/tests/test_build.py b/numpy/linalg/tests/test_build.py index 691fd7a6b..4a151d3f4 100644 --- a/numpy/linalg/tests/test_build.py +++ b/numpy/linalg/tests/test_build.py @@ -1,3 +1,5 @@ +from __future__ import division + from subprocess import call, PIPE, Popen import sys import re diff --git a/numpy/linalg/tests/test_linalg.py b/numpy/linalg/tests/test_linalg.py index 623939863..fb8f89fe9 100644 --- a/numpy/linalg/tests/test_linalg.py +++ b/numpy/linalg/tests/test_linalg.py @@ -1,5 +1,7 @@ """ Test functions for linalg module """ +from __future__ import division + import sys import numpy as np @@ -63,7 +65,7 @@ class LinalgTestCase(object): try: self.do(a, b) raise AssertionError("%s should fail with empty matrices", self.__name__[5:]) - except linalg.LinAlgError, e: + except linalg.LinAlgError as e: pass def test_nonarray(self): diff --git a/numpy/linalg/tests/test_regression.py b/numpy/linalg/tests/test_regression.py index b3188f99c..9ca56e9ff 100644 --- a/numpy/linalg/tests/test_regression.py +++ b/numpy/linalg/tests/test_regression.py @@ -1,5 +1,7 @@ """ Test functions for linalg module """ +from __future__ import division + from numpy.testing import * import numpy as np diff --git a/numpy/ma/__init__.py b/numpy/ma/__init__.py index 17caa9e02..7388a7ce3 100644 --- a/numpy/ma/__init__.py +++ b/numpy/ma/__init__.py @@ -36,6 +36,8 @@ may now proceed to calculate the mean of the other values: invalid operation. """ +from __future__ import division + __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' __revision__ = "$Revision: 3473 $" diff --git a/numpy/ma/bench.py b/numpy/ma/bench.py index 2cc8f6a80..df6933eb9 100644 --- a/numpy/ma/bench.py +++ b/numpy/ma/bench.py @@ -1,5 +1,6 @@ #! python # encoding: utf-8 +from __future__ import division import timeit #import IPython.ipapi diff --git a/numpy/ma/core.py b/numpy/ma/core.py index dbd619b80..371d5f302 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -20,6 +20,8 @@ Released for unlimited redistribution. """ # pylint: disable-msg=E1002 +from __future__ import division + __author__ = "Pierre GF Gerard-Marchant" __docformat__ = "restructuredtext en" @@ -110,7 +112,7 @@ def get_object_signature(obj): """ try: sig = formatargspec(*getargspec(obj)) - except TypeError, errmsg: + except TypeError as errmsg: sig = '' # msg = "Unable to retrieve the signature of %s '%s'\n"\ # "(Initial error message: %s)" @@ -2889,6 +2891,15 @@ class MaskedArray(ndarray): `dtype` is an ndarray sub-class), then the fill value is preserved. Finally, if `fill_value` is specified, but `dtype` is not, the fill value is set to the specified value. + + For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of + bytes per entry than the previous dtype (for example, converting a + regular array to a structured array), then the behavior of the view + cannot be predicted just from the superficial appearance of ``a`` (shown + by ``print(a)``). It also depends on exactly how ``a`` is stored in + memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus + defined as a slice or transpose, etc., the view may give different + results. """ if dtype is None: diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py index c5b3a3957..857d72249 100644 --- a/numpy/ma/extras.py +++ b/numpy/ma/extras.py @@ -8,6 +8,8 @@ A collection of utilities for `numpy.ma`. :version: $Id: extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $ """ +from __future__ import division + __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' __revision__ = "$Revision: 3473 $" @@ -1865,9 +1867,9 @@ def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False): if w is not None: w = asarray(w) if w.ndim != 1: - raise TypeError, "expected a 1-d array for weights" + raise TypeError("expected a 1-d array for weights") if w.shape[0] != y.shape[0] : - raise TypeError, "expected w and y to have the same length" + raise TypeError("expected w and y to have the same length") m = mask_or(m, getmask(w)) if m is not nomask: diff --git a/numpy/ma/mrecords.py b/numpy/ma/mrecords.py index 44d273d34..084859d07 100644 --- a/numpy/ma/mrecords.py +++ b/numpy/ma/mrecords.py @@ -6,7 +6,10 @@ Note that :class:`numpy.ma.MaskedArray` already supports structured datatypes and the masking of individual fields. :author: Pierre Gerard-Marchant + """ +from __future__ import division + #!!!: * We should make sure that no field is called '_mask','mask','_fieldmask', #!!!: or whatever restricted keywords. #!!!: An idea would be to no bother in the first place, and then rename the @@ -252,7 +255,7 @@ class MaskedRecords(MaskedArray, object): optinfo = ndarray.__getattribute__(self, '_optinfo') or {} if not (attr in fielddict or attr in optinfo): exctype, value = sys.exc_info()[:2] - raise exctype, value + raise exctype(value) else: # Get the list of names ...... fielddict = ndarray.__getattribute__(self, 'dtype').fields or {} diff --git a/numpy/ma/setup.py b/numpy/ma/setup.py index 024746655..2191d23f4 100644 --- a/numpy/ma/setup.py +++ b/numpy/ma/setup.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import division + __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' __revision__ = "$Revision: 3473 $" diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py index cd60f7d71..cf8f1111d 100644 --- a/numpy/ma/tests/test_core.py +++ b/numpy/ma/tests/test_core.py @@ -4,6 +4,8 @@ :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu """ +from __future__ import division + __author__ = "Pierre GF Gerard-Marchant" import types diff --git a/numpy/ma/tests/test_extras.py b/numpy/ma/tests/test_extras.py index f1b36a15d..3f25ac21c 100644 --- a/numpy/ma/tests/test_extras.py +++ b/numpy/ma/tests/test_extras.py @@ -5,7 +5,10 @@ Adapted from the original test_ma by Pierre Gerard-Marchant :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu :version: $Id: test_extras.py 3473 2007-10-29 15:18:13Z jarrod.millman $ + """ +from __future__ import division + __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' __revision__ = "$Revision: 3473 $" diff --git a/numpy/ma/tests/test_mrecords.py b/numpy/ma/tests/test_mrecords.py index c8d9b0a46..4e59b8e41 100644 --- a/numpy/ma/tests/test_mrecords.py +++ b/numpy/ma/tests/test_mrecords.py @@ -3,7 +3,10 @@ :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu + """ +from __future__ import division + __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __revision__ = "$Revision: 3473 $" __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' diff --git a/numpy/ma/tests/test_old_ma.py b/numpy/ma/tests/test_old_ma.py index 656f0b318..c9dbe4d4a 100644 --- a/numpy/ma/tests/test_old_ma.py +++ b/numpy/ma/tests/test_old_ma.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy import types from numpy.ma import * diff --git a/numpy/ma/tests/test_regression.py b/numpy/ma/tests/test_regression.py index 3a634452b..85c290160 100644 --- a/numpy/ma/tests/test_regression.py +++ b/numpy/ma/tests/test_regression.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * import numpy as np import numpy.ma as ma diff --git a/numpy/ma/tests/test_subclassing.py b/numpy/ma/tests/test_subclassing.py index fb72ca773..ce3d8c889 100644 --- a/numpy/ma/tests/test_subclassing.py +++ b/numpy/ma/tests/test_subclassing.py @@ -4,7 +4,10 @@ :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu :version: $Id: test_subclassing.py 3473 2007-10-29 15:18:13Z jarrod.millman $ + """ +from __future__ import division + __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = '1.0' __revision__ = "$Revision: 3473 $" diff --git a/numpy/ma/testutils.py b/numpy/ma/testutils.py index 4fb76b330..3707dcc16 100644 --- a/numpy/ma/testutils.py +++ b/numpy/ma/testutils.py @@ -3,7 +3,10 @@ :author: Pierre Gerard-Marchant :contact: pierregm_at_uga_dot_edu :version: $Id: testutils.py 3529 2007-11-13 08:01:14Z jarrod.millman $ + """ +from __future__ import division + __author__ = "Pierre GF Gerard-Marchant ($Author: jarrod.millman $)" __version__ = "1.0" __revision__ = "$Revision: 3529 $" diff --git a/numpy/ma/timer_comparison.py b/numpy/ma/timer_comparison.py index 2588f53b2..adc1fa22b 100644 --- a/numpy/ma/timer_comparison.py +++ b/numpy/ma/timer_comparison.py @@ -1,3 +1,5 @@ +from __future__ import division + import timeit import sys diff --git a/numpy/ma/version.py b/numpy/ma/version.py index 7a925f1a8..73281311d 100644 --- a/numpy/ma/version.py +++ b/numpy/ma/version.py @@ -1,4 +1,7 @@ -"""Version number""" +"""Version number + +""" +from __future__ import division version = '1.00' release = False diff --git a/numpy/matlib.py b/numpy/matlib.py index f55f763c3..ae053373b 100644 --- a/numpy/matlib.py +++ b/numpy/matlib.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy as np from numpy.matrixlib.defmatrix import matrix, asmatrix # need * as we're copying the numpy namespace diff --git a/numpy/matrixlib/__init__.py b/numpy/matrixlib/__init__.py index 468a8829d..dc9a6bca9 100644 --- a/numpy/matrixlib/__init__.py +++ b/numpy/matrixlib/__init__.py @@ -1,4 +1,8 @@ -"""Sub-package containing the matrix class and related functions.""" +"""Sub-package containing the matrix class and related functions. + +""" +from __future__ import division + from defmatrix import * __all__ = defmatrix.__all__ diff --git a/numpy/matrixlib/defmatrix.py b/numpy/matrixlib/defmatrix.py index dbf2909fd..f0299ee88 100644 --- a/numpy/matrixlib/defmatrix.py +++ b/numpy/matrixlib/defmatrix.py @@ -1,3 +1,5 @@ +from __future__ import division + __all__ = ['matrix', 'bmat', 'mat', 'asmatrix'] import sys diff --git a/numpy/matrixlib/setup.py b/numpy/matrixlib/setup.py index 85b090094..539e62a7f 100644 --- a/numpy/matrixlib/setup.py +++ b/numpy/matrixlib/setup.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import division + import os def configuration(parent_package='', top_path=None): diff --git a/numpy/matrixlib/tests/test_defmatrix.py b/numpy/matrixlib/tests/test_defmatrix.py index 0a181fca3..74c379d77 100644 --- a/numpy/matrixlib/tests/test_defmatrix.py +++ b/numpy/matrixlib/tests/test_defmatrix.py @@ -1,9 +1,12 @@ +from __future__ import division + from numpy.testing import * from numpy.core import * from numpy import matrix, asmatrix, bmat from numpy.matrixlib.defmatrix import matrix_power from numpy.matrixlib import mat import numpy as np +import collections class TestCtor(TestCase): def test_basic(self): @@ -285,7 +288,7 @@ class TestMatrixReturn(TestCase): if attrib.startswith('_') or attrib in excluded_methods: continue f = getattr(a, attrib) - if callable(f): + if isinstance(f, collections.Callable): # reset contents of a a.astype('f8') a.fill(1.0) diff --git a/numpy/matrixlib/tests/test_multiarray.py b/numpy/matrixlib/tests/test_multiarray.py index 9ef105aa3..6247a1c48 100644 --- a/numpy/matrixlib/tests/test_multiarray.py +++ b/numpy/matrixlib/tests/test_multiarray.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy as np from numpy.testing import * diff --git a/numpy/matrixlib/tests/test_numeric.py b/numpy/matrixlib/tests/test_numeric.py index 0b96bb05a..5539dac0d 100644 --- a/numpy/matrixlib/tests/test_numeric.py +++ b/numpy/matrixlib/tests/test_numeric.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import assert_equal, TestCase from numpy.core import ones from numpy import matrix diff --git a/numpy/matrixlib/tests/test_regression.py b/numpy/matrixlib/tests/test_regression.py index ba0133dfd..ae352f09c 100644 --- a/numpy/matrixlib/tests/test_regression.py +++ b/numpy/matrixlib/tests/test_regression.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * import numpy as np diff --git a/numpy/numarray/__init__.py b/numpy/numarray/__init__.py index 441ec4450..964ee2baa 100644 --- a/numpy/numarray/__init__.py +++ b/numpy/numarray/__init__.py @@ -1,3 +1,5 @@ +from __future__ import division + from util import * from numerictypes import * from functions import * diff --git a/numpy/numarray/alter_code1.py b/numpy/numarray/alter_code1.py index ae950e7e0..2393aff5a 100644 --- a/numpy/numarray/alter_code1.py +++ b/numpy/numarray/alter_code1.py @@ -52,6 +52,8 @@ Makes the following changes: - .setimaginary() --> .imag """ +from __future__ import division + __all__ = ['convertfile', 'convertall', 'converttree', 'convertsrc'] import sys diff --git a/numpy/numarray/alter_code2.py b/numpy/numarray/alter_code2.py index 4bb773850..4d76222da 100644 --- a/numpy/numarray/alter_code2.py +++ b/numpy/numarray/alter_code2.py @@ -5,7 +5,8 @@ with numpy FIXME: finish this. """ -#__all__ = ['convertfile', 'convertall', 'converttree'] +from __future__ import division + __all__ = [] import warnings diff --git a/numpy/numarray/compat.py b/numpy/numarray/compat.py index e0d13a7c2..794a2d591 100644 --- a/numpy/numarray/compat.py +++ b/numpy/numarray/compat.py @@ -1,3 +1,4 @@ +from __future__ import division __all__ = ['NewAxis', 'ArrayType'] diff --git a/numpy/numarray/convolve.py b/numpy/numarray/convolve.py index 68a4730a1..14c16f008 100644 --- a/numpy/numarray/convolve.py +++ b/numpy/numarray/convolve.py @@ -1,3 +1,5 @@ +from __future__ import division + try: from stsci.convolve import * except ImportError: diff --git a/numpy/numarray/fft.py b/numpy/numarray/fft.py index c7ac6a27e..158c8807e 100644 --- a/numpy/numarray/fft.py +++ b/numpy/numarray/fft.py @@ -1,3 +1,4 @@ +from __future__ import division from numpy.oldnumeric.fft import * import numpy.oldnumeric.fft as nof diff --git a/numpy/numarray/functions.py b/numpy/numarray/functions.py index 1c2141c98..7242f2870 100644 --- a/numpy/numarray/functions.py +++ b/numpy/numarray/functions.py @@ -1,18 +1,6 @@ +from __future__ import division + # missing Numarray defined names (in from numarray import *) -##__all__ = ['ClassicUnpickler', 'Complex32_fromtype', -## 'Complex64_fromtype', 'ComplexArray', 'Error', -## 'MAX_ALIGN', 'MAX_INT_SIZE', 'MAX_LINE_WIDTH', -## 'NDArray', 'NewArray', 'NumArray', -## 'NumError', 'PRECISION', 'Py2NumType', -## 'PyINT_TYPES', 'PyLevel2Type', 'PyNUMERIC_TYPES', 'PyREAL_TYPES', -## 'SUPPRESS_SMALL', -## 'SuitableBuffer', 'USING_BLAS', -## 'UsesOpPriority', -## 'codegenerator', 'generic', 'libnumarray', 'libnumeric', -## 'make_ufuncs', 'memory', -## 'numarrayall', 'numarraycore', 'numinclude', 'safethread', -## 'typecode', 'typecodes', 'typeconv', 'ufunc', 'ufuncFactory', -## 'ieeemask'] __all__ = ['asarray', 'ones', 'zeros', 'array', 'where'] __all__ += ['vdot', 'dot', 'matrixmultiply', 'ravel', 'indices', diff --git a/numpy/numarray/image.py b/numpy/numarray/image.py index 323528905..112fdac9e 100644 --- a/numpy/numarray/image.py +++ b/numpy/numarray/image.py @@ -1,3 +1,5 @@ +from __future__ import division + try: from stsci.image import * except ImportError: diff --git a/numpy/numarray/linear_algebra.py b/numpy/numarray/linear_algebra.py index 238dff952..1c716e05b 100644 --- a/numpy/numarray/linear_algebra.py +++ b/numpy/numarray/linear_algebra.py @@ -1,3 +1,4 @@ +from __future__ import division from numpy.oldnumeric.linear_algebra import * diff --git a/numpy/numarray/ma.py b/numpy/numarray/ma.py index 5c7a19cf2..2b820a98d 100644 --- a/numpy/numarray/ma.py +++ b/numpy/numarray/ma.py @@ -1,2 +1,3 @@ +from __future__ import division from numpy.oldnumeric.ma import * diff --git a/numpy/numarray/matrix.py b/numpy/numarray/matrix.py index 86d79bbe2..723613c63 100644 --- a/numpy/numarray/matrix.py +++ b/numpy/numarray/matrix.py @@ -1,3 +1,4 @@ +from __future__ import division __all__ = ['Matrix'] diff --git a/numpy/numarray/mlab.py b/numpy/numarray/mlab.py index 05f234d37..70ccf077a 100644 --- a/numpy/numarray/mlab.py +++ b/numpy/numarray/mlab.py @@ -1,3 +1,4 @@ +from __future__ import division from numpy.oldnumeric.mlab import * import numpy.oldnumeric.mlab as nom diff --git a/numpy/numarray/nd_image.py b/numpy/numarray/nd_image.py index dff7fa066..a9a7ee1f4 100644 --- a/numpy/numarray/nd_image.py +++ b/numpy/numarray/nd_image.py @@ -1,3 +1,5 @@ +from __future__ import division + try: from ndimage import * except ImportError: diff --git a/numpy/numarray/numerictypes.py b/numpy/numarray/numerictypes.py index 70a134855..ef1ccb2a3 100644 --- a/numpy/numarray/numerictypes.py +++ b/numpy/numarray/numerictypes.py @@ -25,7 +25,10 @@ Exported symbols include: ComplexType $Id: numerictypes.py,v 1.55 2005/12/01 16:22:03 jaytmiller Exp $ + """ +from __future__ import division + __all__ = ['NumericType','HasUInt64','typeDict','IsType', 'BooleanType', 'SignedType', 'UnsignedType', 'IntegralType', diff --git a/numpy/numarray/random_array.py b/numpy/numarray/random_array.py index d70e2694a..654f58346 100644 --- a/numpy/numarray/random_array.py +++ b/numpy/numarray/random_array.py @@ -1,3 +1,4 @@ +from __future__ import division __all__ = ['ArgumentError', 'F', 'beta', 'binomial', 'chi_square', 'exponential', 'gamma', 'get_seed', 'multinomial', diff --git a/numpy/numarray/session.py b/numpy/numarray/session.py index 0982742ab..fab80a1e2 100644 --- a/numpy/numarray/session.py +++ b/numpy/numarray/session.py @@ -72,6 +72,7 @@ Saved modules are re-imported at load time but any "state" in the module which is not restored by a simple import is lost. """ +from __future__ import division __all__ = ['load', 'save'] @@ -168,7 +169,7 @@ def _loadmodule(module): s = "" for i in range(len(modules)): s = ".".join(modules[:i+1]) - exec "import " + s + exec("import " + s) return sys.modules[module] class _ObjectProxy(object): diff --git a/numpy/numarray/setup.py b/numpy/numarray/setup.py index 641990217..ab3f2a4d5 100644 --- a/numpy/numarray/setup.py +++ b/numpy/numarray/setup.py @@ -1,3 +1,5 @@ +from __future__ import division + from os.path import join def configuration(parent_package='',top_path=None): diff --git a/numpy/numarray/ufuncs.py b/numpy/numarray/ufuncs.py index 3fb5671ce..357972c79 100644 --- a/numpy/numarray/ufuncs.py +++ b/numpy/numarray/ufuncs.py @@ -1,3 +1,4 @@ +from __future__ import division __all__ = ['abs', 'absolute', 'add', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_not', diff --git a/numpy/numarray/util.py b/numpy/numarray/util.py index 9555474a8..819987cbf 100644 --- a/numpy/numarray/util.py +++ b/numpy/numarray/util.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import numpy as np diff --git a/numpy/oldnumeric/__init__.py b/numpy/oldnumeric/__init__.py index 05712c02c..5fc8f7c76 100644 --- a/numpy/oldnumeric/__init__.py +++ b/numpy/oldnumeric/__init__.py @@ -1,4 +1,8 @@ -# Don't add these to the __all__ variable though +"""Don't add these to the __all__ variable though + +""" +from __future__ import division + from numpy import * def _move_axis_to_0(a, axis): diff --git a/numpy/oldnumeric/alter_code1.py b/numpy/oldnumeric/alter_code1.py index 87538a855..5eb1c99f2 100644 --- a/numpy/oldnumeric/alter_code1.py +++ b/numpy/oldnumeric/alter_code1.py @@ -27,7 +27,10 @@ Makes the following changes: * Converts uses of type(...) is <type> isinstance(..., <type>) + """ +from __future__ import division + __all__ = ['convertfile', 'convertall', 'converttree', 'convertsrc'] import sys diff --git a/numpy/oldnumeric/alter_code2.py b/numpy/oldnumeric/alter_code2.py index baa6b9d26..61f285f63 100644 --- a/numpy/oldnumeric/alter_code2.py +++ b/numpy/oldnumeric/alter_code2.py @@ -19,6 +19,8 @@ Makes the following changes: oldnumeric.random_array, and oldnumeric.fft """ +from __future__ import division + #__all__ = ['convertfile', 'convertall', 'converttree'] __all__ = [] diff --git a/numpy/oldnumeric/array_printer.py b/numpy/oldnumeric/array_printer.py index 95f3f42c7..7c0428c14 100644 --- a/numpy/oldnumeric/array_printer.py +++ b/numpy/oldnumeric/array_printer.py @@ -1,3 +1,4 @@ +from __future__ import division __all__ = ['array2string'] diff --git a/numpy/oldnumeric/arrayfns.py b/numpy/oldnumeric/arrayfns.py index 683ed309d..1db219d4a 100644 --- a/numpy/oldnumeric/arrayfns.py +++ b/numpy/oldnumeric/arrayfns.py @@ -1,5 +1,7 @@ -"""Backward compatible with arrayfns from Numeric +"""Backward compatible with arrayfns from Numeric. + """ +from __future__ import division __all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask', 'histogram', 'index_sort', 'interp', 'nz', 'reverse', 'span', @@ -20,7 +22,7 @@ def array_set(vals1, indices, vals2): vals1 = asarray(vals1) vals2 = asarray(vals2) if vals1.ndim != vals2.ndim or vals1.ndim < 1: - raise error, "vals1 and vals2 must have same number of dimensions (>=1)" + raise error("vals1 and vals2 must have same number of dimensions (>=1)") vals1[indices] = vals2 from numpy import digitize @@ -38,7 +40,7 @@ def interp(y, x, z, typ=None): if typ == 'f': return res.astype('f') - raise error, "incompatible typecode" + raise error("incompatible typecode") def nz(x): x = asarray(x,dtype=np.ubyte) diff --git a/numpy/oldnumeric/compat.py b/numpy/oldnumeric/compat.py index 083a1fa15..0c18917d0 100644 --- a/numpy/oldnumeric/compat.py +++ b/numpy/oldnumeric/compat.py @@ -1,4 +1,7 @@ -# Compatibility module containing deprecated names +"""Compatibility module containing deprecated names. + +""" +from __future__ import division __all__ = ['NewAxis', 'UFuncType', 'UfuncType', 'ArrayType', 'arraytype', diff --git a/numpy/oldnumeric/fft.py b/numpy/oldnumeric/fft.py index 67f30c750..ace7d27d9 100644 --- a/numpy/oldnumeric/fft.py +++ b/numpy/oldnumeric/fft.py @@ -1,3 +1,4 @@ +from __future__ import division __all__ = ['fft', 'fft2d', 'fftnd', 'hermite_fft', 'inverse_fft', 'inverse_fft2d', 'inverse_fftnd', diff --git a/numpy/oldnumeric/fix_default_axis.py b/numpy/oldnumeric/fix_default_axis.py index 8483de85e..262f82859 100644 --- a/numpy/oldnumeric/fix_default_axis.py +++ b/numpy/oldnumeric/fix_default_axis.py @@ -32,7 +32,10 @@ cumprod prod std mean + """ +from __future__ import division + __all__ = ['convertfile', 'convertall', 'converttree'] import sys diff --git a/numpy/oldnumeric/functions.py b/numpy/oldnumeric/functions.py index db62f7cb5..1e4daef5d 100644 --- a/numpy/oldnumeric/functions.py +++ b/numpy/oldnumeric/functions.py @@ -1,4 +1,7 @@ -# Functions that should behave the same as Numeric and need changing +"""Functions that should behave the same as Numeric and need changing + +""" +from __future__ import division import numpy as np import numpy.core.multiarray as mu diff --git a/numpy/oldnumeric/linear_algebra.py b/numpy/oldnumeric/linear_algebra.py index 2e7a264fe..a8600c77d 100644 --- a/numpy/oldnumeric/linear_algebra.py +++ b/numpy/oldnumeric/linear_algebra.py @@ -1,10 +1,12 @@ """Backward compatible with LinearAlgebra from Numeric -""" -# This module is a lite version of the linalg.py module in SciPy which contains -# high-level Python interface to the LAPACK library. The lite version -# only accesses the following LAPACK functions: dgesv, zgesv, dgeev, -# zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, dpotrf. +This module is a lite version of the linalg.py module in SciPy which contains +high-level Python interface to the LAPACK library. The lite version +only accesses the following LAPACK functions: dgesv, zgesv, dgeev, +zgeev, dgesdd, zgesdd, dgelsd, zgelsd, dsyevd, zheevd, dgetrf, dpotrf. + +""" +from __future__ import division __all__ = ['LinAlgError', 'solve_linear_equations', 'inverse', 'cholesky_decomposition', 'eigenvalues', diff --git a/numpy/oldnumeric/ma.py b/numpy/oldnumeric/ma.py index 732e8447a..46af041ba 100644 --- a/numpy/oldnumeric/ma.py +++ b/numpy/oldnumeric/ma.py @@ -1,4 +1,5 @@ """MA: a facility for dealing with missing observations + MA is generally used as a numpy.array look-alike. by Paul F. Dubois. @@ -8,6 +9,8 @@ Adapted for numpy_core 2005 by Travis Oliphant and (mainly) Paul Dubois. """ +from __future__ import division + import types, sys import numpy.core.umath as umath diff --git a/numpy/oldnumeric/matrix.py b/numpy/oldnumeric/matrix.py index ddd612266..9be08e93c 100644 --- a/numpy/oldnumeric/matrix.py +++ b/numpy/oldnumeric/matrix.py @@ -1,4 +1,7 @@ -# This module is for compatibility only. +"""This module is for compatibility only. + +""" +from __future__ import division __all__ = ['UserArray', 'squeeze', 'Matrix', 'asarray', 'dot', 'k', 'Numeric', 'LinearAlgebra', 'identity', 'multiply', 'types', 'string'] diff --git a/numpy/oldnumeric/misc.py b/numpy/oldnumeric/misc.py index ccd47efbb..3871d8251 100644 --- a/numpy/oldnumeric/misc.py +++ b/numpy/oldnumeric/misc.py @@ -1,5 +1,7 @@ -# Functions that already have the correct syntax or miscellaneous functions +"""Functions that already have the correct syntax or miscellaneous functions +""" +from __future__ import division __all__ = ['sort', 'copy_reg', 'clip', 'rank', 'sign', 'shape', 'types', 'allclose', 'size', diff --git a/numpy/oldnumeric/mlab.py b/numpy/oldnumeric/mlab.py index 2c84b6960..e2ea78c02 100644 --- a/numpy/oldnumeric/mlab.py +++ b/numpy/oldnumeric/mlab.py @@ -1,4 +1,7 @@ -# This module is for compatibility only. All functions are defined elsewhere. +"""This module is for compatibility only. All functions are defined elsewhere. + +""" +from __future__ import division __all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', diff --git a/numpy/oldnumeric/precision.py b/numpy/oldnumeric/precision.py index c773e9478..c6579f302 100644 --- a/numpy/oldnumeric/precision.py +++ b/numpy/oldnumeric/precision.py @@ -1,7 +1,12 @@ -# Lifted from Precision.py. This is for compatibility only. -# -# The character strings are still for "new" NumPy -# which is the only Incompatibility with Numeric +""" + +Lifted from Precision.py. This is for compatibility only. + +The character strings are still for "new" NumPy +which is the only Incompatibility with Numeric + +""" +from __future__ import division __all__ = ['Character', 'Complex', 'Float', 'PrecisionError', 'PyObject', 'Int', 'UInt', diff --git a/numpy/oldnumeric/random_array.py b/numpy/oldnumeric/random_array.py index 777e2a645..a7f6c4112 100644 --- a/numpy/oldnumeric/random_array.py +++ b/numpy/oldnumeric/random_array.py @@ -1,4 +1,7 @@ -# Backward compatible module for RandomArray +"""Backward compatible module for RandomArray + +""" +from __future__ import division __all__ = ['ArgumentError','F','beta','binomial','chi_square', 'exponential', 'gamma', 'get_seed', 'mean_var_test', 'multinomial', @@ -201,20 +204,20 @@ def test(): mt.set_state(obj) obj2 = mt.get_state() if (obj2[1] - obj[1]).any(): - raise SystemExit, "Failed seed test." + raise SystemExit("Failed seed test.") print "First random number is", random() print "Average of 10000 random numbers is", np.sum(random(10000),axis=0)/10000. x = random([10,1000]) if len(x.shape) != 2 or x.shape[0] != 10 or x.shape[1] != 1000: - raise SystemExit, "random returned wrong shape" + raise SystemExit("random returned wrong shape") x.shape = (10000,) print "Average of 100 by 100 random numbers is", np.sum(x,axis=0)/10000. y = uniform(0.5,0.6, (1000,10)) if len(y.shape) !=2 or y.shape[0] != 1000 or y.shape[1] != 10: - raise SystemExit, "uniform returned wrong shape" + raise SystemExit("uniform returned wrong shape") y.shape = (10000,) if np.minimum.reduce(y) <= 0.5 or np.maximum.reduce(y) >= 0.6: - raise SystemExit, "uniform returned out of desired range" + raise SystemExit("uniform returned out of desired range") print "randint(1, 10, shape=[50])" print randint(1, 10, shape=[50]) print "permutation(10)", permutation(10) @@ -224,18 +227,18 @@ def test(): s = 3.0 x = normal(2.0, s, [10, 1000]) if len(x.shape) != 2 or x.shape[0] != 10 or x.shape[1] != 1000: - raise SystemExit, "standard_normal returned wrong shape" + raise SystemExit("standard_normal returned wrong shape") x.shape = (10000,) mean_var_test(x, "normally distributed numbers with mean 2 and variance %f"%(s**2,), 2, s**2, 0) x = exponential(3, 10000) mean_var_test(x, "random numbers exponentially distributed with mean %f"%(s,), s, s**2, 2) x = multivariate_normal(np.array([10,20]), np.array(([1,2],[2,4]))) print "\nA multivariate normal", x - if x.shape != (2,): raise SystemExit, "multivariate_normal returned wrong shape" + if x.shape != (2,): raise SystemExit("multivariate_normal returned wrong shape") x = multivariate_normal(np.array([10,20]), np.array([[1,2],[2,4]]), [4,3]) print "A 4x3x2 array containing multivariate normals" print x - if x.shape != (4,3,2): raise SystemExit, "multivariate_normal returned wrong shape" + if x.shape != (4,3,2): raise SystemExit("multivariate_normal returned wrong shape") x = multivariate_normal(np.array([-100,0,100]), np.array([[3,2,1],[2,2,1],[1,1,1]]), 10000) x_mean = np.sum(x,axis=0)/10000. print "Average of 10000 multivariate normals with mean [-100,0,100]" diff --git a/numpy/oldnumeric/rng.py b/numpy/oldnumeric/rng.py index 28d3f16df..28fb9d591 100644 --- a/numpy/oldnumeric/rng.py +++ b/numpy/oldnumeric/rng.py @@ -1,8 +1,10 @@ -# This module re-creates the RNG interface from Numeric -# Replace import RNG with import numpy.oldnumeric.rng as RNG -# -# It is for backwards compatibility only. +"""Re-create the RNG interface from Numeric. +Replace import RNG with import numpy.oldnumeric.rng as RNG. +It is for backwards compatibility only. + +""" +from __future__ import division __all__ = ['CreateGenerator','ExponentialDistribution','LogNormalDistribution', 'NormalDistribution', 'UniformDistribution', 'error', 'ranf', @@ -36,7 +38,7 @@ class Distribution(object): class ExponentialDistribution(Distribution): def __init__(self, lambda_): if (lambda_ <= 0): - raise error, "parameter must be positive" + raise error("parameter must be positive") Distribution.__init__(self, 'exponential', lambda_) def density(x): @@ -51,7 +53,7 @@ class LogNormalDistribution(Distribution): m = float(m) s = float(s) if (s <= 0): - raise error, "standard deviation must be positive" + raise error("standard deviation must be positive") Distribution.__init__(self, 'lognormal', m, s) sn = math.log(1.0+s*s/(m*m)); self._mn = math.log(m)-0.5*sn @@ -69,7 +71,7 @@ class NormalDistribution(Distribution): m = float(m) s = float(s) if (s <= 0): - raise error, "standard deviation must be positive" + raise error("standard deviation must be positive") Distribution.__init__(self, 'normal', m, s) self._fac = 1.0/math.sqrt(2*math.pi)/s @@ -84,7 +86,7 @@ class UniformDistribution(Distribution): b = float(b) width = b-a if (width <=0): - raise error, "width of uniform distribution must be > 0" + raise error("width of uniform distribution must be > 0") Distribution.__init__(self, 'uniform', a, b) self._fac = 1.0/width @@ -106,7 +108,7 @@ class CreateGenerator(object): if dist is None: dist = default_distribution if not isinstance(dist, Distribution): - raise error, "Not a distribution object" + raise error("Not a distribution object") self._dist = dist def ranf(self): diff --git a/numpy/oldnumeric/rng_stats.py b/numpy/oldnumeric/rng_stats.py index 8c7fec433..96e50f9a4 100644 --- a/numpy/oldnumeric/rng_stats.py +++ b/numpy/oldnumeric/rng_stats.py @@ -1,3 +1,4 @@ +from __future__ import division __all__ = ['average', 'histogram', 'standardDeviation', 'variance'] diff --git a/numpy/oldnumeric/setup.py b/numpy/oldnumeric/setup.py index 31b5ff3cc..9482c216d 100644 --- a/numpy/oldnumeric/setup.py +++ b/numpy/oldnumeric/setup.py @@ -1,3 +1,4 @@ +from __future__ import division def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration diff --git a/numpy/oldnumeric/tests/test_oldnumeric.py b/numpy/oldnumeric/tests/test_oldnumeric.py index 24d709d2c..58ccc710a 100644 --- a/numpy/oldnumeric/tests/test_oldnumeric.py +++ b/numpy/oldnumeric/tests/test_oldnumeric.py @@ -1,3 +1,5 @@ +from __future__ import division + import unittest from numpy.testing import * diff --git a/numpy/oldnumeric/tests/test_regression.py b/numpy/oldnumeric/tests/test_regression.py index 235ae4fe5..dd221699d 100644 --- a/numpy/oldnumeric/tests/test_regression.py +++ b/numpy/oldnumeric/tests/test_regression.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import * rlevel = 1 diff --git a/numpy/oldnumeric/typeconv.py b/numpy/oldnumeric/typeconv.py index 4e203d4ae..014477950 100644 --- a/numpy/oldnumeric/typeconv.py +++ b/numpy/oldnumeric/typeconv.py @@ -1,3 +1,5 @@ +from __future__ import division + __all__ = ['oldtype2dtype', 'convtypecode', 'convtypecode2', 'oldtypecodes'] import numpy as np diff --git a/numpy/oldnumeric/ufuncs.py b/numpy/oldnumeric/ufuncs.py index c26050f55..9ace30a91 100644 --- a/numpy/oldnumeric/ufuncs.py +++ b/numpy/oldnumeric/ufuncs.py @@ -1,3 +1,5 @@ +from __future__ import division + __all__ = ['less', 'cosh', 'arcsinh', 'add', 'ceil', 'arctan2', 'floor_divide', 'fmod', 'hypot', 'logical_and', 'power', 'sinh', 'remainder', 'cos', 'equal', 'arccos', 'less_equal', 'divide', 'bitwise_or', diff --git a/numpy/oldnumeric/user_array.py b/numpy/oldnumeric/user_array.py index 375c4013b..08be8135b 100644 --- a/numpy/oldnumeric/user_array.py +++ b/numpy/oldnumeric/user_array.py @@ -1,4 +1,4 @@ - +from __future__ import division from numpy.oldnumeric import * from numpy.lib.user_array import container as UserArray diff --git a/numpy/polynomial/__init__.py b/numpy/polynomial/__init__.py index 8e06fa171..684720828 100644 --- a/numpy/polynomial/__init__.py +++ b/numpy/polynomial/__init__.py @@ -13,6 +13,8 @@ implemented as operations on the coefficients. Additional (module-specific) information can be found in the docstring for the module of interest. """ +from __future__ import division + import warnings from polynomial import Polynomial diff --git a/numpy/polynomial/chebyshev.py b/numpy/polynomial/chebyshev.py index afeafcb68..9576a4697 100644 --- a/numpy/polynomial/chebyshev.py +++ b/numpy/polynomial/chebyshev.py @@ -2012,4 +2012,4 @@ def chebpts2(npts): # Chebyshev series class # -exec polytemplate.substitute(name='Chebyshev', nick='cheb', domain='[-1,1]') +exec(polytemplate.substitute(name='Chebyshev', nick='cheb', domain='[-1,1]')) diff --git a/numpy/polynomial/hermite.py b/numpy/polynomial/hermite.py index 2beb848ae..b410902ea 100644 --- a/numpy/polynomial/hermite.py +++ b/numpy/polynomial/hermite.py @@ -1747,4 +1747,4 @@ def hermweight(x): # Hermite series class # -exec polytemplate.substitute(name='Hermite', nick='herm', domain='[-1,1]') +exec(polytemplate.substitute(name='Hermite', nick='herm', domain='[-1,1]')) diff --git a/numpy/polynomial/hermite_e.py b/numpy/polynomial/hermite_e.py index c183a5a86..4d3bcd338 100644 --- a/numpy/polynomial/hermite_e.py +++ b/numpy/polynomial/hermite_e.py @@ -1743,4 +1743,4 @@ def hermeweight(x): # HermiteE series class # -exec polytemplate.substitute(name='HermiteE', nick='herme', domain='[-1,1]') +exec(polytemplate.substitute(name='HermiteE', nick='herme', domain='[-1,1]')) diff --git a/numpy/polynomial/laguerre.py b/numpy/polynomial/laguerre.py index f0c1268bf..7b77ea819 100644 --- a/numpy/polynomial/laguerre.py +++ b/numpy/polynomial/laguerre.py @@ -1739,4 +1739,4 @@ def lagweight(x): # Laguerre series class # -exec polytemplate.substitute(name='Laguerre', nick='lag', domain='[-1,1]') +exec(polytemplate.substitute(name='Laguerre', nick='lag', domain='[-1,1]')) diff --git a/numpy/polynomial/legendre.py b/numpy/polynomial/legendre.py index 0efd13ffa..5b88b6287 100644 --- a/numpy/polynomial/legendre.py +++ b/numpy/polynomial/legendre.py @@ -1765,4 +1765,4 @@ def legweight(x): # Legendre series class # -exec polytemplate.substitute(name='Legendre', nick='leg', domain='[-1,1]') +exec(polytemplate.substitute(name='Legendre', nick='leg', domain='[-1,1]')) diff --git a/numpy/polynomial/polynomial.py b/numpy/polynomial/polynomial.py index 8d7251b19..e174fdd96 100644 --- a/numpy/polynomial/polynomial.py +++ b/numpy/polynomial/polynomial.py @@ -1489,4 +1489,4 @@ def polyroots(c): # polynomial class # -exec polytemplate.substitute(name='Polynomial', nick='poly', domain='[-1,1]') +exec(polytemplate.substitute(name='Polynomial', nick='poly', domain='[-1,1]')) diff --git a/numpy/polynomial/polytemplate.py b/numpy/polynomial/polytemplate.py index bb5effc0e..7d67c914c 100644 --- a/numpy/polynomial/polytemplate.py +++ b/numpy/polynomial/polytemplate.py @@ -9,6 +9,8 @@ creating additional specific polynomial classes (e.g., Legendre, Jacobi, etc.) in the future, such that all these classes will have a common API. """ +from __future__ import division + import string import sys diff --git a/numpy/polynomial/setup.py b/numpy/polynomial/setup.py index 173fd126c..f1e68b576 100644 --- a/numpy/polynomial/setup.py +++ b/numpy/polynomial/setup.py @@ -1,4 +1,4 @@ - +from __future__ import division def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration diff --git a/numpy/polynomial/tests/test_printing.py b/numpy/polynomial/tests/test_printing.py index 9803d931c..889966051 100644 --- a/numpy/polynomial/tests/test_printing.py +++ b/numpy/polynomial/tests/test_printing.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy.polynomial as poly from numpy.testing import TestCase, run_module_suite, assert_ diff --git a/numpy/random/__init__.py b/numpy/random/__init__.py index 34e57ba2c..f005bc15a 100644 --- a/numpy/random/__init__.py +++ b/numpy/random/__init__.py @@ -86,6 +86,8 @@ set_state Set state of generator. ==================== ========================================================= """ +from __future__ import division + # To get sub-modules from info import __doc__, __all__ diff --git a/numpy/random/info.py b/numpy/random/info.py index 6139e5784..c886c565e 100644 --- a/numpy/random/info.py +++ b/numpy/random/info.py @@ -82,6 +82,7 @@ set_state Set state of generator. ==================== ========================================================= """ +from __future__ import division depends = ['core'] diff --git a/numpy/random/mtrand/generate_mtrand_c.py b/numpy/random/mtrand/generate_mtrand_c.py index a37fc7266..d6527e695 100644 --- a/numpy/random/mtrand/generate_mtrand_c.py +++ b/numpy/random/mtrand/generate_mtrand_c.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import division + import sys import re import os diff --git a/numpy/random/setup.py b/numpy/random/setup.py index dde3119b7..c4582d007 100644 --- a/numpy/random/setup.py +++ b/numpy/random/setup.py @@ -1,3 +1,5 @@ +from __future__ import division + from os.path import join, split, dirname import os import sys diff --git a/numpy/random/tests/test_random.py b/numpy/random/tests/test_random.py index 1621637d0..410456ef4 100644 --- a/numpy/random/tests/test_random.py +++ b/numpy/random/tests/test_random.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import TestCase, run_module_suite, assert_,\ assert_raises from numpy import random diff --git a/numpy/random/tests/test_regression.py b/numpy/random/tests/test_regression.py index 55852cc98..a19974c47 100644 --- a/numpy/random/tests/test_regression.py +++ b/numpy/random/tests/test_regression.py @@ -1,3 +1,5 @@ +from __future__ import division + from numpy.testing import TestCase, run_module_suite, assert_,\ assert_array_equal from numpy import random diff --git a/numpy/setup.py b/numpy/setup.py index c55c85a25..0ea354bf5 100644 --- a/numpy/setup.py +++ b/numpy/setup.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import division + def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration diff --git a/numpy/testing/__init__.py b/numpy/testing/__init__.py index f391c8053..19b0d2052 100644 --- a/numpy/testing/__init__.py +++ b/numpy/testing/__init__.py @@ -3,7 +3,9 @@ This single module should provide all the common functionality for numpy tests in a single location, so that test scripts can just import it and work right away. + """ +from __future__ import division from unittest import TestCase diff --git a/numpy/testing/decorators.py b/numpy/testing/decorators.py index 053b99211..eae9d93b0 100644 --- a/numpy/testing/decorators.py +++ b/numpy/testing/decorators.py @@ -13,11 +13,14 @@ function name, setup and teardown functions and so on - see ``nose.tools`` for more information. """ +from __future__ import division + import warnings import sys from numpy.testing.utils import \ WarningManager, WarningMessage +import collections def slow(t): """ @@ -122,7 +125,7 @@ def skipif(skip_condition, msg=None): import nose # Allow for both boolean or callable skip conditions. - if callable(skip_condition): + if isinstance(skip_condition, collections.Callable): skip_val = lambda : skip_condition() else: skip_val = lambda : skip_condition @@ -198,7 +201,7 @@ def knownfailureif(fail_condition, msg=None): msg = 'Test skipped due to known failure' # Allow for both boolean or callable known failure conditions. - if callable(fail_condition): + if isinstance(fail_condition, collections.Callable): fail_val = lambda : fail_condition() else: fail_val = lambda : fail_condition @@ -264,7 +267,7 @@ def deprecated(conditional=True): finally: ctx.__exit__() - if callable(conditional): + if isinstance(conditional, collections.Callable): cond = conditional() else: cond = conditional diff --git a/numpy/testing/noseclasses.py b/numpy/testing/noseclasses.py index 5152bdd60..96c779c2e 100644 --- a/numpy/testing/noseclasses.py +++ b/numpy/testing/noseclasses.py @@ -4,6 +4,7 @@ # Because this module imports nose directly, it should not # be used except by nosetester.py to avoid a general NumPy # dependency on nose. +from __future__ import division import os import doctest @@ -35,7 +36,7 @@ class NumpyDocTestFinder(doctest.DocTestFinder): return True elif inspect.isfunction(object): #print '_fm C2' # dbg - return module.__dict__ is object.func_globals + return module.__dict__ is object.__globals__ elif inspect.isbuiltin(object): #print '_fm C2-1' # dbg return module.__name__ == object.__module__ @@ -48,7 +49,7 @@ class NumpyDocTestFinder(doctest.DocTestFinder): # to make by extension code writers, having this safety in place # isn't such a bad idea #print '_fm C3-1' # dbg - return module.__name__ == object.im_class.__module__ + return module.__name__ == object.__self__.__class__.__module__ elif inspect.getmodule(object) is not None: #print '_fm C4' # dbg #print 'C4 mod',module,'obj',object # dbg @@ -100,7 +101,7 @@ class NumpyDocTestFinder(doctest.DocTestFinder): if isinstance(val, staticmethod): val = getattr(obj, valname) if isinstance(val, classmethod): - val = getattr(obj, valname).im_func + val = getattr(obj, valname).__func__ # Recurse to methods, properties, and nested classes. if ((isfunction(val) or isclass(val) or diff --git a/numpy/testing/nosetester.py b/numpy/testing/nosetester.py index 09418bb87..7f1292cd8 100644 --- a/numpy/testing/nosetester.py +++ b/numpy/testing/nosetester.py @@ -4,6 +4,8 @@ Nose test running. This module implements ``test()`` and ``bench()`` functions for NumPy modules. """ +from __future__ import division + import os import sys import warnings diff --git a/numpy/testing/nulltester.py b/numpy/testing/nulltester.py index 8cee43495..e0c7531b3 100644 --- a/numpy/testing/nulltester.py +++ b/numpy/testing/nulltester.py @@ -1,11 +1,13 @@ -''' Null tester to signal nose tests disabled +""" Null tester to signal nose tests disabled Merely returns error reporting lack of nose package or version number below requirements. See pkgtester, nosetester modules -''' +""" +from __future__ import division + class NullTester(object): def test(self, labels=None, *args, **kwargs): diff --git a/numpy/testing/numpytest.py b/numpy/testing/numpytest.py index 683df7a01..5259ba773 100644 --- a/numpy/testing/numpytest.py +++ b/numpy/testing/numpytest.py @@ -1,3 +1,5 @@ +from __future__ import division + import os import sys import traceback @@ -42,8 +44,8 @@ def importall(package): continue name = package_name+'.'+subpackage_name try: - exec 'import %s as m' % (name) - except Exception, msg: + exec('import %s as m' % (name)) + except Exception as msg: print 'Failed importing %s: %s' %(name, msg) continue importall(m) diff --git a/numpy/testing/print_coercion_tables.py b/numpy/testing/print_coercion_tables.py index d87544987..4982f5602 100755 --- a/numpy/testing/print_coercion_tables.py +++ b/numpy/testing/print_coercion_tables.py @@ -1,5 +1,8 @@ #!/usr/bin/env python -"""Prints type-coercion tables for the built-in NumPy types""" +"""Prints type-coercion tables for the built-in NumPy types + +""" +from __future__ import division import numpy as np diff --git a/numpy/testing/setup.py b/numpy/testing/setup.py index 6d8fc85c5..c72dd1d9a 100755 --- a/numpy/testing/setup.py +++ b/numpy/testing/setup.py @@ -1,4 +1,6 @@ #!/usr/bin/env python +from __future__ import division + def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration diff --git a/numpy/testing/tests/test_decorators.py b/numpy/testing/tests/test_decorators.py index a28e24ac3..e2dc2bd7d 100644 --- a/numpy/testing/tests/test_decorators.py +++ b/numpy/testing/tests/test_decorators.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy as np from numpy.testing import * from numpy.testing.noseclasses import KnownFailureTest diff --git a/numpy/testing/tests/test_doctesting.py b/numpy/testing/tests/test_doctesting.py index a34071128..58f65aa45 100644 --- a/numpy/testing/tests/test_doctesting.py +++ b/numpy/testing/tests/test_doctesting.py @@ -1,5 +1,8 @@ """ Doctests for NumPy-specific nose/doctest modifications + """ +from __future__ import division + # try the #random directive on the output line def check_random_directive(): ''' diff --git a/numpy/testing/tests/test_utils.py b/numpy/testing/tests/test_utils.py index 23b2f8e7b..9722c583c 100644 --- a/numpy/testing/tests/test_utils.py +++ b/numpy/testing/tests/test_utils.py @@ -1,3 +1,5 @@ +from __future__ import division + import warnings import sys diff --git a/numpy/testing/utils.py b/numpy/testing/utils.py index 16ed0f803..019adeb27 100644 --- a/numpy/testing/utils.py +++ b/numpy/testing/utils.py @@ -1,6 +1,8 @@ """ Utility function to facilitate testing. + """ +from __future__ import division import os import sys @@ -643,7 +645,7 @@ def assert_array_compare(comparison, x, y, err_msg='', verbose=True, names=('x', 'y')) if not cond : raise AssertionError(msg) - except ValueError, e: + except ValueError as e: import traceback efmt = traceback.format_exc() header = 'error during assertion:\n\n%s\n\n%s' % (efmt, header) @@ -881,7 +883,7 @@ def assert_array_less(x, y, err_msg='', verbose=True): header='Arrays are not less-ordered') def runstring(astr, dict): - exec astr in dict + exec(astr, dict) def assert_string_equal(actual, desired): """ @@ -1050,7 +1052,7 @@ def decorate_methods(cls, decorator, testmatch=None): # delayed import to reduce startup time from inspect import isfunction - methods = filter(isfunction, cls_attr.values()) + methods = [_m for _m in cls_attr.values() if isfunction(_m)] for function in methods: try: if hasattr(function, 'compat_func_name'): @@ -1108,7 +1110,7 @@ def measure(code_str,times=1,label=None): elapsed = jiffies() while i < times: i += 1 - exec code in globs,locs + exec(code, globs,locs) elapsed = jiffies() - elapsed return 0.01*elapsed diff --git a/numpy/tests/test_ctypeslib.py b/numpy/tests/test_ctypeslib.py index ac351191a..9b53ed0c6 100644 --- a/numpy/tests/test_ctypeslib.py +++ b/numpy/tests/test_ctypeslib.py @@ -1,3 +1,5 @@ +from __future__ import division + import sys import numpy as np @@ -18,7 +20,7 @@ class TestLoadLibrary(TestCase): try: cdll = load_library('multiarray', np.core.multiarray.__file__) - except ImportError, e: + except ImportError as e: msg = "ctypes is not available on this python: skipping the test" \ " (import error was: %s)" % str(e) print msg @@ -35,7 +37,7 @@ class TestLoadLibrary(TestCase): np.core.multiarray.__file__) except ImportError: print "No distutils available, skipping test." - except ImportError, e: + except ImportError as e: msg = "ctypes is not available on this python: skipping the test" \ " (import error was: %s)" % str(e) print msg diff --git a/numpy/tests/test_matlib.py b/numpy/tests/test_matlib.py index 010aa8d84..0ac49fed3 100644 --- a/numpy/tests/test_matlib.py +++ b/numpy/tests/test_matlib.py @@ -1,3 +1,5 @@ +from __future__ import division + import numpy as np import numpy.matlib from numpy.testing import assert_array_equal, assert_, run_module_suite |