Commits

Manuel Jacob committed 607e94c Merge

hg merge default

Comments (0)

Files changed (166)

lib_pypy/numpypy/__init__.py

-from _numpypy import *
-from .core import *
+import core
+from core import *
+import lib
+from lib import *
+
+from __builtin__ import bool, int, long, float, complex, object, unicode, str
+from core import abs, max, min
+
+__all__ = []
+__all__ += core.__all__
+__all__ += lib.__all__
 
 import sys
 sys.modules.setdefault('numpy', sys.modules['numpypy'])

lib_pypy/numpypy/core/__init__.py

-from .fromnumeric import *
-from .numeric import *
-from .shape_base import *
+import _numpypy
+from _numpypy import *
+import numeric
+from numeric import *
+import fromnumeric
+from fromnumeric import *
+import shape_base
+from shape_base import *
+import multiarray
+
+from fromnumeric import amax as max, amin as min
+from _numpypy import absolute as abs
+
+__all__ = []
+__all__ += _numpypy.__all__
+__all__ += numeric.__all__
+__all__ += fromnumeric.__all__
+__all__ += shape_base.__all__

lib_pypy/numpypy/core/fromnumeric.py

     array([3, 4, 2, 3, 4, 5, 6, 7, 8, 8])
 
     """
-    raise NotImplementedError('Waiting on interp level method')
+    if not hasattr(a, 'clip'):
+        a = numpypy.array(a)
+    return a.clip(a_min, a_max, out=out)
 
 
 def sum(a, axis=None, dtype=None, out=None):
 
     """
     assert dtype is None
-    assert out is None
     if not hasattr(a, "sum"):
         a = numpypy.array(a)
-    return a.sum(axis=axis)
+    return a.sum(axis=axis, out=out)
 
 
 def product (a, axis=None, dtype=None, out=None):
     4.0
 
     """
-    assert axis is None
-    assert out is None
     if not hasattr(a, "max"):
         a = numpypy.array(a)
-    return a.max()
+    if a.size < 1:
+        return numpypy.array([])
+    return a.max(axis=axis, out=out)
 
 
 def amin(a, axis=None, out=None):
     0.0
 
     """
-    # amin() is equivalent to min()
-    assert axis is None
-    assert out is None
     if not hasattr(a, 'min'):
         a = numpypy.array(a)
