Author: Philip Jenvey <pjen...@underboss.org>
Branch: py3k
Changeset: r74148:638bb3d67bdd
Date: 2014-10-23 22:34 -0700
http://bitbucket.org/pypy/pypy/changeset/638bb3d67bdd/

Log:    reapply py3k changes

diff --git a/pypy/objspace/std/complexobject.py 
b/pypy/objspace/std/complexobject.py
--- a/pypy/objspace/std/complexobject.py
+++ b/pypy/objspace/std/complexobject.py
@@ -141,26 +141,15 @@
         return (w_complex.realval, w_complex.imagval)
     #
     # test for a '__complex__' method, and call it if found.
-    # special case old-style instances, like CPython does.
     w_z = None
-    if space.is_oldstyle_instance(w_complex):
-        try:
-            w_method = space.getattr(w_complex, space.wrap('__complex__'))
-        except OperationError, e:
-            if not e.match(space, space.w_AttributeError):
-                raise
-        else:
-            w_z = space.call_function(w_method)
-    else:
-        w_method = space.lookup(w_complex, '__complex__')
-        if w_method is not None:
-            w_z = space.get_and_call_function(w_method, w_complex)
+    w_method = space.lookup(w_complex, '__complex__')
+    if w_method is not None:
+        w_z = space.get_and_call_function(w_method, w_complex)
     #
     if w_z is not None:
         # __complex__() must return a complex or (float,int,long) object
         # (XXX should not use isinstance here)
         if not strict_typing and (space.isinstance_w(w_z, space.w_int) or
-                                  space.isinstance_w(w_z, space.w_long) or
                                   space.isinstance_w(w_z, space.w_float)):
             return (space.float_w(w_z), 0.0)
         elif isinstance(w_z, W_ComplexObject):
@@ -274,9 +263,8 @@
         if isinstance(w_obj, W_ComplexObject):
             return w_obj
         if space.isinstance_w(w_obj, space.w_int):
-            return W_ComplexObject(float(space.int_w(w_obj)), 0.0)
-        if space.isinstance_w(w_obj, space.w_long):
-            return W_ComplexObject(space.float_w(w_obj), 0.0)
+            w_float = space.float_w(w_obj, allow_conversion=False)
+            return W_ComplexObject(w_float, 0.0)
         if space.isinstance_w(w_obj, space.w_float):
             return W_ComplexObject(space.float_w(w_obj), 0.0)
 
@@ -292,14 +280,14 @@
             and space.is_w(space.type(w_real), space.w_complex)):
             return w_real
 
-        if space.isinstance_w(w_real, space.w_str) or \
-                space.isinstance_w(w_real, space.w_unicode):
+        if space.isinstance_w(w_real, space.w_unicode):
             # a string argument
             if not noarg2:
                 raise oefmt(space.w_TypeError, "complex() can't take second"
                                                " arg if first is a string")
+            unistr = unicode_to_decimal_w(space, w_real)
             try:
-                realstr, imagstr = _split_complex(space.str_w(w_real))
+                realstr, imagstr = _split_complex(unistr)
             except ValueError:
                 raise oefmt(space.w_ValueError,
                             "complex() arg is a malformed string")
@@ -360,19 +348,11 @@
         combined = intmask(hashreal + HASH_IMAG * hashimg)
         return space.newint(-2 if combined == -1 else combined)
 
-    """
-    def descr_coerce(self, space, w_other):
-        w_other = self._to_complex(space, w_other)
-        if w_other is None:
-            return space.w_NotImplemented
-        return space.newtuple([self, w_other])
-        """
-
     def descr_format(self, space, w_format_spec):
         return newformat.run_formatter(space, w_format_spec, "format_complex",
                                        self)
 
-    def descr_nonzero(self, space):
+    def descr_bool(self, space):
         return space.newbool((self.realval != 0.0) or (self.imagval != 0.0))
 
     def descr_float(self, space):