-    return a.min()
+    if a.size < 1:
+        return numpypy.array([])
+    return a.min(axis=axis, out=out)
 
 def alen(a):
     """

lib_pypy/numpypy/core/multiarray.py

+from _numpypy import set_string_function, typeinfo

lib_pypy/numpypy/core/numeric.py

+__all__ = ['asanyarray', 'base_repr',
+           'array_repr', 'array_str', 'set_string_function',
+           'array_equal', 'asarray', 'outer', 'identity']
 
 from _numpypy import array, ndarray, int_, float_, bool_, flexible #, complex_# , longlong
 from _numpypy import concatenate
 from .fromnumeric import any
 import math
 import sys
-import _numpypy as multiarray # ARGH
+import multiarray
 from numpypy.core.arrayprint import array2string
 
 newaxis = None
     a = asarray(a)
     b = asarray(b)
     return a.ravel()[:,newaxis]*b.ravel()[newaxis,:]
+
+def identity(n, dtype=None):
+    """
+    Return the identity array.
+
+    The identity array is a square array with ones on
+    the main diagonal.
+
+    Parameters
+    ----------
+    n : int
+        Number of rows (and columns) in `n` x `n` output.
+    dtype : data-type, optional
+        Data-type of the output.  Defaults to ``float``.
+
+    Returns
+    -------
+    out : ndarray
+        `n` x `n` array with its main diagonal set to one,
+        and all other elements 0.
+
+    Examples
+    --------
+    >>> np.identity(3)
+    array([[ 1.,  0.,  0.],
+           [ 0.,  1.,  0.],
+           [ 0.,  0.,  1.]])
+
+    """
+    from numpy import eye
+    return eye(n, dtype=dtype)

lib_pypy/numpypy/core/shape_base.py

+__all__ = ['atleast_1d', 'atleast_2d', 'atleast_3d', 'vstack', 'hstack']
+
 import _numpypy
 from numeric import array, asanyarray, newaxis
 
         return _numpypy.concatenate(arrs, 0)
     else:
         return _numpypy.concatenate(arrs, 1)
-
-def dstack(tup):
-    """
-    Stack arrays in sequence depth wise (along third axis).
-
-    Takes a sequence of arrays and stack them along the third axis
-    to make a single array. Rebuilds arrays divided by `dsplit`.
-    This is a simple way to stack 2D arrays (images) into a single
-    3D array for processing.
-
-    Parameters
-    ----------
-    tup : sequence of arrays
-        Arrays to stack. All of them must have the same shape along all
-        but the third axis.
-
-    Returns
-    -------
-    stacked : ndarray
-        The array formed by stacking the given arrays.
-
-    See Also
-    --------
-    vstack : Stack along first axis.
-    hstack : Stack along second axis.
-    concatenate : Join arrays.
-    dsplit : Split array along third axis.
-
-    Notes
-    -----
-    Equivalent to ``np.concatenate(tup, axis=2)``.
-
-    Examples
-    --------
-    >>> a = np.array((1,2,3))
-    >>> b = np.array((2,3,4))
-    >>> np.dstack((a,b))
-    array([[[1, 2],
-            [2, 3],
-            [3, 4]]])
-
-    >>> a = np.array([[1],[2],[3]])
-    >>> b = np.array([[2],[3],[4]])
-    >>> np.dstack((a,b))
-    array([[[1, 2]],
-           [[2, 3]],
-           [[3, 4]]])
-
-    """
-    return _numpypy.concatenate(map(atleast_3d,tup),2)

lib_pypy/numpypy/lib/__init__.py

+import function_base
+from function_base import *
+import shape_base
+from shape_base import *
+import twodim_base
+from twodim_base import *
+
+__all__ = []
+__all__ += function_base.__all__
+__all__ += shape_base.__all__
+__all__ += twodim_base.__all__

lib_pypy/numpypy/lib/function_base.py

+__all__ = ['average']
+
+from _numpypy import array
+
+def average(a):
+    # This implements a weighted average, for now we don't implement the
+    # weighting, just the average part!
+    if not hasattr(a, "mean"):
+        a = array(a)
+    return a.mean()

lib_pypy/numpypy/lib/shape_base.py

+__all__ = ['dstack']
+
+import numpypy.core.numeric as _nx
+from numpypy.core import atleast_3d
+
+def dstack(tup):
+    """
+    Stack arrays in sequence depth wise (along third axis).
+
+    Takes a sequence of arrays and stack them along the third axis
+    to make a single array. Rebuilds arrays divided by `dsplit`.
+    This is a simple way to stack 2D arrays (images) into a single
+    3D array for processing.
+
+    Parameters
+    ----------
+    tup : sequence of arrays
+        Arrays to stack. All of them must have the same shape along all
+        but the third axis.
+
+    Returns
+    -------
+    stacked : ndarray
+        The array formed by stacking the given arrays.
+
+    See Also
+    --------
+    vstack : Stack along first axis.
+    hstack : Stack along second axis.
+    concatenate : Join arrays.
+    dsplit : Split array along third axis.
+
+    Notes
+    -----
+    Equivalent to ``np.concatenate(tup, axis=2)``.
+
+    Examples
+    --------
+    >>> a = np.array((1,2,3))
+    >>> b = np.array((2,3,4))
+    >>> np.dstack((a,b))
+    array([[[1, 2],
+            [2, 3],
+            [3, 4]]])
+
+    >>> a = np.array([[1],[2],[3]])
+    >>> b = np.array([[2],[3],[4]])
+    >>> np.dstack((a,b))
+    array([[[1, 2]],
+           [[2, 3]],
+           [[3, 4]]])
+
+    """
+    return _nx.concatenate(map(atleast_3d,tup),2)

lib_pypy/numpypy/lib/twodim_base.py

+__all__ = ['eye']
+
+from _numpypy import zeros
+
+def eye(N, M=None, k=0, dtype=float):
+    """
+    Return a 2-D array with ones on the diagonal and zeros elsewhere.
+
+    Parameters
+    ----------
+    N : int
+      Number of rows in the output.
+    M : int, optional
+      Number of columns in the output. If None, defaults to `N`.
+    k : int, optional
+      Index of the diagonal: 0 (the default) refers to the main diagonal,
+      a positive value refers to an upper diagonal, and a negative value
+      to a lower diagonal.
+    dtype : data-type, optional
+      Data-type of the returned array.
+
+    Returns
+    -------
+    I : ndarray of shape (N,M)
+      An array where all elements are equal to zero, except for the `k`-th
+      diagonal, whose values are equal to one.
+
+    See Also
+    --------
+    identity : (almost) equivalent function
+    diag : diagonal 2-D array from a 1-D array specified by the user.
+
+    Examples
+    --------
+    >>> np.eye(2, dtype=int)
+    array([[1, 0],
+           [0, 1]])
+    >>> np.eye(3, k=1)
+    array([[ 0.,  1.,  0.],
+           [ 0.,  0.,  1.],
+           [ 0.,  0.,  0.]])
+
+    """
+    if M is None:
+        M = N
+    m = zeros((N, M), dtype=dtype)
+    if k >= M:
+        return m
+    if k >= 0:
+        i = k
+    else:
+        i = (-k) * M
+    m[:M-k].flat[i::M+1] = 1
+    return m

pypy/doc/ctypes-implementation.rst

 in dynamic libraries through libffi. Freeing objects in most cases and making
 sure that objects referring to each other are kept alive is responsibility of the higher levels.
 
-This module uses bindings to libffi which are defined in ``pypy/rlib/libffi.py``.
+This module uses bindings to libffi which are defined in ``rpython/rlib/libffi.py``.
 
 We tried to keep this module as small as possible. It is conceivable
 that other implementations (e.g. Jython) could use our ctypes

pypy/doc/discussion/improve-rpython.rst

 
 - Allocate variables on the stack, and pass their address ("by reference") to
   llexternal functions. For a typical usage, see
-  `pypy.rlib.rsocket.RSocket.getsockopt_int`.
+  `rpython.rlib.rsocket.RSocket.getsockopt_int`.
 
 Extensible type system for llexternal
 -------------------------------------

pypy/doc/garbage_collection.rst

 Two arenas of equal size, with only one arena in use and getting filled
 with new objects.  When the arena is full, the live objects are copied
 into the other arena using Cheney's algorithm.  The old arena is then
-cleared.  See `rpython/rtyper/memory/gc/semispace.py`_.
+cleared.  See `rpython/memory/gc/semispace.py`_.
 
 On Unix the clearing is done by reading ``/dev/zero`` into the arena,
 which is extremely memory efficient at least on Linux: it lets the
 Generational GC
 ---------------
 
-This is a two-generations GC.  See `rpython/rtyper/memory/gc/generation.py`_.
+This is a two-generations GC.  See `rpython/memory/gc/generation.py`_.
 
 It is implemented as a subclass of the Semispace copying collector.  It
 adds a nursery, which is a chunk of the current semispace.  Its size is
 Each generation is collected much less often than the previous one.  The
 division of the generations is slightly more complicated than just
 nursery / semispace / external; see the diagram at the start of the
-source code, in `rpython/rtyper/memory/gc/hybrid.py`_.
+source code, in `rpython/memory/gc/hybrid.py`_.
 
 Mark & Compact GC
 -----------------
   to the old stage. The dying case 2 objects are immediately freed.
 
 - The old stage is an area of memory containing old (small) objects.  It
-  is handled by `rpython/rtyper/memory/gc/minimarkpage.py`_.  It is organized
+  is handled by `rpython/memory/gc/minimarkpage.py`_.  It is organized
   as "arenas" of 256KB or 512KB, subdivided into "pages" of 4KB or 8KB.
   Each page can either be free, or contain small objects of all the same
   size.  Furthermore at any point in time each object location can be

pypy/doc/index.rst

 `rpython/rtyper/ootypesystem/`_    the `object-oriented type system`_
                                    for OO backends
 
-`rpython/rtyper/memory/`_          the `garbage collector`_ construction
+`rpython/memory/`_                 the `garbage collector`_ construction
                                    framework
 
 `rpython/translator/`_             translation_ backends and support code

pypy/doc/stackless.rst

 more information about them please see the documentation in the C source
 at `rpython/translator/c/src/stacklet/stacklet.h`_.
 
-The module ``pypy.rlib.rstacklet`` is a thin wrapper around the above
+The module ``rpython.rlib.rstacklet`` is a thin wrapper around the above
 functions.  The key point is that new() and switch() always return a
 fresh stacklet handle (or an empty one), and switch() additionally
 consumes one.  It makes no sense to have code in which the returned

pypy/doc/whatsnew-head.rst

 
 .. branch: coding-guide-update-rlib-refs
 .. branch: rlib-doc-rpython-refs
+.. branch: clean-up-remaining-pypy-rlib-refs
+
+.. branch: enumerate-rstr
+Support enumerate() over rstr types.

pypy/module/_cffi_backend/cbuffer.py

-from pypy.interpreter.error import operationerrfmt
 from pypy.interpreter.baseobjspace import Wrappable
 from pypy.interpreter.buffer import RWBuffer
+from pypy.interpreter.error import operationerrfmt
 from pypy.interpreter.gateway import unwrap_spec, interp2app
 from pypy.interpreter.typedef import TypeDef, make_weakref_descr
+from pypy.module._cffi_backend import cdataobj, ctypeptr, ctypearray
+
 from rpython.rtyper.lltypesystem import rffi
-from pypy.module._cffi_backend import cdataobj, ctypeptr, ctypearray
-from pypy.module.__builtin__.interp_memoryview import W_MemoryView
 
 
 class LLBuffer(RWBuffer):

pypy/module/_cffi_backend/ccallback.py

 Callbacks.
 """
 import os
+
+from rpython.rlib import clibffi, rweakref, jit
+from rpython.rlib.objectmodel import compute_unique_id, keepalive_until_here
+from rpython.rtyper.lltypesystem import lltype, rffi
+
 from pypy.interpreter.error import OperationError, operationerrfmt
-from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
-from rpython.rlib.objectmodel import compute_unique_id, keepalive_until_here
-from rpython.rlib import clibffi, rweakref
-from rpython.rlib import jit
-
+from pypy.module._cffi_backend import cerrno, misc
 from pypy.module._cffi_backend.cdataobj import W_CData
-from pypy.module._cffi_backend.ctypefunc import SIZE_OF_FFI_ARG, BIG_ENDIAN
-from pypy.module._cffi_backend.ctypefunc import W_CTypeFunc
+from pypy.module._cffi_backend.ctypefunc import SIZE_OF_FFI_ARG, BIG_ENDIAN, W_CTypeFunc
 from pypy.module._cffi_backend.ctypeprim import W_CTypePrimitiveSigned
 from pypy.module._cffi_backend.ctypevoid import W_CTypeVoid
-from pypy.module._cffi_backend import cerrno, misc
 
 # ____________________________________________________________
 
 
 STDERR = 2
 
+
 @jit.jit_callback("CFFI")
 def invoke_callback(ffi_cif, ll_res, ll_args, ll_userdata):
     """ Callback specification.

pypy/module/_cffi_backend/cdataobj.py

 import operator
+
+from pypy.interpreter.baseobjspace import Wrappable
 from pypy.interpreter.error import OperationError, operationerrfmt
-from pypy.interpreter.baseobjspace import Wrappable
-from pypy.interpreter.gateway import interp2app, unwrap_spec
+from pypy.interpreter.gateway import interp2app
 from pypy.interpreter.typedef import TypeDef, make_weakref_descr
+
+from rpython.rlib import objectmodel, rgc
+from rpython.rlib.objectmodel import keepalive_until_here, specialize
 from rpython.rtyper.lltypesystem import lltype, rffi
-from rpython.rlib.objectmodel import keepalive_until_here, specialize
-from rpython.rlib import objectmodel, rgc
 from rpython.tool.sourcetools import func_with_new_name
 
 from pypy.module._cffi_backend import misc

pypy/module/_cffi_backend/cerrno.py

 import sys
+
 from rpython.rlib import rposix
+
 from pypy.interpreter.executioncontext import ExecutionContext
 from pypy.interpreter.gateway import unwrap_spec
 

pypy/module/_cffi_backend/ctypearray.py

 Arrays.
 """
 
+from pypy.interpreter.baseobjspace import Wrappable
 from pypy.interpreter.error import OperationError, operationerrfmt
-from pypy.interpreter.baseobjspace import Wrappable
 from pypy.interpreter.gateway import interp2app
 from pypy.interpreter.typedef import TypeDef
+
 from rpython.rtyper.lltypesystem import rffi
 from rpython.rlib.objectmodel import keepalive_until_here
 from rpython.rlib.rarithmetic import ovfcheck
 
-from pypy.module._cffi_backend.ctypeprim import W_CTypePrimitiveChar
-from pypy.module._cffi_backend.ctypeprim import W_CTypePrimitiveUniChar
+from pypy.module._cffi_backend import cdataobj
 from pypy.module._cffi_backend.ctypeptr import W_CTypePtrOrArray
-from pypy.module._cffi_backend import cdataobj
 
 
 class W_CTypeArray(W_CTypePtrOrArray):

pypy/module/_cffi_backend/ctypeenum.py

 Enums.
 """
 
-from pypy.interpreter.error import OperationError, operationerrfmt
-from rpython.rtyper.lltypesystem import rffi
-from rpython.rlib.rarithmetic import intmask, r_ulonglong
 from rpython.rlib.objectmodel import keepalive_until_here
-from rpython.rlib.objectmodel import specialize
 
-from pypy.module._cffi_backend.ctypeprim import W_CTypePrimitiveSigned
-from pypy.module._cffi_backend.ctypeprim import W_CTypePrimitiveUnsigned
 from pypy.module._cffi_backend import misc
+from pypy.module._cffi_backend.ctypeprim import (W_CTypePrimitiveSigned,
+    W_CTypePrimitiveUnsigned)
 
 
 class _Mixin_Enum(object):

pypy/module/_cffi_backend/ctypefunc.py

 
 import sys
 from pypy.interpreter.error import OperationError, operationerrfmt
+
+from rpython.rlib import jit, clibffi, jit_libffi
+from rpython.rlib.jit_libffi import (CIF_DESCRIPTION, CIF_DESCRIPTION_P,
+    FFI_TYPE, FFI_TYPE_P, FFI_TYPE_PP, SIZE_OF_FFI_ARG)
+from rpython.rlib.objectmodel import we_are_translated, instantiate
 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
-from rpython.rlib import jit, clibffi, jit_libffi
-from rpython.rlib.jit_libffi import CIF_DESCRIPTION, CIF_DESCRIPTION_P
-from rpython.rlib.jit_libffi import FFI_TYPE, FFI_TYPE_P, FFI_TYPE_PP
-from rpython.rlib.jit_libffi import SIZE_OF_FFI_ARG
-from rpython.rlib.objectmodel import we_are_translated, instantiate
-from rpython.rlib.objectmodel import keepalive_until_here
 
+from pypy.module._cffi_backend import ctypearray, cdataobj, cerrno
 from pypy.module._cffi_backend.ctypeobj import W_CType
 from pypy.module._cffi_backend.ctypeptr import W_CTypePtrBase, W_CTypePointer
 from pypy.module._cffi_backend.ctypevoid import W_CTypeVoid
 from pypy.module._cffi_backend.ctypestruct import W_CTypeStruct
-from pypy.module._cffi_backend.ctypestruct import W_CTypeStructOrUnion
-from pypy.module._cffi_backend.ctypeprim import W_CTypePrimitiveSigned
-from pypy.module._cffi_backend.ctypeprim import W_CTypePrimitiveUnsigned
-from pypy.module._cffi_backend.ctypeprim import W_CTypePrimitiveCharOrUniChar
-from pypy.module._cffi_backend.ctypeprim import W_CTypePrimitiveFloat
-from pypy.module._cffi_backend.ctypeprim import W_CTypePrimitiveLongDouble
-from pypy.module._cffi_backend import ctypearray, cdataobj, cerrno
+from pypy.module._cffi_backend.ctypeprim import (W_CTypePrimitiveSigned,
+    W_CTypePrimitiveUnsigned, W_CTypePrimitiveCharOrUniChar,
+    W_CTypePrimitiveFloat, W_CTypePrimitiveLongDouble)
 
 
 class W_CTypeFunc(W_CTypePtrBase):
             return self.space.wrap(clibffi.FFI_DEFAULT_ABI)     # XXX
         return W_CTypePtrBase._fget(self, attrchar)
 
-
     def call(self, funcaddr, args_w):
         if self.cif_descr:
             # regular case: this function does not take '...' arguments
             self.bufferp = rffi.ptradd(result, size)
             return result
 
-
     def fb_fill_type(self, ctype, is_result_type):
         return ctype._get_ffi_type(self, is_result_type)
 
 
         return ffistruct
 
-
     def fb_build(self):
         # Build a CIF_DESCRIPTION.  Actually this computes the size and
         # allocates a larger amount of data.  It starts with a
             if self.atypes:
                 self.atypes[i] = atype
 
-
     def align_arg(self, n):
         return (n + 7) & ~7
 

pypy/module/_cffi_backend/ctypeobj.py

+from pypy.interpreter.baseobjspace import Wrappable
 from pypy.interpreter.error import OperationError, operationerrfmt
-from pypy.interpreter.baseobjspace import Wrappable
 from pypy.interpreter.gateway import interp2app
-from pypy.interpreter.typedef import TypeDef
-from pypy.interpreter.typedef import make_weakref_descr
-from pypy.interpreter.typedef import GetSetProperty, interp_attrproperty
+from pypy.interpreter.typedef import TypeDef, make_weakref_descr, GetSetProperty
+
 from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
 from rpython.rlib.objectmodel import we_are_translated
 

pypy/module/_cffi_backend/ctypeprim.py

 """
 
 from pypy.interpreter.error import operationerrfmt
-from rpython.rtyper.lltypesystem import lltype, rffi
+
 from rpython.rlib.rarithmetic import r_uint, r_ulonglong, intmask
 from rpython.rlib.objectmodel import keepalive_until_here
 from rpython.rlib import jit
+from rpython.rtyper.lltypesystem import lltype, rffi
 
+from pypy.module._cffi_backend import cdataobj, misc
 from pypy.module._cffi_backend.ctypeobj import W_CType
-from pypy.module._cffi_backend import cdataobj, misc
 
 
 class W_CTypePrimitive(W_CType):