@@ -396,7 +376,6 @@
             return space.newbool((self.realval == w_other.realval) and
                                  (self.imagval == w_other.imagval))
         if (space.isinstance_w(w_other, space.w_int) or
-            space.isinstance_w(w_other, space.w_long) or
             space.isinstance_w(w_other, space.w_float)):
             if self.imagval:
                 return space.w_False
@@ -407,8 +386,7 @@
         if isinstance(w_other, W_ComplexObject):
             return space.newbool((self.realval != w_other.realval) or
                                  (self.imagval != w_other.imagval))
-        if (space.isinstance_w(w_other, space.w_int) or
-            space.isinstance_w(w_other, space.w_long)):
+        if (space.isinstance_w(w_other, space.w_int)):
             if self.imagval:
                 return space.w_True
             return space.ne(space.newfloat(self.realval), w_other)
@@ -478,66 +456,6 @@
         except ZeroDivisionError, e:
             raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e)))
 
-        """
-    def descr_floordiv(self, space, w_rhs):
-        w_rhs = self._to_complex(space, w_rhs)
-        if w_rhs is None:
-            return space.w_NotImplemented
-        # don't care about the slight slowdown you get from using divmod
-        try:
-            return self.divmod(space, w_rhs)[0]
-        except ZeroDivisionError, e:
-            raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e)))
-
-    def descr_rfloordiv(self, space, w_lhs):
-        w_lhs = self._to_complex(space, w_lhs)
-        if w_lhs is None:
-            return space.w_NotImplemented
-        # don't care about the slight slowdown you get from using divmod
-        try:
-            return w_lhs.divmod(space, self)[0]
-        except ZeroDivisionError, e:
-            raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e)))
-
-    def descr_mod(self, space, w_rhs):
-        w_rhs = self._to_complex(space, w_rhs)
-        if w_rhs is None:
-            return space.w_NotImplemented
-        try:
-            return self.divmod(space, w_rhs)[1]
-        except ZeroDivisionError, e:
-            raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e)))
-
-    def descr_rmod(self, space, w_lhs):
-        w_lhs = self._to_complex(space, w_lhs)
-        if w_lhs is None:
-            return space.w_NotImplemented
-        try:
-            return w_lhs.divmod(space, self)[1]
-        except ZeroDivisionError, e:
-            raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e)))
-
-    def descr_divmod(self, space, w_rhs):
-        w_rhs = self._to_complex(space, w_rhs)
-        if w_rhs is None:
-            return space.w_NotImplemented
-        try:
-            div, mod = self.divmod(space, w_rhs)
-        except ZeroDivisionError, e:
-            raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e)))
-        return space.newtuple([div, mod])
-
-    def descr_rdivmod(self, space, w_lhs):
-        w_lhs = self._to_complex(space, w_lhs)
-        if w_lhs is None:
-            return space.w_NotImplemented
-        try:
-            div, mod = w_lhs.divmod(space, self)
-        except ZeroDivisionError, e:
-            raise OperationError(space.w_ZeroDivisionError, space.wrap(str(e)))
-        return space.newtuple([div, mod])
-        """
-
     @unwrap_spec(w_third_arg=WrappedDefault(None))
     def descr_pow(self, space, w_exponent, w_third_arg):
         w_exponent = self._to_complex(space, w_exponent)
@@ -574,12 +492,12 @@
 w_one = W_ComplexObject(1, 0)
 
 
-def complexwprop(name):
+def complexwprop(name, doc):
     def fget(space, w_obj):
         if not isinstance(w_obj, W_ComplexObject):
             raise oefmt(space.w_TypeError, "descriptor is for 'complex'")
         return space.newfloat(getattr(w_obj, name))
-    return GetSetProperty(fget)
+    return GetSetProperty(fget, doc=doc)
 
 W_ComplexObject.typedef = StdTypeDef("complex",
     __doc__ = """complex(real[, imag]) -> complex number
@@ -588,14 +506,14 @@
 This is equivalent to (real + imag*1j) where imag defaults to 0.""",
     __new__ = interp2app(W_ComplexObject.descr__new__),
     __getnewargs__ = interp2app(W_ComplexObject.descr___getnewargs__),
-    real = complexwprop('realval'),
-    imag = complexwprop('imagval'),
+    real = complexwprop('realval', doc="the real part of a complex number"),
+    imag = complexwprop('imagval',
+                        doc="the imaginary part of a complex number"),
     __repr__ = interp2app(W_ComplexObject.descr_repr),
     __str__ = interp2app(W_ComplexObject.descr_str),
     __hash__ = interp2app(W_ComplexObject.descr_hash),
-    #__coerce__ = interp2app(W_ComplexObject.descr_coerce),
     __format__ = interp2app(W_ComplexObject.descr_format),
-    __nonzero__ = interp2app(W_ComplexObject.descr_nonzero),
+    __bool__ = interp2app(W_ComplexObject.descr_bool),
     __float__ = interp2app(W_ComplexObject.descr_float),
     __neg__ = interp2app(W_ComplexObject.descr_neg),
     __pos__ = interp2app(W_ComplexObject.descr_pos),
@@ -618,12 +536,6 @@
     __rdiv__ = interp2app(W_ComplexObject.descr_rtruediv),
     __truediv__ = interp2app(W_ComplexObject.descr_truediv),
     __rtruediv__ = interp2app(W_ComplexObject.descr_rtruediv),
-    #__floordiv__ = interp2app(W_ComplexObject.descr_floordiv),
-    #__rfloordiv__ = interp2app(W_ComplexObject.descr_rfloordiv),
-    #__mod__ = interp2app(W_ComplexObject.descr_mod),
-    #__rmod__ = interp2app(W_ComplexObject.descr_rmod),
-    #__divmod__ = interp2app(W_ComplexObject.descr_divmod),
-    #__rdivmod__ = interp2app(W_ComplexObject.descr_rdivmod),
     __pow__ = interp2app(W_ComplexObject.descr_pow),
     __rpow__ = interp2app(W_ComplexObject.descr_rpow),
 
diff --git a/pypy/objspace/std/floatobject.py b/pypy/objspace/std/floatobject.py
--- a/pypy/objspace/std/floatobject.py
+++ b/pypy/objspace/std/floatobject.py
@@ -7,8 +7,9 @@
 from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault
 from pypy.interpreter.typedef import GetSetProperty
 from pypy.objspace.std import newformat
-from pypy.objspace.std.intobject import HASH_BITS, HASH_MODULUS
-from pypy.objspace.std.longobject import newlong_from_float
+from pypy.objspace.std.intobject import HASH_BITS, HASH_MODULUS, W_IntObject
+from pypy.objspace.std.longobject import (
+    W_AbstractLongObject, newlong_from_float)
 from rpython.rlib.rarithmetic import (
     LONG_BIT, intmask, ovfcheck_float_to_int, r_uint)
 from pypy.objspace.std.stdtypedef import StdTypeDef
@@ -26,6 +27,9 @@
 HASH_INF  = 314159
 HASH_NAN  = 0
 
+# Here 0.30103 is an upper bound for log10(2)
+NDIGITS_MAX = int((rfloat.DBL_MANT_DIG - rfloat.DBL_MIN_EXP) * 0.30103)
+NDIGITS_MIN = -int((rfloat.DBL_MAX_EXP + 1) * 0.30103)
 
 def float2string(x, code, precision):
     # we special-case explicitly inf and nan here
@@ -123,7 +127,7 @@
     def _compare(self, space, w_other):
         if isinstance(w_other, W_FloatObject):
             return space.newbool(op(self.floatval, w_other.floatval))
-        if space.isinstance_w(w_other, space.w_int):
+        if isinstance(w_other, W_IntObject):
             f1 = self.floatval
             i2 = space.int_w(w_other)
             f2 = float(i2)
@@ -132,7 +136,7 @@
             else:
                 res = op(f1, f2)
             return space.newbool(res)
-        if space.isinstance_w(w_other, space.w_long):
+        if isinstance(w_other, W_AbstractLongObject):
             return space.newbool(do_compare_bigint(self.floatval,
                                                    space.bigint_w(w_other)))
         return space.w_NotImplemented
@@ -385,34 +389,24 @@
         if isinstance(w_obj, W_FloatObject):
             return w_obj
         if space.isinstance_w(w_obj, space.w_int):
-            return W_FloatObject(float(space.int_w(w_obj)))
-        if space.isinstance_w(w_obj, space.w_long):
-            return W_FloatObject(space.float_w(w_obj))
+            return W_FloatObject(space.float_w(w_obj, allow_conversion=False))
+
+    #@staticmethod
+    # XXX: unwrap_spec index?
+    def descr___round__(self, space, w_ndigits=None):
+        return _round_float(space, self, w_ndigits)
 
     def descr_repr(self, space):
         return space.wrap(float2string(self.floatval, 'r', 0))
     descr_str = func_with_new_name(descr_repr, 'descr_str')
 
-    """
-    def descr_str(self, space):
-        return space.wrap(float2string(self.floatval, 'g', DTSF_STR_PRECISION))
-        """
-
     def descr_hash(self, space):
         return space.wrap(_hash_float(space, self.floatval))
 
     def descr_format(self, space, w_spec):
         return newformat.run_formatter(space, w_spec, "format_float", self)
 
-    """
-    def descr_coerce(self, space, w_other):
-        w_other = self._to_float(space, w_other)
-        if w_other is None:
-            return space.w_NotImplemented
-        return space.newtuple([self, w_other])
-        """
-
-    def descr_nonzero(self, space):
+    def descr_bool(self, space):
         return space.newbool(self.floatval != 0.0)
 
     def descr_float(self, space):
@@ -421,18 +415,6 @@
         a = self.floatval
         return W_FloatObject(a)
 
-    """
-    def descr_long(self, space):
-        try:
-            return W_LongObject.fromfloat(space, self.floatval)
-        except OverflowError:
-            raise oefmt(space.w_OverflowError,
-                        "cannot convert float infinity to integer")
-        except ValueError:
-            raise oefmt(space.w_ValueError,
-                        "cannot convert float NaN to integer")
-                        """
-
     def descr_trunc(self, space):
         whole = math.modf(self.floatval)[1]
         try:
@@ -666,16 +648,15 @@
 Convert a string or number to a floating point number, if possible.''',
     __new__ = interp2app(W_FloatObject.descr__new__),
     __getformat__ = interp2app(W_FloatObject.descr___getformat__, 
as_classmethod=True),
+    __round__ = interp2app(W_FloatObject.descr___round__),
     fromhex = interp2app(W_FloatObject.descr_fromhex, as_classmethod=True),
     __repr__ = interp2app(W_FloatObject.descr_repr),
     __str__ = interp2app(W_FloatObject.descr_str),
     __hash__ = interp2app(W_FloatObject.descr_hash),
     __format__ = interp2app(W_FloatObject.descr_format),
-    #__coerce__ = interp2app(W_FloatObject.descr_coerce),
-    __nonzero__ = interp2app(W_FloatObject.descr_nonzero),
+    __bool__ = interp2app(W_FloatObject.descr_bool),
     __int__ = interp2app(W_FloatObject.int),
     __float__ = interp2app(W_FloatObject.descr_float),
-    #__long__ = interp2app(W_FloatObject.descr_long),
     __trunc__ = interp2app(W_FloatObject.descr_trunc),
     __neg__ = interp2app(W_FloatObject.descr_neg),
     __pos__ = interp2app(W_FloatObject.descr_pos),
@@ -875,3 +856,38 @@
     if negate_result:
         z = -z
     return z
+
+
+def _round_float(space, w_float, w_ndigits=None):
+    # Algorithm copied directly from CPython
+    x = w_float.floatval
+
+    if w_ndigits is None:
+        # single-argument round: round to nearest integer
+        rounded = rfloat.round_away(x)
+        if math.fabs(x - rounded) == 0.5:
+            # halfway case: round to even
+            rounded = 2.0 * rfloat.round_away(x / 2.0)
+        return newlong_from_float(space, rounded)
+
+    # interpret 2nd argument as a Py_ssize_t; clip on overflow
+    ndigits = space.getindex_w(w_ndigits, None)
+
+    # nans and infinities round to themselves
+    if not rfloat.isfinite(x):
+        return space.wrap(x)
+
+    # Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
+    # always rounds to itself.  For ndigits < NDIGITS_MIN, x always
+    # rounds to +-0.0
+    if ndigits > NDIGITS_MAX:
+        return space.wrap(x)
+    elif ndigits < NDIGITS_MIN:
+        # return 0.0, but with sign of x
+        return space.wrap(0.0 * x)
+
+    # finite x, and ndigits is not unreasonably large
+    z = rfloat.round_double(x, ndigits, half_even=True)
+    if rfloat.isinf(z):
+        raise oefmt(space.w_OverflowError, "overflow occurred during round")
+    return space.wrap(z)
diff --git a/pypy/objspace/std/noneobject.py b/pypy/objspace/std/noneobject.py
--- a/pypy/objspace/std/noneobject.py
+++ b/pypy/objspace/std/noneobject.py
@@ -7,7 +7,7 @@
     def unwrap(w_self, space):
         return None
 
-    def descr_nonzero(self, space):
+    def descr_bool(self, space):
         return space.w_False
 
     def descr_repr(self, space):
@@ -17,7 +17,7 @@
 W_NoneObject.w_None = W_NoneObject()
 
 W_NoneObject.typedef = StdTypeDef("NoneType",
-    __nonzero__ = interp2app(W_NoneObject.descr_nonzero),
+    __bool__ = interp2app(W_NoneObject.descr_bool),
     __repr__ = interp2app(W_NoneObject.descr_repr),
 )
 W_NoneObject.typedef.acceptable_as_base_class = False
diff --git a/pypy/objspace/std/objectobject.py 
b/pypy/objspace/std/objectobject.py
--- a/pypy/objspace/std/objectobject.py
+++ b/pypy/objspace/std/objectobject.py
@@ -13,8 +13,8 @@
     raise TypeError(err % (typ.__name__, methods))
 
 def reduce_1(obj, proto):
-    import copy_reg
-    return copy_reg._reduce_ex(obj, proto)
+    import copyreg
+    return copyreg._reduce_ex(obj, proto)
 
 def reduce_2(obj):
     cls = obj.__class__
@@ -26,7 +26,7 @@
     else:
         args = getnewargs()
         if not isinstance(args, tuple):
-            raise TypeError, "__getnewargs__ should return a tuple"
+            raise TypeError("__getnewargs__ should return a tuple")
 
     try:
         getstate = obj.__getstate__
@@ -53,12 +53,12 @@
         listitems = None
 
     if isinstance(obj, dict):
-        dictitems = obj.iteritems()
+        dictitems = iter(obj.items())
     else:
         dictitems = None
 
-    import copy_reg
-    newobj = copy_reg.__newobj__
+    import copyreg
+    newobj = copyreg.__newobj__
 
     args2 = (cls,) + args
     return newobj, args2, state, listitems, dictitems
@@ -72,10 +72,10 @@
     except KeyError:
         pass
 
-    import copy_reg
-    slotnames = copy_reg._slotnames(cls)
+    import copyreg
+    slotnames = copyreg._slotnames(cls)
     if not isinstance(slotnames, list) and slotnames is not None:
-        raise TypeError, "copy_reg._slotnames didn't return a list or None"
+        raise TypeError("copyreg._slotnames didn't return a list or None")
     return slotnames
 ''', filename=__file__)
 