pypy/module/_cffi_backend/ctypeptr.py

 
 import os
 
-from pypy.interpreter.error import OperationError, operationerrfmt
-from pypy.interpreter.error import wrap_oserror
-from rpython.rtyper.lltypesystem import lltype, rffi
+from pypy.interpreter.error import OperationError, operationerrfmt, wrap_oserror
+
+from rpython.rlib import rposix
 from rpython.rlib.objectmodel import keepalive_until_here
 from rpython.rlib.rarithmetic import ovfcheck
-from rpython.rlib import rposix
+from rpython.rtyper.lltypesystem import lltype, rffi
 
+from pypy.module._cffi_backend import cdataobj, misc, ctypeprim, ctypevoid
 from pypy.module._cffi_backend.ctypeobj import W_CType
-from pypy.module._cffi_backend import cdataobj, misc, ctypeprim, ctypevoid
 
 
 class W_CTypePtrOrArray(W_CType):
 
 
 rffi_fdopen = rffi.llexternal("fdopen", [rffi.INT, rffi.CCHARP], rffi.CCHARP)
-rffi_setbuf = rffi.llexternal("setbuf", [rffi.CCHARP,rffi.CCHARP], lltype.Void)
+rffi_setbuf = rffi.llexternal("setbuf", [rffi.CCHARP, rffi.CCHARP], lltype.Void)
 rffi_fclose = rffi.llexternal("fclose", [rffi.CCHARP], rffi.INT)
 
 class CffiFileObj(object):
     _immutable_ = True
+
     def __init__(self, fd, mode):
         self.llf = rffi_fdopen(fd, mode)
         if not self.llf:
             raise OSError(rposix.get_errno(), "fdopen failed")
         rffi_setbuf(self.llf, lltype.nullptr(rffi.CCHARP.TO))
+
     def close(self):
         rffi_fclose(self.llf)
 
+
 def prepare_iofile_argument(space, w_fileobj):
     fileobj = space.interpclass_w(w_fileobj)
     from pypy.module._io.interp_iobase import W_IOBase