@@ -150,18 +150,18 @@
 
 def descr__repr__(space, w_obj):
     w_type = space.type(w_obj)
-    classname = w_type.name
+    classname = w_type.name.decode('utf-8')
     if w_type.is_heaptype():
         w_module = w_type.lookup("__module__")
         if w_module is not None:
             try:
-                modulename = space.str_w(w_module)
+                modulename = space.unicode_w(w_module)
             except OperationError, e:
                 if not e.match(space, space.w_TypeError):
                     raise
             else:
-                classname = '%s.%s' % (modulename, classname)
-    return w_obj.getrepr(space, '%s object' % (classname,))
+                classname = u'%s.%s' % (modulename, classname)
+    return w_obj.getrepr(space, u'%s object' % (classname,))
 
 
 def descr__str__(space, w_obj):
@@ -185,16 +185,13 @@
     w_st_reduce = space.wrap('__reduce__')
     w_reduce = space.findattr(w_obj, w_st_reduce)
     if w_reduce is not None:
-        w_cls = space.getattr(w_obj, space.wrap('__class__'))
-        w_cls_reduce_meth = space.getattr(w_cls, w_st_reduce)
-        w_cls_reduce = space.getattr(w_cls_reduce_meth, space.wrap('im_func'))
-        w_objtype = space.w_object
-        w_obj_dict = space.getattr(w_objtype, space.wrap('__dict__'))
-        w_obj_reduce = space.getitem(w_obj_dict, w_st_reduce)
+        # Check if __reduce__ has been overridden:
+        # "type(obj).__reduce__ is not object.__reduce__"
+        w_cls_reduce = space.getattr(space.type(w_obj), w_st_reduce)
+        w_obj_reduce = space.getattr(space.w_object, w_st_reduce)
         override = not space.is_w(w_cls_reduce, w_obj_reduce)