pypy/module/_cffi_backend/ctypestruct.py

 """
 
 from pypy.interpreter.error import OperationError, operationerrfmt
-from rpython.rtyper.lltypesystem import lltype, rffi
 from pypy.interpreter.baseobjspace import Wrappable
 from pypy.interpreter.typedef import TypeDef, interp_attrproperty
+
+from rpython.rlib import jit
 from rpython.rlib.objectmodel import keepalive_until_here
 from rpython.rlib.rarithmetic import r_uint, r_ulonglong, r_longlong, intmask
-from rpython.rlib import jit
+from rpython.rtyper.lltypesystem import rffi
 
+from pypy.module._cffi_backend import cdataobj, ctypeprim, misc
 from pypy.module._cffi_backend.ctypeobj import W_CType
-from pypy.module._cffi_backend import cdataobj, ctypeprim, misc
 
 
 class W_CTypeStructOrUnion(W_CType):
 class W_CTypeStruct(W_CTypeStructOrUnion):
     kind = "struct"
 
+
 class W_CTypeUnion(W_CTypeStructOrUnion):
     kind = "union"
 
         #
         value = misc.as_long_long(space, w_ob)
         if isinstance(ctype, ctypeprim.W_CTypePrimitiveSigned):
-            fmin = -(r_longlong(1) << (self.bitsize-1))
-            fmax = (r_longlong(1) << (self.bitsize-1)) - 1
+            fmin = -(r_longlong(1) << (self.bitsize - 1))
+            fmax = (r_longlong(1) << (self.bitsize - 1)) - 1
             if fmax == 0:
                 fmax = 1      # special case to let "int x:1" receive "1"
         else:

pypy/module/_cffi_backend/libraryobj.py

 from __future__ import with_statement
-from pypy.interpreter.error import OperationError, operationerrfmt
+
 from pypy.interpreter.baseobjspace import Wrappable
+from pypy.interpreter.error import operationerrfmt
 from pypy.interpreter.gateway import interp2app, unwrap_spec
 from pypy.interpreter.typedef import TypeDef
-from rpython.rtyper.lltypesystem import lltype, rffi
+
+from rpython.rtyper.lltypesystem import rffi
 from rpython.rlib.rdynload import DLLHANDLE, dlopen, dlsym, dlclose, DLOpenError
 
 from pypy.module._cffi_backend.cdataobj import W_CData

pypy/module/_cffi_backend/misc.py

 from __future__ import with_statement
-from pypy.interpreter.error import OperationError, operationerrfmt
-from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
+
+from pypy.interpreter.error import OperationError
+
+from rpython.rlib import jit
+from rpython.rlib.objectmodel import keepalive_until_here, specialize
 from rpython.rlib.rarithmetic import r_uint, r_ulonglong, is_signed_integer_type
 from rpython.rlib.unroll import unrolling_iterable
-from rpython.rlib.objectmodel import keepalive_until_here, specialize
-from rpython.rlib import jit
+from rpython.rtyper.lltypesystem import lltype, llmemory, rffi
 from rpython.translator.tool.cbuild import ExternalCompilationInfo
 
 # ____________________________________________________________
 def read_raw_unsigned_data(target, size):
     for TP, TPP in _prim_unsigned_types:
         if size == rffi.sizeof(TP):
-            return rffi.cast(lltype.UnsignedLongLong, rffi.cast(TPP,target)[0])
+            return rffi.cast(lltype.UnsignedLongLong, rffi.cast(TPP, target)[0])
     raise NotImplementedError("bad integer size")
 
 def read_raw_ulong_data(target, size):
     for TP, TPP in _prim_unsigned_types:
         if size == rffi.sizeof(TP):
             assert rffi.sizeof(TP) <= rffi.sizeof(lltype.Unsigned)
-            return rffi.cast(lltype.Unsigned, rffi.cast(TPP,target)[0])
+            return rffi.cast(lltype.Unsigned, rffi.cast(TPP, target)[0])
     raise NotImplementedError("bad integer size")
 
 def read_raw_float_data(target, size):

pypy/module/_cffi_backend/newtype.py

 from pypy.interpreter.error import OperationError, operationerrfmt
 from pypy.interpreter.gateway import unwrap_spec
+
+from rpython.rlib.objectmodel import specialize
+from rpython.rlib.rarithmetic import ovfcheck
 from rpython.rtyper.lltypesystem import lltype, rffi
-from rpython.rlib.rarithmetic import ovfcheck, r_uint, intmask
-from rpython.rlib.rarithmetic import most_neg_value_of, most_pos_value_of
-from rpython.rlib.objectmodel import specialize
 
-from pypy.module._cffi_backend import ctypeobj, ctypeprim, ctypeptr, ctypearray
-from pypy.module._cffi_backend import ctypestruct, ctypevoid, ctypeenum
+from pypy.module._cffi_backend import (ctypeobj, ctypeprim, ctypeptr,
+    ctypearray, ctypestruct, ctypevoid, ctypeenum)
 
 
 @specialize.memo()
         #
         if foffset < 0:
             # align this field to its own 'falign' by inserting padding
-            offset = (offset + falign - 1) & ~(falign-1)
+            offset = (offset + falign - 1) & ~(falign - 1)
         else:
             # a forced field position: ignore the offset just computed,
             # except to know if we must set 'custom_field_pos'
                 fbitsize == 8 * ftype.size and not
                 isinstance(ftype, ctypeprim.W_CTypePrimitiveCharOrUniChar)):
             fbitsize = -1
-            if isinstance(ftype, ctypearray.W_CTypeArray) and ftype.length==0:
+            if isinstance(ftype, ctypearray.W_CTypeArray) and ftype.length == 0:
                 bitshift = ctypestruct.W_CField.BS_EMPTY_ARRAY
             else:
                 bitshift = ctypestruct.W_CField.BS_REGULAR
     # as 1 instead.  But for ctypes support, we allow the manually-
     # specified totalsize to be zero in this case.
     if totalsize < 0:
-        offset = (offset + alignment - 1) & ~(alignment-1)
+        offset = (offset + alignment - 1) & ~(alignment - 1)
         totalsize = offset or 1
     elif totalsize < offset:
         raise operationerrfmt(space.w_TypeError,

pypy/module/_io/interp_bufferedio.py

             return res
         return None
 
+    def readline_w(self, space, w_limit=None):
+        self._check_init(space)
+        self._check_closed(space, "readline of closed file")
+
+        limit = convert_size(space, w_limit)
+
+        # First, try to find a line in the buffer. This can run
+        # unlocked because the calls to the C API are simple enough
+        # that they can't trigger any thread switch.
+        have = self._readahead()
+        if limit >= 0 and have > limit:
+            have = limit
+        for pos in range(self.pos, self.pos+have):
+            if self.buffer[pos] == '\n':
+                break
+        else:
+            pos = -1
+        if pos >= 0:
+            w_res = space.wrap(''.join(self.buffer[self.pos:pos+1]))
+            self.pos = pos + 1
+            return w_res
+        if have == limit:
+            w_res = space.wrap(''.join(self.buffer[self.pos:self.pos+have]))
+            self.pos += have
+            return w_res
+
+        written = 0
+        with self.lock:
+            # Now we try to get some more from the raw stream
+            chunks = []
+            if have > 0:
+                chunks.extend(self.buffer[self.pos:self.pos+have])
+                written += have
+                self.pos += have
+                if limit >= 0:
+                    limit -= have
+            if self.writable:
+                self._flush_and_rewind_unlocked(space)
+
+            while True:
+                self._reader_reset_buf()
+                have = self._fill_buffer(space)
+                if have == 0:
+                    break
+                if limit >= 0 and have > limit:
+                    have = limit
+                pos = 0
+                found = False
+                while pos < have:
+                    c = self.buffer[pos]
+                    pos += 1
+                    if c == '\n':
+                        self.pos = pos
+                        found = True
+                        break
+                chunks.extend(self.buffer[0:pos])
+                if found:
+                    break
+                if have == limit:
+                    self.pos = have
+                    break
+                written += have
+                if limit >= 0:
+                    limit -= have
+            return space.wrap(''.join(chunks))
+
     # ____________________________________________________
     # Write methods
 
     peek = interp2app(W_BufferedReader.peek_w),
     read1 = interp2app(W_BufferedReader.read1_w),
     raw = interp_attrproperty_w("w_raw", cls=W_BufferedReader),
+    readline = interp2app(W_BufferedReader.readline_w),
 
     # from the mixin class
     __repr__ = interp2app(W_BufferedReader.repr_w),
     read = interp2app(W_BufferedRandom.read_w),
     peek = interp2app(W_BufferedRandom.peek_w),
     read1 = interp2app(W_BufferedRandom.read1_w),
+    readline = interp2app(W_BufferedRandom.readline_w),
 
     write = interp2app(W_BufferedRandom.write_w),
     flush = interp2app(W_BufferedRandom.flush_w),

pypy/module/_io/interp_fileio.py

 from pypy.interpreter.error import OperationError, wrap_oserror, wrap_oserror2
 from rpython.rlib.rarithmetic import r_longlong
 from rpython.rlib.rstring import StringBuilder
-from rpython.rlib.rposix import validate_fd
 from os import O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_TRUNC
 import sys, os, stat, errno
 from pypy.module._io.interp_iobase import W_RawIOBase, convert_size
         fd_is_own = False
         try:
             if fd >= 0:
-                validate_fd(fd)
                 try:
                     os.fstat(fd)
                 except OSError, e:
         self.fd = -1
 
         try:
-            validate_fd(fd)
             os.close(fd)
         except OSError, e:
             raise wrap_oserror(space, e,

pypy/module/_io/test/test_bufferedio.py

                 f.flush()
                 assert raw.getvalue() == b'1b\n2def\n3\n'
 
+    def test_readline(self):
+        import _io as io
+        with io.BytesIO(b"abc\ndef\nxyzzy\nfoo\x00bar\nanother line") as raw:
+            with io.BufferedRandom(raw, buffer_size=10) as f:
+                assert f.readline() == b"abc\n"
+                assert f.readline(10) == b"def\n"
+                assert f.readline(2) == b"xy"
+                assert f.readline(4) == b"zzy\n"
+                assert f.readline() == b"foo\x00bar\n"
+                assert f.readline(None) == b"another line"
+                raises(TypeError, f.readline, 5.3)
+
 
 class AppTestDeprecation:
 

pypy/module/micronumpy/__init__.py

         'True_': 'types.Bool.True',
         'False_': 'types.Bool.False',
 
-        'bool': 'space.w_bool',
-        'int': 'space.w_int',
-
         'typeinfo': 'interp_dtype.get_dtype_cache(space).w_typeinfo',
 
         'generic': 'interp_boxes.W_GenericBox',
 
     # ufuncs
     for exposed, impl in [
-        ("abs", "absolute"),
         ("absolute", "absolute"),
         ("add", "add"),
         ("arccos", "arccos"),
         interpleveldefs[exposed] = "interp_ufuncs.get(space).%s" % impl
 
     appleveldefs = {
-        'average': 'app_numpy.average',
-        'sum': 'app_numpy.sum',
-        'min': 'app_numpy.min',
-        'identity': 'app_numpy.identity',
-        'eye': 'app_numpy.eye',
-        'max': 'app_numpy.max',
         'arange': 'app_numpy.arange',
     }
+    def setup_after_space_initialization(self):
+        space = self.space
+        all_list = sorted(Module.interpleveldefs.keys() + \
+                                Module.appleveldefs.keys())
+        # found by set(numpypy.__all__) - set(numpy.__all__)
+        all_list.remove('set_string_function')
+        all_list.remove('typeinfo')
+        w_all = space.wrap(all_list)
+        space.setitem(self.w_dict, space.new_interned_str('__all__'), w_all)
 
 if long_double_size == 16:
     Module.interpleveldefs['float128'] = 'interp_boxes.W_Float128Box'

pypy/module/micronumpy/app_numpy.py

 
 import _numpypy
 
-def average(a):
-    # This implements a weighted average, for now we don't implement the
-    # weighting, just the average part!
-    if not hasattr(a, "mean"):
-        a = _numpypy.array(a)
-    return a.mean()
-
-def identity(n, dtype=None):
-    a = _numpypy.zeros((n, n), dtype=dtype)
-    for i in range(n):
-        a[i][i] = 1
-    return a
-
-def eye(n, m=None, k=0, dtype=None):
-    if m is None:
-        m = n
-    a = _numpypy.zeros((n, m), dtype=dtype)
-    ni = 0
-    mi = 0
-
-    if k < 0:
-        p = n + k
-        ni = -k
-    else:
-        p = n - k
-        mi = k
-
-    while ni < n and mi < m:
-        a[ni][mi] = 1
-        ni += 1
-        mi += 1
-    return a
-
-def sum(a,axis=None, out=None):
-    '''sum(a, axis=None)
-    Sum of array elements over a given axis.
-
-    Parameters
-    ----------
-    a : array_like
-        Elements to sum.
-    axis : integer, optional
-        Axis over which the sum is taken. By default `axis` is None,
-        and all elements are summed.
-
-    Returns
-    -------
-    sum_along_axis : ndarray
-        An array with the same shape as `a`, with the specified
-        axis removed.   If `a` is a 0-d array, or if `axis` is None, a scalar
-        is returned.  If an output array is specified, a reference to
-        `out` is returned.
-
-    See Also
-    --------
-    ndarray.sum : Equivalent method.
-    '''
-    # TODO: add to doc (once it's implemented): cumsum : Cumulative sum of array elements.
-    if not hasattr(a, "sum"):
-        a = _numpypy.array(a)
-    return a.sum(axis=axis, out=out)
-
-def min(a, axis=None, out=None):
-    if not hasattr(a, "min"):
-        a = _numpypy.array(a)
-    if a.size < 1:
-        return _numpypy.array([])
-    return a.min(axis=axis, out=out)
-
-def max(a, axis=None, out=None):
-    if not hasattr(a, "max"):
-        a = _numpypy.array(a)
-    if a.size < 1:
-        return _numpypy.array([])
-    return a.max(axis=axis, out=out)
-
 def arange(start, stop=None, step=1, dtype=None):
     '''arange([start], stop[, step], dtype=None)
     Generate values in the half-interval [start, stop).

pypy/module/micronumpy/interp_numarray.py

 
     @unwrap_spec(mode=str)
     def descr_choose(self, space, w_choices, mode='raise', w_out=None):
-        if w_out is not None and not isinstance(w_out, W_NDimArray):
+        if space.is_none(w_out):
+            w_out = None
+        elif not isinstance(w_out, W_NDimArray):
             raise OperationError(space.w_TypeError, space.wrap(
                 "return arrays must be of ArrayType"))
         return interp_arrayops.choose(space, self, w_choices, w_out, mode)
 
     def descr_clip(self, space, w_min, w_max, w_out=None):
-        if w_out is not None and not isinstance(w_out, W_NDimArray):
+        if space.is_none(w_out):
+            w_out = None
+        elif not isinstance(w_out, W_NDimArray):
             raise OperationError(space.w_TypeError, space.wrap(
                 "return arrays must be of ArrayType"))
         min = convert_to_array(space, w_min)

pypy/module/micronumpy/test/test_arrayops.py

     def test_choose_out(self):
         from _numpypy import array
         a, b, c = array([1, 2, 3]), [4, 5, 6], 13
+        r = array([2, 1, 0]).choose([a, b, c], out=None)
+        assert (r == [13, 5, 3]).all()
+        assert (a == [1, 2, 3]).all()
         r = array([2, 1, 0]).choose([a, b, c], out=a)
         assert (r == [13, 5, 3]).all()
         assert (a == [13, 5, 3]).all()
-        
+
     def test_choose_modes(self):
         from _numpypy import array
         a, b, c = array([1, 2, 3]), [4, 5, 6], 13

pypy/module/micronumpy/test/test_complex.py

 
     def test_conjugate(self):
         from _numpypy import conj, conjugate, complex128, complex64
-        import _numpypy as np
+        import numpypy as np
 
         c0 = complex128(complex(2.5, 0))
         c1 = complex64(complex(1, 2))
 
     def test_basic(self):
         from _numpypy import (complex128, complex64, add, array, dtype,
-            subtract as sub, multiply, divide, negative, abs, floor_divide,
-            real, imag, sign, clongfloat)
+            subtract as sub, multiply, divide, negative, absolute as abs,
+            floor_divide, real, imag, sign, clongfloat)
         from _numpypy import (equal, not_equal, greater, greater_equal, less,
                 less_equal, isnan)
         assert real(4.0) == 4.0

pypy/module/micronumpy/test/test_dtypes.py

     def test_various_types(self):
         import _numpypy as numpy
 
-        assert numpy.bool is bool
-        assert numpy.int is int
-
         assert numpy.int16 is numpy.short
         assert numpy.int8 is numpy.byte
         assert numpy.bool_ is numpy.bool8

pypy/module/micronumpy/test/test_module.py

-from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
-
-
-class AppTestNumPyModule(BaseNumpyAppTest):
-    def test_average(self):
-        from _numpypy import array, average
-        assert average(range(10)) == 4.5
-        assert average(array(range(10))) == 4.5
-
-    def test_sum(self):
-        from _numpypy import array, sum
-        assert sum(range(10)) == 45
-        assert sum(array(range(10))) == 45
-
-    def test_min(self):
-        from _numpypy import array, min, zeros
-        assert min(range(10)) == 0
-        assert min(array(range(10))) == 0
-        assert list(min(zeros((0, 2)), axis=1)) == []
-
-    def test_max(self):
-        from _numpypy import array, max, zeros
-        assert max(range(10)) == 9
-        assert max(array(range(10))) == 9
-        assert list(max(zeros((0, 2)), axis=1)) == []

pypy/module/micronumpy/test/test_numarray.py

         assert (a.mean(1) == [0.5, 2.5, 4.5, 6.5, 8.5]).all()
 
     def test_sum(self):
-        from _numpypy import array
+        from _numpypy import array, zeros
         a = array(range(5))
         assert a.sum() == 10
         assert a[:4].sum() == 6
         assert b == d
         assert b is d
 
+        assert list(zeros((0, 2)).sum(axis=1)) == []
+
     def test_reduce_nd(self):
         from numpypy import arange, array, multiply
         a = arange(15).reshape(5, 3)
         assert (array([[1,2],[3,4]]).prod(0) == [3, 8]).all()
         assert (array([[1,2],[3,4]]).prod(1) == [2, 12]).all()
 
-    def test_identity(self):
-        from _numpypy import identity, array
-        from _numpypy import int32, float64, dtype
-        a = identity(0)
-        assert len(a) == 0
-        assert a.dtype == dtype('float64')
-        assert a.shape == (0, 0)
-        b = identity(1, dtype=int32)
-        assert len(b) == 1
-        assert b[0][0] == 1
-        assert b.shape == (1, 1)
-        assert b.dtype == dtype('int32')
-        c = identity(2)
-        assert c.shape == (2, 2)
-        assert (c == [[1, 0], [0, 1]]).all()
-        d = identity(3, dtype='int32')
-        assert d.shape == (3, 3)
-        assert d.dtype == dtype('int32')
-        assert (d == [[1, 0, 0], [0, 1, 0], [0, 0, 1]]).all()
-
-    def test_eye(self):
-        from _numpypy import eye
-        from _numpypy import int32, dtype
-        a = eye(0)
-        assert len(a) == 0
-        assert a.dtype == dtype('float64')
-        assert a.shape == (0, 0)
-        b = eye(1, dtype=int32)
-        assert len(b) == 1
-        assert b[0][0] == 1
-        assert b.shape == (1, 1)
-        assert b.dtype == dtype('int32')
-        c = eye(2)
-        assert c.shape == (2, 2)
-        assert (c == [[1, 0], [0, 1]]).all()
-        d = eye(3, dtype='int32')
-        assert d.shape == (3, 3)
-        assert d.dtype == dtype('int32')
-        assert (d == [[1, 0, 0], [0, 1, 0], [0, 0, 1]]).all()
-        e = eye(3, 4)
-        assert e.shape == (3, 4)
-        assert (e == [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]]).all()
-        f = eye(2, 4, k=3)
-        assert f.shape == (2, 4)
-        assert (f == [[0, 0, 0, 1], [0, 0, 0, 0]]).all()
-        g = eye(3, 4, k=-1)
-        assert g.shape == (3, 4)
-        assert (g == [[0, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0]]).all()
-
     def test_prod(self):
         from _numpypy import array
         a = array(range(1, 6))
         assert a[:4].prod() == 24.0
 
     def test_max(self):
-        from _numpypy import array
+        from _numpypy import array, zeros
         a = array([-1.2, 3.4, 5.7, -3.0, 2.7])
         assert a.max() == 5.7
         b = array([])
         raises(ValueError, "b.max()")
 
+        assert list(zeros((0, 2)).max(axis=1)) == []
+
     def test_max_add(self):
         from _numpypy import array
         a = array([-1.2, 3.4, 5.7, -3.0, 2.7])
         assert (a + a).max() == 11.4
 
     def test_min(self):
-        from _numpypy import array
+        from _numpypy import array, zeros
         a = array([-1.2, 3.4, 5.7, -3.0, 2.7])
         assert a.min() == -3.0
         b = array([])
         raises(ValueError, "b.min()")
 
+        assert list(zeros((0, 2)).min(axis=1)) == []
+
     def test_argmax(self):
         from _numpypy import array
         a = array([-1.2, 3.4, 5.7, -3.0, 2.7])
         from _numpypy import array
         a = array([1, 2, 17, -3, 12])
         assert (a.clip(-2, 13) == [1, 2, 13, -2, 12]).all()
-        assert (a.clip(-1, 1) == [1, 1, 1, -1, 1]).all()
+        assert (a.clip(-1, 1, out=None) == [1, 1, 1, -1, 1]).all()
+        assert (a == [1, 2, 17, -3, 12]).all()
         assert (a.clip(-1, [1, 2, 3, 4, 5]) == [1, 2, 3, -1, 5]).all()
         assert (a.clip(-2, 13, out=a) == [1, 2, 13, -2, 12]).all()
         assert (a == [1, 2, 13, -2, 12]).all()

pypy/module/micronumpy/test/test_outarg.py

         b = add(10, 10, out=out)
         assert b==out
         assert b.dtype == out.dtype
-        
-    def test_applevel(self):
-        from _numpypy import array, sum, max, min
-        a = array([[1, 2], [3, 4]])
-        out = array([[0, 0], [0, 0]])
-        c = sum(a, axis=0, out=out[0])
-        assert (c == [4, 6]).all()
-        assert (c == out[0]).all()
-        assert (c != out[1]).all()
-        c = max(a, axis=1, out=out[0])
-        assert (c == [2, 4]).all()
-        assert (c == out[0]).all()
-        assert (c != out[1]).all()
-        
+
     def test_ufunc_cast(self):
-        from _numpypy import array, negative, add, sum
+        from _numpypy import array, negative, add
         a = array(16, dtype = int)
         c = array(0, dtype = float)
         b = negative(a, out=c)
         b = add(a, a, out=c)
         assert b == c
         d = array([16, 16], dtype=int)
-        b = sum(d, out=c)
+        b = d.sum(out=c)
         assert b == c
         #cast_error = raises(TypeError, negative, c, a)
         #assert str(cast_error.value) == \

pypy/module/test_lib_pypy/numpypy/core/test_fromnumeric.py

         # a = array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
         # assert shape(a) == (2,)
 
+    def test_clip(self):
+        import numpypy as np
+        a = np.arange(10)
+        b = np.clip(a, 1, 8)
+        assert (b == [1, 1, 2, 3, 4, 5, 6, 7, 8, 8]).all()
+        assert (a == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).all()
+        b = np.clip(a, 3, 6, out=a)
+        assert (b == [3, 3, 3, 3, 4, 5, 6, 6, 6, 6]).all()
+        assert (a == [3, 3, 3, 3, 4, 5, 6, 6, 6, 6]).all()
+        a = np.arange(10)
+        b = np.clip(a, [3,4,1,1,1,4,4,4,4,4], 8)
+        assert (b == [3, 4, 2, 3, 4, 5, 6, 7, 8, 8]).all()
+        assert (a == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]).all()
+
     def test_sum(self):
         # tests taken from numpy/core/fromnumeric.py docstring
-        from numpypy import array, sum, ones
+        from numpypy import array, sum, ones, zeros
         assert sum([0.5, 1.5])== 2.0
         assert sum([[0, 1], [0, 5]]) == 6
         # assert sum([0.5, 0.7, 0.2, 1.5], dtype=int32) == 1
         # If the accumulator is too small, overflow occurs:
         # assert ones(128, dtype=int8).sum(dtype=int8) == -128
 
+        assert sum(range(10)) == 45
+        assert sum(array(range(10))) == 45
+        assert list(sum(zeros((0, 2)), axis=1)) == []
+
+        a = array([[1, 2], [3, 4]])
+        out = array([[0, 0], [0, 0]])
+        c = sum(a, axis=0, out=out[0])
+        assert (c == [4, 6]).all()
+        assert (c == out[0]).all()
+        assert (c != out[1]).all()
+
     def test_amin(self):
         # tests taken from numpy/core/fromnumeric.py docstring
-        from numpypy import array, arange, amin
+        from numpypy import array, arange, amin, zeros
         a = arange(4).reshape((2,2))
         assert amin(a) == 0
         # # Minima along the first axis
         # assert amin(b) == nan
         # assert nanmin(b) == 0.0
 
+        assert amin(range(10)) == 0
+        assert amin(array(range(10))) == 0
+        assert list(amin(zeros((0, 2)), axis=1)) == []
+
+        a = array([[1, 2], [3, 4]])
+        out = array([[0, 0], [0, 0]])
+        c = amin(a, axis=1, out=out[0])
+        assert (c == [1, 3]).all()
+        assert (c == out[0]).all()
+        assert (c != out[1]).all()
+
     def test_amax(self):
         # tests taken from numpy/core/fromnumeric.py docstring
-        from numpypy import array, arange, amax
+        from numpypy import array, arange, amax, zeros
         a = arange(4).reshape((2,2))
         assert amax(a) == 3
         # assert (amax(a, axis=0) == array([2, 3])).all()
         # assert amax(b) == nan
         # assert nanmax(b) == 4.0
 
+        assert amax(range(10)) == 9
+        assert amax(array(range(10))) == 9
+        assert list(amax(zeros((0, 2)), axis=1)) == []
+
+        a = array([[1, 2], [3, 4]])
+        out = array([[0, 0], [0, 0]])
+        c = amax(a, axis=1, out=out[0])
+        assert (c == [2, 4]).all()
+        assert (c == out[0]).all()
+        assert (c != out[1]).all()
+
     def test_alen(self):
         # tests taken from numpy/core/fromnumeric.py docstring
         from numpypy import array, zeros, alen

pypy/module/test_lib_pypy/numpypy/core/test_numeric.py

         assert base_repr(-12, 10, 4) == '-000012'
         assert base_repr(-12, 4) == '-30'
 
+
 class AppTestRepr(BaseNumpyAppTest):
 
     def setup_class(cls):
     def test_equal(self):
         from _numpypy import array
         from numpypy import array_equal
-        
+
         a = [1, 2, 3]
         b = [1, 2, 3]
-        
+
         assert array_equal(a, b)
         assert array_equal(a, array(b))
         assert array_equal(array(a), b)
     def test_not_equal(self):
         from _numpypy import array
         from numpypy import array_equal
-        
+
         a = [1, 2, 3]
         b = [1, 2, 4]
-        
+
         assert not array_equal(a, b)
         assert not array_equal(a, array(b))
         assert not array_equal(array(a), b)
     def test_mismatched_shape(self):
         from _numpypy import array
         from numpypy import array_equal
-        
+
         a = [1, 2, 3]
         b = [[1, 2, 3], [1, 2, 3]]
-        
+
         assert not array_equal(a, b)
         assert not array_equal(a, array(b))
         assert not array_equal(array(a), b)
         assert not array_equal(array(a), array(b))
 
+
 class AppTestNumeric(BaseNumpyAppTest):
-
     def test_outer(self):
         from _numpypy import array
         from numpypy import outer
                           [12, 15, 18]])
         assert (res == expected).all()
 
+    def test_identity(self):
+        from _numpypy import array, int32, float64, dtype
+        from numpypy import identity
+        a = identity(0)
+        assert len(a) == 0
+        assert a.dtype == dtype('float64')
+        assert a.shape == (0, 0)
+        b = identity(1, dtype=int32)
+        assert len(b) == 1
+        assert b[0][0] == 1
+        assert b.shape == (1, 1)
+        assert b.dtype == dtype('int32')
+        c = identity(2)
+        assert c.shape == (2, 2)
+        assert (c == [[1, 0], [0, 1]]).all()
+        d = identity(3, dtype='int32')
+        assert d.shape == (3, 3)
+        assert d.dtype == dtype('int32')
+        assert (d == [[1, 0, 0], [0, 1, 0], [0, 0, 1]]).all()

pypy/module/test_lib_pypy/numpypy/core/test_shape_base.py

                           np.ones((a.shape[0],
                                    a.shape[1] + b.shape[1],
                                    a.shape[2])))
-        
-    def test_dstack(self):
-        import numpypy as np
-        a = np.array((1, 2, 3))
-        b = np.array((2, 3, 4))
-        c = np.dstack((a, b))
-        assert np.array_equal(c, [[[1, 2], [2, 3], [3, 4]]])
-
-        a = np.array([[1], [2], [3]])
-        b = np.array([[2], [3], [4]])
-        c = np.dstack((a, b))
-        assert np.array_equal(c, [[[1, 2]], [[2, 3]], [[3, 4]]])
-
-        #skip("https://bugs.pypy.org/issue1394")
-        for shape1, shape2 in [[(4, 2, 3), (4, 2, 7)],
-                               [(7, 2, 0), (7, 2, 10)],
-                               [(7, 2, 0), (7, 2, 0)]]:
-            a, b = np.ones(shape1), np.ones(shape2)
-            assert np.all(np.dstack((a, b)) ==
-                          np.ones((a.shape[0],
-                                   a.shape[1],
-                                   a.shape[2] + b.shape[2])))
-
-        for shape1, shape2 in [[(4, 2, 3, 5), (4, 2, 7, 5)],
-                               [(7, 2, 0, 5), (7, 2, 10, 5)],
-                               [(7, 2, 0, 5), (7, 2, 0, 5)]]:
-            a, b = np.ones(shape1), np.ones(shape2)
-            assert np.all(np.dstack((a, b)) ==
-                          np.ones((a.shape[0],
-                                   a.shape[1],
-                                   a.shape[2] + b.shape[2],
-                                   a.shape[3])))

pypy/module/test_lib_pypy/numpypy/lib/test_function_base.py

+from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
+
+class AppTestFunctionBase(BaseNumpyAppTest):
+    def test_average(self):
+        from numpypy import array, average
+        assert average(range(10)) == 4.5
+        assert average(array(range(10))) == 4.5

pypy/module/test_lib_pypy/numpypy/lib/test_shape_base_lib.py

+from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
+
+class AppTestShapeBase(BaseNumpyAppTest):
+    def test_dstack(self):
+        import numpypy as np
+        a = np.array((1, 2, 3))
+        b = np.array((2, 3, 4))
+        c = np.dstack((a, b))
+        assert np.array_equal(c, [[[1, 2], [2, 3], [3, 4]]])
+
+        a = np.array([[1], [2], [3]])
+        b = np.array([[2], [3], [4]])
+        c = np.dstack((a, b))
+        assert np.array_equal(c, [[[1, 2]], [[2, 3]], [[3, 4]]])
+
+        #skip("https://bugs.pypy.org/issue1394")
+        for shape1, shape2 in [[(4, 2, 3), (4, 2, 7)],
+                               [(7, 2, 0), (7, 2, 10)],
+                               [(7, 2, 0), (7, 2, 0)]]:
+            a, b = np.ones(shape1), np.ones(shape2)
+            assert np.all(np.dstack((a, b)) ==
+                          np.ones((a.shape[0],
+                                   a.shape[1],
+                                   a.shape[2] + b.shape[2])))
+
+        for shape1, shape2 in [[(4, 2, 3, 5), (4, 2, 7, 5)],
+                               [(7, 2, 0, 5), (7, 2, 10, 5)],
+                               [(7, 2, 0, 5), (7, 2, 0, 5)]]:
+            a, b = np.ones(shape1), np.ones(shape2)
+            assert np.all(np.dstack((a, b)) ==
+                          np.ones((a.shape[0],
+                                   a.shape[1],
+                                   a.shape[2] + b.shape[2],
+                                   a.shape[3])))

pypy/module/test_lib_pypy/numpypy/lib/test_twodim_base.py

+from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
+
+class AppTestTwoDimBase(BaseNumpyAppTest):
+    def test_eye(self):
+        from _numpypy import int32, dtype
+        from numpypy import eye
+        a = eye(0)
+        assert len(a) == 0
+        assert a.dtype == dtype('float64')
+        assert a.shape == (0, 0)
+        b = eye(1, dtype=int32)
+        assert len(b) == 1
+        assert b[0][0] == 1
+        assert b.shape == (1, 1)
+        assert b.dtype == dtype('int32')
+        c = eye(2)
+        assert c.shape == (2, 2)
+        assert (c == [[1, 0], [0, 1]]).all()
+        d = eye(3, dtype='int32')
+        assert d.shape == (3, 3)
+        assert d.dtype == dtype('int32')
+        assert (d == [[1, 0, 0], [0, 1, 0], [0, 0, 1]]).all()
+        e = eye(3, 4)
+        assert e.shape == (3, 4)
+        assert (e == [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]]).all()
+        f = eye(2, 4, k=3)
+        assert f.shape == (2, 4)
+        assert (f == [[0, 0, 0, 1], [0, 0, 0, 0]]).all()
+        g = eye(3, 4, k=-1)
+        assert g.shape == (3, 4)
+        assert (g == [[0, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0]]).all()

pypy/module/test_lib_pypy/numpypy/test_numpy.py

 
     def test_min_max_after_import(self):
         import __builtin__
+        from __builtin__ import *
 
         from numpypy import *
         assert min is __builtin__.min
         assert min(4, 3, 2, 1) == 1
         assert max(1, 2, 3, 4) == 4
 
-        from numpypy import min, max
+        from numpypy import min, max, amin, amax
         assert min is not __builtin__.min
         assert max is not __builtin__.max
+        assert min is amin
+        assert max is amax
+
+    def test_builtin_aliases(self):
+        import __builtin__
+        import numpypy
+        from numpypy import *
+
+        for name in ['bool', 'int', 'long', 'float', 'complex', 'object',
+                     'unicode', 'str']:
+            assert name not in locals()
+            assert getattr(numpypy, name) is getattr(__builtin__, name)
+
+    def test_typeinfo(self):
+        import numpypy
+        assert 'typeinfo' not in dir(numpypy)
+        assert 'typeinfo' in dir(numpypy.core.multiarray)
+
+    def test_set_string_function(self):
+        import numpypy
+        assert numpypy.set_string_function is not \
+               numpypy.core.multiarray.set_string_function

rpython/jit/backend/arm/regalloc.py

             classptr = y_val
             # here, we have to go back from 'classptr' to the value expected
             # from reading the 16 bits in the object header
-            from rpython.rtyper.memory.gctypelayout import GCData
+            from rpython.memory.gctypelayout import