-        # print 'OVR', override, w_cls_reduce, w_obj_reduce
         if override:
-            return space.call(w_reduce, space.newtuple([]))
+            return space.call_function(w_reduce)
     return descr__reduce__(space, w_obj, proto)
 
 def descr___format__(space, w_obj, w_format_spec):
@@ -210,6 +207,19 @@
         space.warn(space.wrap(msg), space.w_PendingDeprecationWarning)
     return space.format(w_as_str, w_format_spec)
 
+def descr__eq__(space, w_self, w_other):
+    if space.is_w(w_self, w_other):
+        return space.w_True
+    # Return NotImplemented instead of False, so if two objects are
+    # compared, both get a chance at the comparison (issue #1393)
+    return space.w_NotImplemented
+
+def descr__ne__(space, w_self, w_other):
+    return space.not_(space.eq(w_self, w_other))
+
+def descr_richcompare(space, w_self, w_other):
+    return space.w_NotImplemented
+
 
 W_ObjectObject.typedef = StdTypeDef("object",
     __doc__ = "The most base type",
@@ -229,4 +239,11 @@
     __reduce__ = interp2app(descr__reduce__),
     __reduce_ex__ = interp2app(descr__reduce_ex__),
     __format__ = interp2app(descr___format__),
+
+    __eq__ = interp2app(descr__eq__),
+    __ne__ = interp2app(descr__ne__),
+    __le__ = interp2app(descr_richcompare),
+    __lt__ = interp2app(descr_richcompare),
+    __ge__ = interp2app(descr_richcompare),
+    __gt__ = interp2app(descr_richcompare),
 )
diff --git a/pypy/objspace/std/typeobject.py b/pypy/objspace/std/typeobject.py
--- a/pypy/objspace/std/typeobject.py
+++ b/pypy/objspace/std/typeobject.py
@@ -605,11 +605,6 @@
         raise oefmt(space.w_AttributeError,
                     "type object '%N' has no attribute %R", self, w_name)
 
-    """
-    def descr_eq(self, space, w_other):
-        return space.is_(self, w_other)
-        """
-
     def descr_ne(self, space, w_other):
         return space.newbool(not space.is_w(self, w_other))
 
@@ -881,7 +876,6 @@
     __call__ = gateway.interp2app(W_TypeObject.descr_call),
     __repr__ = gateway.interp2app(W_TypeObject.descr_repr),
     __getattribute__ = gateway.interp2app(W_TypeObject.descr_getattribute),
-    #__eq__ = gateway.interp2app(W_TypeObject.descr_eq),
     __ne__ = gateway.interp2app(W_TypeObject.descr_ne),
     __prepare__ = gateway.interp2app(descr___prepare__, as_classmethod=True),
 )
_______________________________________________
pypy-commit mailing list
pypy-commit@python.org
https://mail.python.org/mailman/listinfo/pypy-commit

Reply via email to