From python-3000-checkins at python.org Sat Sep 1 08:37:02 2007 From: python-3000-checkins at python.org (martin.v.loewis) Date: Sat, 1 Sep 2007 08:37:02 +0200 (CEST) Subject: [Python-3000-checkins] r57861 - python/branches/py3k/Tools/msi/msi.py Message-ID: <20070901063702.A98791E400B@bag.python.org> Author: martin.v.loewis Date: Sat Sep 1 08:36:49 2007 New Revision: 57861 Modified: python/branches/py3k/Tools/msi/msi.py Log: Bug #1737210: Change Manufacturer of Windows installer to PSF. Modified: python/branches/py3k/Tools/msi/msi.py ============================================================================== --- python/branches/py3k/Tools/msi/msi.py (original) +++ python/branches/py3k/Tools/msi/msi.py Sat Sep 1 08:36:49 2007 @@ -195,7 +195,7 @@ schema, ProductName="Python "+full_current_version, ProductCode=product_code, ProductVersion=current_version, - Manufacturer=u"Martin v. L\xf6wis") + Manufacturer=u"Python Software Foundation") # The default sequencing of the RemoveExistingProducts action causes # removal of files that got just installed. Place it after # InstallInitialize, so we first uninstall everything, but still roll From python-3000-checkins at python.org Sat Sep 1 09:27:37 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 1 Sep 2007 09:27:37 +0200 (CEST) Subject: [Python-3000-checkins] r57862 - python/branches/py3k/Misc/python-config.in Message-ID: <20070901072737.ECE841E400D@bag.python.org> Author: georg.brandl Date: Sat Sep 1 09:27:37 2007 New Revision: 57862 Modified: python/branches/py3k/Misc/python-config.in Log: Bug #1074: make python-config with Py3k. Modified: python/branches/py3k/Misc/python-config.in ============================================================================== --- python/branches/py3k/Misc/python-config.in (original) +++ python/branches/py3k/Misc/python-config.in Sat Sep 1 09:27:37 2007 @@ -5,12 +5,12 @@ import getopt from distutils import sysconfig -valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags', +valid_opts = ['prefix', 'exec-prefix', 'includes', 'libs', 'cflags', 'ldflags', 'help'] def exit_with_usage(code=1): - print >>sys.stderr, "Usage: %s [%s]" % (sys.argv[0], - '|'.join('--'+opt for opt in valid_opts)) + print("Usage: {0} [{1}]".format( + sys.argv[0], '|'.join('--'+opt for opt in valid_opts)), file=sys.stderr) sys.exit(code) try: @@ -30,17 +30,17 @@ exit_with_usage(0) elif opt == '--prefix': - print sysconfig.PREFIX + print(sysconfig.PREFIX) elif opt == '--exec-prefix': - print sysconfig.EXEC_PREFIX + print(sysconfig.EXEC_PREFIX) elif opt in ('--includes', '--cflags'): flags = ['-I' + sysconfig.get_python_inc(), '-I' + sysconfig.get_python_inc(plat_specific=True)] if opt == '--cflags': flags.extend(getvar('CFLAGS').split()) - print ' '.join(flags) + print(' '.join(flags)) elif opt in ('--libs', '--ldflags'): libs = getvar('LIBS').split() + getvar('SYSLIBS').split() @@ -49,5 +49,5 @@ # shared library in prefix/lib/. if opt == '--ldflags' and not getvar('Py_ENABLE_SHARED'): libs.insert(0, '-L' + getvar('LIBPL')) - print ' '.join(libs) + print(' '.join(libs)) From python-3000-checkins at python.org Sat Sep 1 09:34:28 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 1 Sep 2007 09:34:28 +0200 (CEST) Subject: [Python-3000-checkins] r57863 - python/branches/py3k/Doc/library/aepack.rst Message-ID: <20070901073428.0AE451E4006@bag.python.org> Author: georg.brandl Date: Sat Sep 1 09:34:27 2007 New Revision: 57863 Modified: python/branches/py3k/Doc/library/aepack.rst Log: Fix RST link. Modified: python/branches/py3k/Doc/library/aepack.rst ============================================================================== --- python/branches/py3k/Doc/library/aepack.rst (original) +++ python/branches/py3k/Doc/library/aepack.rst Sat Sep 1 09:34:27 2007 @@ -87,6 +87,6 @@ Module :mod:`aetypes` Python definitions of codes for Apple Event descriptor types. - ` Inside Macintosh: Interapplication Communication `_ + `Inside Macintosh: Interapplication Communication `_ Information about inter-process communications on the Macintosh. From python-3000-checkins at python.org Sat Sep 1 12:56:20 2007 From: python-3000-checkins at python.org (eric.smith) Date: Sat, 1 Sep 2007 12:56:20 +0200 (CEST) Subject: [Python-3000-checkins] r57866 - in python/branches/py3k: Lib/test/test_builtin.py Lib/test/test_unicode.py Objects/stringlib/formatter.h Objects/stringlib/stringdefs.h Objects/stringlib/unicodedefs.h Python/bltinmodule.c Message-ID: <20070901105620.A823F1E4010@bag.python.org> Author: eric.smith Date: Sat Sep 1 12:56:01 2007 New Revision: 57866 Modified: python/branches/py3k/Lib/test/test_builtin.py python/branches/py3k/Lib/test/test_unicode.py python/branches/py3k/Objects/stringlib/formatter.h python/branches/py3k/Objects/stringlib/stringdefs.h python/branches/py3k/Objects/stringlib/unicodedefs.h python/branches/py3k/Python/bltinmodule.c Log: Changed to use 'U' argument to PyArg_ParseTuple, instead of manually checking for unicode objects. Modified: python/branches/py3k/Lib/test/test_builtin.py ============================================================================== --- python/branches/py3k/Lib/test/test_builtin.py (original) +++ python/branches/py3k/Lib/test/test_builtin.py Sat Sep 1 12:56:01 2007 @@ -525,10 +525,15 @@ return str(self.x) + format_spec # class that returns a bad type from __format__ - class H: + class B: def __format__(self, format_spec): return 1.0 + # class that is derived from string, used + # as a format spec + class C(str): + pass + self.assertEqual(format(3, ''), '3') self.assertEqual(format(A(3), 'spec'), '3spec') @@ -550,7 +555,10 @@ empty_format_spec(None) # TypeError because self.__format__ returns the wrong type - self.assertRaises(TypeError, format, H(), "") + self.assertRaises(TypeError, format, B(), "") + + # make sure we can take a subclass of str as a format spec + self.assertEqual(format(0, C('10')), ' 0') def test_getattr(self): import sys Modified: python/branches/py3k/Lib/test/test_unicode.py ============================================================================== --- python/branches/py3k/Lib/test/test_unicode.py (original) +++ python/branches/py3k/Lib/test/test_unicode.py Sat Sep 1 12:56:01 2007 @@ -581,9 +581,6 @@ self.assertRaises(ValueError, format, "", "-") self.assertRaises(ValueError, "{0:=s}".format, '') - # check that __format__ returns a string - #self.assertRaises(TypeError, "{0}".format, H()) - def test_formatting(self): string_tests.MixinStrUnicodeUserStringTest.test_formatting(self) # Testing Unicode formatting strings... Modified: python/branches/py3k/Objects/stringlib/formatter.h ============================================================================== --- python/branches/py3k/Objects/stringlib/formatter.h (original) +++ python/branches/py3k/Objects/stringlib/formatter.h Sat Sep 1 12:56:01 2007 @@ -768,12 +768,8 @@ PyObject *result = NULL; InternalFormatSpec format; - if (!PyArg_ParseTuple(args, "O:__format__", &format_spec)) + if (!PyArg_ParseTuple(args, STRINGLIB_PARSE_CODE ":__format__", &format_spec)) goto done; - if (!STRINGLIB_CHECK(format_spec)) { - PyErr_SetString(PyExc_TypeError, STRINGLIB_TYPE_NAME " object required"); - goto done; - } /* check for the special case of zero length format spec, make it equivalent to str(value) */ @@ -843,12 +839,8 @@ PyObject *tmp = NULL; InternalFormatSpec format; - if (!PyArg_ParseTuple(args, "O:__format__", &format_spec)) - goto done; - if (!STRINGLIB_CHECK(format_spec)) { - PyErr_SetString(PyExc_TypeError, STRINGLIB_TYPE_NAME " object required"); + if (!PyArg_ParseTuple(args, STRINGLIB_PARSE_CODE ":__format__", &format_spec)) goto done; - } /* check for the special case of zero length format spec, make it equivalent to str(value) */ @@ -917,12 +909,8 @@ PyObject *tmp = NULL; InternalFormatSpec format; - if (!PyArg_ParseTuple(args, "O:__format__", &format_spec)) - goto done; - if (!STRINGLIB_CHECK(format_spec)) { - PyErr_SetString(PyExc_TypeError, STRINGLIB_TYPE_NAME " object required"); + if (!PyArg_ParseTuple(args, STRINGLIB_PARSE_CODE ":__format__", &format_spec)) goto done; - } /* check for the special case of zero length format spec, make it equivalent to str(value) */ Modified: python/branches/py3k/Objects/stringlib/stringdefs.h ============================================================================== --- python/branches/py3k/Objects/stringlib/stringdefs.h (original) +++ python/branches/py3k/Objects/stringlib/stringdefs.h Sat Sep 1 12:56:01 2007 @@ -8,6 +8,7 @@ #define STRINGLIB_CHAR char #define STRINGLIB_TYPE_NAME "string" +#define STRINGLIB_PARSE_CODE "S" #define STRINGLIB_EMPTY string_empty #define STRINGLIB_ISDECIMAL(x) ((x >= '0') && (x <= '9')) #define STRINGLIB_TODECIMAL(x) (STRINGLIB_ISDECIMAL(x) ? (x - '0') : -1) Modified: python/branches/py3k/Objects/stringlib/unicodedefs.h ============================================================================== --- python/branches/py3k/Objects/stringlib/unicodedefs.h (original) +++ python/branches/py3k/Objects/stringlib/unicodedefs.h Sat Sep 1 12:56:01 2007 @@ -8,6 +8,7 @@ #define STRINGLIB_CHAR Py_UNICODE #define STRINGLIB_TYPE_NAME "unicode" +#define STRINGLIB_PARSE_CODE "U" #define STRINGLIB_EMPTY unicode_empty #define STRINGLIB_ISDECIMAL Py_UNICODE_ISDECIMAL #define STRINGLIB_TODECIMAL Py_UNICODE_TODECIMAL Modified: python/branches/py3k/Python/bltinmodule.c ============================================================================== --- python/branches/py3k/Python/bltinmodule.c (original) +++ python/branches/py3k/Python/bltinmodule.c Sat Sep 1 12:56:01 2007 @@ -293,7 +293,7 @@ goto done; } - if (!PyArg_ParseTuple(args, "O|O:format", &value, &spec)) + if (!PyArg_ParseTuple(args, "O|U:format", &value, &spec)) goto done; /* initialize the default value */ From python-3000-checkins at python.org Sat Sep 1 14:09:38 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 1 Sep 2007 14:09:38 +0200 (CEST) Subject: [Python-3000-checkins] r57867 - python/branches/py3k/Doc/library/stdtypes.rst Message-ID: <20070901120938.D87541E4006@bag.python.org> Author: georg.brandl Date: Sat Sep 1 14:08:51 2007 New Revision: 57867 Modified: python/branches/py3k/Doc/library/stdtypes.rst Log: Add a warning text about mixing bytes and strings. Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Sat Sep 1 14:08:51 2007 @@ -515,6 +515,12 @@ object *b*, ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes object of length 1. + Also, while in previous Python versions, byte strings and Unicode strings + could be exchanged for each other rather freely (barring encoding issues), + strings and bytes are completely separate concepts. There's no implicit + en-/decoding if you pass and object of the wrong type or try to e.g. compare + a string with a bytes object. + Lists are constructed with square brackets, separating items with commas: ``[a, b, c]``. Tuples are constructed by the comma operator (not within square brackets), with or without enclosing parentheses, but an empty tuple must have From python-3000-checkins at python.org Sat Sep 1 14:33:42 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 1 Sep 2007 14:33:42 +0200 (CEST) Subject: [Python-3000-checkins] r57868 - python/branches/py3k/Doc/c-api/abstract.rst python/branches/py3k/Doc/c-api/concrete.rst python/branches/py3k/Doc/c-api/exceptions.rst python/branches/py3k/Doc/c-api/init.rst python/branches/py3k/Doc/c-api/newtypes.rst python/branches/py3k/Doc/c-api/refcounting.rst python/branches/py3k/Doc/c-api/utilities.rst Message-ID: <20070901123342.AE78F1E4006@bag.python.org> Author: georg.brandl Date: Sat Sep 1 14:33:24 2007 New Revision: 57868 Modified: python/branches/py3k/Doc/c-api/abstract.rst python/branches/py3k/Doc/c-api/concrete.rst python/branches/py3k/Doc/c-api/exceptions.rst python/branches/py3k/Doc/c-api/init.rst python/branches/py3k/Doc/c-api/newtypes.rst python/branches/py3k/Doc/c-api/refcounting.rst python/branches/py3k/Doc/c-api/utilities.rst Log: Remove versionadded and versionchanged directives, fold information into text where necessary. Modified: python/branches/py3k/Doc/c-api/abstract.rst ============================================================================== --- python/branches/py3k/Doc/c-api/abstract.rst (original) +++ python/branches/py3k/Doc/c-api/abstract.rst Sat Sep 1 14:33:24 2007 @@ -170,10 +170,6 @@ of the value of that attribute with *cls* will be used to determine the result of this function. - .. versionadded:: 2.1 - - .. versionchanged:: 2.2 - Support for a tuple as the second argument added. Subclass determination is done in a fairly straightforward way, but includes a wrinkle that implementors of extensions to the class system may want to be aware @@ -196,11 +192,6 @@ ``0``. If either *derived* or *cls* is not an actual class object (or tuple), this function uses the generic algorithm described above. - .. versionadded:: 2.1 - - .. versionchanged:: 2.3 - Older versions of Python did not support a tuple as the second argument. - .. cfunction:: int PyCallable_Check(PyObject *o) @@ -217,8 +208,6 @@ success, or *NULL* on failure. This is the equivalent of the Python expression ``callable_object(*args, **kw)``. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyObject_CallObject(PyObject *callable_object, PyObject *args) @@ -257,8 +246,6 @@ of parameters followed by *NULL*. Returns the result of the call on success, or *NULL* on failure. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL) @@ -268,8 +255,6 @@ of parameters followed by *NULL*. Returns the result of the call on success, or *NULL* on failure. - .. versionadded:: 2.2 - .. cfunction:: long PyObject_Hash(PyObject *o) @@ -311,8 +296,6 @@ Return true if the object *o* is of type *type* or a subtype of *type*. Both parameters must be non-*NULL*. - .. versionadded:: 2.2 - .. cfunction:: Py_ssize_t PyObject_Length(PyObject *o) Py_ssize_t PyObject_Size(PyObject *o) @@ -408,8 +391,6 @@ Return the floor of *o1* divided by *o2*, or *NULL* on failure. This is equivalent to the "classic" division of integers. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyNumber_TrueDivide(PyObject *o1, PyObject *o2) @@ -419,8 +400,6 @@ numbers in base two. This function can return a floating point value when passed two integers. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyNumber_Remainder(PyObject *o1, PyObject *o2) @@ -536,8 +515,6 @@ The operation is done *in-place* when *o1* supports it. This is the equivalent of the Python statement ``o1 //= o2``. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2) @@ -547,8 +524,6 @@ numbers in base two. This function can return a floating point value when passed two integers. The operation is done *in-place* when *o1* supports it. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2) @@ -633,8 +608,6 @@ Returns the *o* converted to a Python int or long on success or *NULL* with a TypeError exception raised on failure. - .. versionadded:: 2.5 - .. cfunction:: Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc) @@ -646,16 +619,12 @@ exception is cleared and the value is clipped to *PY_SSIZE_T_MIN* for a negative integer or *PY_SSIZE_T_MAX* for a positive integer. - .. versionadded:: 2.5 - .. cfunction:: int PyIndex_Check(PyObject *o) Returns True if *o* is an index integer (has the nb_index slot of the tp_as_number structure filled in). - .. versionadded:: 2.5 - .. _sequence: @@ -801,8 +770,6 @@ Return the underlying array of PyObject pointers. Assumes that *o* was returned by :cfunc:`PySequence_Fast` and *o* is not *NULL*. - .. versionadded:: 2.4 - .. cfunction:: PyObject* PySequence_ITEM(PyObject *o, Py_ssize_t i) @@ -811,8 +778,6 @@ :cfunc:`PySequence_Check(o)` is true and without adjustment for negative indices. - .. versionadded:: 2.3 - .. cfunction:: Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o) @@ -906,11 +871,8 @@ Iterator Protocol ================= -.. versionadded:: 2.2 - There are only a couple of functions specifically for working with iterators. - .. cfunction:: int PyIter_Check(PyObject *o) Return true if the object *o* supports the iterator protocol. @@ -965,8 +927,6 @@ *buffer_len* to the buffer length. Returns ``-1`` and sets a :exc:`TypeError` on error. - .. versionadded:: 1.6 - .. cfunction:: int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len) @@ -975,16 +935,12 @@ success, returns ``0``, sets *buffer* to the memory location and *buffer_len* to the buffer length. Returns ``-1`` and sets a :exc:`TypeError` on error. - .. versionadded:: 1.6 - .. cfunction:: int PyObject_CheckReadBuffer(PyObject *o) Returns ``1`` if *o* supports the single-segment readable buffer interface. Otherwise returns ``0``. - .. versionadded:: 2.2 - .. cfunction:: int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len) @@ -993,5 +949,3 @@ ``0``, sets *buffer* to the memory location and *buffer_len* to the buffer length. Returns ``-1`` and sets a :exc:`TypeError` on error. - .. versionadded:: 1.6 - Modified: python/branches/py3k/Doc/c-api/concrete.rst ============================================================================== --- python/branches/py3k/Doc/c-api/concrete.rst (original) +++ python/branches/py3k/Doc/c-api/concrete.rst Sat Sep 1 14:33:24 2007 @@ -62,8 +62,6 @@ Return true if the object *o* is a type object, but not a subtype of the standard type object. Return false in all other cases. - .. versionadded:: 2.2 - .. cfunction:: int PyType_HasFeature(PyObject *o, int feature) @@ -76,24 +74,20 @@ Return true if the type object includes support for the cycle detector; this tests the type flag :const:`Py_TPFLAGS_HAVE_GC`. - .. versionadded:: 2.0 - .. cfunction:: int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b) Return true if *a* is a subtype of *b*. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems) - .. versionadded:: 2.2 + XXX: Document. .. cfunction:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds) - .. versionadded:: 2.2 + XXX: Document. .. cfunction:: int PyType_Ready(PyTypeObject *type) @@ -103,8 +97,6 @@ from a type's base class. Return ``0`` on success, or return ``-1`` and sets an exception on error. - .. versionadded:: 2.2 - .. _noneobject: @@ -128,9 +120,8 @@ .. cmacro:: Py_RETURN_NONE - Properly handle returning :cdata:`Py_None` from within a C function. - - .. versionadded:: 2.4 + Properly handle returning :cdata:`Py_None` from within a C function (that is, + increment the reference count of None and return it.) .. _numericobjects: @@ -167,17 +158,12 @@ Return true if *o* is of type :cdata:`PyInt_Type` or a subtype of :cdata:`PyInt_Type`. - .. versionchanged:: 2.2 - Allowed subtypes to be accepted. - .. cfunction:: int PyInt_CheckExact(PyObject *o) Return true if *o* is of type :cdata:`PyInt_Type`, but not a subtype of :cdata:`PyInt_Type`. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyInt_FromString(char *str, char **pend, int base) @@ -212,8 +198,6 @@ Create a new integer object with a value of *ival*. If the value exceeds ``LONG_MAX``, a long integer object is returned. - .. versionadded:: 2.5 - .. cfunction:: long PyInt_AsLong(PyObject *io) @@ -234,8 +218,6 @@ :ctype:`PyLongObject`, if it is not already one, and then return its value as unsigned long. This function does not check for overflow. - .. versionadded:: 2.3 - .. cfunction:: unsigned PY_LONG_LONG PyInt_AsUnsignedLongLongMask(PyObject *io) @@ -243,8 +225,6 @@ :ctype:`PyLongObject`, if it is not already one, and then return its value as unsigned long long, without checking for overflow. - .. versionadded:: 2.3 - .. cfunction:: Py_ssize_t PyInt_AsSsize_t(PyObject *io) @@ -252,8 +232,6 @@ :ctype:`PyLongObject`, if it is not already one, and then return its value as :ctype:`Py_ssize_t`. - .. versionadded:: 2.5 - .. cfunction:: long PyInt_GetMax() @@ -278,8 +256,6 @@ Return true if *o* is of type :cdata:`PyBool_Type`. - .. versionadded:: 2.3 - .. cvar:: PyObject* Py_False @@ -298,24 +274,18 @@ Return :const:`Py_False` from a function, properly incrementing its reference count. - .. versionadded:: 2.4 - .. cmacro:: Py_RETURN_TRUE Return :const:`Py_True` from a function, properly incrementing its reference count. - .. versionadded:: 2.4 - .. cfunction:: PyObject* PyBool_FromLong(long v) Return a new reference to :const:`Py_True` or :const:`Py_False` depending on the truth value of *v*. - .. versionadded:: 2.3 - .. _longobjects: @@ -343,17 +313,12 @@ Return true if its argument is a :ctype:`PyLongObject` or a subtype of :ctype:`PyLongObject`. - .. versionchanged:: 2.2 - Allowed subtypes to be accepted. - .. cfunction:: int PyLong_CheckExact(PyObject *p) Return true if its argument is a :ctype:`PyLongObject`, but not a subtype of :ctype:`PyLongObject`. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyLong_FromLong(long v) @@ -405,18 +370,12 @@ radix must be in the range [2, 36]; if it is out of range, :exc:`ValueError` will be raised. - .. versionadded:: 1.6 - .. cfunction:: PyObject* PyLong_FromVoidPtr(void *p) Create a Python integer or long integer from the pointer *p*. The pointer value can be retrieved from the resulting value using :cfunc:`PyLong_AsVoidPtr`. - - .. versionadded:: 1.5.2 - - .. versionchanged:: 2.5 - If the integer is larger than LONG_MAX, a positive long integer is returned. + If the integer is larger than LONG_MAX, a positive long integer is returned. .. cfunction:: long PyLong_AsLong(PyObject *pylong) @@ -445,8 +404,6 @@ Return a C :ctype:`long long` from a Python long integer. If *pylong* cannot be represented as a :ctype:`long long`, an :exc:`OverflowError` will be raised. - .. versionadded:: 2.2 - .. cfunction:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *pylong) @@ -455,24 +412,18 @@ will be raised if the value is positive, or a :exc:`TypeError` will be raised if the value is negative. - .. versionadded:: 2.2 - .. cfunction:: unsigned long PyLong_AsUnsignedLongMask(PyObject *io) Return a C :ctype:`unsigned long` from a Python long integer, without checking for overflow. - .. versionadded:: 2.3 - .. cfunction:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(PyObject *io) Return a C :ctype:`unsigned long long` from a Python long integer, without checking for overflow. - .. versionadded:: 2.3 - .. cfunction:: double PyLong_AsDouble(PyObject *pylong) @@ -488,10 +439,7 @@ is only assured to produce a usable :ctype:`void` pointer for values created with :cfunc:`PyLong_FromVoidPtr`. - .. versionadded:: 1.5.2 - - .. versionchanged:: 2.5 - For values outside 0..LONG_MAX, both signed and unsigned integers are acccepted. + For values outside 0..LONG_MAX, both signed and unsigned integers are acccepted. .. _floatobjects: @@ -520,17 +468,12 @@ Return true if its argument is a :ctype:`PyFloatObject` or a subtype of :ctype:`PyFloatObject`. - .. versionchanged:: 2.2 - Allowed subtypes to be accepted. - .. cfunction:: int PyFloat_CheckExact(PyObject *p) Return true if its argument is a :ctype:`PyFloatObject`, but not a subtype of :ctype:`PyFloatObject`. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyFloat_FromString(PyObject *str) @@ -646,17 +589,12 @@ Return true if its argument is a :ctype:`PyComplexObject` or a subtype of :ctype:`PyComplexObject`. - .. versionchanged:: 2.2 - Allowed subtypes to be accepted. - .. cfunction:: int PyComplex_CheckExact(PyObject *p) Return true if its argument is a :ctype:`PyComplexObject`, but not a subtype of :ctype:`PyComplexObject`. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyComplex_FromCComplex(Py_complex v) @@ -682,10 +620,9 @@ Return the :ctype:`Py_complex` value of the complex number *op*. - .. versionchanged:: 2.6 - If *op* is not a Python complex number object but has a :meth:`__complex__` - method, this method will first be called to convert *op* to a Python complex - number object. + If *op* is not a Python complex number object but has a :meth:`__complex__` + method, this method will first be called to convert *op* to a Python complex + number object. .. _sequenceobjects: @@ -729,17 +666,12 @@ Return true if the object *o* is a string object or an instance of a subtype of the string type. - .. versionchanged:: 2.2 - Allowed subtypes to be accepted. - .. cfunction:: int PyString_CheckExact(PyObject *o) Return true if the object *o* is a string object, but not an instance of a subtype of the string type. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyString_FromString(const char *v) @@ -763,9 +695,9 @@ must correspond exactly to the format characters in the *format* string. The following format characters are allowed: - .. % This should be exactly the same as the table in PyErr_Format. + .. % XXX: This should be exactly the same as the table in PyErr_Format. .. % One should just refer to the other. - .. % The descriptions for %zd and %zu are wrong, but the truth is complicated + .. % XXX: The descriptions for %zd and %zu are wrong, but the truth is complicated .. % because not all compilers support the %z width modifier -- we fake it .. % when necessary via interpolating PY_FORMAT_SIZE_T. .. % %u, %lu, %zu should have "new in Python 2.5" blurbs. @@ -1011,17 +943,12 @@ Return true if the object *o* is a Unicode object or an instance of a Unicode subtype. - .. versionchanged:: 2.2 - Allowed subtypes to be accepted. - .. cfunction:: int PyUnicode_CheckExact(PyObject *o) Return true if the object *o* is a Unicode object, but not an instance of a subtype. - .. versionadded:: 2.2 - .. cfunction:: Py_ssize_t PyUnicode_GET_SIZE(PyObject *o) @@ -1162,16 +1089,12 @@ *NULL*, the return value might be a shared object. Therefore, modification of the resulting Unicode object is only allowed when *u* is *NULL*. - .. versionadded:: 3.0 - .. cfunction:: PyObject *PyUnicode_FromString(const char *u) Create a Unicode object from an UTF-8 encoded null-terminated char buffer *u*. - .. versionadded:: 3.0 - .. cfunction:: PyObject* PyUnicode_FromFormat(const char *format, ...) @@ -1247,16 +1170,12 @@ An unrecognized format character causes all the rest of the format string to be copied as-is to the result string, and any extra arguments discarded. - .. versionadded:: 3.0 - .. cfunction:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs) Identical to :func:`PyUnicode_FromFormat` except that it takes exactly two arguments. - .. versionadded:: 3.0 - .. cfunction:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode) @@ -1390,8 +1309,6 @@ treated as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in *consumed*. - .. versionadded:: 2.4 - .. cfunction:: PyObject* PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors) @@ -1434,8 +1351,6 @@ Return *NULL* if an exception was raised by the codec. - .. versionadded:: 2.6 - .. cfunction:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed) @@ -1445,8 +1360,6 @@ by four) as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in *consumed*. - .. versionadded:: 2.6 - .. cfunction:: PyObject* PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) @@ -1466,8 +1379,6 @@ Return *NULL* if an exception was raised by the codec. - .. versionadded:: 2.6 - .. cfunction:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode) @@ -1475,8 +1386,6 @@ string always starts with a BOM mark. Error handling is "strict". Return *NULL* if an exception was raised by the codec. - .. versionadded:: 2.6 - These are the UTF-16 codec APIs: @@ -1514,8 +1423,6 @@ split surrogate pair) as an error. Those bytes will not be decoded and the number of bytes that have been decoded will be stored in *consumed*. - .. versionadded:: 2.4 - .. cfunction:: PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder) @@ -1674,9 +1581,6 @@ Byte values greater that the length of the string and U+FFFE "characters" are treated as "undefined mapping". - .. versionchanged:: 2.4 - Allowed unicode string as mapping argument. - .. cfunction:: PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors) @@ -1728,8 +1632,6 @@ trailing lead byte and the number of bytes that have been decoded will be stored in *consumed*. - .. versionadded:: 2.5 - .. cfunction:: PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors) @@ -2032,17 +1934,12 @@ Return true if *p* is a tuple object or an instance of a subtype of the tuple type. - .. versionchanged:: 2.2 - Allowed subtypes to be accepted. - .. cfunction:: int PyTuple_CheckExact(PyObject *p) Return true if *p* is a tuple object, but not an instance of a subtype of the tuple type. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyTuple_New(Py_ssize_t len) @@ -2055,8 +1952,6 @@ are initialized to the subsequent *n* C arguments pointing to Python objects. ``PyTuple_Pack(2, a, b)`` is equivalent to ``Py_BuildValue("(OO)", a, b)``. - .. versionadded:: 2.4 - .. cfunction:: int PyTuple_Size(PyObject *p) @@ -2119,9 +2014,6 @@ ``*p`` is destroyed. On failure, returns ``-1`` and sets ``*p`` to *NULL*, and raises :exc:`MemoryError` or :exc:`SystemError`. - .. versionchanged:: 2.2 - Removed unused third parameter, *last_is_sticky*. - .. _listobjects: @@ -2149,17 +2041,12 @@ Return true if *p* is a list object or an instance of a subtype of the list type. - .. versionchanged:: 2.2 - Allowed subtypes to be accepted. - .. cfunction:: int PyList_CheckExact(PyObject *p) Return true if *p* is a list object, but not an instance of a subtype of the list type. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyList_New(Py_ssize_t len) @@ -2306,17 +2193,12 @@ Return true if *p* is a dict object or an instance of a subtype of the dict type. - .. versionchanged:: 2.2 - Allowed subtypes to be accepted. - .. cfunction:: int PyDict_CheckExact(PyObject *p) Return true if *p* is a dict object, but not an instance of a subtype of the dict type. - .. versionadded:: 2.4 - .. cfunction:: PyObject* PyDict_New() @@ -2329,8 +2211,6 @@ normally used to create a proxy to prevent modification of the dictionary for non-dynamic class types. - .. versionadded:: 2.2 - .. cfunction:: void PyDict_Clear(PyObject *p) @@ -2343,15 +2223,11 @@ return ``1``, otherwise return ``0``. On error, return ``-1``. This is equivalent to the Python expression ``key in p``. - .. versionadded:: 2.4 - .. cfunction:: PyObject* PyDict_Copy(PyObject *p) Return a new dictionary that contains the same key-value pairs as *p*. - .. versionadded:: 1.6 - .. cfunction:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val) @@ -2471,16 +2347,12 @@ if there is not a matching key in *a*. Return ``0`` on success or ``-1`` if an exception was raised. - .. versionadded:: 2.2 - .. cfunction:: int PyDict_Update(PyObject *a, PyObject *b) This is the same as ``PyDict_Merge(a, b, 1)`` in C, or ``a.update(b)`` in Python. Return ``0`` on success or ``-1`` if an exception was raised. - .. versionadded:: 2.2 - .. cfunction:: int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override) @@ -2495,8 +2367,6 @@ if override or key not in a: a[key] = value - .. versionadded:: 2.2 - .. _otherobjects: @@ -2533,17 +2403,12 @@ Return true if its argument is a :ctype:`PyFileObject` or a subtype of :ctype:`PyFileObject`. - .. versionchanged:: 2.2 - Allowed subtypes to be accepted. - .. cfunction:: int PyFile_CheckExact(PyObject *p) Return true if its argument is a :ctype:`PyFileObject`, but not a subtype of :ctype:`PyFileObject`. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyFile_FromString(char *filename, char *mode) @@ -2598,8 +2463,6 @@ Set the file's encoding for Unicode output to *enc*. Return 1 on success and 0 on failure. - .. versionadded:: 2.3 - .. cfunction:: int PyFile_SoftSpace(PyObject *p, int newflag) @@ -2801,17 +2664,12 @@ Return true if *p* is a module object, or a subtype of a module object. - .. versionchanged:: 2.2 - Allowed subtypes to be accepted. - .. cfunction:: int PyModule_CheckExact(PyObject *p) Return true if *p* is a module object, but not a subtype of :cdata:`PyModule_Type`. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyModule_New(const char *name) @@ -2863,8 +2721,6 @@ be used from the module's initialization function. This steals a reference to *value*. Return ``-1`` on error, ``0`` on success. - .. versionadded:: 2.0 - .. cfunction:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value) @@ -2872,8 +2728,6 @@ used from the module's initialization function. Return ``-1`` on error, ``0`` on success. - .. versionadded:: 2.0 - .. cfunction:: int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value) @@ -2881,8 +2735,6 @@ used from the module's initialization function. The string *value* must be null-terminated. Return ``-1`` on error, ``0`` on success. - .. versionadded:: 2.0 - .. _iterator-objects: @@ -2902,15 +2754,11 @@ one-argument form of the :func:`iter` built-in function for built-in sequence types. - .. versionadded:: 2.2 - .. cfunction:: int PySeqIter_Check(op) Return true if the type of *op* is :cdata:`PySeqIter_Type`. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PySeqIter_New(PyObject *seq) @@ -2918,23 +2766,17 @@ iteration ends when the sequence raises :exc:`IndexError` for the subscripting operation. - .. versionadded:: 2.2 - .. cvar:: PyTypeObject PyCallIter_Type Type object for iterator objects returned by :cfunc:`PyCallIter_New` and the two-argument form of the :func:`iter` built-in function. - .. versionadded:: 2.2 - .. cfunction:: int PyCallIter_Check(op) Return true if the type of *op* is :cdata:`PyCallIter_Type`. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel) @@ -2943,8 +2785,6 @@ return the next item in the iteration. When *callable* returns a value equal to *sentinel*, the iteration will be terminated. - .. versionadded:: 2.2 - .. _descriptor-objects: @@ -2954,38 +2794,27 @@ "Descriptors" are objects that describe some attribute of an object. They are found in the dictionary of type objects. +.. XXX document these! .. cvar:: PyTypeObject PyProperty_Type The type object for the built-in descriptor types. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset) - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth) - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth) - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped) - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method) - .. versionadded:: 2.3 - .. cfunction:: int PyDescr_IsData(PyObject *descr) @@ -2993,13 +2822,9 @@ false if it describes a method. *descr* must be a descriptor object; there is no error checking. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyWrapper_New(PyObject *, PyObject *) - .. versionadded:: 2.2 - .. _slice-objects: @@ -3054,8 +2879,6 @@ Returns 0 on success and -1 on error with exception set. - .. versionadded:: 2.3 - .. _weakrefobjects: @@ -3072,22 +2895,16 @@ Return true if *ob* is either a reference or proxy object. - .. versionadded:: 2.2 - .. cfunction:: int PyWeakref_CheckRef(ob) Return true if *ob* is a reference object. - .. versionadded:: 2.2 - .. cfunction:: int PyWeakref_CheckProxy(ob) Return true if *ob* is a proxy object. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback) @@ -3100,8 +2917,6 @@ weakly-referencable object, or if *callback* is not callable, ``None``, or *NULL*, this will return *NULL* and raise :exc:`TypeError`. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback) @@ -3114,24 +2929,18 @@ is not a weakly-referencable object, or if *callback* is not callable, ``None``, or *NULL*, this will return *NULL* and raise :exc:`TypeError`. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyWeakref_GetObject(PyObject *ref) Return the referenced object from a weak reference, *ref*. If the referent is no longer live, returns ``None``. - .. versionadded:: 2.2 - .. cfunction:: PyObject* PyWeakref_GET_OBJECT(PyObject *ref) Similar to :cfunc:`PyWeakref_GetObject`, but implemented as a macro that does no error checking. - .. versionadded:: 2.2 - .. _cobjects: @@ -3305,111 +3114,84 @@ Type-check macros: - .. cfunction:: int PyDate_Check(PyObject *ob) Return true if *ob* is of type :cdata:`PyDateTime_DateType` or a subtype of :cdata:`PyDateTime_DateType`. *ob* must not be *NULL*. - .. versionadded:: 2.4 - .. cfunction:: int PyDate_CheckExact(PyObject *ob) Return true if *ob* is of type :cdata:`PyDateTime_DateType`. *ob* must not be *NULL*. - .. versionadded:: 2.4 - .. cfunction:: int PyDateTime_Check(PyObject *ob) Return true if *ob* is of type :cdata:`PyDateTime_DateTimeType` or a subtype of :cdata:`PyDateTime_DateTimeType`. *ob* must not be *NULL*. - .. versionadded:: 2.4 - .. cfunction:: int PyDateTime_CheckExact(PyObject *ob) Return true if *ob* is of type :cdata:`PyDateTime_DateTimeType`. *ob* must not be *NULL*. - .. versionadded:: 2.4 - .. cfunction:: int PyTime_Check(PyObject *ob) Return true if *ob* is of type :cdata:`PyDateTime_TimeType` or a subtype of :cdata:`PyDateTime_TimeType`. *ob* must not be *NULL*. - .. versionadded:: 2.4 - .. cfunction:: int PyTime_CheckExact(PyObject *ob) Return true if *ob* is of type :cdata:`PyDateTime_TimeType`. *ob* must not be *NULL*. - .. versionadded:: 2.4 - .. cfunction:: int PyDelta_Check(PyObject *ob) Return true if *ob* is of type :cdata:`PyDateTime_DeltaType` or a subtype of :cdata:`PyDateTime_DeltaType`. *ob* must not be *NULL*. - .. versionadded:: 2.4 - .. cfunction:: int PyDelta_CheckExact(PyObject *ob) Return true if *ob* is of type :cdata:`PyDateTime_DeltaType`. *ob* must not be *NULL*. - .. versionadded:: 2.4 - .. cfunction:: int PyTZInfo_Check(PyObject *ob) Return true if *ob* is of type :cdata:`PyDateTime_TZInfoType` or a subtype of :cdata:`PyDateTime_TZInfoType`. *ob* must not be *NULL*. - .. versionadded:: 2.4 - .. cfunction:: int PyTZInfo_CheckExact(PyObject *ob) Return true if *ob* is of type :cdata:`PyDateTime_TZInfoType`. *ob* must not be *NULL*. - .. versionadded:: 2.4 Macros to create objects: - .. cfunction:: PyObject* PyDate_FromDate(int year, int month, int day) Return a ``datetime.date`` object with the specified year, month and day. - .. versionadded:: 2.4 - .. cfunction:: PyObject* PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int usecond) Return a ``datetime.datetime`` object with the specified year, month, day, hour, minute, second and microsecond. - .. versionadded:: 2.4 - .. cfunction:: PyObject* PyTime_FromTime(int hour, int minute, int second, int usecond) Return a ``datetime.time`` object with the specified hour, minute, second and microsecond. - .. versionadded:: 2.4 - .. cfunction:: PyObject* PyDelta_FromDSU(int days, int seconds, int useconds) @@ -3418,116 +3200,88 @@ number of microseconds and seconds lie in the ranges documented for ``datetime.timedelta`` objects. - .. versionadded:: 2.4 Macros to extract fields from date objects. The argument must be an instance of :cdata:`PyDateTime_Date`, including subclasses (such as :cdata:`PyDateTime_DateTime`). The argument must not be *NULL*, and the type is not checked: - .. cfunction:: int PyDateTime_GET_YEAR(PyDateTime_Date *o) Return the year, as a positive int. - .. versionadded:: 2.4 - .. cfunction:: int PyDateTime_GET_MONTH(PyDateTime_Date *o) Return the month, as an int from 1 through 12. - .. versionadded:: 2.4 - .. cfunction:: int PyDateTime_GET_DAY(PyDateTime_Date *o) Return the day, as an int from 1 through 31. - .. versionadded:: 2.4 Macros to extract fields from datetime objects. The argument must be an instance of :cdata:`PyDateTime_DateTime`, including subclasses. The argument must not be *NULL*, and the type is not checked: - .. cfunction:: int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o) Return the hour, as an int from 0 through 23. - .. versionadded:: 2.4 - .. cfunction:: int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o) Return the minute, as an int from 0 through 59. - .. versionadded:: 2.4 - .. cfunction:: int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o) Return the second, as an int from 0 through 59. - .. versionadded:: 2.4 - .. cfunction:: int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o) Return the microsecond, as an int from 0 through 999999. - .. versionadded:: 2.4 Macros to extract fields from time objects. The argument must be an instance of :cdata:`PyDateTime_Time`, including subclasses. The argument must not be *NULL*, and the type is not checked: - .. cfunction:: int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o) Return the hour, as an int from 0 through 23. - .. versionadded:: 2.4 - .. cfunction:: int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o) Return the minute, as an int from 0 through 59. - .. versionadded:: 2.4 - .. cfunction:: int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o) Return the second, as an int from 0 through 59. - .. versionadded:: 2.4 - .. cfunction:: int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o) Return the microsecond, as an int from 0 through 999999. - .. versionadded:: 2.4 Macros for the convenience of modules implementing the DB API: - .. cfunction:: PyObject* PyDateTime_FromTimestamp(PyObject *args) Create and return a new ``datetime.datetime`` object given an argument tuple suitable for passing to ``datetime.datetime.fromtimestamp()``. - .. versionadded:: 2.4 - .. cfunction:: PyObject* PyDate_FromTimestamp(PyObject *args) Create and return a new ``datetime.date`` object given an argument tuple suitable for passing to ``datetime.date.fromtimestamp()``. - .. versionadded:: 2.4 - .. _setobjects: @@ -3541,8 +3295,6 @@ object: set object: frozenset -.. versionadded:: 2.5 - This section details the public API for :class:`set` and :class:`frozenset` objects. Any functionality not listed below is best accessed using the either the abstract object protocol (including :cfunc:`PyObject_CallMethod`, Modified: python/branches/py3k/Doc/c-api/exceptions.rst ============================================================================== --- python/branches/py3k/Doc/c-api/exceptions.rst (original) +++ python/branches/py3k/Doc/c-api/exceptions.rst Sat Sep 1 14:33:24 2007 @@ -257,8 +257,6 @@ Similar to :cfunc:`PyErr_SetFromWindowsErr`, with an additional parameter specifying the exception type to be raised. Availability: Windows. - .. versionadded:: 2.3 - .. cfunction:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename) @@ -272,8 +270,6 @@ Similar to :cfunc:`PyErr_SetFromWindowsErrWithFilename`, with an additional parameter specifying the exception type to be raised. Availability: Windows. - .. versionadded:: 2.3 - .. cfunction:: void PyErr_BadInternalCall() @@ -399,7 +395,7 @@ +------------------------------------+----------------------------+----------+ | C Name | Python Name | Notes | +====================================+============================+==========+ -| :cdata:`PyExc_BaseException` | :exc:`BaseException` | (1), (4) | +| :cdata:`PyExc_BaseException` | :exc:`BaseException` | \(1) | +------------------------------------+----------------------------+----------+ | :cdata:`PyExc_Exception` | :exc:`Exception` | \(1) | +------------------------------------+----------------------------+----------+ @@ -497,19 +493,3 @@ (3) Only defined on Windows; protect code that uses this by testing that the preprocessor macro ``MS_WINDOWS`` is defined. - -(4) - .. versionadded:: 2.5 - - -Deprecation of String Exceptions -================================ - -.. index:: single: BaseException (built-in exception) - -All exceptions built into Python or provided in the standard library are derived -from :exc:`BaseException`. - -String exceptions are still supported in the interpreter to allow existing code -to run unmodified, but this will also change in a future release. - Modified: python/branches/py3k/Doc/c-api/init.rst ============================================================================== --- python/branches/py3k/Doc/c-api/init.rst (original) +++ python/branches/py3k/Doc/c-api/init.rst Sat Sep 1 14:33:24 2007 @@ -42,8 +42,6 @@ *initsigs* is 0, it skips initialization registration of signal handlers, which might be useful when Python is embedded. - .. versionadded:: 2.4 - .. cfunction:: int Py_IsInitialized() @@ -290,8 +288,6 @@ was built from. This number is a string because it may contain a trailing 'M' if Python was built from a mixed revision source tree. - .. versionadded:: 2.5 - .. cfunction:: const char* Py_GetPlatform() @@ -570,8 +566,6 @@ avoid calls to the locking API when running single-threaded. This function is not available when thread support is disabled at compile time. - .. versionadded:: 2.4 - .. cfunction:: void PyEval_AcquireLock() @@ -719,10 +713,6 @@ is available. If this function returns *NULL*, no exception has been raised and the caller should assume no current thread state is available. - .. versionchanged:: 2.3 - Previously this could only be called when a current thread is active, and *NULL* - meant that an exception was raised. - .. cfunction:: int PyThreadState_SetAsyncExc(long id, PyObject *exc) @@ -734,8 +724,6 @@ zero if the thread id isn't found. If *exc* is :const:`NULL`, the pending exception (if any) for the thread is cleared. This raises no exceptions. - .. versionadded:: 2.3 - .. cfunction:: PyGILState_STATE PyGILState_Ensure() @@ -758,8 +746,6 @@ When the function returns, the current thread will hold the GIL. Failure is a fatal error. - .. versionadded:: 2.3 - .. cfunction:: void PyGILState_Release(PyGILState_STATE) @@ -771,8 +757,6 @@ Every call to :cfunc:`PyGILState_Ensure` must be matched by a call to :cfunc:`PyGILState_Release` on the same thread. - .. versionadded:: 2.3 - .. _profiling: @@ -908,29 +892,21 @@ Return the interpreter state object at the head of the list of all such objects. - .. versionadded:: 2.2 - .. cfunction:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp) Return the next interpreter state object after *interp* from the list of all such objects. - .. versionadded:: 2.2 - .. cfunction:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp) Return the a pointer to the first :ctype:`PyThreadState` object in the list of threads associated with the interpreter *interp*. - .. versionadded:: 2.2 - .. cfunction:: PyThreadState* PyThreadState_Next(PyThreadState *tstate) Return the next thread state object after *tstate* from the list of all such objects belonging to the same :ctype:`PyInterpreterState` object. - .. versionadded:: 2.2 - Modified: python/branches/py3k/Doc/c-api/newtypes.rst ============================================================================== --- python/branches/py3k/Doc/c-api/newtypes.rst (original) +++ python/branches/py3k/Doc/c-api/newtypes.rst Sat Sep 1 14:33:24 2007 @@ -67,49 +67,41 @@ .. cfunction:: PyObject* Py_InitModule(char *name, PyMethodDef *methods) - Create a new module object based on a name and table of functions, returning the - new module object. - - .. versionchanged:: 2.3 - Older versions of Python did not support *NULL* as the value for the *methods* - argument. + Create a new module object based on a name and table of functions, returning + the new module object; the *methods* argument can be *NULL* if no methods are + to be defined for the module. .. cfunction:: PyObject* Py_InitModule3(char *name, PyMethodDef *methods, char *doc) - Create a new module object based on a name and table of functions, returning the - new module object. If *doc* is non-*NULL*, it will be used to define the - docstring for the module. - - .. versionchanged:: 2.3 - Older versions of Python did not support *NULL* as the value for the *methods* - argument. + Create a new module object based on a name and table of functions, returning + the new module object. The *methods* argument can be *NULL* if no methods + are to be defined for the module. If *doc* is non-*NULL*, it will be used to + define the docstring for the module. .. cfunction:: PyObject* Py_InitModule4(char *name, PyMethodDef *methods, char *doc, PyObject *self, int apiver) - Create a new module object based on a name and table of functions, returning the - new module object. If *doc* is non-*NULL*, it will be used to define the - docstring for the module. If *self* is non-*NULL*, it will passed to the - functions of the module as their (otherwise *NULL*) first parameter. (This was - added as an experimental feature, and there are no known uses in the current - version of Python.) For *apiver*, the only value which should be passed is - defined by the constant :const:`PYTHON_API_VERSION`. + Create a new module object based on a name and table of functions, returning + the new module object. The *methods* argument can be *NULL* if no methods + are to be defined for the module. If *doc* is non-*NULL*, it will be used to + define the docstring for the module. If *self* is non-*NULL*, it will passed + to the functions of the module as their (otherwise *NULL*) first parameter. + (This was added as an experimental feature, and there are no known uses in + the current version of Python.) For *apiver*, the only value which should be + passed is defined by the constant :const:`PYTHON_API_VERSION`. .. note:: Most uses of this function should probably be using the :cfunc:`Py_InitModule3` instead; only use this if you are sure you need it. - .. versionchanged:: 2.3 - Older versions of Python did not support *NULL* as the value for the *methods* - argument. - .. cvar:: PyObject _Py_NoneStruct Object which is visible in Python as ``None``. This should only be accessed - using the ``Py_None`` macro, which evaluates to a pointer to this object. + using the :cmacro:`Py_None` macro, which evaluates to a pointer to this + object. .. _common-structs: @@ -263,6 +255,7 @@ :ctype:`PyObject\*` parameter representing the single argument. +.. XXX deprecated, should be removed .. data:: METH_OLDARGS This calling convention is deprecated. The method must be of type @@ -286,8 +279,6 @@ instance of the type. This is used to create *class methods*, similar to what is created when using the :func:`classmethod` built-in function. - .. versionadded:: 2.3 - .. data:: METH_STATIC @@ -297,8 +288,6 @@ of the type. This is used to create *static methods*, similar to what is created when using the :func:`staticmethod` built-in function. - .. versionadded:: 2.3 - One other constant controls whether a method is loaded in place of another definition with the same method name. @@ -314,8 +303,6 @@ object and will co-exist with the slot. This is helpful because calls to PyCFunctions are optimized more than wrapper object calls. - .. versionadded:: 2.4 - .. cfunction:: PyObject* Py_FindMethod(PyMethodDef table[], PyObject *ob, char *name) @@ -1718,8 +1705,6 @@ return 0; } - .. versionadded:: 2.4 - The :attr:`tp_clear` handler must be of the :ctype:`inquiry` type, or *NULL* if the object is immutable. Modified: python/branches/py3k/Doc/c-api/refcounting.rst ============================================================================== --- python/branches/py3k/Doc/c-api/refcounting.rst (original) +++ python/branches/py3k/Doc/c-api/refcounting.rst Sat Sep 1 14:33:24 2007 @@ -61,12 +61,11 @@ It is a good idea to use this macro whenever decrementing the value of a variable that might be traversed during garbage collection. - .. versionadded:: 2.4 The following functions are for runtime dynamic embedding of Python: -``Py_IncRef(PyObject \*o)``, `Py_DecRef(PyObject \*o)``. They are -simply exported function versions of :cfunc:`Py_XINCREF` and -:cfunc:`Py_XDECREF`, respectively. +``Py_IncRef(PyObject \*o)``, `Py_DecRef(PyObject \*o)``. They are simply +exported function versions of :cfunc:`Py_XINCREF` and :cfunc:`Py_XDECREF`, +respectively. The following functions or macros are only for use within the interpreter core: :cfunc:`_Py_Dealloc`, :cfunc:`_Py_ForgetReference`, :cfunc:`_Py_NewReference`, Modified: python/branches/py3k/Doc/c-api/utilities.rst ============================================================================== --- python/branches/py3k/Doc/c-api/utilities.rst (original) +++ python/branches/py3k/Doc/c-api/utilities.rst Sat Sep 1 14:33:24 2007 @@ -121,6 +121,7 @@ .. index:: single: package variable; __all__ single: __all__ (package variable) + single: modules (in module sys) This is a simplified interface to :cfunc:`PyImport_ImportModuleEx` below, leaving the *globals* and *locals* arguments set to *NULL*. When the *name* @@ -135,11 +136,6 @@ to find out. Starting with Python 2.4, a failing import of a module no longer leaves the module in ``sys.modules``. - .. versionchanged:: 2.4 - failing imports remove incomplete module objects. - - .. index:: single: modules (in module sys) - .. cfunction:: PyObject* PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist) @@ -155,20 +151,16 @@ when a submodule of a package was requested is normally the top-level package, unless a non-empty *fromlist* was given. - .. versionchanged:: 2.4 - failing imports remove incomplete module objects. + Failing imports remove incomplete module objects, like with + :cfunc:`PyImport_ImportModule`. .. cfunction:: PyObject* PyImport_Import(PyObject *name) - .. index:: - module: rexec - module: ihooks - This is a higher-level interface that calls the current "import hook function". It invokes the :func:`__import__` function from the ``__builtins__`` of the current globals. This means that the import is done using whatever import hooks - are installed in the current environment, e.g. by :mod:`rexec` or :mod:`ihooks`. + are installed in the current environment. .. cfunction:: PyObject* PyImport_ReloadModule(PyObject *m) @@ -213,9 +205,6 @@ If *name* points to a dotted name of the form ``package.module``, any package structures not already created will still not be created. - .. versionchanged:: 2.4 - *name* is removed from ``sys.modules`` in error cases. - .. cfunction:: long PyImport_GetMagicNumber() @@ -345,26 +334,19 @@ Marshal a :ctype:`long` integer, *value*, to *file*. This will only write the least-significant 32 bits of *value*; regardless of the size of the native - :ctype:`long` type. - - .. versionchanged:: 2.4 - *version* indicates the file format. + :ctype:`long` type. *version* indicates the file format. .. cfunction:: void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version) Marshal a Python object, *value*, to *file*. - - .. versionchanged:: 2.4 - *version* indicates the file format. + *version* indicates the file format. .. cfunction:: PyObject* PyMarshal_WriteObjectToString(PyObject *value, int version) Return a string object containing the marshalled representation of *value*. - - .. versionchanged:: 2.4 - *version* indicates the file format. + *version* indicates the file format. The following functions allow marshalled values to be read back in. @@ -557,8 +539,6 @@ Convert a Python integer to a tiny int without overflow checking, stored in a C :ctype:`unsigned char`. - .. versionadded:: 2.3 - ``h`` (integer) [short int] Convert a Python integer to a C :ctype:`short int`. @@ -566,8 +546,6 @@ Convert a Python integer to a C :ctype:`unsigned short int`, without overflow checking. - .. versionadded:: 2.3 - ``i`` (integer) [int] Convert a Python integer to a plain C :ctype:`int`. @@ -575,8 +553,6 @@ Convert a Python integer to a C :ctype:`unsigned int`, without overflow checking. - .. versionadded:: 2.3 - ``l`` (integer) [long int] Convert a Python integer to a C :ctype:`long int`. @@ -584,8 +560,6 @@ Convert a Python integer or long integer to a C :ctype:`unsigned long` without overflow checking. - .. versionadded:: 2.3 - ``L`` (integer) [PY_LONG_LONG] Convert a Python integer to a C :ctype:`long long`. This format is only available on platforms that support :ctype:`long long` (or :ctype:`_int64` on @@ -596,13 +570,9 @@ without overflow checking. This format is only available on platforms that support :ctype:`unsigned long long` (or :ctype:`unsigned _int64` on Windows). - .. versionadded:: 2.3 - ``n`` (integer) [Py_ssize_t] Convert a Python integer or long integer to a C :ctype:`Py_ssize_t`. - .. versionadded:: 2.5 - ``c`` (string of length 1) [char] Convert a Python character, represented as a string of length 1, to a C :ctype:`char`. @@ -677,13 +647,6 @@ in *items*. The C arguments must correspond to the individual format units in *items*. Format units for sequences may be nested. - .. note:: - - Prior to Python version 1.5.2, this format specifier only accepted a tuple - containing the individual parameters, not an arbitrary sequence. Code which - previously caused :exc:`TypeError` to be raised here may now proceed without an - exception. This is not expected to be a problem for existing code. - It is possible to pass Python long integers where integers are requested; however no proper range checking is done --- the most significant bits are silently truncated when the receiving field is too small to receive the value @@ -798,8 +761,6 @@ PyArg_ParseTuple(args, "O|O:ref", &object, &callback) - .. versionadded:: 2.2 - .. cfunction:: PyObject* Py_BuildValue(const char *format, ...) @@ -898,8 +859,6 @@ ``n`` (int) [Py_ssize_t] Convert a C :ctype:`Py_ssize_t` to a Python integer or long integer. - .. versionadded:: 2.5 - ``c`` (string of length 1) [char] Convert a C :ctype:`int` representing a character to a Python string of length 1. @@ -1010,8 +969,6 @@ :cfunc:`PyOS_ascii_strtod` should typically be used for reading configuration files or other non-user input that should be locale independent. - .. versionadded:: 2.4 - See the Unix man page :manpage:`strtod(2)` for details. @@ -1025,14 +982,10 @@ The return value is a pointer to *buffer* with the converted string or NULL if the conversion failed. - .. versionadded:: 2.4 - .. cfunction:: double PyOS_ascii_atof(const char *nptr) Convert a string to a :ctype:`double` in a locale-independent way. - .. versionadded:: 2.4 - See the Unix man page :manpage:`atof(2)` for details. From python-3000-checkins at python.org Sat Sep 1 14:38:26 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 1 Sep 2007 14:38:26 +0200 (CEST) Subject: [Python-3000-checkins] r57869 - python/branches/py3k/Doc/reference/compound_stmts.rst python/branches/py3k/Doc/reference/datamodel.rst python/branches/py3k/Doc/reference/expressions.rst Message-ID: <20070901123826.B36941E4006@bag.python.org> Author: georg.brandl Date: Sat Sep 1 14:38:06 2007 New Revision: 57869 Modified: python/branches/py3k/Doc/reference/compound_stmts.rst python/branches/py3k/Doc/reference/datamodel.rst python/branches/py3k/Doc/reference/expressions.rst Log: Remove versionadded/versionchanged in the reference. Modified: python/branches/py3k/Doc/reference/compound_stmts.rst ============================================================================== --- python/branches/py3k/Doc/reference/compound_stmts.rst (original) +++ python/branches/py3k/Doc/reference/compound_stmts.rst Sat Sep 1 14:38:06 2007 @@ -211,6 +211,7 @@ ============================ .. index:: statement: try +.. index:: keyword: except The :keyword:`try` statement specifies exception handlers and/or cleanup code for a group of statements: @@ -224,13 +225,6 @@ try2_stmt: "try" ":" `suite` : "finally" ":" `suite` -.. versionchanged:: 2.5 - In previous versions of Python, :keyword:`try`...\ :keyword:`except`...\ - :keyword:`finally` did not work. :keyword:`try`...\ :keyword:`except` had to be - nested in :keyword:`try`...\ :keyword:`finally`. - -.. index:: keyword: except - The :keyword:`except` clause(s) specify one or more exception handlers. When no exception occurs in the :keyword:`try` clause, no exception handler is executed. When an exception occurs in the :keyword:`try` suite, a search for an exception @@ -317,8 +311,6 @@ .. index:: statement: with -.. versionadded:: 2.5 - The :keyword:`with` statement is used to wrap the execution of a block with methods defined by a context manager (see section :ref:`context-managers`). This allows common :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` usage Modified: python/branches/py3k/Doc/reference/datamodel.rst ============================================================================== --- python/branches/py3k/Doc/reference/datamodel.rst (original) +++ python/branches/py3k/Doc/reference/datamodel.rst Sat Sep 1 14:38:06 2007 @@ -508,9 +508,6 @@ Most of the attributes labelled "Writable" check the type of the assigned value. - .. versionchanged:: 2.4 - ``__name__`` is now writable. - Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and set such attributes. *Note that the current @@ -550,9 +547,6 @@ ``im_func.__name__``); :attr:`__module__` is the name of the module the method was defined in, or ``None`` if unavailable. - .. versionchanged:: 2.2 - :attr:`im_self` used to refer to the class that defined the method. - .. index:: single: __doc__ (method attribute) single: __name__ (method attribute) @@ -1029,8 +1023,6 @@ slice. Missing or out-of-bounds indices are handled in a manner consistent with regular slices. - .. versionadded:: 2.3 - Static method objects Static method objects provide a way of defeating the transformation of function objects to method objects described above. A static method object is a wrapper @@ -1240,8 +1232,6 @@ object.__gt__(self, other) object.__ge__(self, other) - .. versionadded:: 2.1 - These are the so-called "rich comparison" methods, and are called for comparison operators in preference to :meth:`__cmp__` below. The correspondence between operator symbols and method names is as follows: ``x Author: georg.brandl Date: Sat Sep 1 15:51:09 2007 New Revision: 57870 Modified: python/branches/py3k/Doc/distutils/setupscript.rst python/branches/py3k/Doc/distutils/uploading.rst python/branches/py3k/Doc/extending/newtypes.rst python/branches/py3k/Doc/install/index.rst python/branches/py3k/Doc/library/_ast.rst python/branches/py3k/Doc/library/_winreg.rst python/branches/py3k/Doc/library/array.rst python/branches/py3k/Doc/library/atexit.rst python/branches/py3k/Doc/library/audioop.rst python/branches/py3k/Doc/library/basehttpserver.rst python/branches/py3k/Doc/library/bisect.rst python/branches/py3k/Doc/library/bsddb.rst python/branches/py3k/Doc/library/bz2.rst python/branches/py3k/Doc/library/calendar.rst python/branches/py3k/Doc/library/cgi.rst python/branches/py3k/Doc/library/cgitb.rst python/branches/py3k/Doc/library/cmath.rst python/branches/py3k/Doc/library/cmd.rst python/branches/py3k/Doc/library/codecs.rst python/branches/py3k/Doc/library/collections.rst python/branches/py3k/Doc/library/configparser.rst python/branches/py3k/Doc/library/constants.rst python/branches/py3k/Doc/library/contextlib.rst python/branches/py3k/Doc/library/cookie.rst python/branches/py3k/Doc/library/cookielib.rst python/branches/py3k/Doc/library/copy.rst python/branches/py3k/Doc/library/csv.rst python/branches/py3k/Doc/library/ctypes.rst python/branches/py3k/Doc/library/curses.ascii.rst python/branches/py3k/Doc/library/curses.rst python/branches/py3k/Doc/library/datetime.rst python/branches/py3k/Doc/library/decimal.rst python/branches/py3k/Doc/library/difflib.rst python/branches/py3k/Doc/library/doctest.rst python/branches/py3k/Doc/library/docxmlrpcserver.rst python/branches/py3k/Doc/library/dumbdbm.rst python/branches/py3k/Doc/library/easydialogs.rst python/branches/py3k/Doc/library/email.charset.rst python/branches/py3k/Doc/library/email.errors.rst python/branches/py3k/Doc/library/email.generator.rst python/branches/py3k/Doc/library/email.header.rst python/branches/py3k/Doc/library/email.message.rst python/branches/py3k/Doc/library/email.mime.rst python/branches/py3k/Doc/library/email.parser.rst python/branches/py3k/Doc/library/email.rst python/branches/py3k/Doc/library/email.util.rst python/branches/py3k/Doc/library/exceptions.rst python/branches/py3k/Doc/library/fileinput.rst python/branches/py3k/Doc/library/fnmatch.rst python/branches/py3k/Doc/library/ftplib.rst python/branches/py3k/Doc/library/functions.rst python/branches/py3k/Doc/library/functools.rst python/branches/py3k/Doc/library/gc.rst python/branches/py3k/Doc/library/getopt.rst python/branches/py3k/Doc/library/getpass.rst python/branches/py3k/Doc/library/gettext.rst python/branches/py3k/Doc/library/glob.rst python/branches/py3k/Doc/library/hashlib.rst python/branches/py3k/Doc/library/heapq.rst python/branches/py3k/Doc/library/hmac.rst python/branches/py3k/Doc/library/hotshot.rst python/branches/py3k/Doc/library/htmllib.rst python/branches/py3k/Doc/library/htmlparser.rst python/branches/py3k/Doc/library/httplib.rst python/branches/py3k/Doc/library/imaplib.rst python/branches/py3k/Doc/library/imghdr.rst python/branches/py3k/Doc/library/imp.rst python/branches/py3k/Doc/library/imputil.rst python/branches/py3k/Doc/library/inspect.rst python/branches/py3k/Doc/library/itertools.rst python/branches/py3k/Doc/library/linecache.rst python/branches/py3k/Doc/library/locale.rst python/branches/py3k/Doc/library/logging.rst python/branches/py3k/Doc/library/marshal.rst python/branches/py3k/Doc/library/math.rst python/branches/py3k/Doc/library/mimetypes.rst python/branches/py3k/Doc/library/mmap.rst python/branches/py3k/Doc/library/modulefinder.rst python/branches/py3k/Doc/library/msilib.rst python/branches/py3k/Doc/library/netrc.rst python/branches/py3k/Doc/library/nis.rst python/branches/py3k/Doc/library/nntplib.rst python/branches/py3k/Doc/library/operator.rst python/branches/py3k/Doc/library/optparse.rst python/branches/py3k/Doc/library/os.path.rst python/branches/py3k/Doc/library/os.rst python/branches/py3k/Doc/library/ossaudiodev.rst python/branches/py3k/Doc/library/pdb.rst python/branches/py3k/Doc/library/pickle.rst python/branches/py3k/Doc/library/pickletools.rst python/branches/py3k/Doc/library/pkgutil.rst python/branches/py3k/Doc/library/platform.rst python/branches/py3k/Doc/library/poplib.rst python/branches/py3k/Doc/library/pprint.rst python/branches/py3k/Doc/library/profile.rst python/branches/py3k/Doc/library/pydoc.rst python/branches/py3k/Doc/library/pyexpat.rst python/branches/py3k/Doc/library/queue.rst python/branches/py3k/Doc/library/random.rst python/branches/py3k/Doc/library/re.rst python/branches/py3k/Doc/library/readline.rst python/branches/py3k/Doc/library/repr.rst python/branches/py3k/Doc/library/resource.rst python/branches/py3k/Doc/library/runpy.rst python/branches/py3k/Doc/library/sgmllib.rst python/branches/py3k/Doc/library/shelve.rst python/branches/py3k/Doc/library/shlex.rst python/branches/py3k/Doc/library/shutil.rst python/branches/py3k/Doc/library/simplehttpserver.rst python/branches/py3k/Doc/library/simplexmlrpcserver.rst python/branches/py3k/Doc/library/site.rst python/branches/py3k/Doc/library/smtplib.rst python/branches/py3k/Doc/library/socket.rst python/branches/py3k/Doc/library/spwd.rst python/branches/py3k/Doc/library/sqlite3.rst python/branches/py3k/Doc/library/ssl.rst python/branches/py3k/Doc/library/stdtypes.rst python/branches/py3k/Doc/library/string.rst python/branches/py3k/Doc/library/stringprep.rst python/branches/py3k/Doc/library/struct.rst python/branches/py3k/Doc/library/subprocess.rst python/branches/py3k/Doc/library/sys.rst python/branches/py3k/Doc/library/tarfile.rst python/branches/py3k/Doc/library/telnetlib.rst python/branches/py3k/Doc/library/tempfile.rst python/branches/py3k/Doc/library/test.rst python/branches/py3k/Doc/library/textwrap.rst python/branches/py3k/Doc/library/thread.rst python/branches/py3k/Doc/library/threading.rst python/branches/py3k/Doc/library/time.rst python/branches/py3k/Doc/library/timeit.rst python/branches/py3k/Doc/library/tkinter.rst python/branches/py3k/Doc/library/tokenize.rst python/branches/py3k/Doc/library/traceback.rst python/branches/py3k/Doc/library/turtle.rst python/branches/py3k/Doc/library/types.rst python/branches/py3k/Doc/library/unicodedata.rst python/branches/py3k/Doc/library/unittest.rst python/branches/py3k/Doc/library/urllib.rst python/branches/py3k/Doc/library/urllib2.rst python/branches/py3k/Doc/library/urlparse.rst python/branches/py3k/Doc/library/userdict.rst python/branches/py3k/Doc/library/uuid.rst python/branches/py3k/Doc/library/warnings.rst python/branches/py3k/Doc/library/weakref.rst python/branches/py3k/Doc/library/webbrowser.rst python/branches/py3k/Doc/library/winsound.rst python/branches/py3k/Doc/library/wsgiref.rst python/branches/py3k/Doc/library/xml.dom.minidom.rst python/branches/py3k/Doc/library/xml.dom.pulldom.rst python/branches/py3k/Doc/library/xml.dom.rst python/branches/py3k/Doc/library/xml.etree.elementtree.rst python/branches/py3k/Doc/library/xml.etree.rst python/branches/py3k/Doc/library/xml.sax.handler.rst python/branches/py3k/Doc/library/xml.sax.reader.rst python/branches/py3k/Doc/library/xml.sax.rst python/branches/py3k/Doc/library/xml.sax.utils.rst python/branches/py3k/Doc/library/xmlrpclib.rst python/branches/py3k/Doc/library/zipfile.rst python/branches/py3k/Doc/library/zipimport.rst python/branches/py3k/Doc/library/zlib.rst Log: Get rid of the remaining versionadded/versionchanged directives. Modified: python/branches/py3k/Doc/distutils/setupscript.rst ============================================================================== --- python/branches/py3k/Doc/distutils/setupscript.rst (original) +++ python/branches/py3k/Doc/distutils/setupscript.rst Sat Sep 1 15:51:09 2007 @@ -488,8 +488,6 @@ package_data={'mypkg': ['data/*.dat']}, ) -.. versionadded:: 2.4 - Installing Additional Files =========================== Modified: python/branches/py3k/Doc/distutils/uploading.rst ============================================================================== --- python/branches/py3k/Doc/distutils/uploading.rst (original) +++ python/branches/py3k/Doc/distutils/uploading.rst Sat Sep 1 15:51:09 2007 @@ -4,8 +4,6 @@ Uploading Packages to the Package Index *************************************** -.. versionadded:: 2.5 - The Python Package Index (PyPI) not only stores the package info, but also the package data if the author of the package wishes to. The distutils command :command:`upload` pushes the distribution files to PyPI. Modified: python/branches/py3k/Doc/extending/newtypes.rst ============================================================================== --- python/branches/py3k/Doc/extending/newtypes.rst (original) +++ python/branches/py3k/Doc/extending/newtypes.rst Sat Sep 1 15:51:09 2007 @@ -1125,8 +1125,6 @@ Generic Attribute Management ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -.. versionadded:: 2.2 - Most extension types only use *simple* attributes. So, what makes the attributes simple? There are only a couple of conditions that must be met: Modified: python/branches/py3k/Doc/install/index.rst ============================================================================== --- python/branches/py3k/Doc/install/index.rst (original) +++ python/branches/py3k/Doc/install/index.rst Sat Sep 1 15:51:09 2007 @@ -343,9 +343,6 @@ | data | :file:`{home}/share` | :option:`--install-data` | +------------------------------+---------------------------+-----------------------------+ -.. versionchanged:: 2.4 - The :option:`--home` option used to be supported only on Unix. - .. _inst-alt-install-home: Modified: python/branches/py3k/Doc/library/_ast.rst ============================================================================== --- python/branches/py3k/Doc/library/_ast.rst (original) +++ python/branches/py3k/Doc/library/_ast.rst Sat Sep 1 15:51:09 2007 @@ -9,8 +9,6 @@ .. sectionauthor:: Martin v. L?wis -.. versionadded:: 2.5 - The ``_ast`` module helps Python applications to process trees of the Python abstract syntax grammar. The Python compiler currently provides read-only access to such trees, meaning that applications can only create a tree for a given Modified: python/branches/py3k/Doc/library/_winreg.rst ============================================================================== --- python/branches/py3k/Doc/library/_winreg.rst (original) +++ python/branches/py3k/Doc/library/_winreg.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Mark Hammond -.. versionadded:: 2.0 - These functions expose the Windows registry API to Python. Instead of using an integer as the registry handle, a handle object is used to ensure that the handles are closed correctly, even if the programmer neglects to explicitly Modified: python/branches/py3k/Doc/library/array.rst ============================================================================== --- python/branches/py3k/Doc/library/array.rst (original) +++ python/branches/py3k/Doc/library/array.rst Sat Sep 1 15:51:09 2007 @@ -59,9 +59,6 @@ from the optional *initializer* value, which must be a list, string, or iterable over elements of the appropriate type. - .. versionchanged:: 2.4 - Formerly, only lists or strings were accepted. - If given a list or string, the initializer is passed to the new array's :meth:`fromlist`, :meth:`fromstring`, or :meth:`fromunicode` method (see below) to add initial items to the array. Otherwise, the iterable initializer is @@ -135,9 +132,6 @@ be raised. If *iterable* is not an array, it must be iterable and its elements must be the right type to be appended to the array. - .. versionchanged:: 2.4 - Formerly, the argument could only be another array. - .. method:: array.fromfile(f, n) Modified: python/branches/py3k/Doc/library/atexit.rst ============================================================================== --- python/branches/py3k/Doc/library/atexit.rst (original) +++ python/branches/py3k/Doc/library/atexit.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Skip Montanaro -.. versionadded:: 2.0 - The :mod:`atexit` module defines functions to register and unregister cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination. @@ -36,9 +34,8 @@ saved. After all exit handlers have had a chance to run the last exception to be raised is re-raised. - .. versionchanged:: 2.6 - This function now returns *func* which makes it possible to use it as a - decorator without binding the original name to ``None``. + This function returns *func* which makes it possible to use it as a decorator + without binding the original name to ``None``. .. function:: unregister(func) @@ -47,8 +44,6 @@ shutdown. After calling :func:`unregister`, *func* is guaranteed not to be called when the interpreter shuts down. - .. versionadded:: 3.0 - .. seealso:: Modified: python/branches/py3k/Doc/library/audioop.rst ============================================================================== --- python/branches/py3k/Doc/library/audioop.rst (original) +++ python/branches/py3k/Doc/library/audioop.rst Sat Sep 1 15:51:09 2007 @@ -53,8 +53,6 @@ a-LAW encoding always uses 8 bits samples, so *width* refers only to the sample width of the output fragment here. - .. versionadded:: 2.5 - .. function:: avg(fragment, width) @@ -133,8 +131,6 @@ range of about 13 bits using only 8 bit samples. It is used by the Sun audio hardware, among others. - .. versionadded:: 2.5 - .. function:: lin2lin(fragment, width, newwidth) Modified: python/branches/py3k/Doc/library/basehttpserver.rst ============================================================================== --- python/branches/py3k/Doc/library/basehttpserver.rst (original) +++ python/branches/py3k/Doc/library/basehttpserver.rst Sat Sep 1 15:51:09 2007 @@ -228,9 +228,6 @@ The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``. - .. versionadded:: 2.5 - The *timestamp* parameter. - .. method:: BaseHTTPRequestHandler.log_date_time_string() Modified: python/branches/py3k/Doc/library/bisect.rst ============================================================================== --- python/branches/py3k/Doc/library/bisect.rst (original) +++ python/branches/py3k/Doc/library/bisect.rst Sat Sep 1 15:51:09 2007 @@ -30,16 +30,12 @@ existing entries. The return value is suitable for use as the first parameter to ``list.insert()``. This assumes that *list* is already sorted. - .. versionadded:: 2.1 - .. function:: bisect_right(list, item[, lo[, hi]]) Similar to :func:`bisect_left`, but returns an insertion point which comes after (to the right of) any existing entries of *item* in *list*. - .. versionadded:: 2.1 - .. function:: bisect(...) @@ -52,16 +48,12 @@ ``list.insert(bisect.bisect_left(list, item, lo, hi), item)``. This assumes that *list* is already sorted. - .. versionadded:: 2.1 - .. function:: insort_right(list, item[, lo[, hi]]) Similar to :func:`insort_left`, but inserting *item* in *list* after any existing entries of *item*. - .. versionadded:: 2.1 - .. function:: insort(...) Modified: python/branches/py3k/Doc/library/bsddb.rst ============================================================================== --- python/branches/py3k/Doc/library/bsddb.rst (original) +++ python/branches/py3k/Doc/library/bsddb.rst Sat Sep 1 15:51:09 2007 @@ -82,8 +82,6 @@ Wrapper class around a DB object that supports string keys (rather than bytes). All keys are encoded as UTF-8, then passed to the underlying object. - - .. versionadded:: 3.0 .. class:: StringValues(db) @@ -91,8 +89,6 @@ Wrapper class around a DB object that supports string values (rather than bytes). All values are encoded as UTF-8, then passed to the underlying object. - .. versionadded:: 3.0 - .. seealso:: @@ -108,9 +104,6 @@ Once instantiated, hash, btree and record objects support the same methods as dictionaries. In addition, they support the methods listed below. -.. versionchanged:: 2.3.1 - Added dictionary methods. - .. method:: bsddbobject.close() Modified: python/branches/py3k/Doc/library/bz2.rst ============================================================================== --- python/branches/py3k/Doc/library/bz2.rst (original) +++ python/branches/py3k/Doc/library/bz2.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Gustavo Niemeyer -.. versionadded:: 2.3 - This module provides a comprehensive interface for the bz2 compression library. It implements a complete file interface, one-shot (de)compression functions, and types for sequential (de)compression. Modified: python/branches/py3k/Doc/library/calendar.rst ============================================================================== --- python/branches/py3k/Doc/library/calendar.rst (original) +++ python/branches/py3k/Doc/library/calendar.rst Sat Sep 1 15:51:09 2007 @@ -32,11 +32,9 @@ preparing the calendar data for formatting. This class doesn't do any formatting itself. This is the job of subclasses. - .. versionadded:: 2.5 :class:`Calendar` instances have the following methods: - .. method:: Calendar.iterweekdays(weekday) Return an iterator for the week day numbers that will be used for one week. The @@ -109,11 +107,9 @@ This class can be used to generate plain text calendars. - .. versionadded:: 2.5 :class:`TextCalendar` instances have the following methods: - .. method:: TextCalendar.formatmonth(theyear, themonth[, w[, l]]) Return a month's calendar in a multi-line string. If *w* is provided, it @@ -145,11 +141,9 @@ This class can be used to generate HTML calendars. - .. versionadded:: 2.5 :class:`HTMLCalendar` instances have the following methods: - .. method:: HTMLCalendar.formatmonth(theyear, themonth[, withyear]) Return a month's calendar as an HTML table. If *withyear* is true the year will @@ -178,8 +172,6 @@ this locale includes an encoding all strings containing month and weekday names will be returned as unicode. - .. versionadded:: 2.5 - .. class:: LocaleHTMLCalendar([firstweekday[, locale]]) @@ -188,11 +180,9 @@ this locale includes an encoding all strings containing month and weekday names will be returned as unicode. - .. versionadded:: 2.5 For simple text calendars this module provides the following functions. - .. function:: setfirstweekday(weekday) Sets the weekday (``0`` is Monday, ``6`` is Sunday) to start each week. The @@ -203,15 +193,11 @@ import calendar calendar.setfirstweekday(calendar.SUNDAY) - .. versionadded:: 2.0 - .. function:: firstweekday() Returns the current setting for the weekday to start each week. - .. versionadded:: 2.0 - .. function:: isleap(year) @@ -223,9 +209,7 @@ Returns the number of leap years in the range from *y1* to *y2* (exclusive), where *y1* and *y2* are years. - .. versionchanged:: 2.0 - This function didn't work for ranges spanning a century change in Python - 1.5.2. + This function works for ranges spanning a century change. .. function:: weekday(year, month, day) @@ -263,8 +247,6 @@ Returns a month's calendar in a multi-line string using the :meth:`formatmonth` of the :class:`TextCalendar` class. - .. versionadded:: 2.0 - .. function:: prcal(year[, w[, l[c]]]) @@ -276,8 +258,6 @@ Returns a 3-column calendar for an entire year as a multi-line string using the :meth:`formatyear` of the :class:`TextCalendar` class. - .. versionadded:: 2.0 - .. function:: timegm(tuple) @@ -286,11 +266,9 @@ Unix timestamp value, assuming an epoch of 1970, and the POSIX encoding. In fact, :func:`time.gmtime` and :func:`timegm` are each others' inverse. - .. versionadded:: 2.0 The :mod:`calendar` module exports the following data attributes: - .. data:: day_name An array that represents the days of the week in the current locale. Modified: python/branches/py3k/Doc/library/cgi.rst ============================================================================== --- python/branches/py3k/Doc/library/cgi.rst (original) +++ python/branches/py3k/Doc/library/cgi.rst Sat Sep 1 15:51:09 2007 @@ -164,8 +164,6 @@ Higher Level Interface ---------------------- -.. versionadded:: 2.2 - The previous section explains how to read CGI form data using the :class:`FieldStorage` class. This section describes a higher level interface which was added to this class to allow one to do it in a more readable and Modified: python/branches/py3k/Doc/library/cgitb.rst ============================================================================== --- python/branches/py3k/Doc/library/cgitb.rst (original) +++ python/branches/py3k/Doc/library/cgitb.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Fred L. Drake, Jr. -.. versionadded:: 2.2 - .. index:: single: CGI; exceptions single: CGI; tracebacks Modified: python/branches/py3k/Doc/library/cmath.rst ============================================================================== --- python/branches/py3k/Doc/library/cmath.rst (original) +++ python/branches/py3k/Doc/library/cmath.rst Sat Sep 1 15:51:09 2007 @@ -84,9 +84,6 @@ specified, returns the natural logarithm of *x*. There is one branch cut, from 0 along the negative real axis to -?, continuous from above. - .. versionchanged:: 2.4 - *base* argument added. - .. function:: log10(x) Modified: python/branches/py3k/Doc/library/cmd.rst ============================================================================== --- python/branches/py3k/Doc/library/cmd.rst (original) +++ python/branches/py3k/Doc/library/cmd.rst Sat Sep 1 15:51:09 2007 @@ -28,9 +28,6 @@ objects that the Cmd instance or subclass instance will use for input and output. If not specified, they will default to *sys.stdin* and *sys.stdout*. - .. versionchanged:: 2.3 - The *stdin* and *stdout* parameters were added. - .. _cmd-objects: Modified: python/branches/py3k/Doc/library/codecs.rst ============================================================================== --- python/branches/py3k/Doc/library/codecs.rst (original) +++ python/branches/py3k/Doc/library/codecs.rst Sat Sep 1 15:51:09 2007 @@ -118,8 +118,6 @@ Raises a :exc:`LookupError` in case the encoding cannot be found or the codec doesn't support an incremental encoder. - .. versionadded:: 2.5 - .. function:: getincrementaldecoder(encoding) @@ -129,8 +127,6 @@ Raises a :exc:`LookupError` in case the encoding cannot be found or the codec doesn't support an incremental decoder. - .. versionadded:: 2.5 - .. function:: getreader(encoding) @@ -245,8 +241,6 @@ *iterable*. This function is a generator. *errors* (as well as any other keyword argument) is passed through to the incremental encoder. - .. versionadded:: 2.5 - .. function:: iterdecode(iterable, encoding[, errors]) @@ -254,8 +248,6 @@ *iterable*. This function is a generator. *errors* (as well as any other keyword argument) is passed through to the incremental decoder. - .. versionadded:: 2.5 - The module also provides the following constants which are useful for reading and writing to platform dependent files: @@ -390,8 +382,6 @@ IncrementalEncoder Objects ^^^^^^^^^^^^^^^^^^^^^^^^^^ -.. versionadded:: 2.5 - The :class:`IncrementalEncoder` class is used for encoding an input in multiple steps. It defines the following methods which every incremental encoder must define in order to be compatible with the Python codec registry. @@ -447,16 +437,12 @@ marshaling/pickling the state and encoding the bytes of the resulting string into an integer). - .. versionadded:: 3.0 - .. method:: IncrementalEncoder.setstate(state) Set the state of the encoder to *state*. *state* must be an encoder state returned by :meth:`getstate`. - .. versionadded:: 3.0 - .. _incremental-decoder-objects: @@ -524,16 +510,12 @@ marshaling/pickling the info and encoding the bytes of the resulting string into an integer.) - .. versionadded:: 3.0 - .. method:: IncrementalDecoder.setstate(state) Set the state of the encoder to *state*. *state* must be a decoder state returned by :meth:`getstate`. - .. versionadded:: 3.0 - The :class:`StreamWriter` and :class:`StreamReader` classes provide generic working interfaces which can be used to implement new encoding submodules very easily. See :mod:`encodings.utf_8` for an example of how this is done. @@ -661,12 +643,6 @@ e.g. if optional encoding endings or state markers are available on the stream, these should be read too. - .. versionchanged:: 2.4 - *chars* argument added. - - .. versionchanged:: 2.4.2 - *firstline* argument added. - .. method:: StreamReader.readline([size[, keepends]]) @@ -677,9 +653,6 @@ If *keepends* is false line-endings will be stripped from the lines returned. - .. versionchanged:: 2.4 - *keepends* argument added. - .. method:: StreamReader.readlines([sizehint[, keepends]]) @@ -1157,9 +1130,6 @@ | | | | operand | +--------------------+---------+----------------+---------------------------+ -.. versionadded:: 2.3 - The ``idna`` and ``punycode`` encodings. - :mod:`encodings.idna` --- Internationalized Domain Names in Applications ------------------------------------------------------------------------ @@ -1168,8 +1138,6 @@ :synopsis: Internationalized Domain Names implementation .. moduleauthor:: Martin v. L?wis -.. versionadded:: 2.3 - This module implements :rfc:`3490` (Internationalized Domain Names in Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding @@ -1229,8 +1197,6 @@ :synopsis: UTF-8 codec with BOM signature .. moduleauthor:: Walter D?rwald -.. versionadded:: 2.5 - This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this is only done once (on the first write to the byte stream). For decoding an Modified: python/branches/py3k/Doc/library/collections.rst ============================================================================== --- python/branches/py3k/Doc/library/collections.rst (original) +++ python/branches/py3k/Doc/library/collections.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Raymond Hettinger -.. versionadded:: 2.4 - This module implements high-performance container datatypes. Currently, there are two datatypes, :class:`deque` and :class:`defaultdict`, and one datatype factory function, :func:`NamedTuple`. Python already @@ -21,12 +19,6 @@ Future editions of the standard library may include balanced trees and ordered dictionaries. -.. versionchanged:: 2.5 - Added :class:`defaultdict`. - -.. versionchanged:: 2.6 - Added :class:`NamedTuple`. - .. _deque-objects: @@ -49,11 +41,9 @@ ``pop(0)`` and ``insert(0, v)`` operations which change both the size and position of the underlying data representation. - .. versionadded:: 2.4 Deque objects support the following methods: - .. method:: deque.append(x) Add *x* to the right side of the deque. @@ -99,8 +89,6 @@ Removed the first occurrence of *value*. If not found, raises a :exc:`ValueError`. - .. versionadded:: 2.5 - .. method:: deque.rotate(n) @@ -256,12 +244,10 @@ as if they were passed to the :class:`dict` constructor, including keyword arguments. - .. versionadded:: 2.5 :class:`defaultdict` objects support the following method in addition to the standard :class:`dict` operations: - .. method:: defaultdict.__missing__(key) If the :attr:`default_factory` attribute is ``None``, this raises an @@ -372,8 +358,6 @@ helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__` method which lists the tuple contents in a ``name=value`` format. - .. versionadded:: 2.6 - The *fieldnames* are specified in a single string and are separated by spaces. Any valid Python identifier may be used for a field name. Modified: python/branches/py3k/Doc/library/configparser.rst ============================================================================== --- python/branches/py3k/Doc/library/configparser.rst (original) +++ python/branches/py3k/Doc/library/configparser.rst Sat Sep 1 15:51:09 2007 @@ -63,11 +63,6 @@ options within a section, and for the default values. This class does not support the magical interpolation behavior. - .. versionadded:: 2.3 - - .. versionchanged:: 2.6 - *dict_type* was added. - .. class:: ConfigParser([defaults]) @@ -94,8 +89,6 @@ .. % XXX Need to explain what's safer/more predictable about it. - .. versionadded:: 2.3 - .. exception:: NoSectionError @@ -131,16 +124,12 @@ Exception raised when an option referenced from a value does not exist. Subclass of :exc:`InterpolationError`. - .. versionadded:: 2.3 - .. exception:: InterpolationSyntaxError Exception raised when the source text into which substitutions are made does not conform to the required syntax. Subclass of :exc:`InterpolationError`. - .. versionadded:: 2.3 - .. exception:: MissingSectionHeaderError @@ -206,8 +195,6 @@ If the given section exists, and contains the given option, return :const:`True`; otherwise return :const:`False`. - .. versionadded:: 1.6 - .. method:: RawConfigParser.read(filenames) @@ -229,9 +216,6 @@ config.readfp(open('defaults.cfg')) config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')]) - .. versionchanged:: 2.4 - Returns list of successfully parsed filenames. - .. method:: RawConfigParser.readfp(fp[, filename]) @@ -281,16 +265,12 @@ true) for *internal* storage of non-string values, full functionality (including interpolation and output to files) can only be achieved using string values. - .. versionadded:: 1.6 - .. method:: RawConfigParser.write(fileobject) Write a representation of the configuration to the specified file object. This representation can be parsed by a future :meth:`read` call. - .. versionadded:: 1.6 - .. method:: RawConfigParser.remove_option(section, option) @@ -298,8 +278,6 @@ not exist, raise :exc:`NoSectionError`. If the option existed to be removed, return :const:`True`; otherwise return :const:`False`. - .. versionadded:: 1.6 - .. method:: RawConfigParser.remove_section(section) @@ -339,8 +317,6 @@ Return a list of ``(name, value)`` pairs for each option in the given *section*. Optional arguments have the same meaning as for the :meth:`get` method. - .. versionadded:: 2.3 - .. _safeconfigparser-objects: @@ -357,5 +333,3 @@ otherwise raise :exc:`NoSectionError`. *value* must be a string (:class:`str` or :class:`unicode`); if not, :exc:`TypeError` is raised. - .. versionadded:: 2.4 - Modified: python/branches/py3k/Doc/library/constants.rst ============================================================================== --- python/branches/py3k/Doc/library/constants.rst (original) +++ python/branches/py3k/Doc/library/constants.rst Sat Sep 1 15:51:09 2007 @@ -5,19 +5,17 @@ A small number of constants live in the built-in namespace. They are: +.. XXX False, True, None are keywords too + .. data:: False The false value of the :class:`bool` type. - .. versionadded:: 2.3 - .. data:: True The true value of the :class:`bool` type. - .. versionadded:: 2.3 - .. data:: None Modified: python/branches/py3k/Doc/library/contextlib.rst ============================================================================== --- python/branches/py3k/Doc/library/contextlib.rst (original) +++ python/branches/py3k/Doc/library/contextlib.rst Sat Sep 1 15:51:09 2007 @@ -6,8 +6,6 @@ :synopsis: Utilities for with-statement contexts. -.. versionadded:: 2.5 - This module provides utilities for common tasks involving the :keyword:`with` statement. For more information see also :ref:`typecontextmanager` and :ref:`context-managers`. Modified: python/branches/py3k/Doc/library/cookie.rst ============================================================================== --- python/branches/py3k/Doc/library/cookie.rst (original) +++ python/branches/py3k/Doc/library/cookie.rst Sat Sep 1 15:51:09 2007 @@ -110,10 +110,6 @@ to join the headers together, and is by default the combination ``'\r\n'`` (CRLF). - .. versionchanged:: 2.5 - The default separator has been changed from ``'\n'`` to match the cookie - specification. - .. method:: BaseCookie.js_output([attrs]) Modified: python/branches/py3k/Doc/library/cookielib.rst ============================================================================== --- python/branches/py3k/Doc/library/cookielib.rst (original) +++ python/branches/py3k/Doc/library/cookielib.rst Sat Sep 1 15:51:09 2007 @@ -8,10 +8,6 @@ .. sectionauthor:: John J. Lee -.. versionadded:: 2.4 - - - The :mod:`cookielib` module defines classes for automatic handling of HTTP cookies. It is useful for accessing web sites that require small pieces of data -- :dfn:`cookies` -- to be set on the client machine by an HTTP response from a @@ -517,19 +513,17 @@ case RFC 2109 cookies are downgraded if and only if RFC 2965 handling is turned off. Therefore, RFC 2109 cookies are downgraded by default. - .. versionadded:: 2.5 General strictness switches: - .. attribute:: DefaultCookiePolicy.strict_domain Don't allow sites to set two-component domains with country-code top-level domains like ``.co.uk``, ``.gov.uk``, ``.co.nz``.etc. This is far from perfect and isn't guaranteed to work! -RFC 2965 protocol strictness switches: +RFC 2965 protocol strictness switches: .. attribute:: DefaultCookiePolicy.strict_rfc2965_unverifiable @@ -538,8 +532,8 @@ another site). If this is false, cookies are *never* blocked on the basis of verifiability -Netscape protocol strictness switches: +Netscape protocol strictness switches: .. attribute:: DefaultCookiePolicy.strict_ns_unverifiable @@ -683,8 +677,6 @@ :mod:`cookielib` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which case :attr:`version` is 0. - .. versionadded:: 2.5 - .. attribute:: Cookie.port_specified Modified: python/branches/py3k/Doc/library/copy.rst ============================================================================== --- python/branches/py3k/Doc/library/copy.rst (original) +++ python/branches/py3k/Doc/library/copy.rst Sat Sep 1 15:51:09 2007 @@ -54,9 +54,6 @@ classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the :mod:`pickle` module. -.. versionchanged:: 2.5 - Added copying functions. - .. index:: module: pickle Classes can use the same interfaces to control copying that they use to control Modified: python/branches/py3k/Doc/library/csv.rst ============================================================================== --- python/branches/py3k/Doc/library/csv.rst (original) +++ python/branches/py3k/Doc/library/csv.rst Sat Sep 1 15:51:09 2007 @@ -7,8 +7,6 @@ .. sectionauthor:: Skip Montanaro -.. versionadded:: 2.3 - .. index:: single: csv pair: data; tabular @@ -77,14 +75,13 @@ All data read are returned as strings. No automatic data type conversion is performed. - .. versionchanged:: 2.5 - The parser is now stricter with respect to multi-line quoted fields. Previously, - if a line ended within a quoted field without a terminating newline character, a - newline would be inserted into the returned field. This behavior caused problems - when reading files which contained carriage return characters within fields. - The behavior was changed to return the field without inserting newlines. As a - consequence, if newlines embedded within fields are important, the input should - be split into lines in a manner which preserves the newline characters. + The parser is quite strict with respect to multi-line quoted fields. Previously, + if a line ended within a quoted field without a terminating newline character, a + newline would be inserted into the returned field. This behavior caused problems + when reading files which contained carriage return characters within fields. + The behavior was changed to return the field without inserting newlines. As a + consequence, if newlines embedded within fields are important, the input should + be split into lines in a manner which preserves the newline characters. .. function:: writer(csvfile[, dialect='excel'][, fmtparam]) @@ -138,11 +135,9 @@ Returns the current maximum field size allowed by the parser. If *new_limit* is given, this becomes the new limit. - .. versionadded:: 2.5 The :mod:`csv` module defines the following classes: - .. class:: DictReader(csvfile[, fieldnames=:const:None,[, restkey=:const:None[, restval=None[, dialect='excel'[, *args, **kwds]]]]]) Create an object which operates like a regular reader but maps the information @@ -352,7 +347,6 @@ The number of lines read from the source iterator. This is not the same as the number of records returned, as records can span multiple lines. - .. versionadded:: 2.5 Writer Objects Modified: python/branches/py3k/Doc/library/ctypes.rst ============================================================================== --- python/branches/py3k/Doc/library/ctypes.rst (original) +++ python/branches/py3k/Doc/library/ctypes.rst Sat Sep 1 15:51:09 2007 @@ -7,8 +7,6 @@ .. moduleauthor:: Thomas Heller -.. versionadded:: 2.5 - ``ctypes`` is a foreign function library for Python. It provides C compatible data types, and allows calling functions in dlls/shared libraries. It can be used to wrap these libraries in pure Python. @@ -2209,8 +2207,6 @@ can be True or False, and the constructor accepts any object that has a truth value. - .. versionadded:: 2.6 - .. class:: HRESULT Modified: python/branches/py3k/Doc/library/curses.ascii.rst ============================================================================== --- python/branches/py3k/Doc/library/curses.ascii.rst (original) +++ python/branches/py3k/Doc/library/curses.ascii.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Eric S. Raymond -.. versionadded:: 1.6 - The :mod:`curses.ascii` module supplies name constants for ASCII characters and functions to test membership in various ASCII character classes. The constants supplied are names for control characters as follows: Modified: python/branches/py3k/Doc/library/curses.rst ============================================================================== --- python/branches/py3k/Doc/library/curses.rst (original) +++ python/branches/py3k/Doc/library/curses.rst Sat Sep 1 15:51:09 2007 @@ -8,9 +8,6 @@ .. sectionauthor:: Eric Raymond -.. versionchanged:: 1.6 - Added support for the ``ncurses`` library and converted to a package. - The :mod:`curses` module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling. @@ -1520,8 +1517,6 @@ .. sectionauthor:: Eric Raymond -.. versionadded:: 1.6 - The :mod:`curses.textpad` module provides a :class:`Textbox` class that handles elementary text editing in a curses window, supporting a set of keybindings resembling those of Emacs (thus, also of Netscape Navigator, BBedit 6.x, @@ -1656,8 +1651,6 @@ .. sectionauthor:: Eric Raymond -.. versionadded:: 1.6 - This module supplies one function, :func:`wrapper`, which runs another function which should be the rest of your curses-using application. If the application raises an exception, :func:`wrapper` will restore the terminal to a sane state Modified: python/branches/py3k/Doc/library/datetime.rst ============================================================================== --- python/branches/py3k/Doc/library/datetime.rst (original) +++ python/branches/py3k/Doc/library/datetime.rst Sat Sep 1 15:51:09 2007 @@ -11,8 +11,6 @@ .. sectionauthor:: A.M. Kuchling -.. versionadded:: 2.3 - The :mod:`datetime` module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient member extraction for output @@ -604,7 +602,6 @@ can't be parsed by :func:`time.strptime` or if it returns a value which isn't a time tuple. - .. versionadded:: 2.5 Class attributes: Modified: python/branches/py3k/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k/Doc/library/decimal.rst (original) +++ python/branches/py3k/Doc/library/decimal.rst Sat Sep 1 15:51:09 2007 @@ -5,19 +5,14 @@ .. module:: decimal :synopsis: Implementation of the General Decimal Arithmetic Specification. - .. moduleauthor:: Eric Price .. moduleauthor:: Facundo Batista .. moduleauthor:: Raymond Hettinger .. moduleauthor:: Aahz .. moduleauthor:: Tim Peters - - .. sectionauthor:: Raymond D. Hettinger -.. versionadded:: 2.4 - The :mod:`decimal` module provides support for decimal floating point arithmetic. It offers several advantages over the :class:`float()` datatype: @@ -436,8 +431,6 @@ when exiting the with-statement. If no context is specified, a copy of the current context is used. - .. versionadded:: 2.5 - For example, the following code sets the current decimal precision to 42 places, performs a calculation, and then automatically restores the previous context:: Modified: python/branches/py3k/Doc/library/difflib.rst ============================================================================== --- python/branches/py3k/Doc/library/difflib.rst (original) +++ python/branches/py3k/Doc/library/difflib.rst Sat Sep 1 15:51:09 2007 @@ -10,9 +10,6 @@ .. % LaTeXification by Fred L. Drake, Jr. . -.. versionadded:: 2.1 - - .. class:: SequenceMatcher This is a flexible class for comparing pairs of sequences of any type, so long @@ -117,8 +114,6 @@ :file:`Tools/scripts/diff.py` is a command-line front-end to this class and contains a good example of its use. - .. versionadded:: 2.4 - .. function:: context_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm]) @@ -146,8 +141,6 @@ :file:`Tools/scripts/diff.py` is a command-line front-end for this function. - .. versionadded:: 2.3 - .. function:: get_close_matches(word, possibilities[, n][, cutoff]) @@ -263,8 +256,6 @@ :file:`Tools/scripts/diff.py` is a command-line front-end for this function. - .. versionadded:: 2.3 - .. function:: IS_LINE_JUNK(line) @@ -382,12 +373,6 @@ then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent triples always describe non-adjacent equal blocks. - .. % Explain why a dummy is used! - - .. versionchanged:: 2.5 - The guarantee that adjacent triples always describe non-adjacent blocks was - implemented. - :: >>> s = SequenceMatcher(None, "abxcd", "abcd") @@ -445,8 +430,6 @@ The groups are returned in the same format as :meth:`get_opcodes`. - .. versionadded:: 2.3 - .. method:: SequenceMatcher.ratio() Modified: python/branches/py3k/Doc/library/doctest.rst ============================================================================== --- python/branches/py3k/Doc/library/doctest.rst (original) +++ python/branches/py3k/Doc/library/doctest.rst Sat Sep 1 15:51:09 2007 @@ -290,9 +290,6 @@ Any classes found are recursively searched similarly, to test docstrings in their contained methods and nested classes. -.. versionchanged:: 2.4 - A "private name" concept is deprecated and no longer documented. - .. _doctest-finding-examples: @@ -305,10 +302,6 @@ don't believe tabs should mean that, too bad: don't use hard tabs, or write your own :class:`DocTestParser` class. -.. versionchanged:: 2.4 - Expanding tabs to spaces is new; previous versions tried to preserve hard tabs, - with confusing results. - :: >>> # comments are ignored @@ -338,10 +331,6 @@ blank line, put ```` in your doctest example each place a blank line is expected. - .. versionchanged:: 2.4 - ```` was added; there was no way to use expected output containing - empty lines in previous versions. - * Output to stdout is captured, but not output to stderr (exception tracebacks are captured via a different means). @@ -498,10 +487,6 @@ ^ SyntaxError: invalid syntax -.. versionchanged:: 2.4 - The ability to handle a multi-line exception detail, and the - :const:`IGNORE_EXCEPTION_DETAIL` doctest option, were added. - .. _doctest-options: @@ -663,7 +648,7 @@ is on a single line. This test also passes, and also requires a directive to do so:: - >>> print range(20) # doctest:+ELLIPSIS + >>> print range(20) # doctest: +ELLIPSIS [0, 1, ..., 18, 19] Multiple directives can be used on a single physical line, separated by commas:: @@ -692,17 +677,6 @@ functions that run doctests, establishing different defaults. In such cases, disabling an option via ``-`` in a directive can be useful. -.. versionchanged:: 2.4 - Constants :const:`DONT_ACCEPT_BLANKLINE`, :const:`NORMALIZE_WHITESPACE`, - :const:`ELLIPSIS`, :const:`IGNORE_EXCEPTION_DETAIL`, :const:`REPORT_UDIFF`, - :const:`REPORT_CDIFF`, :const:`REPORT_NDIFF`, - :const:`REPORT_ONLY_FIRST_FAILURE`, :const:`COMPARISON_FLAGS` and - :const:`REPORTING_FLAGS` were added; by default ```` in expected - output matches an empty line in actual output; and doctest directives were - added. - -.. versionchanged:: 2.5 - Constant :const:`SKIP` was added. There's also a way to register new option flag names, although this isn't useful unless you intend to extend :mod:`doctest` internals via subclassing: @@ -718,8 +692,6 @@ MY_FLAG = register_optionflag('MY_FLAG') - .. versionadded:: 2.4 - .. _doctest-warnings: @@ -868,11 +840,6 @@ Optional argument *encoding* specifies an encoding that should be used to convert the file to unicode. - .. versionadded:: 2.4 - - .. versionchanged:: 2.5 - The parameter *encoding* was added. - .. function:: testmod([m][, name][, globs][, verbose][, report][, optionflags][, extraglobs][, raise_on_error][, exclude_empty]) @@ -906,14 +873,6 @@ *raise_on_error*, and *globs* are the same as for function :func:`testfile` above, except that *globs* defaults to ``m.__dict__``. - .. versionchanged:: 2.3 - The parameter *optionflags* was added. - - .. versionchanged:: 2.4 - The parameters *extraglobs*, *raise_on_error* and *exclude_empty* were added. - - .. versionchanged:: 2.5 - The optional argument *isprivate*, deprecated in 2.4, was removed. There's also a function to run the doctests associated with a single object. This function is provided for backward compatibility. There are no plans to @@ -1031,14 +990,8 @@ Optional argument *encoding* specifies an encoding that should be used to convert the file to unicode. - .. versionadded:: 2.4 - - .. versionchanged:: 2.5 - The global ``__file__`` was added to the globals provided to doctests loaded - from a text file using :func:`DocFileSuite`. - - .. versionchanged:: 2.5 - The parameter *encoding* was added. + The global ``__file__`` is added to the globals provided to doctests loaded + from a text file using :func:`DocFileSuite`. .. function:: DocTestSuite([module][, globs][, extraglobs][, test_finder][, setUp][, tearDown][, checker]) @@ -1068,12 +1021,8 @@ Optional arguments *setUp*, *tearDown*, and *optionflags* are the same as for function :func:`DocFileSuite` above. - .. versionadded:: 2.3 + This function uses the same search technique as :func:`testmod`. - .. versionchanged:: 2.4 - The parameters *globs*, *extraglobs*, *test_finder*, *setUp*, *tearDown*, and - *optionflags* were added; this function now uses the same search technique as - :func:`testmod`. Under the covers, :func:`DocTestSuite` creates a :class:`unittest.TestSuite` out of :class:`doctest.DocTestCase` instances, and :class:`DocTestCase` is a @@ -1119,8 +1068,6 @@ The value of the :mod:`unittest` reporting flags in effect before the function was called is returned by the function. - .. versionadded:: 2.4 - .. _doctest-advanced-api: @@ -1181,7 +1128,6 @@ constructor arguments are used to initialize the member variables of the same names. - .. versionadded:: 2.4 :class:`DocTest` defines the following member variables. They are initialized by the constructor, and should not be modified directly. @@ -1239,7 +1185,6 @@ output. The constructor arguments are used to initialize the member variables of the same names. - .. versionadded:: 2.4 :class:`Example` defines the following member variables. They are initialized by the constructor, and should not be modified directly. @@ -1316,7 +1261,6 @@ If the optional argument *exclude_empty* is false, then :meth:`DocTestFinder.find` will include tests for objects with empty docstrings. - .. versionadded:: 2.4 :class:`DocTestFinder` defines the following method: @@ -1369,7 +1313,6 @@ A processing class used to extract interactive examples from a string, and use them to create a :class:`DocTest` object. - .. versionadded:: 2.4 :class:`DocTestParser` defines the following methods: @@ -1438,7 +1381,6 @@ runner compares expected output to actual output, and how it displays failures. For more information, see section :ref:`doctest-options`. - .. versionadded:: 2.4 :class:`DocTestParser` defines the following methods: @@ -1530,11 +1472,9 @@ if they match; and :meth:`output_difference`, which returns a string describing the differences between two outputs. - .. versionadded:: 2.4 :class:`OutputChecker` defines the following methods: - .. method:: OutputChecker.check_output(want, got, optionflags) Return ``True`` iff the actual output from an example (*got*) matches the @@ -1616,8 +1556,6 @@ (0, 3) >>> - .. versionchanged:: 2.4 - The ability to use :func:`pdb.set_trace` usefully inside doctests was added. Functions that convert doctests to Python code, and possibly run the synthesized code under the debugger: @@ -1656,8 +1594,6 @@ useful when you want to transform an interactive Python session into a Python script. - .. versionadded:: 2.4 - .. function:: testsource(module, name) @@ -1676,8 +1612,6 @@ prints a script version of function :func:`f`'s docstring, with doctests converted to code, and the rest placed in comments. - .. versionadded:: 2.3 - .. function:: debug(module, name[, pm]) @@ -1699,11 +1633,6 @@ specified, or is false, the script is run under the debugger from the start, via passing an appropriate :func:`exec` call to :func:`pdb.run`. - .. versionadded:: 2.3 - - .. versionchanged:: 2.4 - The *pm* argument was added. - .. function:: debug_src(src[, pm][, globs]) @@ -1718,7 +1647,6 @@ execution context. If not specified, or ``None``, an empty dictionary is used. If specified, a shallow copy of the dictionary is used. - .. versionadded:: 2.4 The :class:`DebugRunner` class, and the special exceptions it may raise, are of most interest to testing framework authors, and will only be sketched here. See Modified: python/branches/py3k/Doc/library/docxmlrpcserver.rst ============================================================================== --- python/branches/py3k/Doc/library/docxmlrpcserver.rst (original) +++ python/branches/py3k/Doc/library/docxmlrpcserver.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Brian Quinlan -.. versionadded:: 2.3 - The :mod:`DocXMLRPCServer` module extends the classes found in :mod:`SimpleXMLRPCServer` to serve HTML documentation in response to HTTP GET requests. Servers can either be free standing, using :class:`DocXMLRPCServer`, Modified: python/branches/py3k/Doc/library/dumbdbm.rst ============================================================================== --- python/branches/py3k/Doc/library/dumbdbm.rst (original) +++ python/branches/py3k/Doc/library/dumbdbm.rst Sat Sep 1 15:51:09 2007 @@ -43,9 +43,6 @@ database has to be created. It defaults to octal ``0666`` (and will be modified by the prevailing umask). - .. versionchanged:: 2.2 - The *mode* argument was ignored in earlier versions. - .. seealso:: Modified: python/branches/py3k/Doc/library/easydialogs.rst ============================================================================== --- python/branches/py3k/Doc/library/easydialogs.rst (original) +++ python/branches/py3k/Doc/library/easydialogs.rst Sat Sep 1 15:51:09 2007 @@ -96,8 +96,6 @@ chosen, the text of *cmdstr* will be appended to the command line as is, except that a trailing ``':'`` or ``'='`` (if present) will be trimmed off. - .. versionadded:: 2.0 - .. function:: AskFileForOpen( [message] [, typeList] [, defaultLocation] [, defaultOptionFlags] [, location] [, clientName] [, windowTitle] [, actionButtonLabel] [, cancelButtonLabel] [, preferenceKey] [, popupExtension] [, eventProc] [, previewProc] [, filterProc] [, wanted] ) @@ -150,9 +148,6 @@ progress bars are supported. The bar will be determinate if its maximum value is greater than zero; otherwise it will be indeterminate. -.. versionchanged:: 2.2 - Support for indeterminate-style progress bars was added. - The dialog is displayed immediately after creation. If the dialog's "Cancel" button is pressed, or if :kbd:`Cmd-.` or :kbd:`ESC` is typed, the dialog window is hidden and :exc:`KeyboardInterrupt` is raised (but note that this response Modified: python/branches/py3k/Doc/library/email.charset.rst ============================================================================== --- python/branches/py3k/Doc/library/email.charset.rst (original) +++ python/branches/py3k/Doc/library/email.charset.rst Sat Sep 1 15:51:09 2007 @@ -13,8 +13,6 @@ Import this class from the :mod:`email.charset` module. -.. versionadded:: 2.2.2 - .. class:: Charset([input_charset]) Modified: python/branches/py3k/Doc/library/email.errors.rst ============================================================================== --- python/branches/py3k/Doc/library/email.errors.rst (original) +++ python/branches/py3k/Doc/library/email.errors.rst Sat Sep 1 15:51:09 2007 @@ -66,9 +66,6 @@ All defect classes are subclassed from :class:`email.errors.MessageDefect`, but this class is *not* an exception! -.. versionadded:: 2.4 - All the defect classes were added. - * :class:`NoBoundaryInMultipartDefect` -- A message claimed to be a multipart, but had no :mimetype:`boundary` parameter. Modified: python/branches/py3k/Doc/library/email.generator.rst ============================================================================== --- python/branches/py3k/Doc/library/email.generator.rst (original) +++ python/branches/py3k/Doc/library/email.generator.rst Sat Sep 1 15:51:09 2007 @@ -61,16 +61,12 @@ Note that for subparts, no envelope header is ever printed. - .. versionadded:: 2.2.2 - .. method:: Generator.clone(fp) Return an independent clone of this :class:`Generator` instance with the exact same options. - .. versionadded:: 2.2.2 - .. method:: Generator.write(s) @@ -115,9 +111,3 @@ The default value for *fmt* is ``None``, meaning :: [Non-text (%(type)s) part of message omitted, filename %(filename)s] - - .. versionadded:: 2.2.2 - -.. versionchanged:: 2.5 - The previously deprecated method :meth:`__call__` was removed. - Modified: python/branches/py3k/Doc/library/email.header.rst ============================================================================== --- python/branches/py3k/Doc/library/email.header.rst (original) +++ python/branches/py3k/Doc/library/email.header.rst Sat Sep 1 15:51:09 2007 @@ -43,8 +43,6 @@ properly :rfc:`2047` encoded. MIME-aware mail readers would show this header using the embedded ISO-8859-1 character. -.. versionadded:: 2.2.2 - Here is the :class:`Header` class description: Modified: python/branches/py3k/Doc/library/email.message.rst ============================================================================== --- python/branches/py3k/Doc/library/email.message.rst (original) +++ python/branches/py3k/Doc/library/email.message.rst Sat Sep 1 15:51:09 2007 @@ -116,9 +116,6 @@ responsibility to ensure the payload invariants. Optional *charset* sets the message's default character set; see :meth:`set_charset` for details. - .. versionchanged:: 2.2.2 - *charset* argument added. - .. method:: Message.set_charset(charset) @@ -136,15 +133,11 @@ :mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will be added as needed. - .. versionadded:: 2.2.2 - .. method:: Message.get_charset() Return the :class:`Charset` instance associated with the message's payload. - .. versionadded:: 2.2.2 - The following methods implement a mapping-like interface for accessing the message's :rfc:`2822` headers. Note that there are some semantic differences between these methods and a normal mapping (i.e. dictionary) interface. For @@ -270,8 +263,6 @@ *_name*, retaining header order and field name case. If no matching header was found, a :exc:`KeyError` is raised. - .. versionadded:: 2.2.2 - .. method:: Message.get_content_type() @@ -288,24 +279,18 @@ has an invalid type specification, :rfc:`2045` mandates that the default type be :mimetype:`text/plain`. - .. versionadded:: 2.2.2 - .. method:: Message.get_content_maintype() Return the message's main content type. This is the :mimetype:`maintype` part of the string returned by :meth:`get_content_type`. - .. versionadded:: 2.2.2 - .. method:: Message.get_content_subtype() Return the message's sub-content type. This is the :mimetype:`subtype` part of the string returned by :meth:`get_content_type`. - .. versionadded:: 2.2.2 - .. method:: Message.get_default_type() @@ -314,8 +299,6 @@ :mimetype:`multipart/digest` containers. Such subparts have a default content type of :mimetype:`message/rfc822`. - .. versionadded:: 2.2.2 - .. method:: Message.set_default_type(ctype) @@ -323,8 +306,6 @@ or :mimetype:`message/rfc822`, although this is not enforced. The default content type is not stored in the :mailheader:`Content-Type` header. - .. versionadded:: 2.2.2 - .. method:: Message.get_params([failobj[, header[, unquote]]]) @@ -339,9 +320,6 @@ :mailheader:`Content-Type` header. Optional *header* is the header to search instead of :mailheader:`Content-Type`. - .. versionchanged:: 2.2.2 - *unquote* argument added. - .. method:: Message.get_param(param[, failobj[, header[, unquote]]]) @@ -371,9 +349,6 @@ In any case, the parameter value (either the returned string, or the ``VALUE`` item in the 3-tuple) is always unquoted, unless *unquote* is set to ``False``. - .. versionchanged:: 2.2.2 - *unquote* argument added, and 3-tuple return value possible. - .. method:: Message.set_param(param, value[, header[, requote[, charset[, language]]]]) @@ -391,8 +366,6 @@ :rfc:`2231`. Optional *language* specifies the RFC 2231 language, defaulting to the empty string. Both *charset* and *language* should be strings. - .. versionadded:: 2.2.2 - .. method:: Message.del_param(param[, header[, requote]]) @@ -402,8 +375,6 @@ (the default is ``True``). Optional *header* specifies an alternative to :mailheader:`Content-Type`. - .. versionadded:: 2.2.2 - .. method:: Message.set_type(type[, header][, requote]) @@ -419,8 +390,6 @@ :mailheader:`Content-Type` header is set a :mailheader:`MIME-Version` header is also added. - .. versionadded:: 2.2.2 - .. method:: Message.get_filename([failobj]) @@ -464,8 +433,6 @@ Note that this method differs from :meth:`get_charset` which returns the :class:`Charset` instance for the default encoding of the message body. - .. versionadded:: 2.2.2 - .. method:: Message.get_charsets([failobj]) @@ -499,10 +466,6 @@ text/plain message/rfc822 -.. versionchanged:: 2.5 - The previously deprecated methods :meth:`get_type`, :meth:`get_main_type`, and - :meth:`get_subtype` were removed. - :class:`Message` objects can also optionally contain two instance attributes, which can be used when generating the plain text of a MIME message. @@ -533,9 +496,8 @@ that it contains text that appears between the last boundary and the end of the message. - .. versionchanged:: 2.5 - You do not need to set the epilogue to the empty string in order for the - :class:`Generator` to print a newline at the end of the file. + You do not need to set the epilogue to the empty string in order for the + :class:`Generator` to print a newline at the end of the file. .. data:: defects @@ -543,6 +505,3 @@ The *defects* attribute contains a list of all the problems found when parsing this message. See :mod:`email.errors` for a detailed description of the possible parsing defects. - - .. versionadded:: 2.4 - Modified: python/branches/py3k/Doc/library/email.mime.rst ============================================================================== --- python/branches/py3k/Doc/library/email.mime.rst (original) +++ python/branches/py3k/Doc/library/email.mime.rst Sat Sep 1 15:51:09 2007 @@ -49,8 +49,6 @@ :mimetype:`multipart` messages. If :meth:`attach` is called, a :exc:`MultipartConversionError` exception is raised. - .. versionadded:: 2.2.2 - .. class:: MIMEMultipart([subtype[, boundary[, _subparts[, _params]]]]) @@ -74,8 +72,6 @@ the keyword arguments, or passed into the *_params* argument, which is a keyword dictionary. - .. versionadded:: 2.2.2 - .. class:: MIMEApplication(_data[, _subtype[, _encoder[, **_params]]]) @@ -96,8 +92,6 @@ *_params* are passed straight through to the base class constructor. - .. versionadded:: 2.5 - .. class:: MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]]) @@ -169,7 +163,3 @@ :class:`MIMENonMultipart` constructor; it defaults to ``us-ascii``. No guessing or encoding is performed on the text data. - .. versionchanged:: 2.4 - The previously deprecated *_encoding* argument has been removed. Encoding - happens implicitly based on the *_charset* argument. - Modified: python/branches/py3k/Doc/library/email.parser.rst ============================================================================== --- python/branches/py3k/Doc/library/email.parser.rst (original) +++ python/branches/py3k/Doc/library/email.parser.rst Sat Sep 1 15:51:09 2007 @@ -38,8 +38,6 @@ FeedParser API ^^^^^^^^^^^^^^ -.. versionadded:: 2.4 - The :class:`FeedParser`, imported from the :mod:`email.feedparser` module, provides an API that is conducive to incremental parsing of email messages, such as would be necessary when reading the text of an email message from a source @@ -113,12 +111,6 @@ effectively non-strict. You should simply stop passing a *strict* flag to the :class:`Parser` constructor. - .. versionchanged:: 2.2.2 - The *strict* flag was added. - - .. versionchanged:: 2.4 - The *strict* flag was deprecated. - The other public :class:`Parser` methods are: @@ -136,9 +128,6 @@ Optional *headersonly* is as with the :meth:`parse` method. - .. versionchanged:: 2.2.2 - The *headersonly* flag was added. - .. method:: Parser.parsestr(text[, headersonly]) @@ -150,8 +139,6 @@ reading the headers or not. The default is ``False``, meaning it parses the entire contents of the file. - .. versionchanged:: 2.2.2 - The *headersonly* flag was added. Since creating a message object structure from a string or a file object is such a common task, two functions are provided as a convenience. They are available @@ -164,9 +151,6 @@ ``Parser().parsestr(s)``. Optional *_class* and *strict* are interpreted as with the :class:`Parser` class constructor. - .. versionchanged:: 2.2.2 - The *strict* flag was added. - .. function:: message_from_file(fp[, _class[, strict]]) @@ -174,9 +158,6 @@ exactly equivalent to ``Parser().parse(fp)``. Optional *_class* and *strict* are interpreted as with the :class:`Parser` class constructor. - .. versionchanged:: 2.2.2 - The *strict* flag was added. - Here's an example of how you might use this at an interactive Python prompt:: >>> import email Modified: python/branches/py3k/Doc/library/email.rst ============================================================================== --- python/branches/py3k/Doc/library/email.rst (original) +++ python/branches/py3k/Doc/library/email.rst Sat Sep 1 15:51:09 2007 @@ -12,8 +12,6 @@ .. sectionauthor:: Barry A. Warsaw -.. versionadded:: 2.2 - The :mod:`email` package is a library for managing email messages, including MIME and other :rfc:`2822`\ -based message documents. It subsumes most of the functionality in several older standard modules such as :mod:`rfc822`, Modified: python/branches/py3k/Doc/library/email.util.rst ============================================================================== --- python/branches/py3k/Doc/library/email.util.rst (original) +++ python/branches/py3k/Doc/library/email.util.rst Sat Sep 1 15:51:09 2007 @@ -104,8 +104,6 @@ needed for some protocols (such as HTTP). This only applies when *localtime* is ``False``. - .. versionadded:: 2.4 - .. function:: make_msgid([idstring]) @@ -146,17 +144,6 @@ Decode parameters list according to :rfc:`2231`. *params* is a sequence of 2-tuples containing elements of the form ``(content-type, string-value)``. -.. versionchanged:: 2.4 - The :func:`dump_address_pair` function has been removed; use :func:`formataddr` - instead. - -.. versionchanged:: 2.4 - The :func:`decode` function has been removed; use the - :meth:`Header.decode_header` method instead. - -.. versionchanged:: 2.4 - The :func:`encode` function has been removed; use the :meth:`Header.encode` - method instead. .. rubric:: Footnotes Modified: python/branches/py3k/Doc/library/exceptions.rst ============================================================================== --- python/branches/py3k/Doc/library/exceptions.rst (original) +++ python/branches/py3k/Doc/library/exceptions.rst Sat Sep 1 15:51:09 2007 @@ -56,17 +56,12 @@ string when there were no arguments. All arguments are stored in :attr:`args` as a tuple. - .. versionadded:: 2.5 - .. exception:: Exception All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class. - .. versionchanged:: 2.5 - Changed to inherit from :exc:`BaseException`. - .. exception:: ArithmeticError @@ -91,8 +86,6 @@ :attr:`strerror` attribute (it is usually the associated error message). The tuple itself is also available on the :attr:`args` attribute. - .. versionadded:: 1.5.2 - When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the first two items are available as above, while the third item is available on the :attr:`filename` attribute. However, for backwards compatibility, the @@ -143,11 +136,6 @@ Raise when a generator's :meth:`close` method is called. - .. versionadded:: 2.5 - - .. versionchanged:: 3.0 - Changed to inherit from Exception instead of StandardError. - .. exception:: IOError @@ -189,9 +177,6 @@ accidentally caught by code that catches :exc:`Exception` and thus prevent the interpreter from exiting. - .. versionchanged:: 2.5 - Changed to inherit from :exc:`BaseException`. - .. exception:: MemoryError @@ -217,8 +202,6 @@ classes, abstract methods should raise this exception when they require derived classes to override the method. - .. versionadded:: 1.5.2 - .. exception:: OSError @@ -226,10 +209,6 @@ :mod:`os` module's ``os.error`` exception. See :exc:`EnvironmentError` above for a description of the possible associated values. - .. % xref for os module - - .. versionadded:: 1.5.2 - .. exception:: OverflowError @@ -247,9 +226,6 @@ after it has been garbage collected. For more information on weak references, see the :mod:`weakref` module. - .. versionadded:: 2.2 - Previously known as the :exc:`weakref.ReferenceError` exception. - .. exception:: RuntimeError @@ -264,11 +240,6 @@ Raised by builtin :func:`next` and an iterator's :meth:`__next__` method to signal that there are no further values. - .. versionadded:: 2.2 - - .. versionchanged:: 3.0 - Changed to inherit from Exception instead of StandardError. - .. exception:: SyntaxError @@ -320,9 +291,6 @@ that it is not accidentally caught by code that catches :exc:`Exception`. This allows the exception to properly propagate up and cause the interpreter to exit. - .. versionchanged:: 2.5 - Changed to inherit from :exc:`BaseException`. - .. exception:: TypeError @@ -336,40 +304,30 @@ no value has been bound to that variable. This is a subclass of :exc:`NameError`. - .. versionadded:: 2.0 - .. exception:: UnicodeError Raised when a Unicode-related encoding or decoding error occurs. It is a subclass of :exc:`ValueError`. - .. versionadded:: 2.0 - .. exception:: UnicodeEncodeError Raised when a Unicode-related error occurs during encoding. It is a subclass of :exc:`UnicodeError`. - .. versionadded:: 2.3 - .. exception:: UnicodeDecodeError Raised when a Unicode-related error occurs during decoding. It is a subclass of :exc:`UnicodeError`. - .. versionadded:: 2.3 - .. exception:: UnicodeTranslateError Raised when a Unicode-related error occurs during translating. It is a subclass of :exc:`UnicodeError`. - .. versionadded:: 2.3 - .. exception:: ValueError @@ -387,11 +345,6 @@ Platform API. The :attr:`errno` value maps the :attr:`winerror` value to corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`. - .. versionadded:: 2.0 - - .. versionchanged:: 2.5 - Previous versions put the :cfunc:`GetLastError` codes into :attr:`errno`. - .. exception:: ZeroDivisionError @@ -443,15 +396,11 @@ Base class for warnings about probable mistakes in module imports. - .. versionadded:: 2.5 - .. exception:: UnicodeWarning Base class for warnings related to Unicode. - .. versionadded:: 2.5 - The class hierarchy for built-in exceptions is: Modified: python/branches/py3k/Doc/library/fileinput.rst ============================================================================== --- python/branches/py3k/Doc/library/fileinput.rst (original) +++ python/branches/py3k/Doc/library/fileinput.rst Sat Sep 1 15:51:09 2007 @@ -53,8 +53,6 @@ during iteration. The parameters to this function will be passed along to the constructor of the :class:`FileInput` class. - .. versionchanged:: 2.5 - Added the *mode* and *openhook* parameters. The following functions use the global state created by :func:`fileinput.input`; if there is no active state, :exc:`RuntimeError` is raised. @@ -71,8 +69,6 @@ Return the integer "file descriptor" for the current file. When no file is opened (before the first line and between files), returns ``-1``. - .. versionadded:: 2.5 - .. function:: lineno() @@ -135,8 +131,6 @@ *filename* and *mode*, and returns an accordingly opened file-like object. You cannot use *inplace* and *openhook* together. - .. versionchanged:: 2.5 - Added the *mode* and *openhook* parameters. **Optional in-place filtering:** if the keyword argument ``inplace=1`` is passed to :func:`fileinput.input` or to the :class:`FileInput` constructor, the file is @@ -165,8 +159,6 @@ Usage example: ``fi = fileinput.FileInput(openhook=fileinput.hook_compressed)`` - .. versionadded:: 2.5 - .. function:: hook_encoded(encoding) @@ -181,5 +173,3 @@ With this hook, :class:`FileInput` might return Unicode strings depending on the specified *encoding*. - .. versionadded:: 2.5 - Modified: python/branches/py3k/Doc/library/fnmatch.rst ============================================================================== --- python/branches/py3k/Doc/library/fnmatch.rst (original) +++ python/branches/py3k/Doc/library/fnmatch.rst Sat Sep 1 15:51:09 2007 @@ -65,8 +65,6 @@ Return the subset of the list of *names* that match *pattern*. It is the same as ``[n for n in names if fnmatch(n, pattern)]``, but implemented more efficiently. - .. versionadded:: 2.2 - .. function:: translate(pattern) Modified: python/branches/py3k/Doc/library/ftplib.rst ============================================================================== --- python/branches/py3k/Doc/library/ftplib.rst (original) +++ python/branches/py3k/Doc/library/ftplib.rst Sat Sep 1 15:51:09 2007 @@ -46,9 +46,6 @@ specifies a timeout in seconds for the connection attempt (if is not specified, or passed as None, the global default timeout setting will be used). - .. versionchanged:: 2.6 - *timeout* was added. - .. data:: all_errors @@ -128,9 +125,6 @@ is used (the timeout that you passed when instantiating the class); if the object timeout is also None, the global default timeout setting will be used. - .. versionchanged:: 2.6 - *timeout* was added. - .. method:: FTP.getwelcome() @@ -203,9 +197,6 @@ read until EOF using its :meth:`read` method in blocks of size *blocksize* to provide the data to be stored. The *blocksize* argument defaults to 8192. - .. versionchanged:: 2.1 - default for *blocksize* added. - .. method:: FTP.storlines(command, file) Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Sat Sep 1 15:51:09 2007 @@ -12,8 +12,6 @@ .. index:: statement: import - module: ihooks - module: rexec module: imp .. note:: @@ -23,9 +21,9 @@ The function is invoked by the :keyword:`import` statement. It mainly exists so that you can replace it with another function that has a compatible - interface, in order to change the semantics of the :keyword:`import` statement. - For examples of why and how you would do this, see the standard library modules - :mod:`ihooks` and :mod:`rexec`. See also the built-in module :mod:`imp`, which + interface, in order to change the semantics of the :keyword:`import` + statement. For examples of why and how you would do this, see the standard + library module :mod:`ihooks`. See also the built-in module :mod:`imp`, which defines some useful operations out of which you can build your own :func:`__import__` function. @@ -64,12 +62,6 @@ the number of parent directories to search relative to the directory of the module calling :func:`__import__`. - .. versionchanged:: 2.5 - The level parameter was added. - - .. versionchanged:: 2.5 - Keyword support for parameters was added. - .. function:: abs(x) @@ -88,8 +80,6 @@ return False return True - .. versionadded:: 2.5 - .. function:: any(iterable) @@ -101,8 +91,6 @@ return True return False - .. versionadded:: 2.5 - .. function:: basestring() @@ -111,8 +99,6 @@ is an instance of :class:`str` (or a user-defined type inherited from :class:`basestring`). - .. versionadded:: 2.3 - .. function:: bin(x) @@ -120,8 +106,6 @@ expression. If *x* is not a Python :class:`int` object, it has to define an :meth:`__index__` method that returns an integer. - .. versionadded:: 3.0 - .. function:: bool([x]) @@ -133,11 +117,6 @@ .. index:: pair: Boolean; type - .. versionadded:: 2.2.1 - - .. versionchanged:: 2.3 - If no argument is given, this function returns :const:`False`. - .. function:: bytes([arg[, encoding[, errors]]]) @@ -199,11 +178,6 @@ For more information on class methods, consult the documentation on the standard type hierarchy in :ref:`types`. - .. versionadded:: 2.2 - - .. versionchanged:: 2.4 - Function decorator syntax added. - .. function:: cmp(x, y) @@ -340,9 +314,6 @@ *a*, if ``a % b`` is non-zero it has the same sign as *b*, and ``0 <= abs(a % b) < abs(b)``. - .. versionchanged:: 2.3 - Using :func:`divmod` with complex numbers is deprecated. - .. function:: enumerate(iterable) @@ -360,8 +331,6 @@ 2 Fall 3 Winter - .. versionadded:: 2.3 - .. function:: eval(expression[, globals[, locals]]) @@ -369,9 +338,6 @@ *globals* must be a dictionary. If provided, *locals* can be any mapping object. - .. versionchanged:: 2.4 - formerly *locals* was required to be a dictionary. - The *expression* argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the *globals* and *locals* dictionaries as global and local name space. If the *globals* dictionary is @@ -499,8 +465,6 @@ For other containers see the built in :class:`dict`, :class:`list`, and :class:`tuple` classes, and the :mod:`collections` module. - .. versionadded:: 2.4 - .. function:: getattr(object, name[, default]) @@ -543,8 +507,6 @@ topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated. - .. versionadded:: 2.2 - .. function:: hex(x) @@ -552,9 +514,6 @@ expression. If *x* is not a Python :class:`int` object, it has to define an :meth:`__index__` method that returns an integer. - .. versionchanged:: 2.4 - Formerly only returned an unsigned literal. - .. function:: id(object) @@ -590,9 +549,6 @@ accepted). If *classinfo* is not a type or tuple of types and such tuples, a :exc:`TypeError` exception is raised. - .. versionchanged:: 2.2 - Support for a tuple of type information was added. - .. function:: issubclass(class, classinfo) @@ -601,9 +557,6 @@ objects, in which case every entry in *classinfo* will be checked. In any other case, a :exc:`TypeError` exception is raised. - .. versionchanged:: 2.3 - Support for a tuple of type information was added. - .. function:: iter(o[, sentinel]) @@ -618,8 +571,6 @@ its :meth:`__next__` method; if the value returned is equal to *sentinel*, :exc:`StopIteration` will be raised, otherwise the value will be returned. - .. versionadded:: 2.2 - .. function:: len(s) @@ -668,18 +619,14 @@ the result is always a list. -.. function:: max(iterable[, args...][key]) +.. function:: max(iterable[, args...], *[, key]) With a single argument *iterable*, return the largest item of a non-empty iterable (such as a string, tuple or list). With more than one argument, return the largest of the arguments. - The optional *key* argument specifies a one-argument ordering function like that - used for :meth:`list.sort`. The *key* argument, if supplied, must be in keyword - form (for example, ``max(a,b,c,key=func)``). - - .. versionchanged:: 2.5 - Added support for the optional *key* argument. + The optional keyword-only *key* argument specifies a one-argument ordering + function like that used for :meth:`list.sort`. .. function:: memoryview(obj) @@ -689,18 +636,14 @@ XXX: To be documented. -.. function:: min(iterable[, args...][key]) +.. function:: min(iterable[, args...], *[, key]) With a single argument *iterable*, return the smallest item of a non-empty iterable (such as a string, tuple or list). With more than one argument, return the smallest of the arguments. - The optional *key* argument specifies a one-argument ordering function like that - used for :meth:`list.sort`. The *key* argument, if supplied, must be in keyword - form (for example, ``min(a,b,c,key=func)``). - - .. versionchanged:: 2.5 - Added support for the optional *key* argument. + The optional keyword-only *key* argument specifies a one-argument ordering + function like that used for :meth:`list.sort`. .. function:: next(iterator[, default]) @@ -713,19 +656,14 @@ .. function:: object() Return a new featureless object. :class:`object` is a base for all classes. - It has the methods that are common to all instances of Python classes. + It has the methods that are common to all instances of Python classes. This + function does not accept any arguments. .. note:: :class:`object` does *not* have a :attr:`__dict__`, so you can't assign arbitrary attributes to an instance of the :class:`object` class. - .. versionadded:: 2.2 - - .. versionchanged:: 2.3 - This function does not accept any arguments. Formerly, it accepted arguments but - ignored them. - .. function:: oct(x) @@ -733,9 +671,6 @@ expression. If *x* is not a Python :class:`int` object, it has to define an :meth:`__index__` method that returns an integer. - .. versionchanged:: 2.4 - Formerly only returned an unsigned literal. - .. function:: open(filename[, mode[, bufsize]]) @@ -792,9 +727,6 @@ See also the :mod:`fileinput` module. - .. versionchanged:: 2.5 - Restriction on first letter of mode string introduced. - .. function:: ord(c) @@ -860,11 +792,6 @@ turns the :meth:`voltage` method into a "getter" for a read-only attribute with the same name. - .. versionadded:: 2.2 - - .. versionchanged:: 2.5 - Use *fget*'s docstring if no *doc* given. - .. function:: range([start,] stop[, step]) @@ -909,8 +836,6 @@ protocol (the :meth:`__len__` method and the :meth:`__getitem__` method with integer arguments starting at ``0``). - .. versionadded:: 2.4 - .. function:: round(x[, n]) @@ -930,8 +855,6 @@ For other containers see the built in :class:`dict`, :class:`list`, and :class:`tuple` classes, and the :mod:`collections` module. - .. versionadded:: 2.4 - .. function:: setattr(object, name, value) @@ -980,8 +903,6 @@ multiple times for each list element while *key* and *reverse* touch each element only once. - .. versionadded:: 2.4 - .. function:: staticmethod(function) @@ -1006,11 +927,6 @@ For more information on static methods, consult the documentation on the standard type hierarchy in :ref:`types`. - .. versionadded:: 2.2 - - .. versionchanged:: 2.4 - Function decorator syntax added. - .. function:: str([object[, encoding[, errors]]]) @@ -1051,8 +967,6 @@ and are not allowed to be strings. The fast, correct way to concatenate a sequence of strings is by calling ``''.join(sequence)``. - .. versionadded:: 2.3 - .. function:: super(type[, object-or-type]) @@ -1074,8 +988,6 @@ Accordingly, :func:`super` is undefined for implicit lookups using statements or operators such as ``super(C, self)[name]``. - .. versionadded:: 2.2 - .. function:: tuple([iterable]) @@ -1121,8 +1033,6 @@ ... >>> X = type('X', (object,), dict(a=1)) - .. versionadded:: 2.2 - .. function:: vars([object]) @@ -1143,11 +1053,6 @@ sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list. - .. versionadded:: 2.0 - - .. versionchanged:: 2.4 - Formerly, :func:`zip` required at least one argument and ``zip()`` raised a - :exc:`TypeError` instead of returning an empty list. .. % --------------------------------------------------------------------------- Modified: python/branches/py3k/Doc/library/functools.rst ============================================================================== --- python/branches/py3k/Doc/library/functools.rst (original) +++ python/branches/py3k/Doc/library/functools.rst Sat Sep 1 15:51:09 2007 @@ -9,8 +9,6 @@ .. sectionauthor:: Peter Harris -.. versionadded:: 2.5 - The :mod:`functools` module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module. @@ -23,8 +21,6 @@ This is the same function as :func:`reduce`. It is made available in this module to allow writing code more forward-compatible with Python 3. - .. versionadded:: 2.6 - .. function:: partial(func[,*args][, **keywords]) Modified: python/branches/py3k/Doc/library/gc.rst ============================================================================== --- python/branches/py3k/Doc/library/gc.rst (original) +++ python/branches/py3k/Doc/library/gc.rst Sat Sep 1 15:51:09 2007 @@ -44,9 +44,6 @@ :exc:`ValueError` is raised if the generation number is invalid. The number of unreachable objects found is returned. - .. versionchanged:: 2.5 - The optional *generation* argument was added. - .. function:: set_debug(flags) @@ -65,8 +62,6 @@ Returns a list of all objects tracked by the collector, excluding the list returned. - .. versionadded:: 2.2 - .. function:: set_threshold(threshold0[, threshold1[, threshold2]]) @@ -93,8 +88,6 @@ Return the current collection counts as a tuple of ``(count0, count1, count2)``. - .. versionadded:: 2.5 - .. function:: get_threshold() @@ -119,8 +112,6 @@ invalid state. Avoid using :func:`get_referrers` for any purpose other than debugging. - .. versionadded:: 2.2 - .. function:: get_referents(*objs) @@ -132,12 +123,10 @@ be involved in a cycle. So, for example, if an integer is directly reachable from an argument, that integer object may or may not appear in the result list. - .. versionadded:: 2.3 The following variable is provided for read-only access (you can mutate its value but should not rebind it): - .. data:: garbage A list of objects which the collector found to be unreachable but could not be Modified: python/branches/py3k/Doc/library/getopt.rst ============================================================================== --- python/branches/py3k/Doc/library/getopt.rst (original) +++ python/branches/py3k/Doc/library/getopt.rst Sat Sep 1 15:51:09 2007 @@ -61,8 +61,6 @@ variable POSIXLY_CORRECT is set, then option processing stops as soon as a non-option argument is encountered. - .. versionadded:: 2.3 - .. exception:: GetoptError @@ -74,10 +72,7 @@ related option; if there is no specific option to which the exception relates, :attr:`opt` is an empty string. - .. versionchanged:: 1.6 - Introduced :exc:`GetoptError` as a synonym for :exc:`error`. - - +.. XXX deprecated? .. exception:: error Alias for :exc:`GetoptError`; for backward compatibility. Modified: python/branches/py3k/Doc/library/getpass.rst ============================================================================== --- python/branches/py3k/Doc/library/getpass.rst (original) +++ python/branches/py3k/Doc/library/getpass.rst Sat Sep 1 15:51:09 2007 @@ -22,9 +22,6 @@ Availability: Macintosh, Unix, Windows. - .. versionchanged:: 2.5 - The *stream* parameter was added. - .. function:: getuser() Modified: python/branches/py3k/Doc/library/gettext.rst ============================================================================== --- python/branches/py3k/Doc/library/gettext.rst (original) +++ python/branches/py3k/Doc/library/gettext.rst Sat Sep 1 15:51:09 2007 @@ -49,8 +49,6 @@ :func:`gettext` family of functions. If *codeset* is omitted, then the current binding is returned. - .. versionadded:: 2.4 - .. function:: textdomain([domain]) @@ -72,8 +70,6 @@ system encoding, if no other encoding was explicitly set with :func:`bind_textdomain_codeset`. - .. versionadded:: 2.4 - .. function:: dgettext(domain, message) @@ -86,8 +82,6 @@ system encoding, if no other encoding was explicitly set with :func:`bind_textdomain_codeset`. - .. versionadded:: 2.4 - .. function:: ngettext(singular, plural, n) @@ -102,8 +96,6 @@ syntax to be used in :file:`.po` files and the formulas for a variety of languages. - .. versionadded:: 2.3 - .. function:: lngettext(singular, plural, n) @@ -111,15 +103,11 @@ system encoding, if no other encoding was explicitly set with :func:`bind_textdomain_codeset`. - .. versionadded:: 2.4 - .. function:: dngettext(domain, singular, plural, n) Like :func:`ngettext`, but look the message up in the specified *domain*. - .. versionadded:: 2.3 - .. function:: ldngettext(domain, singular, plural, n) @@ -127,7 +115,6 @@ preferred system encoding, if no other encoding was explicitly set with :func:`bind_textdomain_codeset`. - .. versionadded:: 2.4 Note that GNU :program:`gettext` also defines a :func:`dcgettext` method, but this was deemed not useful and so it is currently unimplemented. @@ -199,9 +186,6 @@ *fallback* is false (which is the default), and returns a :class:`NullTranslations` instance if *fallback* is true. - .. versionchanged:: 2.4 - Added the *codeset* parameter. - .. function:: install(domain[, localedir[, unicode [, codeset[, names]]]]) @@ -223,12 +207,6 @@ builtin namespace, so it is easily accessible in all modules of your application. - .. versionchanged:: 2.4 - Added the *codeset* parameter. - - .. versionchanged:: 2.5 - Added the *names* parameter. - The :class:`NullTranslations` class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -275,8 +253,6 @@ If a fallback has been set, forward :meth:`lgettext` to the fallback. Otherwise, return the translated message. Overridden in derived classes. - .. versionadded:: 2.4 - .. method:: NullTranslations.ugettext(message) @@ -290,16 +266,12 @@ If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise, return the translated message. Overridden in derived classes. - .. versionadded:: 2.3 - .. method:: NullTranslations.lngettext(singular, plural, n) If a fallback has been set, forward :meth:`ngettext` to the fallback. Otherwise, return the translated message. Overridden in derived classes. - .. versionadded:: 2.4 - .. method:: NullTranslations.ungettext(singular, plural, n) @@ -307,8 +279,6 @@ Otherwise, return the translated message as a Unicode string. Overridden in derived classes. - .. versionadded:: 2.3 - .. method:: NullTranslations.info() @@ -325,16 +295,12 @@ Return the "protected" :attr:`_output_charset` variable, which defines the encoding used to return translated messages. - .. versionadded:: 2.4 - .. method:: NullTranslations.set_output_charset(charset) Change the "protected" :attr:`_output_charset` variable, which defines the encoding used to return translated messages. - .. versionadded:: 2.4 - .. method:: NullTranslations.install([unicode [, names]]) @@ -362,9 +328,6 @@ This puts :func:`_` only in the module's global namespace and so only affects calls within this module. - .. versionchanged:: 2.5 - Added the *names* parameter. - The :class:`GNUTranslations` class ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -415,8 +378,6 @@ system encoding, if no other encoding was explicitly set with :meth:`set_output_charset`. - .. versionadded:: 2.4 - .. method:: GNUTranslations.ugettext(message) @@ -437,8 +398,6 @@ request is forwarded to the fallback's :meth:`ngettext` method. Otherwise, when *n* is 1 *singular* is returned, and *plural* is returned in all other cases. - .. versionadded:: 2.3 - .. method:: GNUTranslations.lngettext(singular, plural, n) @@ -446,8 +405,6 @@ system encoding, if no other encoding was explicitly set with :meth:`set_output_charset`. - .. versionadded:: 2.4 - .. method:: GNUTranslations.ungettext(singular, plural, n) @@ -469,8 +426,6 @@ 'There are %(num)d files in this directory', n) % {'num': n} - .. versionadded:: 2.3 - Solaris message catalog support ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Modified: python/branches/py3k/Doc/library/glob.rst ============================================================================== --- python/branches/py3k/Doc/library/glob.rst (original) +++ python/branches/py3k/Doc/library/glob.rst Sat Sep 1 15:51:09 2007 @@ -31,7 +31,6 @@ Return an iterator which yields the same values as :func:`glob` without actually storing them all simultaneously. - .. versionadded:: 2.5 For example, consider a directory containing only the following files: :file:`1.gif`, :file:`2.txt`, and :file:`card.gif`. :func:`glob` will produce Modified: python/branches/py3k/Doc/library/hashlib.rst ============================================================================== --- python/branches/py3k/Doc/library/hashlib.rst (original) +++ python/branches/py3k/Doc/library/hashlib.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Gregory P. Smith -.. versionadded:: 2.5 - .. index:: single: message digest, MD5 single: secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512 Modified: python/branches/py3k/Doc/library/heapq.rst ============================================================================== --- python/branches/py3k/Doc/library/heapq.rst (original) +++ python/branches/py3k/Doc/library/heapq.rst Sat Sep 1 15:51:09 2007 @@ -11,8 +11,6 @@ .. % Theoretical explanation: -.. versionadded:: 2.3 - This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. @@ -99,8 +97,6 @@ not pull the data into memory all at once, and assumes that each of the input streams is already sorted (smallest to largest). - .. versionadded:: 2.6 - .. function:: nlargest(n, iterable[, key]) @@ -110,11 +106,6 @@ ``key=str.lower`` Equivalent to: ``sorted(iterable, key=key, reverse=True)[:n]`` - .. versionadded:: 2.4 - - .. versionchanged:: 2.5 - Added the optional *key* argument. - .. function:: nsmallest(n, iterable[, key]) @@ -123,10 +114,6 @@ used to extract a comparison key from each element in the iterable: ``key=str.lower`` Equivalent to: ``sorted(iterable, key=key)[:n]`` - .. versionadded:: 2.4 - - .. versionchanged:: 2.5 - Added the optional *key* argument. The latter two functions perform best for smaller values of *n*. For larger values, it is more efficient to use the :func:`sorted` function. Also, when Modified: python/branches/py3k/Doc/library/hmac.rst ============================================================================== --- python/branches/py3k/Doc/library/hmac.rst (original) +++ python/branches/py3k/Doc/library/hmac.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Gerhard H?ring -.. versionadded:: 2.2 - This module implements the HMAC algorithm as described by :rfc:`2104`. Modified: python/branches/py3k/Doc/library/hotshot.rst ============================================================================== --- python/branches/py3k/Doc/library/hotshot.rst (original) +++ python/branches/py3k/Doc/library/hotshot.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Anthony Baxter -.. versionadded:: 2.2 - This module provides a nicer interface to the :mod:`_hotshot` C module. Hotshot is a replacement for the existing :mod:`profile` module. As it's written mostly in C, it should result in a much smaller performance impact than the existing @@ -22,10 +20,6 @@ recommended to use :mod:`cProfile` instead. :mod:`hotshot` is not maintained and might be removed from the standard library in the future. -.. versionchanged:: 2.5 - the results should be more meaningful than in the past: the timing core - contained a critical bug. - .. warning:: The :mod:`hotshot` profiler does not yet work well with threads. It is useful to @@ -104,8 +98,6 @@ :synopsis: Statistical analysis for Hotshot -.. versionadded:: 2.2 - This module loads hotshot profiling data into the standard :mod:`pstats` Stats objects. Modified: python/branches/py3k/Doc/library/htmllib.rst ============================================================================== --- python/branches/py3k/Doc/library/htmllib.rst (original) +++ python/branches/py3k/Doc/library/htmllib.rst Sat Sep 1 15:51:09 2007 @@ -68,8 +68,6 @@ Exception raised by the :class:`HTMLParser` class when it encounters an error while parsing. - .. versionadded:: 2.4 - .. seealso:: @@ -175,12 +173,8 @@ A dictionary that maps HTML entity names to the Unicode codepoints. - .. versionadded:: 2.3 - .. data:: codepoint2name A dictionary that maps Unicode codepoints to HTML entity names. - .. versionadded:: 2.3 - Modified: python/branches/py3k/Doc/library/htmlparser.rst ============================================================================== --- python/branches/py3k/Doc/library/htmlparser.rst (original) +++ python/branches/py3k/Doc/library/htmlparser.rst Sat Sep 1 15:51:09 2007 @@ -6,11 +6,7 @@ :synopsis: A simple parser that can handle HTML and XHTML. -.. versionadded:: 2.2 - -.. index:: - single: HTML - single: XHTML +.. index:: HTML, XHTML This module defines a class :class:`HTMLParser` which serves as the basis for parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML. @@ -91,9 +87,8 @@ HREF="http://www.cwi.nl/">``, this method would be called as ``handle_starttag('a', [('href', 'http://www.cwi.nl/')])``. - .. versionchanged:: 2.6 - All entity references from htmlentitydefs are now replaced in the attribute - values. + All entity references from htmlentitydefs are replaced in the attribute + values. .. method:: HTMLParser.handle_startendtag(tag, attrs) Modified: python/branches/py3k/Doc/library/httplib.rst ============================================================================== --- python/branches/py3k/Doc/library/httplib.rst (original) +++ python/branches/py3k/Doc/library/httplib.rst Sat Sep 1 15:51:09 2007 @@ -44,11 +44,6 @@ >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80) >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80, timeout=10) - .. versionadded:: 2.0 - - .. versionchanged:: 2.6 - *timeout* was added. - .. class:: HTTPSConnection(host[, port[, key_file[, cert_file[, strict[, timeout]]]]]) @@ -61,18 +56,12 @@ This does not do any certificate verification! - .. versionadded:: 2.0 - - .. versionchanged:: 2.6 - *timeout* was added. - .. class:: HTTPResponse(sock[, debuglevel=0][, strict=0]) Class whose instances are returned upon successful connection. Not instantiated directly by user. - .. versionadded:: 2.0 The following exceptions are raised as appropriate: @@ -82,87 +71,63 @@ The base class of the other exceptions in this module. It is a subclass of :exc:`Exception`. - .. versionadded:: 2.0 - .. exception:: NotConnected A subclass of :exc:`HTTPException`. - .. versionadded:: 2.0 - .. exception:: InvalidURL A subclass of :exc:`HTTPException`, raised if a port is given and is either non-numeric or empty. - .. versionadded:: 2.3 - .. exception:: UnknownProtocol A subclass of :exc:`HTTPException`. - .. versionadded:: 2.0 - .. exception:: UnknownTransferEncoding A subclass of :exc:`HTTPException`. - .. versionadded:: 2.0 - .. exception:: UnimplementedFileMode A subclass of :exc:`HTTPException`. - .. versionadded:: 2.0 - .. exception:: IncompleteRead A subclass of :exc:`HTTPException`. - .. versionadded:: 2.0 - .. exception:: ImproperConnectionState A subclass of :exc:`HTTPException`. - .. versionadded:: 2.0 - .. exception:: CannotSendRequest A subclass of :exc:`ImproperConnectionState`. - .. versionadded:: 2.0 - .. exception:: CannotSendHeader A subclass of :exc:`ImproperConnectionState`. - .. versionadded:: 2.0 - .. exception:: ResponseNotReady A subclass of :exc:`ImproperConnectionState`. - .. versionadded:: 2.0 - .. exception:: BadStatusLine A subclass of :exc:`HTTPException`. Raised if a server responds with a HTTP status code that we don't understand. - .. versionadded:: 2.0 - The constants defined in this module are: @@ -375,8 +340,6 @@ Example: ``httplib.responses[httplib.NOT_FOUND]`` is ``'Not Found'``. - .. versionadded:: 2.5 - .. _httpconnection-objects: @@ -396,9 +359,6 @@ Content-Length is automatically set to the correct value. The *headers* argument should be a mapping of extra HTTP headers to send with the request. - .. versionchanged:: 2.6 - *body* can be a file object. - .. method:: HTTPConnection.getresponse() @@ -439,9 +399,6 @@ content encodings), specify *skip_host* or *skip_accept_encoding* with non-False values. - .. versionchanged:: 2.4 - *skip_accept_encoding* argument added. - .. method:: HTTPConnection.putheader(header, argument[, ...]) @@ -486,8 +443,6 @@ Return a list of (header, value) tuples. - .. versionadded:: 2.4 - .. attribute:: HTTPResponse.msg Modified: python/branches/py3k/Doc/library/imaplib.rst ============================================================================== --- python/branches/py3k/Doc/library/imaplib.rst (original) +++ python/branches/py3k/Doc/library/imaplib.rst Sat Sep 1 15:51:09 2007 @@ -82,7 +82,6 @@ ``stdin/stdout`` file descriptors created by passing *command* to ``os.popen2()``. - .. versionadded:: 2.3 The following utility functions are defined: @@ -207,8 +206,6 @@ Delete the ACLs (remove any rights) set for who on mailbox. - .. versionadded:: 2.4 - .. method:: IMAP4.expunge() @@ -235,24 +232,18 @@ Retrieve the specified ``ANNOTATION``\ s for *mailbox*. The method is non-standard, but is supported by the ``Cyrus`` server. - .. versionadded:: 2.5 - .. method:: IMAP4.getquota(root) Get the ``quota`` *root*'s resource usage and limits. This method is part of the IMAP4 QUOTA extension defined in rfc2087. - .. versionadded:: 2.3 - .. method:: IMAP4.getquotaroot(mailbox) Get the list of ``quota`` ``roots`` for the named *mailbox*. This method is part of the IMAP4 QUOTA extension defined in rfc2087. - .. versionadded:: 2.3 - .. method:: IMAP4.list([directory[, pattern]]) @@ -272,8 +263,6 @@ the password. Will only work if the server ``CAPABILITY`` response includes the phrase ``AUTH=CRAM-MD5``. - .. versionadded:: 2.3 - .. method:: IMAP4.logout() @@ -291,15 +280,11 @@ Show my ACLs for a mailbox (i.e. the rights that I have on mailbox). - .. versionadded:: 2.4 - .. method:: IMAP4.namespace() Returns IMAP namespaces as defined in RFC2342. - .. versionadded:: 2.3 - .. method:: IMAP4.noop() @@ -324,8 +309,6 @@ Assume authentication as *user*. Allows an authorised administrator to proxy into any user's mailbox. - .. versionadded:: 2.3 - .. method:: IMAP4.read(size) @@ -393,16 +376,12 @@ Set ``ANNOTATION``\ s for *mailbox*. The method is non-standard, but is supported by the ``Cyrus`` server. - .. versionadded:: 2.5 - .. method:: IMAP4.setquota(root, limits) Set the ``quota`` *root*'s resource *limits*. This method is part of the IMAP4 QUOTA extension defined in rfc2087. - .. versionadded:: 2.3 - .. method:: IMAP4.shutdown() @@ -476,8 +455,6 @@ This is an ``IMAP4rev1`` extension command. - .. versionadded:: 2.4 - .. method:: IMAP4.uid(command, arg[, ...]) Modified: python/branches/py3k/Doc/library/imghdr.rst ============================================================================== --- python/branches/py3k/Doc/library/imghdr.rst (original) +++ python/branches/py3k/Doc/library/imghdr.rst Sat Sep 1 15:51:09 2007 @@ -47,9 +47,6 @@ | ``'png'`` | Portable Network Graphics | +------------+-----------------------------------+ -.. versionadded:: 2.5 - Exif detection. - You can extend the list of file types :mod:`imghdr` can recognize by appending to this variable: Modified: python/branches/py3k/Doc/library/imp.rst ============================================================================== --- python/branches/py3k/Doc/library/imp.rst (original) +++ python/branches/py3k/Doc/library/imp.rst Sat Sep 1 15:51:09 2007 @@ -116,15 +116,12 @@ be used by import hooks to ensure thread-safety when importing modules. On platforms without threads, this function does nothing. - .. versionadded:: 2.3 - .. function:: release_lock() Release the interpreter's import lock. On platforms without threads, this function does nothing. - .. versionadded:: 2.3 The following constants with integer values, defined in this module, are used to indicate the search result of :func:`find_module`. @@ -265,8 +262,6 @@ This method always returns ``None``, indicating that the requested module could not be found. - .. versionadded:: 2.5 - .. _examples-imp: Modified: python/branches/py3k/Doc/library/imputil.rst ============================================================================== --- python/branches/py3k/Doc/library/imputil.rst (original) +++ python/branches/py3k/Doc/library/imputil.rst Sat Sep 1 15:51:09 2007 @@ -1,6 +1,6 @@ :mod:`imputil` --- Import utilities -===================================================== +=================================== .. module:: imputil :synopsis: Manage and augment the import process. Modified: python/branches/py3k/Doc/library/inspect.rst ============================================================================== --- python/branches/py3k/Doc/library/inspect.rst (original) +++ python/branches/py3k/Doc/library/inspect.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Ka-Ping Yee -.. versionadded:: 2.1 - The :mod:`inspect` module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you @@ -33,156 +31,150 @@ They also help you determine when you can expect to find the following special attributes: -+-----------+-----------------+---------------------------+-------+ -| Type | Attribute | Description | Notes | -+===========+=================+===========================+=======+ -| module | __doc__ | documentation string | | -+-----------+-----------------+---------------------------+-------+ -| | __file__ | filename (missing for | | -| | | built-in modules) | | -+-----------+-----------------+---------------------------+-------+ -| class | __doc__ | documentation string | | -+-----------+-----------------+---------------------------+-------+ -| | __module__ | name of module in which | | -| | | this class was defined | | -+-----------+-----------------+---------------------------+-------+ -| method | __doc__ | documentation string | | -+-----------+-----------------+---------------------------+-------+ -| | __name__ | name with which this | | -| | | method was defined | | -+-----------+-----------------+---------------------------+-------+ -| | im_class | class object that asked | \(1) | -| | | for this method | | -+-----------+-----------------+---------------------------+-------+ -| | im_func | function object | | -| | | containing implementation | | -| | | of method | | -+-----------+-----------------+---------------------------+-------+ -| | im_self | instance to which this | | -| | | method is bound, or | | -| | | ``None`` | | -+-----------+-----------------+---------------------------+-------+ -| function | __doc__ | documentation string | | -+-----------+-----------------+---------------------------+-------+ -| | __name__ | name with which this | | -| | | function was defined | | -+-----------+-----------------+---------------------------+-------+ -| | __code__ | code object containing | | -| | | compiled function | | -| | | bytecode | | -+-----------+-----------------+---------------------------+-------+ -| | __defaults__ | tuple of any default | | -| | | values for arguments | | -+-----------+-----------------+---------------------------+-------+ -| | __globals__ | global namespace in which | | -| | | this function was defined | | -+-----------+-----------------+---------------------------+-------+ -| traceback | tb_frame | frame object at this | | -| | | level | | -+-----------+-----------------+---------------------------+-------+ -| | tb_lasti | index of last attempted | | -| | | instruction in bytecode | | -+-----------+-----------------+---------------------------+-------+ -| | tb_lineno | current line number in | | -| | | Python source code | | -+-----------+-----------------+---------------------------+-------+ -| | tb_next | next inner traceback | | -| | | object (called by this | | -| | | level) | | -+-----------+-----------------+---------------------------+-------+ -| frame | f_back | next outer frame object | | -| | | (this frame's caller) | | -+-----------+-----------------+---------------------------+-------+ -| | f_builtins | built-in namespace seen | | -| | | by this frame | | -+-----------+-----------------+---------------------------+-------+ -| | f_code | code object being | | -| | | executed in this frame | | -+-----------+-----------------+---------------------------+-------+ -| | f_exc_traceback | traceback if raised in | | -| | | this frame, or ``None`` | | -+-----------+-----------------+---------------------------+-------+ -| | f_exc_type | exception type if raised | | -| | | in this frame, or | | -| | | ``None`` | | -+-----------+-----------------+---------------------------+-------+ -| | f_exc_value | exception value if raised | | -| | | in this frame, or | | -| | | ``None`` | | -+-----------+-----------------+---------------------------+-------+ -| | f_globals | global namespace seen by | | -| | | this frame | | -+-----------+-----------------+---------------------------+-------+ -| | f_lasti | index of last attempted | | -| | | instruction in bytecode | | -+-----------+-----------------+---------------------------+-------+ -| | f_lineno | current line number in | | -| | | Python source code | | -+-----------+-----------------+---------------------------+-------+ -| | f_locals | local namespace seen by | | -| | | this frame | | -+-----------+-----------------+---------------------------+-------+ -| | f_restricted | 0 or 1 if frame is in | | -| | | restricted execution mode | | -+-----------+-----------------+---------------------------+-------+ -| | f_trace | tracing function for this | | -| | | frame, or ``None`` | | -+-----------+-----------------+---------------------------+-------+ -| code | co_argcount | number of arguments (not | | -| | | including \* or \*\* | | -| | | args) | | -+-----------+-----------------+---------------------------+-------+ -| | co_code | string of raw compiled | | -| | | bytecode | | -+-----------+-----------------+---------------------------+-------+ -| | co_consts | tuple of constants used | | -| | | in the bytecode | | -+-----------+-----------------+---------------------------+-------+ -| | co_filename | name of file in which | | -| | | this code object was | | -| | | created | | -+-----------+-----------------+---------------------------+-------+ -| | co_firstlineno | number of first line in | | -| | | Python source code | | -+-----------+-----------------+---------------------------+-------+ -| | co_flags | bitmap: 1=optimized ``|`` | | -| | | 2=newlocals ``|`` 4=\*arg | | -| | | ``|`` 8=\*\*arg | | -+-----------+-----------------+---------------------------+-------+ -| | co_lnotab | encoded mapping of line | | -| | | numbers to bytecode | | -| | | indices | | -+-----------+-----------------+---------------------------+-------+ -| | co_name | name with which this code | | -| | | object was defined | | -+-----------+-----------------+---------------------------+-------+ -| | co_names | tuple of names of local | | -| | | variables | | -+-----------+-----------------+---------------------------+-------+ -| | co_nlocals | number of local variables | | -+-----------+-----------------+---------------------------+-------+ -| | co_stacksize | virtual machine stack | | -| | | space required | | -+-----------+-----------------+---------------------------+-------+ -| | co_varnames | tuple of names of | | -| | | arguments and local | | -| | | variables | | -+-----------+-----------------+---------------------------+-------+ -| builtin | __doc__ | documentation string | | -+-----------+-----------------+---------------------------+-------+ -| | __name__ | original name of this | | -| | | function or method | | -+-----------+-----------------+---------------------------+-------+ -| | __self__ | instance to which a | | -| | | method is bound, or | | -| | | ``None`` | | -+-----------+-----------------+---------------------------+-------+ - -Note: - -(1) - .. versionchanged:: 2.2 - :attr:`im_class` used to refer to the class that defined the method. ++-----------+-----------------+---------------------------+ +| Type | Attribute | Description | ++===========+=================+===========================+ +| module | __doc__ | documentation string | ++-----------+-----------------+---------------------------+ +| | __file__ | filename (missing for | +| | | built-in modules) | ++-----------+-----------------+---------------------------+ +| class | __doc__ | documentation string | ++-----------+-----------------+---------------------------+ +| | __module__ | name of module in which | +| | | this class was defined | ++-----------+-----------------+---------------------------+ +| method | __doc__ | documentation string | ++-----------+-----------------+---------------------------+ +| | __name__ | name with which this | +| | | method was defined | ++-----------+-----------------+---------------------------+ +| | im_class | class object that asked | +| | | for this method | ++-----------+-----------------+---------------------------+ +| | im_func | function object | +| | | containing implementation | +| | | of method | ++-----------+-----------------+---------------------------+ +| | im_self | instance to which this | +| | | method is bound, or | +| | | ``None`` | ++-----------+-----------------+---------------------------+ +| function | __doc__ | documentation string | ++-----------+-----------------+---------------------------+ +| | __name__ | name with which this | +| | | function was defined | ++-----------+-----------------+---------------------------+ +| | __code__ | code object containing | +| | | compiled function | +| | | bytecode | ++-----------+-----------------+---------------------------+ +| | __defaults__ | tuple of any default | +| | | values for arguments | ++-----------+-----------------+---------------------------+ +| | __globals__ | global namespace in which | +| | | this function was defined | ++-----------+-----------------+---------------------------+ +| traceback | tb_frame | frame object at this | +| | | level | ++-----------+-----------------+---------------------------+ +| | tb_lasti | index of last attempted | +| | | instruction in bytecode | ++-----------+-----------------+---------------------------+ +| | tb_lineno | current line number in | +| | | Python source code | ++-----------+-----------------+---------------------------+ +| | tb_next | next inner traceback | +| | | object (called by this | +| | | level) | ++-----------+-----------------+---------------------------+ +| frame | f_back | next outer frame object | +| | | (this frame's caller) | ++-----------+-----------------+---------------------------+ +| | f_builtins | built-in namespace seen | +| | | by this frame | ++-----------+-----------------+---------------------------+ +| | f_code | code object being | +| | | executed in this frame | ++-----------+-----------------+---------------------------+ +| | f_exc_traceback | traceback if raised in | +| | | this frame, or ``None`` | ++-----------+-----------------+---------------------------+ +| | f_exc_type | exception type if raised | +| | | in this frame, or | +| | | ``None`` | ++-----------+-----------------+---------------------------+ +| | f_exc_value | exception value if raised | +| | | in this frame, or | +| | | ``None`` | ++-----------+-----------------+---------------------------+ +| | f_globals | global namespace seen by | +| | | this frame | ++-----------+-----------------+---------------------------+ +| | f_lasti | index of last attempted | +| | | instruction in bytecode | ++-----------+-----------------+---------------------------+ +| | f_lineno | current line number in | +| | | Python source code | ++-----------+-----------------+---------------------------+ +| | f_locals | local namespace seen by | +| | | this frame | ++-----------+-----------------+---------------------------+ +| | f_restricted | 0 or 1 if frame is in | +| | | restricted execution mode | ++-----------+-----------------+---------------------------+ +| | f_trace | tracing function for this | +| | | frame, or ``None`` | ++-----------+-----------------+---------------------------+ +| code | co_argcount | number of arguments (not | +| | | including \* or \*\* | +| | | args) | ++-----------+-----------------+---------------------------+ +| | co_code | string of raw compiled | +| | | bytecode | ++-----------+-----------------+---------------------------+ +| | co_consts | tuple of constants used | +| | | in the bytecode | ++-----------+-----------------+---------------------------+ +| | co_filename | name of file in which | +| | | this code object was | +| | | created | ++-----------+-----------------+---------------------------+ +| | co_firstlineno | number of first line in | +| | | Python source code | ++-----------+-----------------+---------------------------+ +| | co_flags | bitmap: 1=optimized ``|`` | +| | | 2=newlocals ``|`` 4=\*arg | +| | | ``|`` 8=\*\*arg | ++-----------+-----------------+---------------------------+ +| | co_lnotab | encoded mapping of line | +| | | numbers to bytecode | +| | | indices | ++-----------+-----------------+---------------------------+ +| | co_name | name with which this code | +| | | object was defined | ++-----------+-----------------+---------------------------+ +| | co_names | tuple of names of local | +| | | variables | ++-----------+-----------------+---------------------------+ +| | co_nlocals | number of local variables | ++-----------+-----------------+---------------------------+ +| | co_stacksize | virtual machine stack | +| | | space required | ++-----------+-----------------+---------------------------+ +| | co_varnames | tuple of names of | +| | | arguments and local | +| | | variables | ++-----------+-----------------+---------------------------+ +| builtin | __doc__ | documentation string | ++-----------+-----------------+---------------------------+ +| | __name__ | original name of this | +| | | function or method | ++-----------+-----------------+---------------------------+ +| | __self__ | instance to which a | +| | | method is bound, or | +| | | ``None`` | ++-----------+-----------------+---------------------------+ .. function:: getmembers(object[, predicate]) @@ -286,8 +278,6 @@ have __name__ and __doc__ attributes (properties, getsets, and members have both of these attributes), but this is not guaranteed. - .. versionadded:: 2.3 - .. function:: isgetsetdescriptor(object) @@ -297,8 +287,6 @@ structures. For Python implementations without such types, this method will always return ``False``. - .. versionadded:: 2.5 - .. function:: ismemberdescriptor(object) @@ -308,8 +296,6 @@ ``PyMemberDef`` structures. For Python implementations without such types, this method will always return ``False``. - .. versionadded:: 2.5 - .. _inspect-source: Modified: python/branches/py3k/Doc/library/itertools.rst ============================================================================== --- python/branches/py3k/Doc/library/itertools.rst (original) +++ python/branches/py3k/Doc/library/itertools.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Raymond Hettinger -.. versionadded:: 2.3 - This module implements a number of iterator building blocks inspired by constructs from the Haskell and SML programming languages. Each has been recast in a form suitable for Python. @@ -178,8 +176,6 @@ self.currvalue = next(self.it) # Exit on StopIteration self.currkey = self.keyfunc(self.currvalue) - .. versionadded:: 2.4 - .. function:: ifilter(predicate, iterable) @@ -253,9 +249,6 @@ If *start* is ``None``, then iteration starts at zero. If *step* is ``None``, then the step defaults to one. - .. versionchanged:: 2.5 - accept ``None`` values for default *start* and *step*. - .. function:: izip(*iterables) @@ -269,9 +262,7 @@ result = [next(it) for it in iterables] yield tuple(result) - .. versionchanged:: 2.4 - When no iterables are specified, returns a zero length iterator instead of - raising a :exc:`TypeError` exception. + When no iterables are specified, return a zero length iterator. Note, the left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using @@ -313,8 +304,6 @@ function should be wrapped with something that limits the number of calls (for example :func:`islice` or :func:`takewhile`). - .. versionadded:: 2.6 - .. function:: repeat(object[, times]) @@ -385,8 +374,6 @@ iterator is going to use most or all of the data before the other iterator, it is faster to use :func:`list` instead of :func:`tee`. - .. versionadded:: 2.4 - .. _itertools-example: Modified: python/branches/py3k/Doc/library/linecache.rst ============================================================================== --- python/branches/py3k/Doc/library/linecache.rst (original) +++ python/branches/py3k/Doc/library/linecache.rst Sat Sep 1 15:51:09 2007 @@ -28,9 +28,6 @@ ``__loader__`` in *module_globals*, in case the module was imported from a zipfile or other non-filesystem import source. - .. versionadded:: 2.5 - The *module_globals* parameter was added. - .. function:: clearcache() Modified: python/branches/py3k/Doc/library/locale.rst ============================================================================== --- python/branches/py3k/Doc/library/locale.rst (original) +++ python/branches/py3k/Doc/library/locale.rst Sat Sep 1 15:51:09 2007 @@ -50,9 +50,6 @@ specified in the :envvar:`LANG` environment variable). If the locale is not changed thereafter, using multithreading should not cause problems. - .. versionchanged:: 2.0 - Added support for tuple values of the *locale* parameter. - .. function:: localeconv() @@ -176,8 +173,6 @@ *language code* and *encoding* may be ``None`` if their values cannot be determined. - .. versionadded:: 2.0 - .. function:: getlocale([category]) @@ -189,8 +184,6 @@ *language code* and *encoding* may be ``None`` if their values cannot be determined. - .. versionadded:: 2.0 - .. function:: getpreferredencoding([do_setlocale]) @@ -203,8 +196,6 @@ preferences, so this function is not thread-safe. If invoking setlocale is not necessary or desired, *do_setlocale* should be set to ``False``. - .. versionadded:: 2.3 - .. function:: normalize(localename) @@ -215,8 +206,6 @@ If the given encoding is not known, the function defaults to the default encoding for the locale code just like :func:`setlocale`. - .. versionadded:: 2.0 - .. function:: resetlocale([category]) @@ -225,8 +214,6 @@ The default setting is determined by calling :func:`getdefaultlocale`. *category* defaults to :const:`LC_ALL`. - .. versionadded:: 2.0 - .. function:: strcoll(string1, string2) @@ -259,17 +246,12 @@ Please note that this function will only work for exactly one %char specifier. For whole format strings, use :func:`format_string`. - .. versionchanged:: 2.5 - Added the *monetary* parameter. - .. function:: format_string(format, val[, grouping]) Processes formatting specifiers as in ``format % val``, but takes the current locale settings into account. - .. versionadded:: 2.5 - .. function:: currency(val[, symbol[, grouping[, international]]]) @@ -283,8 +265,6 @@ Note that this function will not work with the 'C' locale, so you have to set a locale via :func:`setlocale` first. - .. versionadded:: 2.5 - .. function:: str(float) Modified: python/branches/py3k/Doc/library/logging.rst ============================================================================== --- python/branches/py3k/Doc/library/logging.rst (original) +++ python/branches/py3k/Doc/library/logging.rst Sat Sep 1 15:51:09 2007 @@ -15,8 +15,6 @@ .. index:: pair: Errors; logging -.. versionadded:: 2.3 - This module defines functions and classes which implement a flexible error logging system for applications. @@ -222,9 +220,6 @@ above example). In such circumstances, it is likely that specialized :class:`Formatter`\ s would be used with particular :class:`Handler`\ s. - .. versionchanged:: 2.5 - *extra* was added. - .. function:: info(msg[, *args[, **kwargs]]) @@ -307,9 +302,6 @@ :func:`error` and :func:`critical` will call :func:`basicConfig` automatically if no handlers are defined for the root logger. - .. versionchanged:: 2.4 - Formerly, :func:`basicConfig` did not take any keyword arguments. - The following keyword arguments are supported. +--------------+---------------------------------------------+ @@ -464,9 +456,6 @@ above example). In such circumstances, it is likely that specialized :class:`Formatter`\ s would be used with particular :class:`Handler`\ s. - .. versionchanged:: 2.5 - *extra* was added. - .. method:: Logger.info(msg[, *args[, **kwargs]]) @@ -536,10 +525,6 @@ Finds the caller's source filename and line number. Returns the filename, line number and function name as a 3-element tuple. - .. versionchanged:: 2.4 - The function name was added. In earlier versions, the filename and line number - were returned as a 2-element tuple.. - .. method:: Logger.handle(record) @@ -554,18 +539,12 @@ This is a factory method which can be overridden in subclasses to create specialized :class:`LogRecord` instances. - .. versionchanged:: 2.5 - *func* and *extra* were added. - .. _minimal-example: Basic example ------------- -.. versionchanged:: 2.4 - formerly :func:`basicConfig` did not take any keyword arguments. - The :mod:`logging` package provides a lot of flexibility, and its configuration can appear daunting. This section demonstrates that simple use of the logging package is possible. @@ -1042,8 +1021,6 @@ WatchedFileHandler ^^^^^^^^^^^^^^^^^^ -.. versionadded:: 2.6 - The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers` module, is a :class:`FileHandler` which watches the file it is logging to. If the file changes, it is closed and reopened using the file name. @@ -1369,9 +1346,6 @@ the standard SMTP port is used. If your SMTP server requires authentication, you can specify a (username, password) tuple for the *credentials* argument. - .. versionchanged:: 2.6 - *credentials* was added. - .. method:: SMTPHandler.emit(record) @@ -1542,9 +1516,6 @@ | | args``. | +-------------------------+-----------------------------------------------+ -.. versionchanged:: 2.5 - *funcName* was added. - .. class:: Formatter([fmt[, datefmt]]) @@ -1631,9 +1602,6 @@ the name of the function from which the logging call was made. If not specified, it defaults to ``None``. - .. versionchanged:: 2.5 - *func* was added. - .. method:: LogRecord.getMessage() Modified: python/branches/py3k/Doc/library/marshal.rst ============================================================================== --- python/branches/py3k/Doc/library/marshal.rst (original) +++ python/branches/py3k/Doc/library/marshal.rst Sat Sep 1 15:51:09 2007 @@ -70,9 +70,8 @@ :exc:`ValueError` exception is raised --- but garbage data will also be written to the file. The object will not be properly read back by :func:`load`. - .. versionadded:: 2.4 - The *version* argument indicates the data format that ``dump`` should use - (see below). + The *version* argument indicates the data format that ``dump`` should use + (see below). .. function:: load(file) @@ -95,9 +94,8 @@ value must be a supported type. Raise a :exc:`ValueError` exception if value has (or contains an object that has) an unsupported type. - .. versionadded:: 2.4 - The *version* argument indicates the data format that ``dumps`` should use - (see below). + The *version* argument indicates the data format that ``dumps`` should use + (see below). .. function:: loads(string) @@ -116,8 +114,6 @@ Python 2.5) uses a binary format for floating point numbers. The current version is 2. - .. versionadded:: 2.4 - .. rubric:: Footnotes Modified: python/branches/py3k/Doc/library/math.rst ============================================================================== --- python/branches/py3k/Doc/library/math.rst (original) +++ python/branches/py3k/Doc/library/math.rst Sat Sep 1 15:51:09 2007 @@ -99,9 +99,6 @@ Return the logarithm of *x* to the given *base*. If the *base* is not specified, return the natural logarithm of *x* (that is, the logarithm to base *e*). - .. versionchanged:: 2.3 - *base* argument added. - .. function:: log10(x) Modified: python/branches/py3k/Doc/library/mimetypes.rst ============================================================================== --- python/branches/py3k/Doc/library/mimetypes.rst (original) +++ python/branches/py3k/Doc/library/mimetypes.rst Sat Sep 1 15:51:09 2007 @@ -154,7 +154,6 @@ The optional *filenames* parameter can be used to cause additional files to be loaded "on top" of the default database. - .. versionadded:: 2.2 An example usage of the module:: Modified: python/branches/py3k/Doc/library/mmap.rst ============================================================================== --- python/branches/py3k/Doc/library/mmap.rst (original) +++ python/branches/py3k/Doc/library/mmap.rst Sat Sep 1 15:51:09 2007 @@ -35,9 +35,7 @@ file. Assignment to an :const:`ACCESS_COPY` memory map affects memory but does not update the underlying file. -.. versionchanged:: 2.5 - To map anonymous memory, -1 should be passed as the fileno along with the - length. +To map anonymous memory, -1 should be passed as the fileno along with the length. .. function:: mmap(fileno, length[, tagname[, access]]) Modified: python/branches/py3k/Doc/library/modulefinder.rst ============================================================================== --- python/branches/py3k/Doc/library/modulefinder.rst (original) +++ python/branches/py3k/Doc/library/modulefinder.rst Sat Sep 1 15:51:09 2007 @@ -9,8 +9,6 @@ :synopsis: Find modules used by a script. -.. versionadded:: 2.3 - This module provides a :class:`ModuleFinder` class that can be used to determine the set of modules imported by a script. ``modulefinder.py`` can also be run as a script, giving the filename of a Python script as its argument, after which a Modified: python/branches/py3k/Doc/library/msilib.rst ============================================================================== --- python/branches/py3k/Doc/library/msilib.rst (original) +++ python/branches/py3k/Doc/library/msilib.rst Sat Sep 1 15:51:09 2007 @@ -11,8 +11,6 @@ .. index:: single: msi -.. versionadded:: 2.5 - The :mod:`msilib` supports the creation of Microsoft Installer (``.msi``) files. Because these files often contain an embedded "cabinet" file (``.cab``), it also exposes an API to create CAB files. Support for reading ``.cab`` files is Modified: python/branches/py3k/Doc/library/netrc.rst ============================================================================== --- python/branches/py3k/Doc/library/netrc.rst (original) +++ python/branches/py3k/Doc/library/netrc.rst Sat Sep 1 15:51:09 2007 @@ -8,10 +8,6 @@ .. sectionauthor:: Eric S. Raymond -.. % Note the \protect needed for \file... ;-( - -.. versionadded:: 1.5.2 - The :class:`netrc` class parses and encapsulates the netrc file format used by the Unix :program:`ftp` program and other FTP clients. Modified: python/branches/py3k/Doc/library/nis.rst ============================================================================== --- python/branches/py3k/Doc/library/nis.rst (original) +++ python/branches/py3k/Doc/library/nis.rst Sat Sep 1 15:51:09 2007 @@ -26,9 +26,8 @@ Note that *mapname* is first checked if it is an alias to another name. - .. versionchanged:: 2.5 - The *domain* argument allows to override the NIS domain used for the lookup. If - unspecified, lookup is in the default NIS domain. + The *domain* argument allows to override the NIS domain used for the lookup. If + unspecified, lookup is in the default NIS domain. .. function:: cat(mapname[, domain=default_domain]) @@ -39,29 +38,25 @@ Note that *mapname* is first checked if it is an alias to another name. - .. versionchanged:: 2.5 - The *domain* argument allows to override the NIS domain used for the lookup. If - unspecified, lookup is in the default NIS domain. + The *domain* argument allows to override the NIS domain used for the lookup. If + unspecified, lookup is in the default NIS domain. .. function:: maps([domain=default_domain]) Return a list of all valid maps. - .. versionchanged:: 2.5 - The *domain* argument allows to override the NIS domain used for the lookup. If - unspecified, lookup is in the default NIS domain. + The *domain* argument allows to override the NIS domain used for the lookup. If + unspecified, lookup is in the default NIS domain. .. function:: get_default_domain() Return the system default NIS domain. - .. versionadded:: 2.5 The :mod:`nis` module defines the following exception: - .. exception:: error An error raised when a NIS function returns an error code. Modified: python/branches/py3k/Doc/library/nntplib.rst ============================================================================== --- python/branches/py3k/Doc/library/nntplib.rst (original) +++ python/branches/py3k/Doc/library/nntplib.rst Sat Sep 1 15:51:09 2007 @@ -51,7 +51,7 @@ The module itself defines the following items: -.. class:: NNTP(host[, port [, user[, password [, readermode] [, usenetrc]]]]) +.. class:: NNTP(host[, port [, user[, password [, readermode][, usenetrc]]]]) Return a new instance of the :class:`NNTP` class, representing a connection to the NNTP server running on host *host*, listening at port *port*. The @@ -66,9 +66,6 @@ :exc:`NNTPPermanentError`\ s, you might need to set *readermode*. *readermode* defaults to ``None``. *usenetrc* defaults to ``True``. - .. versionchanged:: 2.4 - *usenetrc* argument added. - .. exception:: NNTPError @@ -185,8 +182,6 @@ strings). Return a pair ``(response, list)``, where *list* is a list of tuples containing ``(name, title)``. - .. versionadded:: 2.4 - .. method:: NNTP.description(group) @@ -197,8 +192,6 @@ This elides the response code from the server. If the response code is needed, use :meth:`descriptions`. - .. versionadded:: 2.4 - .. method:: NNTP.group(name) Modified: python/branches/py3k/Doc/library/operator.rst ============================================================================== --- python/branches/py3k/Doc/library/operator.rst (original) +++ python/branches/py3k/Doc/library/operator.rst Sat Sep 1 15:51:09 2007 @@ -42,7 +42,6 @@ return any value, which may or may not be interpretable as a Boolean value. See :ref:`comparisons` for more information about rich comparisons. - .. versionadded:: 2.2 The logical operations are also generally applicable to all objects, and support truth tests, identity tests, and boolean operations: @@ -67,14 +66,11 @@ Return ``a is b``. Tests object identity. - .. versionadded:: 2.3 - .. function:: is_not(a, b) Return ``a is not b``. Tests object identity. - .. versionadded:: 2.3 The mathematical and bitwise operations are the most numerous: @@ -109,8 +105,6 @@ Return ``a // b``. - .. versionadded:: 2.2 - .. function:: inv(o) invert(o) @@ -119,9 +113,6 @@ Return the bitwise inverse of the number *o*. This is equivalent to ``~o``. - .. versionadded:: 2.0 - The names :func:`invert` and :func:`__invert__`. - .. function:: lshift(a, b) __lshift__(a, b) @@ -164,8 +155,6 @@ Return ``a ** b``, for *a* and *b* numbers. - .. versionadded:: 2.3 - .. function:: rshift(a, b) __rshift__(a, b) @@ -185,8 +174,6 @@ Return ``a / b`` when ``__future__.division`` is in effect. This is also known as "true" division. - .. versionadded:: 2.2 - .. function:: xor(a, b) __xor__(a, b) @@ -199,8 +186,6 @@ Return *a* converted to an integer. Equivalent to ``a.__index__()``. - .. versionadded:: 2.5 - Operations which work with sequences include: @@ -215,9 +200,6 @@ Return the outcome of the test ``b in a``. Note the reversed operands. - .. versionadded:: 2.0 - The name :func:`__contains__`. - .. function:: countOf(a, b) @@ -290,24 +272,18 @@ ``a = iadd(a, b)`` is equivalent to ``a += b``. - .. versionadded:: 2.5 - .. function:: iand(a, b) __iand__(a, b) ``a = iand(a, b)`` is equivalent to ``a &= b``. - .. versionadded:: 2.5 - .. function:: iconcat(a, b) __iconcat__(a, b) ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences. - .. versionadded:: 2.5 - .. function:: idiv(a, b) __idiv__(a, b) @@ -315,23 +291,17 @@ ``a = idiv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` is not in effect. - .. versionadded:: 2.5 - .. function:: ifloordiv(a, b) __ifloordiv__(a, b) ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``. - .. versionadded:: 2.5 - .. function:: ilshift(a, b) __ilshift__(a, b) - ``a = ilshift(a, b)`` is equivalent to ``a <``\ ``<= b``. - - .. versionadded:: 2.5 + ``a = ilshift(a, b)`` is equivalent to ``a <<= b``. .. function:: imod(a, b) @@ -339,32 +309,24 @@ ``a = imod(a, b)`` is equivalent to ``a %= b``. - .. versionadded:: 2.5 - .. function:: imul(a, b) __imul__(a, b) ``a = imul(a, b)`` is equivalent to ``a *= b``. - .. versionadded:: 2.5 - .. function:: ior(a, b) __ior__(a, b) ``a = ior(a, b)`` is equivalent to ``a |= b``. - .. versionadded:: 2.5 - .. function:: ipow(a, b) __ipow__(a, b) ``a = ipow(a, b)`` is equivalent to ``a **= b``. - .. versionadded:: 2.5 - .. function:: irepeat(a, b) __irepeat__(a, b) @@ -372,24 +334,18 @@ ``a = irepeat(a, b)`` is equivalent to ``a *= b`` where *a* is a sequence and *b* is an integer. - .. versionadded:: 2.5 - .. function:: irshift(a, b) __irshift__(a, b) ``a = irshift(a, b)`` is equivalent to ``a >>= b``. - .. versionadded:: 2.5 - .. function:: isub(a, b) __isub__(a, b) ``a = isub(a, b)`` is equivalent to ``a -= b``. - .. versionadded:: 2.5 - .. function:: itruediv(a, b) __itruediv__(a, b) @@ -397,16 +353,12 @@ ``a = itruediv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` is in effect. - .. versionadded:: 2.5 - .. function:: ixor(a, b) __ixor__(a, b) ``a = ixor(a, b)`` is equivalent to ``a ^= b``. - .. versionadded:: 2.5 - The :mod:`operator` module also defines a few predicates to test the type of objects. @@ -497,11 +449,6 @@ ``f=attrgetter('name', 'date')``, the call ``f(b)`` returns ``(b.name, b.date)``. - .. versionadded:: 2.4 - - .. versionchanged:: 2.5 - Added support for multiple attributes. - .. function:: itemgetter(item[, args...]) @@ -510,10 +457,6 @@ call ``f(b)`` returns ``b[2]``. After, ``f=itemgetter(2,5,3)``, the call ``f(b)`` returns ``(b[2], b[5], b[3])``. - .. versionadded:: 2.4 - - .. versionchanged:: 2.5 - Added support for multiple item extraction. Examples:: Modified: python/branches/py3k/Doc/library/optparse.rst ============================================================================== --- python/branches/py3k/Doc/library/optparse.rst (original) +++ python/branches/py3k/Doc/library/optparse.rst Sat Sep 1 15:51:09 2007 @@ -8,10 +8,6 @@ .. module:: optparse :synopsis: More convenient, flexible, and powerful command-line parsing library. .. moduleauthor:: Greg Ward - - -.. versionadded:: 2.3 - .. sectionauthor:: Greg Ward Modified: python/branches/py3k/Doc/library/os.path.rst ============================================================================== --- python/branches/py3k/Doc/library/os.path.rst (original) +++ python/branches/py3k/Doc/library/os.path.rst Sat Sep 1 15:51:09 2007 @@ -23,8 +23,6 @@ Return a normalized absolutized version of the pathname *path*. On most platforms, this is equivalent to ``normpath(join(os.getcwd(), path))``. - .. versionadded:: 1.5.2 - .. function:: basename(path) @@ -62,8 +60,6 @@ broken symbolic links. Equivalent to :func:`exists` on platforms lacking :func:`os.lstat`. - .. versionadded:: 2.4 - .. function:: expanduser(path) @@ -103,11 +99,8 @@ the number of seconds since the epoch (see the :mod:`time` module). Raise :exc:`os.error` if the file does not exist or is inaccessible. - .. versionadded:: 1.5.2 - - .. versionchanged:: 2.3 - If :func:`os.stat_float_times` returns True, the result is a floating point - number. + If :func:`os.stat_float_times` returns True, the result is a floating point + number. .. function:: getmtime(path) @@ -116,11 +109,8 @@ giving the number of seconds since the epoch (see the :mod:`time` module). Raise :exc:`os.error` if the file does not exist or is inaccessible. - .. versionadded:: 1.5.2 - - .. versionchanged:: 2.3 - If :func:`os.stat_float_times` returns True, the result is a floating point - number. + If :func:`os.stat_float_times` returns True, the result is a floating point + number. .. function:: getctime(path) @@ -131,16 +121,12 @@ the :mod:`time` module). Raise :exc:`os.error` if the file does not exist or is inaccessible. - .. versionadded:: 2.3 - .. function:: getsize(path) Return the size, in bytes, of *path*. Raise :exc:`os.error` if the file does not exist or is inaccessible. - .. versionadded:: 1.5.2 - .. function:: isabs(path) @@ -207,8 +193,6 @@ Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system). - .. versionadded:: 2.2 - .. function:: relpath(path[, start]) @@ -217,8 +201,6 @@ *start* defaults to :attr:`os.curdir`. Availability: Windows, Unix. - .. versionadded:: 2.6 - .. function:: samefile(path1, path2) @@ -260,8 +242,6 @@ specifications, *drive* will always be the empty string. In all cases, ``drive + tail`` will be the same as *path*. - .. versionadded:: 1.3 - .. function:: splitext(path) @@ -270,10 +250,6 @@ period. Leading periods on the basename are ignored; ``splitext('.cshrc')`` returns ``('.cshrc', '')``. - .. versionchanged:: 2.6 - Earlier versions could produce an empty root when the only period was the - first character. - .. function:: splitunc(path) @@ -312,6 +288,3 @@ True if arbitrary Unicode strings can be used as file names (within limitations imposed by the file system), and if :func:`os.listdir` returns Unicode strings for a Unicode argument. - - .. versionadded:: 2.3 - Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Sat Sep 1 15:51:09 2007 @@ -174,8 +174,6 @@ Return the process group id of the process with process id *pid*. If *pid* is 0, the process group id of the current process is returned. Availability: Unix. - .. versionadded:: 2.3 - .. function:: getpgrp() @@ -254,8 +252,6 @@ identifying a group. This operation is typical available only to the superuser. Availability: Unix. - .. versionadded:: 2.2 - .. function:: setpgrp() @@ -286,8 +282,6 @@ Calls the system call :cfunc:`getsid`. See the Unix manual for the semantics. Availability: Unix. - .. versionadded:: 2.4 - .. function:: setsid() @@ -361,14 +355,12 @@ and *bufsize* arguments have the same meaning as the corresponding arguments to the built-in :func:`open` function. Availability: Macintosh, Unix, Windows. - .. versionchanged:: 2.3 - When specified, the *mode* argument must now start with one of the letters - ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised. - - .. versionchanged:: 2.5 - On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is - set on the file descriptor (which the :cfunc:`fdopen` implementation already - does on most platforms). + When specified, the *mode* argument must start with one of the letters + ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised. + + On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is + set on the file descriptor (which the :cfunc:`fdopen` implementation already + does on most platforms). .. function:: popen(command[, mode[, bufsize]]) @@ -385,12 +377,6 @@ .. deprecated:: 2.6 This function is obsolete. Use the :mod:`subprocess` module. - .. versionchanged:: 2.0 - This function worked unreliably under Windows in earlier versions of Python. - This was due to the use of the :cfunc:`_popen` function from the libraries - provided with Windows. Newer versions of Python do not use the broken - implementation from the Windows libraries. - .. function:: tmpfile() @@ -644,8 +630,6 @@ Parameters to the :func:`lseek` function. Their values are 0, 1, and 2, respectively. Availability: Windows, Macintosh, Unix. - .. versionadded:: 2.5 - .. _os-file-dir: @@ -716,8 +700,6 @@ descriptor *fd*. The descriptor must refer to an opened directory, not an open file. Availability: Unix. - .. versionadded:: 2.3 - .. function:: getcwd() @@ -730,8 +712,6 @@ Return a Unicode object representing the current working directory. Availability: Macintosh, Unix, Windows. - .. versionadded:: 2.3 - .. function:: chflags(path, flags) @@ -751,16 +731,12 @@ Availability: Macintosh, Unix. - .. versionadded:: 2.6 - .. function:: chroot(path) Change the root directory of the current process to *path*. Availability: Macintosh, Unix. - .. versionadded:: 2.2 - .. function:: chmod(path, mode) @@ -809,16 +785,12 @@ Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not follow symbolic links. Availability: Unix. - .. versionadded:: 2.6 - .. function:: lchown(path, uid, gid) Change the owner and group id of *path* to the numeric *uid* and gid. This function will not follow symbolic links. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. function:: link(src, dst) @@ -832,9 +804,8 @@ ``'..'`` even if they are present in the directory. Availability: Macintosh, Unix, Windows. - .. versionchanged:: 2.3 - On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be - a list of Unicode objects. + On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be + a list of Unicode objects. .. function:: lstat(path) @@ -867,31 +838,23 @@ ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using :func:`os.makedev`), otherwise it is ignored. - .. versionadded:: 2.3 - .. function:: major(device) Extracts the device major number from a raw device number (usually the :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`). - .. versionadded:: 2.3 - .. function:: minor(device) Extracts the device minor number from a raw device number (usually the :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`). - .. versionadded:: 2.3 - .. function:: makedev(major, minor) Composes a raw device number from the major and minor device numbers. - .. versionadded:: 2.3 - .. function:: mkdir(path[, mode]) @@ -917,10 +880,7 @@ :func:`makedirs` will become confused if the path elements to create include *os.pardir*. - .. versionadded:: 1.5.2 - - .. versionchanged:: 2.3 - This function now handles UNC paths correctly. + This function handles UNC paths correctly. .. function:: pathconf(path, name) @@ -955,8 +915,7 @@ be converted to an absolute pathname using ``os.path.join(os.path.dirname(path), result)``. - .. versionchanged:: 2.6 - If the *path* is a Unicode object the result will also be a Unicode object. + If the *path* is a Unicode object, the result will also be a Unicode object. Availability: Macintosh, Unix. @@ -985,8 +944,6 @@ they are empty. Raises :exc:`OSError` if the leaf directory could not be successfully removed. - .. versionadded:: 1.5.2 - .. function:: rename(src, dst) @@ -1007,8 +964,6 @@ attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned away using :func:`removedirs`. - .. versionadded:: 1.5.2 - .. note:: This function can fail with the new directory structure made if you lack @@ -1040,11 +995,10 @@ 926L >>> - .. versionchanged:: 2.3 - If :func:`stat_float_times` returns true, the time values are floats, measuring - seconds. Fractions of a second may be reported if the system supports that. On - Mac OS, the times are always floats. See :func:`stat_float_times` for further - discussion. + If :func:`stat_float_times` returns true, the time values are floats, measuring + seconds. Fractions of a second may be reported if the system supports that. On + Mac OS, the times are always floats. See :func:`stat_float_times` for further + discussion. On some Unix systems (such as Linux), the following attributes may also be available: :attr:`st_blocks` (number of blocks allocated for file), @@ -1080,12 +1034,6 @@ Availability: Macintosh, Unix, Windows. - .. versionchanged:: 2.2 - Added access to values as attributes of the returned object. - - .. versionchanged:: 2.5 - Added st_gen, st_birthtime. - .. function:: stat_float_times([newvalue]) @@ -1097,10 +1045,9 @@ For compatibility with older Python versions, accessing :class:`stat_result` as a tuple always returns integers. - .. versionchanged:: 2.5 - Python now returns float values by default. Applications which do not work - correctly with floating point time stamps can use this function to restore the - old behaviour. + Python now returns float values by default. Applications which do not work + correctly with floating point time stamps can use this function to restore the + old behaviour. The resolution of the timestamps (that is the smallest possible fraction) depends on the system. Some systems only support second resolution; on these @@ -1131,9 +1078,6 @@ this remains useful when writing code that needs to work with versions of Python that don't support accessing the fields as attributes. - .. versionchanged:: 2.2 - Added access to values as attributes of the returned object. - .. function:: symlink(src, dst) @@ -1206,9 +1150,6 @@ depending on the resolution with which your operating system records access and modification times; see :func:`stat`. - .. versionchanged:: 2.0 - Added support for ``None`` for *times*. - Availability: Macintosh, Unix, Windows. @@ -1255,9 +1196,6 @@ directories. Set *followlinks* to True to visit directories pointed to by symlinks, on systems that support them. - .. versionadded:: 2.6 - The *followlinks* parameter. - .. note:: Be aware that setting *followlinks* to true can lead to infinite recursion if a @@ -1297,8 +1235,6 @@ for name in dirs: os.rmdir(os.path.join(root, name)) - .. versionadded:: 2.3 - .. _os-process: @@ -1391,96 +1327,72 @@ Exit code that means no error occurred. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_USAGE Exit code that means the command was used incorrectly, such as when the wrong number of arguments are given. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_DATAERR Exit code that means the input data was incorrect. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_NOINPUT Exit code that means an input file did not exist or was not readable. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_NOUSER Exit code that means a specified user did not exist. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_NOHOST Exit code that means a specified host did not exist. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_UNAVAILABLE Exit code that means that a required service is unavailable. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_SOFTWARE Exit code that means an internal software error was detected. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_OSERR Exit code that means an operating system error was detected, such as the inability to fork or create a pipe. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_OSFILE Exit code that means some system file did not exist, could not be opened, or had some other kind of error. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_CANTCREAT Exit code that means a user specified output file could not be created. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_IOERR Exit code that means that an error occurred while doing I/O on some file. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_TEMPFAIL @@ -1488,16 +1400,12 @@ that may not really be an error, such as a network connection that couldn't be made during a retryable operation. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_PROTOCOL Exit code that means that a protocol exchange was illegal, invalid, or not understood. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_NOPERM @@ -1505,24 +1413,18 @@ operation (but not intended for file system problems). Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_CONFIG Exit code that means that some kind of configuration error occurred. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. data:: EX_NOTFOUND Exit code that means something like "an entry was not found". Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. function:: fork() @@ -1559,8 +1461,6 @@ Send the signal *sig* to the process group *pgid*. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. function:: nice(increment) @@ -1640,8 +1540,6 @@ Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp` and :func:`spawnvpe` are not available on Windows. - .. versionadded:: 1.6 - .. data:: P_NOWAIT P_NOWAITO @@ -1651,8 +1549,6 @@ will return as soon as the new process has been created, with the process ID as the return value. Availability: Macintosh, Unix, Windows. - .. versionadded:: 1.6 - .. data:: P_WAIT @@ -1662,8 +1558,6 @@ of the process the run is successful, or ``-signal`` if a signal kills the process. Availability: Macintosh, Unix, Windows. - .. versionadded:: 1.6 - .. data:: P_DETACH P_OVERLAY @@ -1675,8 +1569,6 @@ process will be replaced; the :func:`spawn\*` function will not return. Availability: Windows. - .. versionadded:: 1.6 - .. function:: startfile(path[, operation]) @@ -1700,11 +1592,6 @@ doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that the path is properly encoded for Win32. Availability: Windows. - .. versionadded:: 2.0 - - .. versionadded:: 2.5 - The *operation* parameter. - .. function:: system(command) @@ -1785,8 +1672,6 @@ argument is the same as that provided to :func:`waitpid` and :func:`wait4`. Availability: Unix. - .. versionadded:: 2.5 - .. function:: wait4(pid, options) @@ -1796,8 +1681,6 @@ information. The arguments to :func:`wait4` are the same as those provided to :func:`waitpid`. Availability: Unix. - .. versionadded:: 2.5 - .. data:: WNOHANG @@ -1812,8 +1695,6 @@ from a job control stop since their status was last reported. Availability: Some Unix systems. - .. versionadded:: 2.3 - .. data:: WUNTRACED @@ -1821,28 +1702,22 @@ their current state has not been reported since they were stopped. Availability: Macintosh, Unix. - .. versionadded:: 2.3 The following functions take a process status code as returned by :func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be used to determine the disposition of a process. - .. function:: WCOREDUMP(status) Returns ``True`` if a core dump was generated for the process, otherwise it returns ``False``. Availability: Macintosh, Unix. - .. versionadded:: 2.3 - .. function:: WIFCONTINUED(status) Returns ``True`` if the process has been continued from a job control stop, otherwise it returns ``False``. Availability: Unix. - .. versionadded:: 2.3 - .. function:: WIFSTOPPED(status) @@ -1920,8 +1795,6 @@ 5, and 15 minutes or raises :exc:`OSError` if the load average was unobtainable. - .. versionadded:: 2.3 - .. function:: sysconf(name) @@ -1980,8 +1853,6 @@ The character which separates the base filename from the extension; for example, the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`. - .. versionadded:: 2.2 - .. data:: pathsep @@ -2010,8 +1881,6 @@ The file path of the null device. For example: ``'/dev/null'`` for POSIX or ``'Dev:Nul'`` for Mac OS 9. Also available via :mod:`os.path`. - .. versionadded:: 2.4 - .. _os-miscfunc: @@ -2028,6 +1897,3 @@ though its exact quality depends on the OS implementation. On a UNIX-like system this will query /dev/urandom, and on Windows it will use CryptGenRandom. If a randomness source is not found, :exc:`NotImplementedError` will be raised. - - .. versionadded:: 2.4 - Modified: python/branches/py3k/Doc/library/ossaudiodev.rst ============================================================================== --- python/branches/py3k/Doc/library/ossaudiodev.rst (original) +++ python/branches/py3k/Doc/library/ossaudiodev.rst Sat Sep 1 15:51:09 2007 @@ -7,8 +7,6 @@ :synopsis: Access to OSS-compatible audio devices. -.. versionadded:: 2.3 - This module allows you to access the OSS (Open Sound System) audio interface. OSS is available for a wide range of open-source and commercial Unices, and is the standard audio interface for Linux and recent versions of FreeBSD. Modified: python/branches/py3k/Doc/library/pdb.rst ============================================================================== --- python/branches/py3k/Doc/library/pdb.rst (original) +++ python/branches/py3k/Doc/library/pdb.rst Sat Sep 1 15:51:09 2007 @@ -51,9 +51,6 @@ restarting preserves pdb's state (such as breakpoints) and in most cases is more useful than quitting the debugger upon program's exit. -.. versionadded:: 2.4 - Restarting post-mortem behavior added. - Typical usage to inspect a crashed program is:: >>> import pdb @@ -252,8 +249,6 @@ that are to print a specific message and then continue. If none of the other commands print anything, you see no sign that the breakpoint was reached. - .. versionadded:: 2.5 - s(tep) Execute the current line, stop at the first possible occasion (either in a function that is called or on the next line in the current function). @@ -338,8 +333,6 @@ with "shlex" and the result is used as the new sys.argv. History, breakpoints, actions and debugger options are preserved. "restart" is an alias for "run". - .. versionadded:: 2.6 - q(uit) Quit from the debugger. The program being executed is aborted. Modified: python/branches/py3k/Doc/library/pickle.rst ============================================================================== --- python/branches/py3k/Doc/library/pickle.rst (original) +++ python/branches/py3k/Doc/library/pickle.rst Sat Sep 1 15:51:09 2007 @@ -130,9 +130,6 @@ as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version available will be used. -.. versionchanged:: 2.3 - Introduced the *protocol* parameter. - A binary format, which is slightly more efficient, can be chosen by specifying a *protocol* version >= 1. @@ -151,8 +148,6 @@ The highest protocol version available. This value can be passed as a *protocol* value. - .. versionadded:: 2.3 - .. note:: Be sure to always open pickle files created with protocols >= 1 in binary mode. @@ -176,9 +171,6 @@ specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version will be used. - .. versionchanged:: 2.3 - Introduced the *protocol* parameter. - *file* must have a :meth:`write` method that accepts a single string argument. It can thus be a file object opened for writing, a :mod:`StringIO` object, or any other custom object that meets this interface. @@ -209,9 +201,6 @@ specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version will be used. - .. versionchanged:: 2.3 - The *protocol* parameter was added. - .. function:: loads(string) @@ -252,9 +241,6 @@ specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version will be used. - .. versionchanged:: 2.3 - Introduced the *protocol* parameter. - *file* must have a :meth:`write` method that accepts a single string argument. It can thus be an open file object, a :mod:`StringIO` object, or any other custom object that meets this interface. @@ -494,10 +480,7 @@ :exc:`UnpicklingError` will be raised in the unpickling environment. Note that as usual, the callable itself is pickled by name. -* A tuple of arguments for the callable object. - - .. versionchanged:: 2.5 - Formerly, this argument could also be ``None``. +* A tuple of arguments for the callable object, not ``None``. * Optionally, the object's state, which will be passed to the object's :meth:`__setstate__` method as described in section :ref:`pickle-inst`. If the Modified: python/branches/py3k/Doc/library/pickletools.rst ============================================================================== --- python/branches/py3k/Doc/library/pickletools.rst (original) +++ python/branches/py3k/Doc/library/pickletools.rst Sat Sep 1 15:51:09 2007 @@ -7,8 +7,6 @@ opcodes, as well as some useful functions. -.. versionadded:: 2.3 - This module contains various constants relating to the intimate details of the :mod:`pickle` module, some lengthy comments about the implementation, and a few useful functions for analyzing pickled data. The contents of this module are Modified: python/branches/py3k/Doc/library/pkgutil.rst ============================================================================== --- python/branches/py3k/Doc/library/pkgutil.rst (original) +++ python/branches/py3k/Doc/library/pkgutil.rst Sat Sep 1 15:51:09 2007 @@ -6,8 +6,6 @@ :synopsis: Utilities to support extension of packages. -.. versionadded:: 2.3 - This module provides a single function: Modified: python/branches/py3k/Doc/library/platform.rst ============================================================================== --- python/branches/py3k/Doc/library/platform.rst (original) +++ python/branches/py3k/Doc/library/platform.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Bjorn Pettersen -.. versionadded:: 2.3 - .. note:: Specific platforms listed alphabetically, with Linux included in the Unix @@ -93,23 +91,17 @@ Returns a string identifying the Python implementation SCM branch. - .. versionadded:: 2.6 - .. function:: python_implementation() Returns a string identifying the Python implementation. Possible return values are: 'CPython', 'IronPython', 'Jython' - .. versionadded:: 2.6 - .. function:: python_revision() Returns a string identifying the Python implementation SCM revision. - .. versionadded:: 2.6 - .. function:: python_version() Modified: python/branches/py3k/Doc/library/poplib.rst ============================================================================== --- python/branches/py3k/Doc/library/poplib.rst (original) +++ python/branches/py3k/Doc/library/poplib.rst Sat Sep 1 15:51:09 2007 @@ -37,9 +37,6 @@ connection attempt (if not specified, or passed as None, the global default timeout setting will be used). - .. versionchanged:: 2.6 - *timeout* was added. - .. class:: POP3_SSL(host[, port[, keyfile[, certfile]]]) @@ -48,7 +45,6 @@ port is used. *keyfile* and *certfile* are also optional - they can contain a PEM formatted private key and certificate chain file for the SSL connection. - .. versionadded:: 2.4 One exception is defined as an attribute of the :mod:`poplib` module: Modified: python/branches/py3k/Doc/library/pprint.rst ============================================================================== --- python/branches/py3k/Doc/library/pprint.rst (original) +++ python/branches/py3k/Doc/library/pprint.rst Sat Sep 1 15:51:09 2007 @@ -20,10 +20,7 @@ Construct :class:`PrettyPrinter` objects explicitly if you need to adjust the width constraint. -.. versionchanged:: 2.5 - Dictionaries are sorted by key before the display is computed; before 2.5, a - dictionary was sorted only if its display required more than one line, although - that wasn't documented. +Dictionaries are sorted by key before the display is computed. The :mod:`pprint` module defines one class: @@ -84,9 +81,6 @@ and *depth* will be passed to the :class:`PrettyPrinter` constructor as formatting parameters. - .. versionchanged:: 2.4 - The parameters *indent*, *width* and *depth* were added. - .. function:: pprint(object[, stream[, indent[, width[, depth]]]]) @@ -107,9 +101,6 @@ '/usr/local/lib/python1.5/sharedmodules', '/usr/local/lib/python1.5/tkinter'] - .. versionchanged:: 2.4 - The parameters *indent*, *width* and *depth* were added. - .. function:: isreadable(object) @@ -208,6 +199,3 @@ is no requested limit. This argument should be passed unmodified to recursive calls. The fourth argument, *level*, gives the current level; recursive calls should be passed a value less than that of the current call. - - .. versionadded:: 2.3 - Modified: python/branches/py3k/Doc/library/profile.rst ============================================================================== --- python/branches/py3k/Doc/library/profile.rst (original) +++ python/branches/py3k/Doc/library/profile.rst Sat Sep 1 15:51:09 2007 @@ -62,22 +62,13 @@ #. :mod:`profile`, a pure Python module, described in the sequel. Copyright ? 1994, by InfoSeek Corporation. - .. versionchanged:: 2.4 - also reports the time spent in calls to built-in functions and methods. - #. :mod:`cProfile`, a module written in C, with a reasonable overhead that makes it suitable for profiling long-running programs. Based on :mod:`lsprof`, contributed by Brett Rosen and Ted Czotter. - .. versionadded:: 2.5 - #. :mod:`hotshot`, a C module focusing on minimizing the overhead while profiling, at the expense of long data post-processing times. - .. versionchanged:: 2.5 - the results should be more meaningful than in the past: the timing core - contained a critical bug. - The :mod:`profile` and :mod:`cProfile` modules export the same interface, so they are mostly interchangeables; :mod:`cProfile` has a much lower overhead but is not so far as well-tested and might not be available on all systems. @@ -376,11 +367,6 @@ a single report. If additional files need to be combined with data in an existing :class:`Stats` object, the :meth:`add` method can be used. - .. % (such as the old system profiler). - - .. versionchanged:: 2.5 - The *stream* parameter was added. - .. _profile-stats: @@ -419,8 +405,6 @@ exists. This is equivalent to the method of the same name on the :class:`profile.Profile` and :class:`cProfile.Profile` classes. - .. versionadded:: 2.3 - .. method:: Stats.sort_stats(key[, ...]) Modified: python/branches/py3k/Doc/library/pydoc.rst ============================================================================== --- python/branches/py3k/Doc/library/pydoc.rst (original) +++ python/branches/py3k/Doc/library/pydoc.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Ka-Ping Yee -.. versionadded:: 2.1 - .. index:: single: documentation; generation single: documentation; online Modified: python/branches/py3k/Doc/library/pyexpat.rst ============================================================================== --- python/branches/py3k/Doc/library/pyexpat.rst (original) +++ python/branches/py3k/Doc/library/pyexpat.rst Sat Sep 1 15:51:09 2007 @@ -16,8 +16,6 @@ .. % should be marked using the \member macro and should not include the .. % parentheses used when marking functions and methods. -.. versionadded:: 2.0 - .. index:: single: Expat The :mod:`xml.parsers.expat` module is a Python interface to the Expat @@ -147,8 +145,6 @@ in the encoding of the entity which contains the text. When called while an event handler is not active, the return value is ``None``. - .. versionadded:: 2.1 - .. method:: xmlparser.ExternalEntityParserCreate(context[, encoding]) @@ -177,8 +173,6 @@ :exc:`ExpatError` to be raised with the :attr:`code` attribute set to :const:`errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING`. - .. versionadded:: 2.3 - :class:`xmlparser` objects have the following attributes: @@ -187,8 +181,6 @@ The size of the buffer used when :attr:`buffer_text` is true. This value cannot be changed at this time. - .. versionadded:: 2.3 - .. attribute:: xmlparser.buffer_text @@ -199,8 +191,6 @@ at every line ending. This attribute is false by default, and may be changed at any time. - .. versionadded:: 2.3 - .. attribute:: xmlparser.buffer_used @@ -208,8 +198,6 @@ These bytes represent UTF-8 encoded text. This attribute has no meaningful interpretation when :attr:`buffer_text` is false. - .. versionadded:: 2.3 - .. attribute:: xmlparser.ordered_attributes @@ -220,8 +208,6 @@ module also used this format.) By default, this attribute is false; it may be changed at any time. - .. versionadded:: 2.1 - .. attribute:: xmlparser.specified_attributes @@ -232,7 +218,6 @@ needed to comply with the standards for the behavior of XML processors. By default, this attribute is false; it may be changed at any time. - .. versionadded:: 2.1 The following attributes contain values relating to the most recent error encountered by an :class:`xmlparser` object, and will only have correct values @@ -268,8 +253,6 @@ just past the last parse event (regardless of whether there was an associated callback). -.. versionadded:: 2.4 - .. attribute:: xmlparser.CurrentByteIndex @@ -302,8 +285,6 @@ or ``-1`` if the standalone clause was omitted. This is only available with Expat version 1.95.0 or newer. - .. versionadded:: 2.1 - .. method:: xmlparser.StartDoctypeDeclHandler(doctypeName, systemId, publicId, has_internal_subset) @@ -386,8 +367,6 @@ general entities). This is only available starting with version 1.95.0 of the Expat library. - .. versionadded:: 2.1 - .. method:: xmlparser.NotationDeclHandler(notationName, base, systemId, publicId) @@ -491,23 +470,17 @@ Expat's internal error number for the specific error. This will match one of the constants defined in the ``errors`` object from this module. - .. versionadded:: 2.1 - .. attribute:: ExpatError.lineno Line number on which the error was detected. The first line is numbered ``1``. - .. versionadded:: 2.1 - .. attribute:: ExpatError.offset Character offset into the line where the error occurred. The first column is numbered ``0``. - .. versionadded:: 2.1 - .. _expat-example: Modified: python/branches/py3k/Doc/library/queue.rst ============================================================================== --- python/branches/py3k/Doc/library/queue.rst (original) +++ python/branches/py3k/Doc/library/queue.rst Sat Sep 1 15:51:09 2007 @@ -74,9 +74,6 @@ immediately available, else raise the :exc:`Full` exception (*timeout* is ignored in that case). - .. versionadded:: 2.3 - The *timeout* parameter. - .. method:: Queue.put_nowait(item) @@ -92,9 +89,6 @@ Otherwise (*block* is false), return an item if one is immediately available, else raise the :exc:`Empty` exception (*timeout* is ignored in that case). - .. versionadded:: 2.3 - The *timeout* parameter. - .. method:: Queue.get_nowait() @@ -117,8 +111,6 @@ Raises a :exc:`ValueError` if called more times than there were items placed in the queue. - .. versionadded:: 2.5 - .. method:: Queue.join() @@ -129,7 +121,6 @@ indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks. - .. versionadded:: 2.5 Example of how to wait for enqueued tasks to be completed:: Modified: python/branches/py3k/Doc/library/random.rst ============================================================================== --- python/branches/py3k/Doc/library/random.rst (original) +++ python/branches/py3k/Doc/library/random.rst Sat Sep 1 15:51:09 2007 @@ -39,9 +39,6 @@ Optionally, a new generator can supply a :meth:`getrandombits` method --- this allows :meth:`randrange` to produce selections over an arbitrarily large range. -.. versionadded:: 2.4 - the :meth:`getrandombits` method. - As an example of subclassing, the :mod:`random` module provides the :class:`WichmannHill` class that implements an alternative generator in pure Python. The class provides a backward compatible way to reproduce results from @@ -51,9 +48,6 @@ known to fail some stringent randomness tests. See the references below for a recent variant that repairs these flaws. -.. versionchanged:: 2.3 - Substituted MersenneTwister for Wichmann-Hill. - Bookkeeping functions: @@ -66,9 +60,6 @@ they are used instead of the system time (see the :func:`os.urandom` function for details on availability). - .. versionchanged:: 2.4 - formerly, operating system resources were not used. - If *x* is not ``None`` or an int or long, ``hash(x)`` is used instead. If *x* is an int or long, *x* is used directly. @@ -78,8 +69,6 @@ Return an object capturing the current internal state of the generator. This object can be passed to :func:`setstate` to restore the state. - .. versionadded:: 2.1 - .. function:: setstate(state) @@ -87,8 +76,6 @@ :func:`setstate` restores the internal state of the generator to what it was at the time :func:`setstate` was called. - .. versionadded:: 2.1 - .. function:: jumpahead(n) @@ -100,12 +87,6 @@ same internal state, and then :meth:`jumpahead` can be used to force the instances' states far apart. - .. versionadded:: 2.1 - - .. versionchanged:: 2.3 - Instead of jumping to a specific state, *n* steps ahead, ``jumpahead(n)`` - jumps to another state likely to be separated by many steps. - .. function:: getrandbits(k) @@ -114,26 +95,22 @@ as an optional part of the API. When available, :meth:`getrandbits` enables :meth:`randrange` to handle arbitrarily large ranges. - .. versionadded:: 2.4 Functions for integers: - .. function:: randrange([start,] stop[, step]) Return a randomly selected element from ``range(start, stop, step)``. This is equivalent to ``choice(range(start, stop, step))``, but doesn't actually build a range object. - .. versionadded:: 1.5.2 - .. function:: randint(a, b) Return a random integer *N* such that ``a <= N <= b``. -Functions for sequences: +Functions for sequences: .. function:: choice(seq) @@ -157,8 +134,6 @@ Return a *k* length list of unique elements chosen from the population sequence. Used for random sampling without replacement. - .. versionadded:: 2.3 - Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners @@ -274,7 +249,6 @@ The :meth:`getstate` and :meth:`setstate` methods raise :exc:`NotImplementedError` if called. - .. versionadded:: 2.4 Examples of basic usage:: Modified: python/branches/py3k/Doc/library/re.rst ============================================================================== --- python/branches/py3k/Doc/library/re.rst (original) +++ python/branches/py3k/Doc/library/re.rst Sat Sep 1 15:51:09 2007 @@ -287,7 +287,6 @@ matching pattern, which will match with ``''`` as well as ``'user at host.com'``, but not with ``' -.. versionadded:: 2.5 - The :mod:`runpy` module is used to locate and run Python modules without importing them first. Its main use is to implement the :option:`-m` command line switch that allows scripts to be located using the Python module namespace Modified: python/branches/py3k/Doc/library/sgmllib.rst ============================================================================== --- python/branches/py3k/Doc/library/sgmllib.rst (original) +++ python/branches/py3k/Doc/library/sgmllib.rst Sat Sep 1 15:51:09 2007 @@ -40,8 +40,6 @@ Exception raised by the :class:`SGMLParser` class when it encounters an error while parsing. - .. versionadded:: 2.1 - :class:`SGMLParser` instances have the following methods: @@ -106,9 +104,6 @@ base implementation simply calls *method* with *attributes* as the only argument. - .. versionadded:: 2.5 - Handling of entity and character references within attribute values. - .. method:: SGMLParser.handle_endtag(tag, method) @@ -133,9 +128,6 @@ a string. If that method returns a string, it is passed to :meth:`handle_data`, otherwise ``unknown_charref(ref)`` is called to handle the error. - .. versionchanged:: 2.5 - Use :meth:`convert_charref` instead of hard-coding the conversion. - .. method:: SGMLParser.convert_charref(ref) @@ -146,16 +138,12 @@ method returns ``None``. This method is called by the default :meth:`handle_charref` implementation and by the attribute value parser. - .. versionadded:: 2.5 - .. method:: SGMLParser.convert_codepoint(codepoint) Convert a codepoint to a :class:`str` value. Encodings can be handled here if appropriate, though the rest of :mod:`sgmllib` is oblivious on this matter. - .. versionadded:: 2.5 - .. method:: SGMLParser.handle_entityref(ref) @@ -166,9 +154,6 @@ method ``unknown_entityref(ref)``. The default :attr:`entitydefs` defines translations for ``&``, ``&apos``, ``>``, ``<``, and ``"``. - .. versionchanged:: 2.5 - Use :meth:`convert_entityref` instead of hard-coding the conversion. - .. method:: SGMLParser.convert_entityref(ref) @@ -180,8 +165,6 @@ ``None``. This method is called by the default :meth:`handle_entityref` implementation and by the attribute value parser. - .. versionadded:: 2.5 - .. method:: SGMLParser.handle_comment(comment) Modified: python/branches/py3k/Doc/library/shelve.rst ============================================================================== --- python/branches/py3k/Doc/library/shelve.rst (original) +++ python/branches/py3k/Doc/library/shelve.rst Sat Sep 1 15:51:09 2007 @@ -26,9 +26,6 @@ By default, version 0 pickles are used to serialize values. The version of the pickle protocol can be specified with the *protocol* parameter. - .. versionchanged:: 2.3 - The *protocol* parameter was added. - By default, mutations to persistent-dictionary mutable entries are not automatically written back. If the optional *writeback* parameter is set to *True*, all entries accessed are cached in memory, and written back at close @@ -90,9 +87,6 @@ pickle protocol can be specified with the *protocol* parameter. See the :mod:`pickle` documentation for a discussion of the pickle protocols. - .. versionchanged:: 2.3 - The *protocol* parameter was added. - If the *writeback* parameter is ``True``, the object will hold a cache of all entries accessed and write them back to the *dict* at sync and close times. This allows natural operations on mutable entries, but can consume much more Modified: python/branches/py3k/Doc/library/shlex.rst ============================================================================== --- python/branches/py3k/Doc/library/shlex.rst (original) +++ python/branches/py3k/Doc/library/shlex.rst Sat Sep 1 15:51:09 2007 @@ -10,8 +10,6 @@ .. sectionauthor:: Gustavo Niemeyer -.. versionadded:: 1.5.2 - The :class:`shlex` class makes it easy to write lexical analyzers for simple syntaxes resembling that of the Unix shell. This will often be useful for writing minilanguages, (for example, in run control files for Python @@ -32,11 +30,6 @@ empty string). This function operates in POSIX mode by default, but uses non-POSIX mode if the *posix* argument is false. - .. versionadded:: 2.3 - - .. versionchanged:: 2.6 - Added the *posix* parameter. - .. note:: Since the :func:`split` function instantiates a :class:`shlex` instance, passing @@ -129,16 +122,12 @@ specified it will later be available for use in error messages. This is the same method used internally by the :meth:`sourcehook` method. - .. versionadded:: 2.1 - .. method:: shlex.pop_source() Pop the last-pushed input source from the input stack. This is the same method used internally when the lexer reaches EOF on a stacked input stream. - .. versionadded:: 2.1 - .. method:: shlex.error_leader([file[, line]]) @@ -179,8 +168,6 @@ Characters that will be considered as escape. This will be only used in POSIX mode, and includes just ``'\'`` by default. - .. versionadded:: 2.3 - .. attribute:: shlex.quotes @@ -195,8 +182,6 @@ :attr:`escape`. This is only used in POSIX mode, and includes just ``'"'`` by default. - .. versionadded:: 2.3 - .. attribute:: shlex.whitespace_split @@ -204,8 +189,6 @@ example, for parsing command lines with :class:`shlex`, getting tokens in a similar way to shell arguments. - .. versionadded:: 2.3 - .. attribute:: shlex.infile @@ -252,8 +235,6 @@ Token used to determine end of file. This will be set to the empty string (``''``), in non-POSIX mode, and to ``None`` in POSIX mode. - .. versionadded:: 2.3 - .. _shlex-parsing-rules: Modified: python/branches/py3k/Doc/library/shutil.rst ============================================================================== --- python/branches/py3k/Doc/library/shutil.rst (original) +++ python/branches/py3k/Doc/library/shutil.rst Sat Sep 1 15:51:09 2007 @@ -82,15 +82,7 @@ files are copied to the new tree. If exception(s) occur, an :exc:`Error` is raised with a list of reasons. - The source code for this should be considered an example rather than a tool. - - .. versionchanged:: 2.3 - :exc:`Error` is raised if any exceptions occur during copying, rather than - printing a message. - - .. versionchanged:: 2.5 - Create intermediate directories needed to create *dst*, rather than raising an - error. Copy permissions and times of directories using :func:`copystat`. + The source code for this should be considered an example rather than a tool. .. function:: rmtree(path[, ignore_errors[, onerror]]) @@ -118,8 +110,6 @@ If the destination is on our current filesystem, then simply use rename. Otherwise, copy src to the dst and then remove src. - .. versionadded:: 2.3 - .. exception:: Error @@ -127,8 +117,6 @@ :func:`copytree`, the exception argument is a list of 3-tuples (*srcname*, *dstname*, *exception*). - .. versionadded:: 2.3 - .. _shutil-example: Modified: python/branches/py3k/Doc/library/simplehttpserver.rst ============================================================================== --- python/branches/py3k/Doc/library/simplehttpserver.rst (original) +++ python/branches/py3k/Doc/library/simplehttpserver.rst Sat Sep 1 15:51:09 2007 @@ -75,9 +75,6 @@ For example usage, see the implementation of the :func:`test` function. - .. versionadded:: 2.5 - The ``'Last-Modified'`` header. - .. seealso:: Modified: python/branches/py3k/Doc/library/simplexmlrpcserver.rst ============================================================================== --- python/branches/py3k/Doc/library/simplexmlrpcserver.rst (original) +++ python/branches/py3k/Doc/library/simplexmlrpcserver.rst Sat Sep 1 15:51:09 2007 @@ -8,15 +8,13 @@ .. sectionauthor:: Fred L. Drake, Jr. -.. versionadded:: 2.2 - The :mod:`SimpleXMLRPCServer` module provides a basic server framework for XML-RPC servers written in Python. Servers can either be free standing, using :class:`SimpleXMLRPCServer`, or embedded in a CGI environment, using :class:`CGIXMLRPCRequestHandler`. -.. class:: SimpleXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[, encoding]]]]) +.. class:: SimpleXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[, encoding[, bind_and_activate]]]]]) Create a new server instance. This class provides methods for registration of functions that can be called by the XML-RPC protocol. The *requestHandler* @@ -31,12 +29,6 @@ constructor; it defaults to true. Setting it to false allows code to manipulate the *allow_reuse_address* class variable before the address is bound. - .. versionchanged:: 2.5 - The *allow_none* and *encoding* parameters were added. - - .. versionchanged:: 2.6 - The *bind_and_activate* parameter was added. - .. class:: CGIXMLRPCRequestHandler([allow_none[, encoding]]) @@ -44,11 +36,6 @@ *allow_none* and *encoding* parameters are passed on to :mod:`xmlrpclib` and control the XML-RPC responses that will be returned from the server. - .. versionadded:: 2.3 - - .. versionchanged:: 2.5 - The *allow_none* and *encoding* parameters were added. - .. class:: SimpleXMLRPCRequestHandler() @@ -102,18 +89,12 @@ module's global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network. - .. versionchanged:: 2.3.5, 2.4.1 - *allow_dotted_names* was added to plug a security hole; prior versions are - insecure. - .. method:: SimpleXMLRPCServer.register_introspection_functions() Registers the XML-RPC introspection functions ``system.listMethods``, ``system.methodHelp`` and ``system.methodSignature``. - .. versionadded:: 2.3 - .. method:: SimpleXMLRPCServer.register_multicall_functions() @@ -127,7 +108,6 @@ 404 "no such page" HTTP error. If this tuple is empty, all paths will be considered valid. The default value is ``('/', '/RPC2')``. - .. versionadded:: 2.5 Example:: Modified: python/branches/py3k/Doc/library/site.rst ============================================================================== --- python/branches/py3k/Doc/library/site.rst (original) +++ python/branches/py3k/Doc/library/site.rst Sat Sep 1 15:51:09 2007 @@ -34,9 +34,6 @@ once. Blank lines and lines beginning with ``#`` are skipped. Lines starting with ``import`` (followed by space or tab) are executed. -.. versionchanged:: 2.6 - A space or tab is now required after the import keyword. - .. index:: single: package triple: path; configuration; file Modified: python/branches/py3k/Doc/library/smtplib.rst ============================================================================== --- python/branches/py3k/Doc/library/smtplib.rst (original) +++ python/branches/py3k/Doc/library/smtplib.rst Sat Sep 1 15:51:09 2007 @@ -30,9 +30,6 @@ For normal use, you should only require the initialization/connect, :meth:`sendmail`, and :meth:`quit` methods. An example is included below. - .. versionchanged:: 2.6 - *timeout* was added. - .. class:: SMTP_SSL([host[, port[, local_hostname[, keyfile[, certfile[, timeout]]]]]]) @@ -46,9 +43,6 @@ timeout in seconds for the connection attempt (if not specified, or passed as None, the global default timeout setting will be used). - .. versionchanged:: 2.6 - *timeout* was added. - .. class:: LMTP([host[, port[, local_hostname]]]) @@ -61,7 +55,6 @@ socket, LMTP generally don't support or require any authentication, but your mileage might vary. - .. versionadded:: 2.6 A nice selection of exceptions is defined as well: Modified: python/branches/py3k/Doc/library/socket.rst ============================================================================== --- python/branches/py3k/Doc/library/socket.rst (original) +++ python/branches/py3k/Doc/library/socket.rst Sat Sep 1 15:51:09 2007 @@ -63,8 +63,7 @@ resolution and/or the host configuration. For deterministic behavior use a numeric address in *host* portion. -.. versionadded:: 2.5 - AF_NETLINK sockets are represented as pairs ``pid, groups``. +AF_NETLINK sockets are represented as pairs ``pid, groups``. All errors raise exceptions. The normal exceptions for invalid argument types and out-of-memory conditions can be raised; errors related to socket or address @@ -114,8 +113,6 @@ timeouts enabled via a prior call to :meth:`settimeout`. The accompanying value is a string whose value is currently always "timed out". - .. versionadded:: 2.3 - .. data:: AF_UNIX AF_INET @@ -164,8 +161,6 @@ This constant contains a boolean value which indicates if IPv6 is supported on this platform. - .. versionadded:: 2.3 - .. function:: create_connection(address[, timeout]) @@ -176,8 +171,6 @@ instance (if it is not given or ``None``, the global default timeout setting is used). - .. versionadded:: 2.6 - .. function:: getaddrinfo(host, port[, family[, socktype[, proto[, flags]]]]) @@ -200,8 +193,6 @@ address, as described above. See the source for :mod:`socket` and other library modules for a typical usage of the function. - .. versionadded:: 2.2 - .. function:: getfqdn([name]) @@ -212,8 +203,6 @@ case no fully qualified domain name is available, the hostname as returned by :func:`gethostname` is returned. - .. versionadded:: 2.0 - .. function:: gethostbyname(hostname) @@ -264,8 +253,6 @@ or numeric address representation in *host*. Similarly, *port* can contain a string port name or a numeric port number. - .. versionadded:: 2.2 - .. function:: getprotobyname(protocolname) @@ -308,8 +295,6 @@ if defined on the platform; otherwise, the default is :const:`AF_INET`. Availability: Unix. - .. versionadded:: 2.4 - .. function:: fromfd(fd, family, type[, proto]) @@ -396,8 +381,6 @@ Availability: Unix (maybe not all platforms). - .. versionadded:: 2.3 - .. function:: inet_ntop(address_family, packed_ip) @@ -414,8 +397,6 @@ Availability: Unix (maybe not all platforms). - .. versionadded:: 2.3 - .. function:: getdefaulttimeout() @@ -423,8 +404,6 @@ of ``None`` indicates that new socket objects have no timeout. When the socket module is first imported, the default is ``None``. - .. versionadded:: 2.3 - .. function:: setdefaulttimeout(timeout) @@ -432,8 +411,6 @@ ``None`` indicates that new socket objects have no timeout. When the socket module is first imported, the default is ``None``. - .. versionadded:: 2.3 - .. data:: SocketType @@ -599,8 +576,6 @@ optional argument *flags*; it defaults to zero. (The format of *address* depends on the address family --- see above.) - .. versionadded:: 2.5 - .. method:: socket.recv_into(buffer[, nbytes[, flags]]) @@ -610,8 +585,6 @@ :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults to zero. - .. versionadded:: 2.5 - .. method:: socket.send(string[, flags]) @@ -662,8 +635,6 @@ ``s.settimeout(0.0)`` is equivalent to ``s.setblocking(0)``; ``s.settimeout(None)`` is equivalent to ``s.setblocking(1)``. - .. versionadded:: 2.3 - .. method:: socket.gettimeout() @@ -671,7 +642,6 @@ ``None`` if no timeout is set. This reflects the last call to :meth:`setblocking` or :meth:`settimeout`. - .. versionadded:: 2.3 Some notes on socket blocking and timeouts: A socket object can be in one of three modes: blocking, non-blocking, or timeout. Sockets are always created in @@ -724,22 +694,16 @@ The socket family. - .. versionadded:: 2.5 - .. attribute:: socket.type The socket type. - .. versionadded:: 2.5 - .. attribute:: socket.proto The socket protocol. - .. versionadded:: 2.5 - .. _socket-example: Modified: python/branches/py3k/Doc/library/spwd.rst ============================================================================== --- python/branches/py3k/Doc/library/spwd.rst (original) +++ python/branches/py3k/Doc/library/spwd.rst Sat Sep 1 15:51:09 2007 @@ -7,8 +7,6 @@ :synopsis: The shadow password database (getspnam() and friends). -.. versionadded:: 2.5 - This module provides access to the Unix shadow password database. It is available on various Unix versions. Modified: python/branches/py3k/Doc/library/sqlite3.rst ============================================================================== --- python/branches/py3k/Doc/library/sqlite3.rst (original) +++ python/branches/py3k/Doc/library/sqlite3.rst Sat Sep 1 15:51:09 2007 @@ -7,8 +7,6 @@ .. sectionauthor:: Gerhard H??ring -.. versionadded:: 2.5 - SQLite is a C library that provides a lightweight disk-based database that doesn't require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use Modified: python/branches/py3k/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k/Doc/library/ssl.rst (original) +++ python/branches/py3k/Doc/library/ssl.rst Sat Sep 1 15:51:09 2007 @@ -6,9 +6,6 @@ :synopsis: SSL wrapper for socket objects .. moduleauthor:: Bill Janssen - -.. versionadded:: 2.6 - .. sectionauthor:: Bill Janssen Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Sat Sep 1 15:51:09 2007 @@ -417,8 +417,6 @@ Iterator Types ============== -.. versionadded:: 2.2 - .. index:: single: iterator protocol single: protocol; iterator @@ -654,9 +652,6 @@ method which assures consistent linear concatenation performance across versions and implementations. - .. versionchanged:: 2.4 - Formerly, string concatenation never occurred in-place. - .. _string-methods: @@ -680,9 +675,6 @@ Return centered in a string of length *width*. Padding is done using the specified *fillchar* (default is a space). - .. versionchanged:: 2.4 - Support for the *fillchar* argument. - .. method:: str.count(sub[, start[, end]]) @@ -702,12 +694,6 @@ :ref:`codec-base-classes`. For a list of possible encodings, see section :ref:`standard-encodings`. - .. versionadded:: 2.0 - - .. versionchanged:: 2.3 - Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error - handling schemes added. - .. method:: str.endswith(suffix[, start[, end]]) @@ -716,9 +702,6 @@ *start*, test beginning at that position. With optional *end*, stop comparing at that position. - .. versionchanged:: 2.5 - Accept tuples as *suffix*. - .. method:: str.expandtabs([tabsize]) @@ -749,8 +732,6 @@ See :ref:`formatstrings` for a description of the various formatting options that can be specified in format strings. - .. versionadded:: 3.0 - .. method:: str.index(sub[, start[, end]]) @@ -818,9 +799,6 @@ using the specified *fillchar* (default is a space). The original string is returned if *width* is less than ``len(s)``. - .. versionchanged:: 2.4 - Support for the *fillchar* argument. - .. method:: str.lower() @@ -839,9 +817,6 @@ >>> 'www.example.com'.lstrip('cmowz.') 'example.com' - .. versionchanged:: 2.2.2 - Support for the *chars* argument. - .. method:: str.partition(sep) @@ -850,8 +825,6 @@ after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings. - .. versionadded:: 2.5 - .. method:: str.replace(old, new[, count]) @@ -879,9 +852,6 @@ using the specified *fillchar* (default is a space). The original string is returned if *width* is less than ``len(s)``. - .. versionchanged:: 2.4 - Support for the *fillchar* argument. - .. method:: str.rpartition(sep) @@ -890,8 +860,6 @@ after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself. - .. versionadded:: 2.5 - .. method:: str.rsplit([sep[, maxsplit]]) @@ -901,8 +869,6 @@ separator. Except for splitting from the right, :meth:`rsplit` behaves like :meth:`split` which is described in detail below. - .. versionadded:: 2.4 - .. method:: str.rstrip([chars]) @@ -916,9 +882,6 @@ >>> 'mississippi'.rstrip('ipz') 'mississ' - .. versionchanged:: 2.2.2 - Support for the *chars* argument. - .. method:: str.split([sep[, maxsplit]]) @@ -955,9 +918,6 @@ test string beginning at that position. With optional *end*, stop comparing string at that position. - .. versionchanged:: 2.5 - Accept tuples as *prefix*. - .. method:: str.strip([chars]) @@ -972,9 +932,6 @@ >>> 'www.example.com'.strip('cmowz.') 'example' - .. versionchanged:: 2.2.2 - Support for the *chars* argument. - .. method:: str.swapcase() @@ -1012,8 +969,6 @@ Return the numeric string left filled with zeros in a string of length *width*. The original string is returned if *width* is less than ``len(s)``. - .. versionadded:: 2.2.2 - .. _old-string-formatting: @@ -1315,18 +1270,11 @@ length is added, as for slice indices. If it is still negative, it is truncated to zero, as for slice indices. - .. versionchanged:: 2.3 - Previously, :meth:`index` didn't have arguments for specifying start and stop - positions. - (4) When a negative index is passed as the first parameter to the :meth:`insert` method, the sequence length is added, as for slice indices. If it is still negative, it is truncated to zero, as for slice indices. - .. versionchanged:: 2.3 - Previously, all negative indices were truncated to zero. - (5) The optional argument *i* defaults to ``-1``, so that by default the last item is removed and returned. @@ -1359,12 +1307,6 @@ multiple times for each list element while *key* and *reverse* touch each element only once. - .. versionchanged:: 2.3 - Support for ``None`` as an equivalent to omitting *cmp* was added. - - .. versionchanged:: 2.4 - Support for *key* and *reverse* was added. - Starting with Python 2.3, the :meth:`sort` method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal --- this is helpful for sorting in multiple passes (for @@ -1572,9 +1514,6 @@ (For other containers see the built in :class:`dict`, :class:`list`, and :class:`tuple` classes, and the :mod:`collections` module.) - -.. versionadded:: 2.4 - Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in set``. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or @@ -1796,11 +1735,6 @@ The first example only works for keys that are valid Python identifiers; the others work with any valid keys. - .. versionadded:: 2.2 - - .. versionchanged:: 2.3 - Support for building a dictionary from keyword arguments added. - These are the operations that dictionaries support (and therefore, custom mapping types should support too): @@ -1814,16 +1748,14 @@ Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is not in the map. - .. versionadded:: 2.5 - If a subclass of dict defines a method :meth:`__missing__`, if the key - *key* is not present, the ``d[key]`` operation calls that method with the - key *key* as argument. The ``d[key]`` operation then returns or raises - whatever is returned or raised by the ``__missing__(key)`` call if the key - is not present. No other operations or methods invoke - :meth:`__missing__`. If :meth:`__missing__` is not defined, - :exc:`KeyError` is raised. :meth:`__missing__` must be a method; it - cannot be an instance variable. For an example, see - :class:`collections.defaultdict`. + If a subclass of dict defines a method :meth:`__missing__`, if the key *key* + is not present, the ``d[key]`` operation calls that method with the key *key* + as argument. The ``d[key]`` operation then returns or raises whatever is + returned or raised by the ``__missing__(key)`` call if the key is not + present. No other operations or methods invoke :meth:`__missing__`. If + :meth:`__missing__` is not defined, :exc:`KeyError` is raised. + :meth:`__missing__` must be a method; it cannot be an instance variable. For + an example, see :class:`collections.defaultdict`. .. describe:: d[key] = value @@ -1838,14 +1770,10 @@ Return ``True`` if *d* has a key *key*, else ``False``. - .. versionadded:: 2.2 - .. describe:: key not in d Equivalent to ``not key in d``. - .. versionadded:: 2.2 - .. method:: dict.clear() Remove all items from the dictionary. @@ -1861,8 +1789,6 @@ :func:`fromkeys` is a class method that returns a new dictionary. *value* defaults to ``None``. - .. versionadded:: 2.3 - .. method:: dict.get(key[, default]) Return the value for *key* if *key* is in the dictionary, else *default*. If @@ -1895,22 +1821,16 @@ Return an iterator over the dictionary's ``(key, value)`` pairs. See the note for :meth:`dict.items`. - .. versionadded:: 2.2 - .. method:: dict.iterkeys() Return an iterator over the dictionary's keys. See the note for :meth:`dict.items`. - .. versionadded:: 2.2 - .. method:: dict.itervalues() Return an iterator over the dictionary's values. See the note for :meth:`dict.items`. - .. versionadded:: 2.2 - .. method:: dict.keys() Return a copy of the dictionary's list of keys. See the note for @@ -1922,8 +1842,6 @@ *default*. If *default* is not given and *key* is not in the dictionary, a :exc:`KeyError` is raised. - .. versionadded:: 2.3 - .. method:: dict.popitem() Remove and return an arbitrary ``(key, value)`` pair from the dictionary. @@ -1947,10 +1865,6 @@ arguments are specified, the dictionary is then is updated with those key/value pairs: ``d.update(red=1, blue=2)``. - .. versionchanged:: 2.4 - Allowed the argument to be an iterable of key/value pairs and allowed - keyword arguments. - .. method:: dict.values() Return a copy of the dictionary's list of values. See the note for @@ -2068,8 +1982,6 @@ right. However, using :meth:`seek` to reposition the file to an absolute position will flush the read-ahead buffer. - .. versionadded:: 2.3 - .. method:: file.read([size]) @@ -2124,9 +2036,6 @@ Note that not all file objects are seekable. - .. versionchanged:: 2.6 - Passing float values as offset has been deprecated - .. method:: file.tell() @@ -2191,8 +2100,6 @@ on all file-like objects. It may also be ``None``, in which case the file uses the system default encoding for converting Unicode strings. - .. versionadded:: 2.3 - .. attribute:: file.mode @@ -2243,8 +2150,6 @@ Context Manager Types ===================== -.. versionadded:: 2.5 - .. index:: single: context manager single: context management protocol Modified: python/branches/py3k/Doc/library/string.rst ============================================================================== --- python/branches/py3k/Doc/library/string.rst (original) +++ python/branches/py3k/Doc/library/string.rst Sat Sep 1 15:51:09 2007 @@ -178,7 +178,6 @@ (as in the tuple returned by the :meth:`parse` method.) The default version understands 'r' (repr) and 's' (str) conversion types. - .. versionadded:: 3.0 .. _formatstrings: @@ -274,7 +273,6 @@ (The extra space is because we specified a field width of 10, and because left alignment is the default for strings.) -.. versionadded:: 3.0 .. _formatspec: @@ -446,8 +444,6 @@ Any other appearance of ``$`` in the string will result in a :exc:`ValueError` being raised. -.. versionadded:: 2.4 - The :mod:`string` module provides a :class:`Template` class that implements these rules. The methods of :class:`Template` are: Modified: python/branches/py3k/Doc/library/stringprep.rst ============================================================================== --- python/branches/py3k/Doc/library/stringprep.rst (original) +++ python/branches/py3k/Doc/library/stringprep.rst Sat Sep 1 15:51:09 2007 @@ -9,8 +9,6 @@ .. sectionauthor:: Martin v. L?wis -.. versionadded:: 2.3 - When identifying things (such as host names) in the internet, it is often necessary to compare such identifications for "equality". Exactly how this comparison is executed may depend on the application domain, e.g. whether it Modified: python/branches/py3k/Doc/library/struct.rst ============================================================================== --- python/branches/py3k/Doc/library/struct.rst (original) +++ python/branches/py3k/Doc/library/struct.rst Sat Sep 1 15:51:09 2007 @@ -37,8 +37,6 @@ bytes into the writable *buffer* starting at *offset*. Note that the offset is a required argument. - .. versionadded:: 2.5 - .. function:: unpack(fmt, string) @@ -55,8 +53,6 @@ of data required by the format (``len(buffer[offset:])`` must be at least ``calcsize(fmt)``). - .. versionadded:: 2.5 - .. function:: calcsize(fmt) @@ -114,15 +110,11 @@ C99. If this type is not available, it is simulated using a :ctype:`char`. In standard mode, it is always represented by one byte. - .. versionadded:: 2.6 - (2) The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if the platform C compiler supports C :ctype:`long long`, or, on Windows, :ctype:`__int64`. They are always available in standard modes. - .. versionadded:: 2.2 - A format character may be preceded by an integral repeat count. For example, the format string ``'4h'`` means exactly the same as ``'hhhh'``. @@ -258,11 +250,9 @@ is more efficient than calling the :mod:`struct` functions with the same format since the format string only needs to be compiled once. - .. versionadded:: 2.5 Compiled Struct objects support the following methods and attributes: - .. method:: Struct.pack(v1, v2, ...) Identical to the :func:`pack` function, using the compiled format. Modified: python/branches/py3k/Doc/library/subprocess.rst ============================================================================== --- python/branches/py3k/Doc/library/subprocess.rst (original) +++ python/branches/py3k/Doc/library/subprocess.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Peter ?strand -.. versionadded:: 2.4 - The :mod:`subprocess` module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, such as:: @@ -138,8 +136,6 @@ check_call(["ls", "-l"]) - .. versionadded:: 2.5 - Exceptions ^^^^^^^^^^ Modified: python/branches/py3k/Doc/library/sys.rst ============================================================================== --- python/branches/py3k/Doc/library/sys.rst (original) +++ python/branches/py3k/Doc/library/sys.rst Sat Sep 1 15:51:09 2007 @@ -29,8 +29,6 @@ big-endian (most-significant byte first) platforms, and ``'little'`` on little-endian (least-significant byte first) platforms. - .. versionadded:: 2.0 - .. data:: subversion @@ -43,8 +41,6 @@ exported (or svnversion was not available), it is the revision of ``Include/patchlevel.h`` if the branch is a tag. Otherwise, it is ``None``. - .. versionadded:: 2.5 - .. data:: builtin_module_names @@ -73,8 +69,6 @@ This function should be used for internal and specialized purposes only. - .. versionadded:: 2.5 - .. data:: dllhandle @@ -194,16 +188,12 @@ Return the interpreter's "check interval"; see :func:`setcheckinterval`. - .. versionadded:: 2.3 - .. function:: getdefaultencoding() Return the name of the current default string encoding used by the Unicode implementation. - .. versionadded:: 2.0 - .. function:: getdlopenflags() @@ -211,8 +201,6 @@ The flag constants are defined in the :mod:`dl` and :mod:`DLFCN` modules. Availability: Unix. - .. versionadded:: 2.2 - .. function:: getfilesystemencoding() @@ -232,8 +220,6 @@ the encoding that applications should use when they explicitly want to convert Unicode strings to byte strings that are equivalent when used as file names. - .. versionadded:: 2.3 - .. function:: getrefcount(object) @@ -285,8 +271,6 @@ Availability: Windows. - .. versionadded:: 2.3 - .. data:: hexversion @@ -306,8 +290,6 @@ ``version_info`` value may be used for a more human-friendly encoding of the same information. - .. versionadded:: 1.5.2 - .. function:: intern(string) @@ -319,10 +301,8 @@ names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys. - .. versionchanged:: 2.3 - Interned strings are not immortal (like they used to be in Python 2.2 and - before); you must keep a reference to the return value of :func:`intern` around - to benefit from it. + Interned strings are not immortal; you must keep a reference to the return + value of :func:`intern` around to benefit from it. .. data:: last_type @@ -381,9 +361,6 @@ A program is free to modify this list for its own purposes. - .. versionchanged:: 2.3 - Unicode strings are no longer ignored. - .. data:: platform @@ -441,8 +418,6 @@ .. % the \programopt{-S} option is passed to the interpreter, in which .. % case this function will remain available. - .. versionadded:: 2.0 - .. function:: setdlopenflags(n) @@ -456,8 +431,6 @@ :file:`/usr/include/dlfcn.h` using the :program:`h2py` script. Availability: Unix. - .. versionadded:: 2.2 - .. function:: setprofile(profilefunc) @@ -515,8 +488,6 @@ available only if Python was compiled with :option:`--with-tsc`. To understand the output of this dump, read :file:`Python/ceval.c` in the Python sources. - .. versionadded:: 2.4 - .. data:: stdin stdout @@ -569,8 +540,6 @@ The C API version for this interpreter. Programmers may find this useful when debugging version conflicts between Python and extension modules. - .. versionadded:: 2.3 - .. data:: version_info @@ -580,8 +549,6 @@ ``'final'``. The ``version_info`` value corresponding to the Python version 2.0 is ``(2, 0, 0, 'final', 0)``. - .. versionadded:: 2.0 - .. data:: warnoptions Modified: python/branches/py3k/Doc/library/tarfile.rst ============================================================================== --- python/branches/py3k/Doc/library/tarfile.rst (original) +++ python/branches/py3k/Doc/library/tarfile.rst Sat Sep 1 15:51:09 2007 @@ -7,8 +7,6 @@ :synopsis: Read and write tar-format archive files. -.. versionadded:: 2.3 - .. moduleauthor:: Lars Gust?bel .. sectionauthor:: Lars Gust?bel @@ -25,8 +23,6 @@ * read/write support for the POSIX.1-2001 (pax) format. - .. versionadded:: 2.6 - * handles directories, regular files, hardlinks, symbolic links, fifos, character devices and block devices and is able to acquire and restore file information like timestamp, access permissions and owner. @@ -172,7 +168,6 @@ Is raised by :meth:`frombuf` if the buffer it gets is invalid. - .. versionadded:: 2.6 Each of the following constants defines a tar archive format that the :mod:`tarfile` module is able to create. See section :ref:`tar-formats` for @@ -248,13 +243,9 @@ :const:`USTAR_FORMAT`, :const:`GNU_FORMAT` or :const:`PAX_FORMAT` that are defined at module level. - .. versionadded:: 2.6 - The *tarinfo* argument can be used to replace the default :class:`TarInfo` class with a different one. - .. versionadded:: 2.6 - If *dereference* is ``False``, add symbolic and hard links to the archive. If it is ``True``, add the content of the target files to the archive. This has no effect on systems that do not support symbolic links. @@ -277,13 +268,9 @@ to be handled. The default settings will work for most users. See section :ref:`tar-unicode` for in-depth information. - .. versionadded:: 2.6 - The *pax_headers* argument is an optional dictionary of strings which will be added as a pax global header if *format* is :const:`PAX_FORMAT`. - .. versionadded:: 2.6 - .. method:: TarFile.open(...) @@ -345,8 +332,6 @@ that have absolute filenames starting with ``"/"`` or filenames with two dots ``".."``. - .. versionadded:: 2.5 - .. method:: TarFile.extract(member[, path]) @@ -384,14 +369,11 @@ Add the file *name* to the archive. *name* may be any type of file (directory, fifo, symbolic link, etc.). If given, *arcname* specifies an alternative name for the file in the archive. Directories are added recursively by default. This - can be avoided by setting *recursive* to :const:`False`. If *exclude* is given + can be avoided by setting *recursive* to :const:`False`. If *exclude* is given, it must be a function that takes one filename argument and returns a boolean value. Depending on this value the respective file is either excluded (:const:`True`) or added (:const:`False`). - .. versionchanged:: 2.6 - Added the *exclude* parameter. - .. method:: TarFile.addfile(tarinfo[, fileobj]) @@ -425,8 +407,7 @@ attribute to :const:`USTAR_FORMAT`, :const:`False` is equivalent to :const:`GNU_FORMAT`. - .. versionchanged:: 2.4 - *posix* defaults to :const:`False`. + *posix* defaults to :const:`False`. .. deprecated:: 2.6 Use the :attr:`format` attribute instead. @@ -436,7 +417,6 @@ A dictionary containing key-value pairs of pax global headers. - .. versionadded:: 2.6 .. % ----------------- .. % TarInfo Objects @@ -466,8 +446,7 @@ Create and return a :class:`TarInfo` object from string buffer *buf*. - .. versionadded:: 2.6 - Raises :exc:`HeaderError` if the buffer is invalid.. + Raises :exc:`HeaderError` if the buffer is invalid.. .. method:: TarInfo.fromtarfile(tarfile) @@ -475,16 +454,12 @@ Read the next member from the :class:`TarFile` object *tarfile* and return it as a :class:`TarInfo` object. - .. versionadded:: 2.6 - .. method:: TarInfo.tobuf([format[, encoding [, errors]]]) Create a string buffer from a :class:`TarInfo` object. For information on the arguments see the constructor of the :class:`TarFile` class. - .. versionchanged:: 2.6 - The arguments were added. A ``TarInfo`` object has the following public data attributes: @@ -548,7 +523,6 @@ A dictionary containing key-value pairs of an associated pax extended header. - .. versionadded:: 2.6 A :class:`TarInfo` object also provides some convenient query methods: Modified: python/branches/py3k/Doc/library/telnetlib.rst ============================================================================== --- python/branches/py3k/Doc/library/telnetlib.rst (original) +++ python/branches/py3k/Doc/library/telnetlib.rst Sat Sep 1 15:51:09 2007 @@ -39,9 +39,6 @@ :exc:`EOFError` when the end of the connection is read, because they can return an empty string for other reasons. See the individual descriptions below. - .. versionchanged:: 2.6 - *timeout* was added. - .. seealso:: @@ -119,8 +116,6 @@ callback should access these data when it was invoked with a ``SE`` command. This method never blocks. - .. versionadded:: 2.3 - .. method:: Telnet.open(host[, port[, timeout]]) @@ -131,9 +126,6 @@ Do not try to reopen an already connected instance. - .. versionchanged:: 2.6 - *timeout* was added. - .. method:: Telnet.msg(msg[, *args]) Modified: python/branches/py3k/Doc/library/tempfile.rst ============================================================================== --- python/branches/py3k/Doc/library/tempfile.rst (original) +++ python/branches/py3k/Doc/library/tempfile.rst Sat Sep 1 15:51:09 2007 @@ -60,11 +60,6 @@ across platforms (it can be so used on Unix; it cannot on Windows NT or later). If *delete* is true (the default), the file is deleted as soon as it is closed. - .. versionadded:: 2.3 - - .. versionadded:: 2.6 - The *delete* parameter. - .. function:: SpooledTemporaryFile([max_size=0, [mode='w+b'[, bufsize=-1[, suffix[, prefix[, dir]]]]]]) @@ -76,8 +71,6 @@ The resulting file has one additional method, :func:`rollover`, which causes the file to roll over to an on-disk file regardless of its size. - .. versionadded:: 2.6 - .. function:: mkstemp([suffix[, prefix[, dir[, text]]]]) @@ -114,8 +107,6 @@ (as would be returned by :func:`os.open`) and the absolute pathname of that file, in that order. - .. versionadded:: 2.3 - .. function:: mkdtemp([suffix[, prefix[, dir]]]) @@ -130,8 +121,6 @@ :func:`mkdtemp` returns the absolute pathname of the new directory. - .. versionadded:: 2.3 - .. function:: mktemp([suffix[, prefix[, dir]]]) @@ -209,5 +198,3 @@ contain the directory component. Using this function is preferred over reading the *template* variable directly. - .. versionadded:: 1.5.2 - Modified: python/branches/py3k/Doc/library/test.rst ============================================================================== --- python/branches/py3k/Doc/library/test.rst (original) +++ python/branches/py3k/Doc/library/test.rst Sat Sep 1 15:51:09 2007 @@ -297,8 +297,6 @@ warnings.warn("foo") assert str(w.message) == "foo" - .. versionadded:: 2.6 - .. function:: captured_stdout() @@ -312,8 +310,6 @@ print "hello" assert s.getvalue() == "hello" - .. versionadded:: 2.6 - The :mod:`test.test_support` module defines the following classes: @@ -325,16 +321,12 @@ :keyword:`with` statement. Only if all pairs match properly against attributes on the exception is :exc:`ResourceDenied` raised. - .. versionadded:: 2.6 - .. class:: EnvironmentVarGuard() Class used to temporarily set or unset environment variables. Instances can be used as a context manager. - .. versionadded:: 2.6 - .. method:: EnvironmentVarGuard.set(envvar, value) Modified: python/branches/py3k/Doc/library/textwrap.rst ============================================================================== --- python/branches/py3k/Doc/library/textwrap.rst (original) +++ python/branches/py3k/Doc/library/textwrap.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Greg Ward -.. versionadded:: 2.3 - The :mod:`textwrap` module provides two convenience functions, :func:`wrap` and :func:`fill`, as well as :class:`TextWrapper`, the class that does all the work, and a utility function :func:`dedent`. If you're just wrapping or filling one @@ -124,9 +122,6 @@ at the beginning or end of a line is dropped (leading whitespace in the first line is always preserved, though). - .. versionadded:: 2.6 - Whitespace was always dropped in earlier versions. - .. attribute:: TextWrapper.initial_indent Modified: python/branches/py3k/Doc/library/thread.rst ============================================================================== --- python/branches/py3k/Doc/library/thread.rst (original) +++ python/branches/py3k/Doc/library/thread.rst Sat Sep 1 15:51:09 2007 @@ -55,8 +55,6 @@ Raise a :exc:`KeyboardInterrupt` exception in the main thread. A subthread can use this function to interrupt the main thread. - .. versionadded:: 2.3 - .. function:: exit() @@ -102,7 +100,6 @@ the suggested approach in the absence of more specific information). Availability: Windows, systems with POSIX threads. - .. versionadded:: 2.5 Lock objects have the following methods: Modified: python/branches/py3k/Doc/library/threading.rst ============================================================================== --- python/branches/py3k/Doc/library/threading.rst (original) +++ python/branches/py3k/Doc/library/threading.rst Sat Sep 1 15:51:09 2007 @@ -67,8 +67,6 @@ For more details and extensive examples, see the documentation string of the :mod:`_threading_local` module. - .. versionadded:: 2.4 - .. function:: Lock() @@ -123,8 +121,6 @@ The *func* will be passed to :func:`sys.settrace` for each thread, before its :meth:`run` method is called. - .. versionadded:: 2.3 - .. function:: setprofile(func) @@ -134,8 +130,6 @@ The *func* will be passed to :func:`sys.setprofile` for each thread, before its :meth:`run` method is called. - .. versionadded:: 2.3 - .. function:: stack_size([size]) @@ -154,7 +148,6 @@ the suggested approach in the absence of more specific information). Availability: Windows, systems with POSIX threads. - .. versionadded:: 2.5 Detailed interfaces for the objects are documented below. Modified: python/branches/py3k/Doc/library/time.rst ============================================================================== --- python/branches/py3k/Doc/library/time.rst (original) +++ python/branches/py3k/Doc/library/time.rst Sat Sep 1 15:51:09 2007 @@ -115,10 +115,6 @@ :class:`struct_time`, or having elements of the wrong type, a :exc:`TypeError` is raised. - .. versionchanged:: 2.2 - The time value sequence was changed from a tuple to a :class:`struct_time`, with - the addition of attribute names for the fields. - The module defines the following functions and data items: @@ -149,9 +145,6 @@ Unlike the C function of the same name, there is no trailing newline. - .. versionchanged:: 2.1 - Allowed *t* to be omitted. - .. function:: clock() @@ -178,12 +171,6 @@ returned by :func:`time` is used. ``ctime(secs)`` is equivalent to ``asctime(localtime(secs))``. Locale information is not used by :func:`ctime`. - .. versionchanged:: 2.1 - Allowed *secs* to be omitted. - - .. versionchanged:: 2.4 - If *secs* is :const:`None`, the current time is used. - .. data:: daylight @@ -199,12 +186,6 @@ :class:`struct_time` object. See :func:`calendar.timegm` for the inverse of this function. - .. versionchanged:: 2.1 - Allowed *secs* to be omitted. - - .. versionchanged:: 2.4 - If *secs* is :const:`None`, the current time is used. - .. function:: localtime([secs]) @@ -212,12 +193,6 @@ :const:`None`, the current time as returned by :func:`time` is used. The dst flag is set to ``1`` when DST applies to the given time. - .. versionchanged:: 2.1 - Allowed *secs* to be omitted. - - .. versionchanged:: 2.4 - If *secs* is :const:`None`, the current time is used. - .. function:: mktime(t) @@ -249,96 +224,89 @@ :func:`localtime` is used. *format* must be a string. :exc:`ValueError` is raised if any field in *t* is outside of the allowed range. - .. versionchanged:: 2.1 - Allowed *t* to be omitted. - - .. versionchanged:: 2.4 - :exc:`ValueError` raised if a field in *t* is out of range. - - .. versionchanged:: 2.5 - 0 is now a legal argument for any position in the time tuple; if it is normally - illegal the value is forced to a correct one.. + 0 is a legal argument for any position in the time tuple; if it is normally + illegal the value is forced to a correct one. The following directives can be embedded in the *format* string. They are shown without the optional field width and precision specification, and are replaced by the indicated characters in the :func:`strftime` result: - +-----------+--------------------------------+-------+ - | Directive | Meaning | Notes | - +===========+================================+=======+ - | ``%a`` | Locale's abbreviated weekday | | - | | name. | | - +-----------+--------------------------------+-------+ - | ``%A`` | Locale's full weekday name. | | - +-----------+--------------------------------+-------+ - | ``%b`` | Locale's abbreviated month | | - | | name. | | - +-----------+--------------------------------+-------+ - | ``%B`` | Locale's full month name. | | - +-----------+--------------------------------+-------+ - | ``%c`` | Locale's appropriate date and | | - | | time representation. | | - +-----------+--------------------------------+-------+ - | ``%d`` | Day of the month as a decimal | | - | | number [01,31]. | | - +-----------+--------------------------------+-------+ - | ``%H`` | Hour (24-hour clock) as a | | - | | decimal number [00,23]. | | - +-----------+--------------------------------+-------+ - | ``%I`` | Hour (12-hour clock) as a | | - | | decimal number [01,12]. | | - +-----------+--------------------------------+-------+ - | ``%j`` | Day of the year as a decimal | | - | | number [001,366]. | | - +-----------+--------------------------------+-------+ - | ``%m`` | Month as a decimal number | | - | | [01,12]. | | - +-----------+--------------------------------+-------+ - | ``%M`` | Minute as a decimal number | | - | | [00,59]. | | - +-----------+--------------------------------+-------+ - | ``%p`` | Locale's equivalent of either | \(1) | - | | AM or PM. | | - +-----------+--------------------------------+-------+ - | ``%S`` | Second as a decimal number | \(2) | - | | [00,61]. | | - +-----------+--------------------------------+-------+ - | ``%U`` | Week number of the year | \(3) | - | | (Sunday as the first day of | | - | | the week) as a decimal number | | - | | [00,53]. All days in a new | | - | | year preceding the first | | - | | Sunday are considered to be in | | - | | week 0. | | - +-----------+--------------------------------+-------+ - | ``%w`` | Weekday as a decimal number | | - | | [0(Sunday),6]. | | - +-----------+--------------------------------+-------+ - | ``%W`` | Week number of the year | \(3) | - | | (Monday as the first day of | | - | | the week) as a decimal number | | - | | [00,53]. All days in a new | | - | | year preceding the first | | - | | Monday are considered to be in | | - | | week 0. | | - +-----------+--------------------------------+-------+ - | ``%x`` | Locale's appropriate date | | - | | representation. | | - +-----------+--------------------------------+-------+ - | ``%X`` | Locale's appropriate time | | - | | representation. | | - +-----------+--------------------------------+-------+ - | ``%y`` | Year without century as a | | - | | decimal number [00,99]. | | - +-----------+--------------------------------+-------+ - | ``%Y`` | Year with century as a decimal | | - | | number. | | - +-----------+--------------------------------+-------+ - | ``%Z`` | Time zone name (no characters | | - | | if no time zone exists). | | - +-----------+--------------------------------+-------+ - | ``%%`` | A literal ``'%'`` character. | | - +-----------+--------------------------------+-------+ + +-----------+------------------------------------------------+-------+ + | Directive | Meaning | Notes | + +===========+================================================+=======+ + | ``%a`` | Locale's abbreviated weekday name. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%A`` | Locale's full weekday name. | | + +-----------+------------------------------------------------+-------+ + | ``%b`` | Locale's abbreviated month name. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%B`` | Locale's full month name. | | + +-----------+------------------------------------------------+-------+ + | ``%c`` | Locale's appropriate date and time | | + | | representation. | | + +-----------+------------------------------------------------+-------+ + | ``%d`` | Day of the month as a decimal number [01,31]. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%H`` | Hour (24-hour clock) as a decimal number | | + | | [00,23]. | | + +-----------+------------------------------------------------+-------+ + | ``%I`` | Hour (12-hour clock) as a decimal number | | + | | [01,12]. | | + +-----------+------------------------------------------------+-------+ + | ``%j`` | Day of the year as a decimal number [001,366]. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%m`` | Month as a decimal number [01,12]. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%M`` | Minute as a decimal number [00,59]. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%p`` | Locale's equivalent of either AM or PM. | \(1) | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%S`` | Second as a decimal number [00,61]. | \(2) | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%U`` | Week number of the year (Sunday as the first | \(3) | + | | day of the week) as a decimal number [00,53]. | | + | | All days in a new year preceding the first | | + | | Sunday are considered to be in week 0. | | + | | | | + | | | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%w`` | Weekday as a decimal number [0(Sunday),6]. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%W`` | Week number of the year (Monday as the first | \(3) | + | | day of the week) as a decimal number [00,53]. | | + | | All days in a new year preceding the first | | + | | Monday are considered to be in week 0. | | + | | | | + | | | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%x`` | Locale's appropriate date representation. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%X`` | Locale's appropriate time representation. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%y`` | Year without century as a decimal number | | + | | [00,99]. | | + +-----------+------------------------------------------------+-------+ + | ``%Y`` | Year with century as a decimal number. | | + | | | | + +-----------+------------------------------------------------+-------+ + | ``%Z`` | Time zone name (no characters if no time zone | | + | | exists). | | + +-----------+------------------------------------------------+-------+ + | ``%%`` | A literal ``'%'`` character. | | + +-----------+------------------------------------------------+-------+ Notes: @@ -405,8 +373,6 @@ The type of the time value sequence returned by :func:`gmtime`, :func:`localtime`, and :func:`strptime`. - .. versionadded:: 2.2 - .. function:: time() @@ -436,8 +402,6 @@ Resets the time conversion rules used by the library routines. The environment variable :envvar:`TZ` specifies how this is done. - .. versionadded:: 2.3 - Availability: Unix. .. note:: Modified: python/branches/py3k/Doc/library/timeit.rst ============================================================================== --- python/branches/py3k/Doc/library/timeit.rst (original) +++ python/branches/py3k/Doc/library/timeit.rst Sat Sep 1 15:51:09 2007 @@ -6,8 +6,6 @@ :synopsis: Measure the execution time of small code snippets. -.. versionadded:: 2.3 - .. index:: single: Benchmarking single: Performance @@ -33,11 +31,10 @@ method. The :meth:`repeat` method is a convenience to call :meth:`timeit` multiple times and return a list of results. - .. versionchanged:: 2.6 - The *stmt* and *setup* parameters can now also take objects that are callable - without arguments. This will embed calls to them in a timer function that will - then be executed by :meth:`timeit`. Note that the timing overhead is a little - larger in this case because of the extra function calls. + The *stmt* and *setup* parameters can also take objects that are callable + without arguments. This will embed calls to them in a timer function that + will then be executed by :meth:`timeit`. Note that the timing overhead is a + little larger in this case because of the extra function calls. .. method:: Timer.print_exc([file=None]) @@ -105,16 +102,12 @@ function and run its :meth:`repeat` method with the given repeat count and *number* executions. - .. versionadded:: 2.6 - .. function:: timeit(stmt[, setup[, timer[, number=1000000]]]) Create a :class:`Timer` instance with the given statement, setup code and timer function and run its :meth:`timeit` method with *number* executions. - .. versionadded:: 2.6 - Command Line Interface ---------------------- Modified: python/branches/py3k/Doc/library/tkinter.rst ============================================================================== --- python/branches/py3k/Doc/library/tkinter.rst (original) +++ python/branches/py3k/Doc/library/tkinter.rst Sat Sep 1 15:51:09 2007 @@ -61,9 +61,6 @@ .. % FIXME: The following keyword arguments are currently recognized: - .. versionchanged:: 2.4 - The *useTk* parameter was added. - .. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=0) @@ -75,7 +72,6 @@ created by the :func:`Tcl` object can have a Toplevel window created (and the Tk subsystem initialized) by calling its :meth:`loadtk` method. - .. versionadded:: 2.4 Other modules that provide Tk support include: Modified: python/branches/py3k/Doc/library/tokenize.rst ============================================================================== --- python/branches/py3k/Doc/library/tokenize.rst (original) +++ python/branches/py3k/Doc/library/tokenize.rst Sat Sep 1 15:51:09 2007 @@ -31,11 +31,9 @@ token was found. The line passed is the *logical* line; continuation lines are included. - .. versionadded:: 2.2 An older entry point is retained for backward compatibility: - .. function:: tokenize(readline[, tokeneater]) The :func:`tokenize` function accepts two parameters: one representing the input @@ -47,18 +45,15 @@ line of input as a string. Alternately, *readline* may be a callable object that signals completion by raising :exc:`StopIteration`. - .. versionchanged:: 2.5 - Added :exc:`StopIteration` support. - The second parameter, *tokeneater*, must also be a callable object. It is called once for each token, with five arguments, corresponding to the tuples generated by :func:`generate_tokens`. + All constants from the :mod:`token` module are also exported from :mod:`tokenize`, as are two additional token type values that might be passed to the *tokeneater* function by :func:`tokenize`: - .. data:: COMMENT Token value used to indicate a comment. @@ -87,7 +82,6 @@ type and token string as the spacing between tokens (column positions) may change. - .. versionadded:: 2.5 Example of a script re-writer that transforms float literals into Decimal objects:: Modified: python/branches/py3k/Doc/library/traceback.rst ============================================================================== --- python/branches/py3k/Doc/library/traceback.rst (original) +++ python/branches/py3k/Doc/library/traceback.rst Sat Sep 1 15:51:09 2007 @@ -50,8 +50,6 @@ This is like ``print_exc(limit)`` but returns a string instead of printing to a file. - .. versionadded:: 2.4 - .. function:: print_last([limit[, file]]) Modified: python/branches/py3k/Doc/library/turtle.rst ============================================================================== --- python/branches/py3k/Doc/library/turtle.rst (original) +++ python/branches/py3k/Doc/library/turtle.rst Sat Sep 1 15:51:09 2007 @@ -92,15 +92,11 @@ ``'fastest'`` (no delay), ``'fast'``, (delay 5ms), ``'normal'`` (delay 10ms), ``'slow'`` (delay 15ms), and ``'slowest'`` (delay 20ms). - .. versionadded:: 2.5 - .. function:: delay(delay) Set the speed of the turtle to *delay*, which is given in ms. - .. versionadded:: 2.5 - .. function:: forward(distance) @@ -168,15 +164,11 @@ Switch turtle into filling mode; Must eventually be followed by a corresponding end_fill() call. Otherwise it will be ignored. - .. versionadded:: 2.5 - .. function:: end_fill() End filling mode, and fill the shape; equivalent to ``fill(0)``. - .. versionadded:: 2.5 - .. function:: circle(radius[, extent]) @@ -203,56 +195,41 @@ The co-ordinates may be specified either as two separate arguments, as a 2-tuple, or as another pen object. - .. versionadded:: 2.5 - .. function:: heading() Return the current orientation of the turtle. - .. versionadded:: 2.3 - .. function:: setheading(angle) Set the orientation of the turtle to *angle*. - .. versionadded:: 2.3 - .. function:: position() Return the current location of the turtle as an ``(x,y)`` pair. - .. versionadded:: 2.3 - .. function:: setx(x) Set the x coordinate of the turtle to *x*. - .. versionadded:: 2.3 - .. function:: sety(y) Set the y coordinate of the turtle to *y*. - .. versionadded:: 2.3 - .. function:: window_width() Return the width of the canvas window. - .. versionadded:: 2.3 - .. function:: window_height() Return the height of the canvas window. - .. versionadded:: 2.3 This module also does ``from math import *``, so see the documentation for the :mod:`math` module for additional constants and functions useful for turtle Modified: python/branches/py3k/Doc/library/types.rst ============================================================================== --- python/branches/py3k/Doc/library/types.rst (original) +++ python/branches/py3k/Doc/library/types.rst Sat Sep 1 15:51:09 2007 @@ -54,8 +54,6 @@ The type of the :class:`bool` values ``True`` and ``False``; alias of the built-in :class:`bool`. - .. versionadded:: 2.3 - .. data:: IntType @@ -123,8 +121,6 @@ The type of generator-iterator objects, produced by calling a generator function. - .. versionadded:: 2.2 - .. data:: CodeType @@ -225,8 +221,6 @@ defined in implementations of Python that do not have such extension types, so for portable code use ``hasattr(types, 'GetSetDescriptorType')``. - .. versionadded:: 2.5 - .. data:: MemberDescriptorType @@ -235,8 +229,6 @@ Python that do not have such extension types, so for portable code use ``hasattr(types, 'MemberDescriptorType')``. - .. versionadded:: 2.5 - .. data:: StringTypes @@ -245,5 +237,3 @@ sequence of the two string types constructed elsewhere since it only contains ``UnicodeType`` if it has been built in the running version of Python. For example: ``isinstance(s, types.StringTypes)``. - - .. versionadded:: 2.2 Modified: python/branches/py3k/Doc/library/unicodedata.rst ============================================================================== --- python/branches/py3k/Doc/library/unicodedata.rst (original) +++ python/branches/py3k/Doc/library/unicodedata.rst Sat Sep 1 15:51:09 2007 @@ -81,8 +81,6 @@ Returns the east asian width assigned to the Unicode character *unichr* as string. - .. versionadded:: 2.4 - .. function:: mirrored(unichr) @@ -130,17 +128,13 @@ a human reader, if one has combining characters and the other doesn't, they may not compare equal. - .. versionadded:: 2.3 In addition, the module exposes the following constant: - .. data:: unidata_version The version of the Unicode database used in this module. - .. versionadded:: 2.3 - .. data:: ucd_3_2_0 @@ -148,8 +142,6 @@ Unicode database version 3.2 instead, for applications that require this specific version of the Unicode database (such as IDNA). - .. versionadded:: 2.5 - Examples:: >>> unicodedata.lookup('LEFT CURLY BRACKET') Modified: python/branches/py3k/Doc/library/unittest.rst ============================================================================== --- python/branches/py3k/Doc/library/unittest.rst (original) +++ python/branches/py3k/Doc/library/unittest.rst Sat Sep 1 15:51:09 2007 @@ -10,8 +10,6 @@ .. sectionauthor:: Raymond Hettinger -.. versionadded:: 2.1 - The Python unit testing framework, sometimes referred to as "PyUnit," is a Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in turn, a Java version of Kent's Smalltalk testing framework. Each is the de @@ -505,8 +503,6 @@ automatically build :class:`unittest.TestSuite` instances from the existing :mod:`doctest`\ -based tests. -.. versionadded:: 2.3 - .. _testcase-objects: @@ -750,9 +746,6 @@ formatted tracebacks. Each tuple represents a test which raised an unexpected exception. - .. versionchanged:: 2.2 - Contains formatted tracebacks instead of :func:`sys.exc_info` results. - .. attribute:: TestResult.failures @@ -761,9 +754,6 @@ explicitly signalled using the :meth:`TestCase.fail\*` or :meth:`TestCase.assert\*` methods. - .. versionchanged:: 2.2 - Contains formatted tracebacks instead of :func:`sys.exc_info` results. - .. attribute:: TestResult.testsRun Modified: python/branches/py3k/Doc/library/urllib.rst ============================================================================== --- python/branches/py3k/Doc/library/urllib.rst (original) +++ python/branches/py3k/Doc/library/urllib.rst Sat Sep 1 15:51:09 2007 @@ -106,9 +106,6 @@ Proxies which require authentication for use are not currently supported; this is considered an implementation limitation. - .. versionchanged:: 2.3 - Added the *proxies* support. - .. function:: urlretrieve(url[, filename[, reporthook[, data]]]) @@ -135,22 +132,21 @@ :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode` function below. - .. versionchanged:: 2.5 - :func:`urlretrieve` will raise :exc:`ContentTooShortError` when it detects that - the amount of data available was less than the expected amount (which is the - size reported by a *Content-Length* header). This can occur, for example, when - the download is interrupted. - - The *Content-Length* is treated as a lower bound: if there's more data to read, - urlretrieve reads more data, but if less data is available, it raises the - exception. - - You can still retrieve the downloaded data in this case, it is stored in the - :attr:`content` attribute of the exception instance. - - If no *Content-Length* header was supplied, urlretrieve can not check the size - of the data it has downloaded, and just returns it. In this case you just have - to assume that the download was successful. + :func:`urlretrieve` will raise :exc:`ContentTooShortError` when it detects that + the amount of data available was less than the expected amount (which is the + size reported by a *Content-Length* header). This can occur, for example, when + the download is interrupted. + + The *Content-Length* is treated as a lower bound: if there's more data to read, + urlretrieve reads more data, but if less data is available, it raises the + exception. + + You can still retrieve the downloaded data in this case, it is stored in the + :attr:`content` attribute of the exception instance. + + If no *Content-Length* header was supplied, urlretrieve can not check the size + of the data it has downloaded, and just returns it. In this case you just have + to assume that the download was successful. .. data:: _urlopener @@ -301,8 +297,6 @@ *Content-Length* header). The :attr:`content` attribute stores the downloaded (and supposedly truncated) data. - .. versionadded:: 2.5 - Restrictions: .. index:: Modified: python/branches/py3k/Doc/library/urllib2.rst ============================================================================== --- python/branches/py3k/Doc/library/urllib2.rst (original) +++ python/branches/py3k/Doc/library/urllib2.rst Sat Sep 1 15:51:09 2007 @@ -44,9 +44,6 @@ default installed global :class:`OpenerDirector` uses :class:`UnknownHandler` to ensure this never happens). - .. versionchanged:: 2.6 - *timeout* was added. - .. function:: install_opener(opener) @@ -302,16 +299,12 @@ Add a header that will not be added to a redirected request. - .. versionadded:: 2.4 - .. method:: Request.has_header(header) Return whether the instance has the named header (checks both regular and unredirected). - .. versionadded:: 2.4 - .. method:: Request.get_full_url() @@ -392,9 +385,6 @@ specified, or passed as None, the global default timeout setting will be used; this actually only work for HTTP, HTTPS, FTP and FTPS connections). - .. versionchanged:: 2.6 - *timeout* was added. - .. method:: OpenerDirector.error(proto[, arg[, ...]]) @@ -611,11 +601,8 @@ HTTPCookieProcessor Objects --------------------------- -.. versionadded:: 2.4 - :class:`HTTPCookieProcessor` instances have one attribute: - .. attribute:: HTTPCookieProcessor.cookiejar The :class:`cookielib.CookieJar` in which cookies are stored. @@ -825,9 +812,6 @@ HTTPErrorProcessor Objects -------------------------- -.. versionadded:: 2.4 - - .. method:: HTTPErrorProcessor.unknown_open() Process HTTP error responses. Modified: python/branches/py3k/Doc/library/urlparse.rst ============================================================================== --- python/branches/py3k/Doc/library/urlparse.rst (original) +++ python/branches/py3k/Doc/library/urlparse.rst Sat Sep 1 15:51:09 2007 @@ -24,9 +24,6 @@ ``rsync``, ``rtsp``, ``rtspu``, ``sftp``, ``shttp``, ``sip``, ``sips``, ``snews``, ``svn``, ``svn+ssh``, ``telnet``, ``wais``. -.. versionadded:: 2.5 - Support for the ``sftp`` and ``sips`` schemes. - The :mod:`urlparse` module defines the following functions: @@ -91,9 +88,6 @@ See section :ref:`urlparse-result-object` for more information on the result object. - .. versionchanged:: 2.5 - Added attributes to return value. - .. function:: urlunparse(parts) @@ -142,11 +136,6 @@ See section :ref:`urlparse-result-object` for more information on the result object. - .. versionadded:: 2.2 - - .. versionchanged:: 2.5 - Added attributes to return value. - .. function:: urlunsplit(parts) @@ -156,8 +145,6 @@ originally had unnecessary delimiters (for example, a ? with an empty query; the RFC states that these are equivalent). - .. versionadded:: 2.2 - .. function:: urljoin(base, url[, allow_fragments]) @@ -242,7 +229,6 @@ >>> r2.geturl() 'http://www.Python.org/doc/' - .. versionadded:: 2.5 The following classes provide the implementations of the parse results:: Modified: python/branches/py3k/Doc/library/userdict.rst ============================================================================== --- python/branches/py3k/Doc/library/userdict.rst (original) +++ python/branches/py3k/Doc/library/userdict.rst Sat Sep 1 15:51:09 2007 @@ -120,11 +120,6 @@ consult the sources for information about the methods which need to be provided in that case. -.. versionchanged:: 2.0 - Python versions 1.5.2 and 1.6 also required that the constructor be callable - with no parameters, and offer a mutable :attr:`data` attribute. Earlier - versions of Python did not attempt to create instances of the derived class. - :mod:`UserString` --- Class wrapper for string objects ====================================================== Modified: python/branches/py3k/Doc/library/uuid.rst ============================================================================== --- python/branches/py3k/Doc/library/uuid.rst (original) +++ python/branches/py3k/Doc/library/uuid.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: George Yoshida -.. versionadded:: 2.5 - This module provides immutable :class:`UUID` objects (the :class:`UUID` class) and the functions :func:`uuid1`, :func:`uuid3`, :func:`uuid4`, :func:`uuid5` for generating version 1, 3, 4, and 5 UUIDs as specified in :rfc:`4122`. Modified: python/branches/py3k/Doc/library/warnings.rst ============================================================================== --- python/branches/py3k/Doc/library/warnings.rst (original) +++ python/branches/py3k/Doc/library/warnings.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ :synopsis: Issue warning messages and control their disposition. -.. versionadded:: 2.1 - Warning messages are typically issued in situations where it is useful to alert the user of some condition in a program, where that condition (normally) doesn't warrant raising an exception and terminating the program. For example, one Modified: python/branches/py3k/Doc/library/weakref.rst ============================================================================== --- python/branches/py3k/Doc/library/weakref.rst (original) +++ python/branches/py3k/Doc/library/weakref.rst Sat Sep 1 15:51:09 2007 @@ -10,8 +10,6 @@ .. sectionauthor:: Fred L. Drake, Jr. -.. versionadded:: 2.1 - The :mod:`weakref` module allows the Python programmer to create :dfn:`weak references` to objects. @@ -54,9 +52,6 @@ objects from the :mod:`bsddb` module, sockets, arrays, deques, and regular expression pattern objects. -.. versionchanged:: 2.4 - Added support for files, sockets, arrays, and patterns. - Several builtin types such as :class:`list` and :class:`dict` do not directly support weak references but can add support through subclassing:: @@ -97,9 +92,7 @@ referents (regardless of the *callback*). If either referent has been deleted, the references are equal only if the reference objects are the same object. - .. versionchanged:: 2.4 - This is now a subclassable type rather than a factory function; it derives from - :class:`object`. + This is a subclassable type rather than a factory function. .. function:: proxy(object[, callback]) @@ -152,15 +145,11 @@ Return an iterator that yields the weak references to the keys. - .. versionadded:: 2.5 - .. method:: WeakKeyDictionary.keyrefs() Return a list of weak references to the keys. - .. versionadded:: 2.5 - .. class:: WeakValueDictionary([dict]) @@ -184,15 +173,11 @@ Return an iterator that yields the weak references to the values. - .. versionadded:: 2.5 - .. method:: WeakValueDictionary.valuerefs() Return a list of weak references to the values. - .. versionadded:: 2.5 - .. data:: ReferenceType Modified: python/branches/py3k/Doc/library/webbrowser.rst ============================================================================== --- python/branches/py3k/Doc/library/webbrowser.rst (original) +++ python/branches/py3k/Doc/library/webbrowser.rst Sat Sep 1 15:51:09 2007 @@ -55,9 +55,6 @@ under many window managers this will occur regardless of the setting of this variable). - .. versionchanged:: 2.5 - *new* can now be 2. - .. function:: open_new(url) @@ -70,8 +67,6 @@ Open *url* in a new page ("tab") of the default browser, if possible, otherwise equivalent to :func:`open_new`. - .. versionadded:: 2.5 - .. function:: get([name]) @@ -194,6 +189,3 @@ Open *url* in a new page ("tab") of the browser handled by this controller, if possible, otherwise equivalent to :func:`open_new`. - - .. versionadded:: 2.5 - Modified: python/branches/py3k/Doc/library/winsound.rst ============================================================================== --- python/branches/py3k/Doc/library/winsound.rst (original) +++ python/branches/py3k/Doc/library/winsound.rst Sat Sep 1 15:51:09 2007 @@ -9,8 +9,6 @@ .. sectionauthor:: Fred L. Drake, Jr. -.. versionadded:: 1.5.2 - The :mod:`winsound` module provides access to the basic sound-playing machinery provided by Windows platforms. It includes functions and several constants. @@ -29,8 +27,6 @@ port manipulation (added in version 2.1). It's unknown whether that will work on all systems. - .. versionadded:: 1.6 - .. function:: PlaySound(sound, flags) @@ -50,8 +46,6 @@ described below. The value ``-1`` produces a "simple beep"; this is the final fallback if a sound cannot be played otherwise. - .. versionadded:: 2.3 - .. data:: SND_FILENAME Modified: python/branches/py3k/Doc/library/wsgiref.rst ============================================================================== --- python/branches/py3k/Doc/library/wsgiref.rst (original) +++ python/branches/py3k/Doc/library/wsgiref.rst Sat Sep 1 15:51:09 2007 @@ -7,8 +7,6 @@ .. sectionauthor:: Phillip J. Eby -.. versionadded:: 2.5 - The Web Server Gateway Interface (WSGI) is a standard interface between web server software and web applications written in Python. Having a standard interface makes it easy to use an application that supports WSGI with a number Modified: python/branches/py3k/Doc/library/xml.dom.minidom.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.dom.minidom.rst (original) +++ python/branches/py3k/Doc/library/xml.dom.minidom.rst Sat Sep 1 15:51:09 2007 @@ -9,8 +9,6 @@ .. sectionauthor:: Martin v. L?wis -.. versionadded:: 2.0 - :mod:`xml.dom.minidom` is a light-weight implementation of the Document Object Model interface. It is intended to be simpler than the full DOM and also significantly smaller. @@ -136,13 +134,8 @@ indentation to use for subnodes of the current one. The *newl* parameter specifies the string to use to terminate newlines. - .. versionchanged:: 2.1 - The optional keyword parameters *indent*, *addindent*, and *newl* were added to - support pretty output. - - .. versionchanged:: 2.3 - For the :class:`Document` node, an additional keyword argument *encoding* can be - used to specify the encoding field of the XML header. + For the :class:`Document` node, an additional keyword argument *encoding* can be + used to specify the encoding field of the XML header. .. method:: Node.toxml([encoding]) @@ -159,25 +152,19 @@ avoid :exc:`UnicodeError` exceptions in case of unrepresentable text data, the encoding argument should be specified as "utf-8". - .. versionchanged:: 2.3 - the *encoding* argument was introduced. - -.. method:: Node.toprettyxml([indent[, newl]]) +.. method:: Node.toprettyxml([indent[, newl[, encoding]]]) Return a pretty-printed version of the document. *indent* specifies the indentation string and defaults to a tabulator; *newl* specifies the string emitted at the end of each line and defaults to ``\n``. - .. versionadded:: 2.1 + There's also an *encoding* argument; see :meth:`toxml`. - .. versionchanged:: 2.3 - the encoding argument; see :meth:`toxml`. The following standard DOM methods have special considerations with :mod:`xml.dom.minidom`: - .. method:: Node.cloneNode(deep) Although this method was present in the version of :mod:`xml.dom.minidom` Modified: python/branches/py3k/Doc/library/xml.dom.pulldom.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.dom.pulldom.rst (original) +++ python/branches/py3k/Doc/library/xml.dom.pulldom.rst Sat Sep 1 15:51:09 2007 @@ -7,8 +7,6 @@ .. moduleauthor:: Paul Prescod -.. versionadded:: 2.0 - :mod:`xml.dom.pulldom` allows building only selected portions of a Document Object Model representation of a document from SAX events. @@ -42,9 +40,8 @@ Default value for the *bufsize* parameter to :func:`parse`. - .. versionchanged:: 2.1 - The value of this variable can be changed before calling :func:`parse` and the - new value will take effect. + The value of this variable can be changed before calling :func:`parse` and + the new value will take effect. .. _domeventstream-objects: Modified: python/branches/py3k/Doc/library/xml.dom.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.dom.rst (original) +++ python/branches/py3k/Doc/library/xml.dom.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Martin v. L?wis -.. versionadded:: 2.0 - The Document Object Model, or "DOM," is a cross-language API from the World Wide Web Consortium (W3C) for accessing and modifying XML documents. A DOM implementation presents an XML document as a tree structure, or allows client @@ -122,16 +120,12 @@ DOM. This is typically found as the :attr:`namespaceURI` of a node, or used as the *namespaceURI* parameter to a namespaces-specific method. - .. versionadded:: 2.2 - .. data:: XML_NAMESPACE The namespace URI associated with the reserved prefix ``xml``, as defined by `Namespaces in XML `_ (section 4). - .. versionadded:: 2.2 - .. data:: XMLNS_NAMESPACE @@ -139,15 +133,12 @@ Model (DOM) Level 2 Core Specification `_ (section 1.1.8). - .. versionadded:: 2.2 - .. data:: XHTML_NAMESPACE The URI of the XHTML namespace as defined by `XHTML 1.0: The Extensible HyperText Markup Language `_ (section 3.1.1). - .. versionadded:: 2.2 In addition, :mod:`xml.dom` contains a base :class:`Node` class and the DOM exception classes. The :class:`Node` class provided by this module does not @@ -404,8 +395,6 @@ :class:`Text` instances. This simplifies processing text from a DOM tree for many applications. - .. versionadded:: 2.1 - .. method:: Node.cloneNode(deep) @@ -813,8 +802,6 @@ Exceptions ^^^^^^^^^^ -.. versionadded:: 2.1 - The DOM Level 2 recommendation defines a single exception, :exc:`DOMException`, and a number of constants that allow applications to determine what sort of error occurred. :exc:`DOMException` instances carry a :attr:`code` attribute Modified: python/branches/py3k/Doc/library/xml.etree.elementtree.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.etree.elementtree.rst (original) +++ python/branches/py3k/Doc/library/xml.etree.elementtree.rst Sat Sep 1 15:51:09 2007 @@ -7,8 +7,6 @@ .. moduleauthor:: Fredrik Lundh -.. versionadded:: 2.5 - The Element type is a flexible container object, designed to store hierarchical data structures in memory. The type can be described as a cross between a list and a dictionary. Modified: python/branches/py3k/Doc/library/xml.etree.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.etree.rst (original) +++ python/branches/py3k/Doc/library/xml.etree.rst Sat Sep 1 15:51:09 2007 @@ -6,8 +6,6 @@ .. moduleauthor:: Fredrik Lundh -.. versionadded:: 2.5 - The ElementTree package is a simple, efficient, and quite popular library for XML manipulation in Python. The :mod:`xml.etree` package contains the most common components from the ElementTree API library. In the current release, Modified: python/branches/py3k/Doc/library/xml.sax.handler.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.sax.handler.rst (original) +++ python/branches/py3k/Doc/library/xml.sax.handler.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Martin v. L?wis -.. versionadded:: 2.0 - The SAX API defines four kinds of handlers: content handlers, DTD handlers, error handlers, and entity resolvers. Applications normally only need to implement those interfaces whose events they are interested in; they can Modified: python/branches/py3k/Doc/library/xml.sax.reader.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.sax.reader.rst (original) +++ python/branches/py3k/Doc/library/xml.sax.reader.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Martin v. L?wis -.. versionadded:: 2.0 - SAX parsers implement the :class:`XMLReader` interface. They are implemented in a Python module, which must provide a function :func:`create_parser`. This function is invoked by :func:`xml.sax.make_parser` with no arguments to create Modified: python/branches/py3k/Doc/library/xml.sax.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.sax.rst (original) +++ python/branches/py3k/Doc/library/xml.sax.rst Sat Sep 1 15:51:09 2007 @@ -9,8 +9,6 @@ .. sectionauthor:: Martin v. L?wis -.. versionadded:: 2.0 - The :mod:`xml.sax` package provides a number of modules which implement the Simple API for XML (SAX) interface for Python. The package itself provides the SAX exceptions and the convenience functions which will be most used by users of Modified: python/branches/py3k/Doc/library/xml.sax.utils.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.sax.utils.rst (original) +++ python/branches/py3k/Doc/library/xml.sax.utils.rst Sat Sep 1 15:51:09 2007 @@ -8,8 +8,6 @@ .. sectionauthor:: Martin v. L?wis -.. versionadded:: 2.0 - The module :mod:`xml.sax.saxutils` contains a number of classes and functions that are commonly useful when creating SAX applications, either in direct use, or as base classes. @@ -32,8 +30,6 @@ *entities* parameter. The keys and values must all be strings; each key will be replaced with its corresponding value. - .. versionadded:: 2.3 - .. function:: quoteattr(data[, entities]) @@ -52,8 +48,6 @@ This function is useful when generating attribute values for HTML or any SGML using the reference concrete syntax. - .. versionadded:: 2.2 - .. class:: XMLGenerator([out[, encoding]]) Modified: python/branches/py3k/Doc/library/xmlrpclib.rst ============================================================================== --- python/branches/py3k/Doc/library/xmlrpclib.rst (original) +++ python/branches/py3k/Doc/library/xmlrpclib.rst Sat Sep 1 15:51:09 2007 @@ -11,8 +11,6 @@ .. % Not everything is documented yet. It might be good to describe .. % Marshaller, Unmarshaller, getparser, dumps, loads, and Transport. -.. versionadded:: 2.2 - XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a transport. With it, a client can call methods with parameters on a remote server (the server is named by a URI) and get back structured data. This module @@ -109,13 +107,6 @@ :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards compatibility. New code should use :class:`ServerProxy`. - .. versionchanged:: 2.5 - The *use_datetime* flag was added. - - .. versionchanged:: 2.6 - Instances of new-style classes can be passed in if they have an *__dict__* - attribute and don't have a base class that is marshalled in a special way. - .. seealso:: @@ -312,8 +303,6 @@ MultiCall Objects ----------------- -.. versionadded:: 2.4 - In http://www.xmlrpc.com/discuss/msgReader%241208, an approach is presented to encapsulate multiple calls to a remote server into a single request. @@ -368,9 +357,6 @@ objects, they are converted to :class:`DateTime` objects internally, so only :class:`datetime.datetime` objects will be returned. - .. versionchanged:: 2.5 - The *use_datetime* flag was added. - .. _xmlrpc-client-example: Modified: python/branches/py3k/Doc/library/zipfile.rst ============================================================================== --- python/branches/py3k/Doc/library/zipfile.rst (original) +++ python/branches/py3k/Doc/library/zipfile.rst Sat Sep 1 15:51:09 2007 @@ -10,8 +10,6 @@ .. % LaTeX markup by Fred L. Drake, Jr. -.. versionadded:: 1.6 - The ZIP file format is a common archive and compression standard. This module provides tools to create, read, write, append, and list a ZIP file. Any advanced use of this module will require an understanding of the format, as @@ -121,9 +119,6 @@ because the default :program:`zip` and :program:`unzip` commands on Unix (the InfoZIP utilities) don't support these extensions. - .. versionchanged:: 2.6 - If the file does not exist, it is created if the mode is 'a'. - .. method:: ZipFile.close() @@ -176,8 +171,6 @@ create a new file object that will be held by the ZipExtFile, allowing it to operate independently of the ZipFile. - .. versionadded:: 2.6 - .. method:: ZipFile.printdir() @@ -188,8 +181,6 @@ Set *pwd* as default password to extract encrypted files. - .. versionadded:: 2.6 - .. method:: ZipFile.read(name[, pwd]) @@ -198,9 +189,6 @@ will override the default password set with :meth:`setpassword`. Calling :meth:`read` on a closed ZipFile will raise a :exc:`RuntimeError`. - .. versionchanged:: 2.6 - *pwd* was added. - .. method:: ZipFile.testzip() Modified: python/branches/py3k/Doc/library/zipimport.rst ============================================================================== --- python/branches/py3k/Doc/library/zipimport.rst (original) +++ python/branches/py3k/Doc/library/zipimport.rst Sat Sep 1 15:51:09 2007 @@ -7,8 +7,6 @@ .. moduleauthor:: Just van Rossum -.. versionadded:: 2.3 - This module adds the ability to import Python modules (:file:`\*.py`, :file:`\*.py[co]`) and packages from ZIP-format archives. It is usually not needed to use the :mod:`zipimport` module explicitly; it is automatically used Modified: python/branches/py3k/Doc/library/zlib.rst ============================================================================== --- python/branches/py3k/Doc/library/zlib.rst (original) +++ python/branches/py3k/Doc/library/zlib.rst Sat Sep 1 15:51:09 2007 @@ -130,7 +130,6 @@ Returns a copy of the compression object. This can be used to efficiently compress a set of data that share a common initial prefix. - .. versionadded:: 2.5 Decompression objects support the following methods, and two attributes: @@ -192,8 +191,6 @@ of the decompressor midway through the data stream in order to speed up random seeks into the stream at a future point. - .. versionadded:: 2.5 - .. seealso:: From python-3000-checkins at python.org Sat Sep 1 16:00:02 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 1 Sep 2007 16:00:02 +0200 (CEST) Subject: [Python-3000-checkins] r57871 - in python/branches/py3k: Doc/c-api/newtypes.rst Include/methodobject.h Objects/methodobject.c Message-ID: <20070901140002.503651E4006@bag.python.org> Author: georg.brandl Date: Sat Sep 1 15:59:50 2007 New Revision: 57871 Modified: python/branches/py3k/Doc/c-api/newtypes.rst python/branches/py3k/Include/methodobject.h python/branches/py3k/Objects/methodobject.c Log: Get rid of METH_OLDARGS. Modified: python/branches/py3k/Doc/c-api/newtypes.rst ============================================================================== --- python/branches/py3k/Doc/c-api/newtypes.rst (original) +++ python/branches/py3k/Doc/c-api/newtypes.rst Sat Sep 1 15:59:50 2007 @@ -255,16 +255,6 @@ :ctype:`PyObject\*` parameter representing the single argument. -.. XXX deprecated, should be removed -.. data:: METH_OLDARGS - - This calling convention is deprecated. The method must be of type - :ctype:`PyCFunction`. The second argument is *NULL* if no arguments are given, - a single object if exactly one argument is given, and a tuple of objects if more - than one argument is given. There is no way for a function using this - convention to distinguish between a call with multiple arguments and a call with - a tuple as the only argument. - These two constants are not used to indicate the calling convention but the binding when use with methods of classes. These may not be used for functions defined for modules. At most one of these flags may be set for any given Modified: python/branches/py3k/Include/methodobject.h ============================================================================== --- python/branches/py3k/Include/methodobject.h (original) +++ python/branches/py3k/Include/methodobject.h Sat Sep 1 15:59:50 2007 @@ -50,7 +50,7 @@ PyObject *); /* Flag passed to newmethodobject */ -#define METH_OLDARGS 0x0000 +/* #define METH_OLDARGS 0x0000 -- unsupported now */ #define METH_VARARGS 0x0001 #define METH_KEYWORDS 0x0002 /* METH_NOARGS and METH_O must not be combined with the flags above. */ Modified: python/branches/py3k/Objects/methodobject.c ============================================================================== --- python/branches/py3k/Objects/methodobject.c (original) +++ python/branches/py3k/Objects/methodobject.c Sat Sep 1 15:59:50 2007 @@ -73,7 +73,6 @@ return (*meth)(self, arg); break; case METH_VARARGS | METH_KEYWORDS: - case METH_OLDARGS | METH_KEYWORDS: return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); case METH_NOARGS: if (kw == NULL || PyDict_Size(kw) == 0) { @@ -97,19 +96,11 @@ return NULL; } break; - case METH_OLDARGS: - /* the really old style */ - if (kw == NULL || PyDict_Size(kw) == 0) { - size = PyTuple_GET_SIZE(arg); - if (size == 1) - arg = PyTuple_GET_ITEM(arg, 0); - else if (size == 0) - arg = NULL; - return (*meth)(self, arg); - } - break; default: - PyErr_BadInternalCall(); + PyErr_SetString(PyExc_SystemError, "Bad call flags in " + "PyCFunction_Call. METH_OLDARGS is no " + "longer supported!"); + return NULL; } PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", From python-3000-checkins at python.org Sat Sep 1 17:25:41 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 1 Sep 2007 17:25:41 +0200 (CEST) Subject: [Python-3000-checkins] r57872 - python/branches/py3k/Tools/bgen/bgen/bgenGenerator.py Message-ID: <20070901152541.CF85F1E400C@bag.python.org> Author: georg.brandl Date: Sat Sep 1 17:25:27 2007 New Revision: 57872 Modified: python/branches/py3k/Tools/bgen/bgen/bgenGenerator.py Log: Use symbolic name for METH_VARAGS. Modified: python/branches/py3k/Tools/bgen/bgen/bgenGenerator.py ============================================================================== --- python/branches/py3k/Tools/bgen/bgen/bgenGenerator.py (original) +++ python/branches/py3k/Tools/bgen/bgen/bgenGenerator.py Sat Sep 1 17:25:27 2007 @@ -68,7 +68,7 @@ if self.condition: Output() Output(self.condition) - Output("{\"%s\", (PyCFunction)%s_%s, 1,", name, self.prefix, self.name) + Output("{\"%s\", (PyCFunction)%s_%s, METH_VARARGS,", name, self.prefix, self.name) Output(" PyDoc_STR(%s)},", stringify(docstring)) if self.condition: Output("#endif") From python-3000-checkins at python.org Sat Sep 1 17:27:45 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 1 Sep 2007 17:27:45 +0200 (CEST) Subject: [Python-3000-checkins] r57873 - python/branches/py3k/Mac/Modules/MacOS.c Message-ID: <20070901152745.D45E11E4006@bag.python.org> Author: georg.brandl Date: Sat Sep 1 17:27:35 2007 New Revision: 57873 Modified: python/branches/py3k/Mac/Modules/MacOS.c Log: Use symbolic name for METH_VARARGS. Modified: python/branches/py3k/Mac/Modules/MacOS.c ============================================================================== --- python/branches/py3k/Mac/Modules/MacOS.c (original) +++ python/branches/py3k/Mac/Modules/MacOS.c Sat Sep 1 17:27:35 2007 @@ -214,11 +214,11 @@ static struct PyMethodDef rf_methods[] = { - {"read", (PyCFunction)rf_read, 1, rf_read__doc__}, - {"write", (PyCFunction)rf_write, 1, rf_write__doc__}, - {"seek", (PyCFunction)rf_seek, 1, rf_seek__doc__}, - {"tell", (PyCFunction)rf_tell, 1, rf_tell__doc__}, - {"close", (PyCFunction)rf_close, 1, rf_close__doc__}, + {"read", (PyCFunction)rf_read, METH_VARARGS, rf_read__doc__}, + {"write", (PyCFunction)rf_write, METH_VARARGS, rf_write__doc__}, + {"seek", (PyCFunction)rf_seek, METH_VARARGS, rf_seek__doc__}, + {"tell", (PyCFunction)rf_tell, METH_VARARGS, rf_tell__doc__}, + {"close", (PyCFunction)rf_close, METH_VARARGS, rf_close__doc__}, {NULL, NULL} /* sentinel */ }; @@ -584,15 +584,15 @@ static PyMethodDef MacOS_Methods[] = { - {"GetCreatorAndType", MacOS_GetCreatorAndType, 1, getcrtp_doc}, - {"SetCreatorAndType", MacOS_SetCreatorAndType, 1, setcrtp_doc}, - {"GetErrorString", MacOS_GetErrorString, 1, geterr_doc}, - {"openrf", MacOS_openrf, 1, openrf_doc}, - {"splash", MacOS_splash, 1, splash_doc}, - {"DebugStr", MacOS_DebugStr, 1, DebugStr_doc}, - {"GetTicks", MacOS_GetTicks, 1, GetTicks_doc}, - {"SysBeep", MacOS_SysBeep, 1, SysBeep_doc}, - {"WMAvailable", MacOS_WMAvailable, 1, WMAvailable_doc}, + {"GetCreatorAndType", MacOS_GetCreatorAndType, METH_VARARGS, getcrtp_doc}, + {"SetCreatorAndType", MacOS_SetCreatorAndType, METH_VARARGS, setcrtp_doc}, + {"GetErrorString", MacOS_GetErrorString, METH_VARARGS, geterr_doc}, + {"openrf", MacOS_openrf, METH_VARARGS, openrf_doc}, + {"splash", MacOS_splash, METH_VARARGS, splash_doc}, + {"DebugStr", MacOS_DebugStr, METH_VARARGS, DebugStr_doc}, + {"GetTicks", MacOS_GetTicks, METH_VARARGS, GetTicks_doc}, + {"SysBeep", MacOS_SysBeep, METH_VARARGS, SysBeep_doc}, + {"WMAvailable", MacOS_WMAvailable, METH_VARARGS, WMAvailable_doc}, {NULL, NULL} /* Sentinel */ }; From python-3000-checkins at python.org Sat Sep 1 17:49:48 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 1 Sep 2007 17:49:48 +0200 (CEST) Subject: [Python-3000-checkins] r57875 - python/branches/py3k/Doc/library/stdtypes.rst Message-ID: <20070901154948.083A61E400B@bag.python.org> Author: georg.brandl Date: Sat Sep 1 17:49:30 2007 New Revision: 57875 Modified: python/branches/py3k/Doc/library/stdtypes.rst Log: Document sets' "<" and ">" operations. Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Sat Sep 1 17:49:30 2007 @@ -1557,11 +1557,21 @@ Test whether every element in the set is in *other*. +.. method:: set < other + + Test whether the set is a true subset of *other*, that is, + ``set <= other and set != other``. + .. method:: set.issuperset(other) set >= other Test whether every element in *other* is in the set. +.. method:: set > other + + Test whether the set is a true superset of *other*, that is, + ``set >= other and set != other``. + .. method:: set.union(other) set | other From python-3000-checkins at python.org Sat Sep 1 18:19:51 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Sat, 1 Sep 2007 18:19:51 +0200 (CEST) Subject: [Python-3000-checkins] r57877 - python/branches/py3k/Doc/c-api/newtypes.rst Message-ID: <20070901161951.2EA9E1E4006@bag.python.org> Author: georg.brandl Date: Sat Sep 1 18:19:25 2007 New Revision: 57877 Modified: python/branches/py3k/Doc/c-api/newtypes.rst Log: Document PyCFunctionWithKeywords, add comment for PEP 3123. Modified: python/branches/py3k/Doc/c-api/newtypes.rst ============================================================================== --- python/branches/py3k/Doc/c-api/newtypes.rst (original) +++ python/branches/py3k/Doc/c-api/newtypes.rst Sat Sep 1 18:19:25 2007 @@ -139,6 +139,7 @@ These macros are used in the definition of :ctype:`PyObject` and :ctype:`PyVarObject`: +.. XXX need to document PEP 3123 changes here .. cmacro:: PyObject_HEAD @@ -171,7 +172,7 @@ Note that :cmacro:`PyObject_HEAD` is part of the expansion, and that its own expansion varies depending on the definition of :cmacro:`Py_TRACE_REFS`. -PyObject_HEAD_INIT +.. cmacro:: PyObject_HEAD_INIT .. ctype:: PyCFunction @@ -183,6 +184,14 @@ in Python. The function must return a new reference. +.. ctype:: PyCFunctionWithKeywords + + Type of the functions used to implement Python callables in C that take + keyword arguments: they take three :ctype:`PyObject\*` parameters and return + one such value. See :ctype:`PyCFunction` above for the meaning of the return + value. + + .. ctype:: PyMethodDef Structure used to describe a method of an extension type. This structure has From python-3000-checkins at python.org Sat Sep 1 21:26:30 2007 From: python-3000-checkins at python.org (andrew.kuchling) Date: Sat, 1 Sep 2007 21:26:30 +0200 (CEST) Subject: [Python-3000-checkins] r57881 - python/branches/py3k/Doc/whatsnew/3.0.rst Message-ID: <20070901192630.530F21E4006@bag.python.org> Author: andrew.kuchling Date: Sat Sep 1 21:26:28 2007 New Revision: 57881 Modified: python/branches/py3k/Doc/whatsnew/3.0.rst Log: I'm not actually an author Modified: python/branches/py3k/Doc/whatsnew/3.0.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/3.0.rst (original) +++ python/branches/py3k/Doc/whatsnew/3.0.rst Sat Sep 1 21:26:28 2007 @@ -2,7 +2,7 @@ What's New in Python 3.0 **************************** -:Author: A.M. Kuchling, Guido van Rossum +:Author: Guido van Rossum :Release: 0.1 .. Rules for maintenance: From python-3000-checkins at python.org Sat Sep 1 21:47:40 2007 From: python-3000-checkins at python.org (kurt.kaiser) Date: Sat, 1 Sep 2007 21:47:40 +0200 (CEST) Subject: [Python-3000-checkins] r57882 - python/branches/py3k/Lib/idlelib/IOBinding.py Message-ID: <20070901194740.33F161E400B@bag.python.org> Author: kurt.kaiser Date: Sat Sep 1 21:47:39 2007 New Revision: 57882 Modified: python/branches/py3k/Lib/idlelib/IOBinding.py Log: Saving a file containing unicode failed. Modified: python/branches/py3k/Lib/idlelib/IOBinding.py ============================================================================== --- python/branches/py3k/Lib/idlelib/IOBinding.py (original) +++ python/branches/py3k/Lib/idlelib/IOBinding.py Sat Sep 1 21:47:39 2007 @@ -11,11 +11,7 @@ from idlelib.configHandler import idleConf -try: - from codecs import BOM_UTF8 -except ImportError: - # only available since Python 2.3 - BOM_UTF8 = '\xef\xbb\xbf' +from codecs import BOM_UTF8 # Try setting the locale, so that we can find out # what encoding to use @@ -111,17 +107,18 @@ def do_edit(self): self.done(1) -def coding_spec(str): +def coding_spec(data): """Return the encoding declaration according to PEP 263. Raise LookupError if the encoding is declared but unknown. """ - # perform string manipulation in latin-1 - str = str.decode("latin-1") + if isinstance(data, bytes): + str = data.decode('utf-8') + else: + str = data # Only consider the first two lines str = str.split("\n")[:2] str = "\n".join(str) - match = coding_re.search(str) if not match: return None @@ -239,12 +236,12 @@ # open the file in binary mode so that we can handle # end-of-line convention ourselves. f = open(filename,'rb') - chars = f.read() + bytes = f.read() f.close() except IOError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False - chars = self.decode(chars) + chars = self.decode(bytes) # We now convert all end-of-lines to '\n's firsteol = self.eol_re.search(chars) if firsteol: @@ -274,7 +271,7 @@ return chars else: # Indicates that this file originally had a BOM - self.fileencoding = BOM_UTF8 + self.fileencoding = 'BOM' return chars # Next look for coding specification try: @@ -401,10 +398,10 @@ if failed: tkMessageBox.showerror( "I/O Error", - "%s. Saving as UTF-8" % failed, + "%s.\nSaving as UTF-8" % failed, master = self.text) # If there was a UTF-8 signature, use that. This should not fail - if self.fileencoding == BOM_UTF8 or failed: + if self.fileencoding == 'BOM' or failed: return BOM_UTF8 + chars.encode("utf-8") # Try the original file encoding next, if any if self.fileencoding: From python-3000-checkins at python.org Sat Sep 1 22:26:44 2007 From: python-3000-checkins at python.org (collin.winter) Date: Sat, 1 Sep 2007 22:26:44 +0200 (CEST) Subject: [Python-3000-checkins] r57886 - in python/branches/py3k: Lib/test/test_raise.py Objects/exceptions.c Python/ceval.c Message-ID: <20070901202644.AD51C1E4006@bag.python.org> Author: collin.winter Date: Sat Sep 1 22:26:44 2007 New Revision: 57886 Modified: python/branches/py3k/Lib/test/test_raise.py python/branches/py3k/Objects/exceptions.c python/branches/py3k/Python/ceval.c Log: Fix refleaks exposed by test_raise. Modified: python/branches/py3k/Lib/test/test_raise.py ============================================================================== --- python/branches/py3k/Lib/test/test_raise.py (original) +++ python/branches/py3k/Lib/test/test_raise.py Sat Sep 1 22:26:44 2007 @@ -37,6 +37,18 @@ else: self.fail("No exception raised") + def test_erroneous_exception(self): + class MyException(Exception): + def __init__(self): + raise RuntimeError() + + try: + raise MyException + except RuntimeError: + pass + else: + self.fail("No exception raised") + class TestCause(unittest.TestCase): def test_invalid_cause(self): @@ -64,6 +76,18 @@ else: self.fail("No exception raised") + def test_erroneous_cause(self): + class MyException(Exception): + def __init__(self): + raise RuntimeError() + + try: + raise IndexError from MyException + except RuntimeError: + pass + else: + self.fail("No exception raised") + class TestTraceback(unittest.TestCase): def test_sets_traceback(self): Modified: python/branches/py3k/Objects/exceptions.c ============================================================================== --- python/branches/py3k/Objects/exceptions.c (original) +++ python/branches/py3k/Objects/exceptions.c Sat Sep 1 22:26:44 2007 @@ -28,7 +28,7 @@ return NULL; /* the dict is created on the fly in PyObject_GenericSetAttr */ self->dict = NULL; - self->traceback = NULL; + self->traceback = self->cause = self->context = NULL; self->args = PyTuple_New(0); if (!self->args) { @@ -58,6 +58,8 @@ Py_CLEAR(self->dict); Py_CLEAR(self->args); Py_CLEAR(self->traceback); + Py_CLEAR(self->cause); + Py_CLEAR(self->context); return 0; } @@ -75,6 +77,8 @@ Py_VISIT(self->dict); Py_VISIT(self->args); Py_VISIT(self->traceback); + Py_VISIT(self->cause); + Py_VISIT(self->context); return 0; } Modified: python/branches/py3k/Python/ceval.c ============================================================================== --- python/branches/py3k/Python/ceval.c (original) +++ python/branches/py3k/Python/ceval.c Sat Sep 1 22:26:44 2007 @@ -2967,7 +2967,6 @@ /* Not something you can raise. You get an exception anyway, just not what you specified :-) */ Py_DECREF(exc); - Py_XDECREF(cause); PyErr_SetString(PyExc_TypeError, "exceptions must derive from BaseException"); goto raise_error; @@ -2980,12 +2979,12 @@ fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto raise_error; + Py_DECREF(cause); } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; } else { - Py_DECREF(cause); PyErr_SetString(PyExc_TypeError, "exception causes must derive from BaseException"); goto raise_error; @@ -3000,6 +2999,7 @@ Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); + Py_XDECREF(cause); return WHY_EXCEPTION; } From python-3000-checkins at python.org Sat Sep 1 22:28:02 2007 From: python-3000-checkins at python.org (collin.winter) Date: Sat, 1 Sep 2007 22:28:02 +0200 (CEST) Subject: [Python-3000-checkins] r57887 - python/branches/py3k/Lib/contextlib.py Message-ID: <20070901202802.9FB1E1E4006@bag.python.org> Author: collin.winter Date: Sat Sep 1 22:27:58 2007 New Revision: 57887 Modified: python/branches/py3k/Lib/contextlib.py Log: Fix a poorly-translated raise statement in contextlib. Modified: python/branches/py3k/Lib/contextlib.py ============================================================================== --- python/branches/py3k/Lib/contextlib.py (original) +++ python/branches/py3k/Lib/contextlib.py Sat Sep 1 22:27:58 2007 @@ -125,7 +125,8 @@ # Don't rely on sys.exc_info() still containing # the right information. Another exception may # have been raised and caught by an exit method - raise exc[0](exc[1]).with_traceback(exc[2]) + # exc[1] already has the __traceback__ attribute populated + raise exc[1] class closing(object): From python-3000-checkins at python.org Sat Sep 1 22:29:18 2007 From: python-3000-checkins at python.org (collin.winter) Date: Sat, 1 Sep 2007 22:29:18 +0200 (CEST) Subject: [Python-3000-checkins] r57888 - python/branches/py3k/Lib/test/test_with.py Message-ID: <20070901202918.82A111E4006@bag.python.org> Author: collin.winter Date: Sat Sep 1 22:29:04 2007 New Revision: 57888 Modified: python/branches/py3k/Lib/test/test_with.py Log: Fix refleaks in test_with caused by reusing the same exception instance over and over. Modified: python/branches/py3k/Lib/test/test_with.py ============================================================================== --- python/branches/py3k/Lib/test/test_with.py (original) +++ python/branches/py3k/Lib/test/test_with.py Sat Sep 1 22:29:04 2007 @@ -187,7 +187,9 @@ self.assertRaises(RuntimeError, shouldThrow) class ContextmanagerAssertionMixin(object): - TEST_EXCEPTION = RuntimeError("test exception") + + def setUp(self): + self.TEST_EXCEPTION = RuntimeError("test exception") def assertInWithManagerInvariants(self, mock_manager): self.assertTrue(mock_manager.enter_called) @@ -353,7 +355,7 @@ self.assertAfterWithManagerInvariantsNoError(mock_nested) -class ExceptionalTestCase(unittest.TestCase, ContextmanagerAssertionMixin): +class ExceptionalTestCase(ContextmanagerAssertionMixin, unittest.TestCase): def testSingleResource(self): cm = mock_contextmanager_generator() def shouldThrow(): From python-3000-checkins at python.org Sat Sep 1 22:35:04 2007 From: python-3000-checkins at python.org (collin.winter) Date: Sat, 1 Sep 2007 22:35:04 +0200 (CEST) Subject: [Python-3000-checkins] r57890 - python/branches/py3k/Lib/plat-os2emx/grp.py python/branches/py3k/Lib/plat-os2emx/pwd.py Message-ID: <20070901203504.5E8331E4006@bag.python.org> Author: collin.winter Date: Sat Sep 1 22:35:04 2007 New Revision: 57890 Modified: python/branches/py3k/Lib/plat-os2emx/grp.py python/branches/py3k/Lib/plat-os2emx/pwd.py Log: Run 2to3's fix_has_key over Lib/plat-os2emx/. Modified: python/branches/py3k/Lib/plat-os2emx/grp.py ============================================================================== --- python/branches/py3k/Lib/plat-os2emx/grp.py (original) +++ python/branches/py3k/Lib/plat-os2emx/grp.py Sat Sep 1 22:35:04 2007 @@ -58,11 +58,11 @@ # try and find the group file __group_path = [] -if os.environ.has_key('ETC_GROUP'): +if 'ETC_GROUP' in os.environ: __group_path.append(os.environ['ETC_GROUP']) -if os.environ.has_key('ETC'): +if 'ETC' in os.environ: __group_path.append('%s/group' % os.environ['ETC']) -if os.environ.has_key('PYTHONHOME'): +if 'PYTHONHOME' in os.environ: __group_path.append('%s/Etc/group' % os.environ['PYTHONHOME']) group_file = None @@ -149,9 +149,9 @@ fields[2] = int(fields[2]) fields[3] = [f.strip() for f in fields[3].split(',')] record = Group(*fields) - if not gidx.has_key(fields[2]): + if fields[2] not in gidx: gidx[fields[2]] = record - if not namx.has_key(fields[0]): + if fields[0] not in namx: namx[fields[0]] = record elif len(entry) > 0: pass # skip empty or malformed records Modified: python/branches/py3k/Lib/plat-os2emx/pwd.py ============================================================================== --- python/branches/py3k/Lib/plat-os2emx/pwd.py (original) +++ python/branches/py3k/Lib/plat-os2emx/pwd.py Sat Sep 1 22:35:04 2007 @@ -61,11 +61,11 @@ # try and find the passwd file __passwd_path = [] -if os.environ.has_key('ETC_PASSWD'): +if 'ETC_PASSWD' in os.environ: __passwd_path.append(os.environ['ETC_PASSWD']) -if os.environ.has_key('ETC'): +if 'ETC' in os.environ: __passwd_path.append('%s/passwd' % os.environ['ETC']) -if os.environ.has_key('PYTHONHOME'): +if 'PYTHONHOME' in os.environ: __passwd_path.append('%s/Etc/passwd' % os.environ['PYTHONHOME']) passwd_file = None @@ -164,7 +164,7 @@ uidx = {} namx = {} sep = None - while 1: + while True: entry = passwd.readline().strip() if len(entry) > 6: if sep == None: @@ -175,9 +175,9 @@ for i in (5, 6): fields[i] = __field_sep[sep](fields[i]) record = Passwd(*fields) - if not uidx.has_key(fields[2]): + if fields[2] not in uidx: uidx[fields[2]] = record - if not namx.has_key(fields[0]): + if fields[0] not in namx: namx[fields[0]] = record elif len(entry) > 0: pass # skip empty or malformed records From python-3000-checkins at python.org Sat Sep 1 22:37:31 2007 From: python-3000-checkins at python.org (collin.winter) Date: Sat, 1 Sep 2007 22:37:31 +0200 (CEST) Subject: [Python-3000-checkins] r57891 - python/branches/py3k/Lib/distutils/command/install.py python/branches/py3k/Lib/distutils/command/register.py python/branches/py3k/Lib/distutils/command/upload.py Message-ID: <20070901203731.771001E4006@bag.python.org> Author: collin.winter Date: Sat Sep 1 22:37:22 2007 New Revision: 57891 Modified: python/branches/py3k/Lib/distutils/command/install.py python/branches/py3k/Lib/distutils/command/register.py python/branches/py3k/Lib/distutils/command/upload.py Log: Run 2to3's fix_has_key over distutils. Modified: python/branches/py3k/Lib/distutils/command/install.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/install.py (original) +++ python/branches/py3k/Lib/distutils/command/install.py Sat Sep 1 22:37:22 2007 @@ -347,7 +347,7 @@ opt_name = opt[0] if opt_name[-1] == "=": opt_name = opt_name[0:-1] - if self.negative_opt.has_key(opt_name): + if opt_name in self.negative_opt: opt_name = longopt_xlate(self.negative_opt[opt_name]) val = not getattr(self, opt_name) else: Modified: python/branches/py3k/Lib/distutils/command/register.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/register.py (original) +++ python/branches/py3k/Lib/distutils/command/register.py Sat Sep 1 22:37:22 2007 @@ -125,7 +125,7 @@ # see if we can short-cut and get the username/password from the # config config = None - if os.environ.has_key('HOME'): + if 'HOME' in os.environ: rc = os.path.join(os.environ['HOME'], '.pypirc') if os.path.exists(rc): print('Using PyPI login from %s'%rc) @@ -168,7 +168,7 @@ print('Server response (%s): %s'%(code, result)) # possibly save the login - if os.environ.has_key('HOME') and config is None and code == 200: + if 'HOME' in os.environ and config is None and code == 200: rc = os.path.join(os.environ['HOME'], '.pypirc') print('I can store your PyPI login so future submissions will be faster.') print('(the login will be stored in %s)'%rc) Modified: python/branches/py3k/Lib/distutils/command/upload.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/upload.py (original) +++ python/branches/py3k/Lib/distutils/command/upload.py Sat Sep 1 22:37:22 2007 @@ -45,7 +45,7 @@ raise DistutilsOptionError( "Must use --sign for --identity to have meaning" ) - if os.environ.has_key('HOME'): + if 'HOME' in os.environ: rc = os.path.join(os.environ['HOME'], '.pypirc') if os.path.exists(rc): self.announce('Using PyPI login from %s' % rc) From python-3000-checkins at python.org Sun Sep 2 01:34:31 2007 From: python-3000-checkins at python.org (collin.winter) Date: Sun, 2 Sep 2007 01:34:31 +0200 (CEST) Subject: [Python-3000-checkins] r57903 - python/branches/py3k/Doc/library/bsddb.rst python/branches/py3k/Doc/library/cgi.rst python/branches/py3k/Doc/library/email.message.rst python/branches/py3k/Doc/library/imputil.rst python/branches/py3k/Doc/library/mailbox.rst python/branches/py3k/Doc/library/rfc822.rst python/branches/py3k/Doc/library/shelve.rst python/branches/py3k/Doc/library/shutil.rst python/branches/py3k/Doc/library/signal.rst python/branches/py3k/Doc/library/stat.rst python/branches/py3k/Doc/library/stdtypes.rst python/branches/py3k/Doc/library/stringio.rst python/branches/py3k/Doc/library/subprocess.rst python/branches/py3k/Doc/library/tarfile.rst python/branches/py3k/Doc/library/telnetlib.rst python/branches/py3k/Doc/library/test.rst python/branches/py3k/Doc/library/textwrap.rst python/branches/py3k/Doc/library/thread.rst python/branches/py3k/Doc/library/threading.rst python/branches/py3k/Doc/library/timeit.rst python/branches/py3k/Doc/library/tix.rst python/branches/py3k/Doc/library/tkinter.rst python/branches/py3k/Doc/library/traceback.rst python/branches/py3k/Doc/library/urllib.rst python/branches/py3k/Doc/library/urllib2.rst python/branches/py3k/Doc/library/weakref.rst python/branches/py3k/Doc/library/wsgiref.rst python/branches/py3k/Doc/library/xdrlib.rst python/branches/py3k/Doc/library/xml.etree.elementtree.rst python/branches/py3k/Doc/library/xml.sax.utils.rst python/branches/py3k/Doc/library/xmlrpclib.rst Message-ID: <20070901233431.A11931E400B@bag.python.org> Author: collin.winter Date: Sun Sep 2 01:34:30 2007 New Revision: 57903 Modified: python/branches/py3k/Doc/library/bsddb.rst python/branches/py3k/Doc/library/cgi.rst python/branches/py3k/Doc/library/email.message.rst python/branches/py3k/Doc/library/imputil.rst python/branches/py3k/Doc/library/mailbox.rst python/branches/py3k/Doc/library/rfc822.rst python/branches/py3k/Doc/library/shelve.rst python/branches/py3k/Doc/library/shutil.rst python/branches/py3k/Doc/library/signal.rst python/branches/py3k/Doc/library/stat.rst python/branches/py3k/Doc/library/stdtypes.rst python/branches/py3k/Doc/library/stringio.rst python/branches/py3k/Doc/library/subprocess.rst python/branches/py3k/Doc/library/tarfile.rst python/branches/py3k/Doc/library/telnetlib.rst python/branches/py3k/Doc/library/test.rst python/branches/py3k/Doc/library/textwrap.rst python/branches/py3k/Doc/library/thread.rst python/branches/py3k/Doc/library/threading.rst python/branches/py3k/Doc/library/timeit.rst python/branches/py3k/Doc/library/tix.rst python/branches/py3k/Doc/library/tkinter.rst python/branches/py3k/Doc/library/traceback.rst python/branches/py3k/Doc/library/urllib.rst python/branches/py3k/Doc/library/urllib2.rst python/branches/py3k/Doc/library/weakref.rst python/branches/py3k/Doc/library/wsgiref.rst python/branches/py3k/Doc/library/xdrlib.rst python/branches/py3k/Doc/library/xml.etree.elementtree.rst python/branches/py3k/Doc/library/xml.sax.utils.rst python/branches/py3k/Doc/library/xmlrpclib.rst Log: Partial py3k-ification of Doc/library/: convert has_key references into either 'k in d' or __contains__; normalize raise statements; convert print statements into print function calls. Modified: python/branches/py3k/Doc/library/bsddb.rst ============================================================================== --- python/branches/py3k/Doc/library/bsddb.rst (original) +++ python/branches/py3k/Doc/library/bsddb.rst Sun Sep 2 01:34:30 2007 @@ -105,6 +105,11 @@ dictionaries. In addition, they support the methods listed below. +.. describe:: key in bsddbobject + + Return ``True`` if the DB file contains the argument as a key. + + .. method:: bsddbobject.close() Close the underlying file. The object can no longer be accessed. Since there @@ -119,11 +124,6 @@ returned is different for different file formats. -.. method:: bsddbobject.has_key(key) - - Return ``1`` if the DB file contains the argument as a key. - - .. method:: bsddbobject.set_location(key) Set the cursor to the item indicated by *key* and return a tuple containing the @@ -169,7 +169,8 @@ >>> import bsddb >>> db = bsddb.btopen('/tmp/spam.db', 'c') - >>> for i in range(10): db['%d'%i] = '%d'% (i*i) + >>> for i in range(10): + ... db[str(i)] = '%d' % (i*i) ... >>> db['3'] '9' @@ -186,7 +187,7 @@ >>> db.previous() ('1', '1') >>> for k, v in db.iteritems(): - ... print k, v + ... print(k, v) 0 0 1 1 2 4 Modified: python/branches/py3k/Doc/library/cgi.rst ============================================================================== --- python/branches/py3k/Doc/library/cgi.rst (original) +++ python/branches/py3k/Doc/library/cgi.rst Sun Sep 2 01:34:30 2007 @@ -91,11 +91,11 @@ consume standard input, it should be instantiated only once. The :class:`FieldStorage` instance can be indexed like a Python dictionary, and -also supports the standard dictionary methods :meth:`has_key` and :meth:`keys`. -The built-in :func:`len` is also supported. Form fields containing empty -strings are ignored and do not appear in the dictionary; to keep such values, -provide a true value for the optional *keep_blank_values* keyword parameter when -creating the :class:`FieldStorage` instance. +also supports the standard dictionary methods :meth:`__contains__` and +:meth:`keys`. The built-in :func:`len` is also supported. Form fields +containing empty strings are ignored and do not appear in the dictionary; to +keep such values, provide a true value for the optional *keep_blank_values* +keyword parameter when creating the :class:`FieldStorage` instance. For instance, the following code (which assumes that the :mailheader:`Content-Type` header and blank line have already been printed) @@ -103,7 +103,7 @@ string:: form = cgi.FieldStorage() - if not (form.has_key("name") and form.has_key("addr")): + if not ("name" in form and "addr" in form): print "

Error

" print "Please fill in the name and addr fields." return Modified: python/branches/py3k/Doc/library/email.message.rst ============================================================================== --- python/branches/py3k/Doc/library/email.message.rst (original) +++ python/branches/py3k/Doc/library/email.message.rst Sun Sep 2 01:34:30 2007 @@ -200,7 +200,7 @@ No exception is raised if the named field isn't present in the headers. -.. method:: Message.has_key(name) +.. method:: Message.__contains__(name) Return true if the message contains a header field named *name*, otherwise return false. Modified: python/branches/py3k/Doc/library/imputil.rst ============================================================================== --- python/branches/py3k/Doc/library/imputil.rst (original) +++ python/branches/py3k/Doc/library/imputil.rst Sun Sep 2 01:34:30 2007 @@ -122,10 +122,10 @@ return m def determine_parent(globals): - if not globals or not globals.has_key("__name__"): + if not globals or not "__name__" in globals: return None pname = globals['__name__'] - if globals.has_key("__path__"): + if "__path__" in globals: parent = sys.modules[pname] assert globals is parent.__dict__ return parent @@ -156,7 +156,7 @@ parent = None q = import_module(head, qname, parent) if q: return q, tail - raise ImportError, "No module named " + qname + raise ImportError("No module named " + qname) def load_tail(q, tail): m = q @@ -167,7 +167,7 @@ mname = "%s.%s" % (m.__name__, head) m = import_module(head, mname, m) if not m: - raise ImportError, "No module named " + mname + raise ImportError("No module named " + mname) return m def ensure_fromlist(m, fromlist, recursive=0): @@ -185,7 +185,7 @@ subname = "%s.%s" % (m.__name__, sub) submod = import_module(sub, subname, m) if not submod: - raise ImportError, "No module named " + subname + raise ImportError("No module named " + subname) def import_module(partname, fqname, parent): try: Modified: python/branches/py3k/Doc/library/mailbox.rst ============================================================================== --- python/branches/py3k/Doc/library/mailbox.rst (original) +++ python/branches/py3k/Doc/library/mailbox.rst Sun Sep 2 01:34:30 2007 @@ -188,8 +188,7 @@ subclass. -.. method:: Mailbox.has_key(key) - Mailbox.__contains__(key) +.. method:: Mailbox.__contains__(key) Return ``True`` if *key* corresponds to a message, ``False`` otherwise. Modified: python/branches/py3k/Doc/library/rfc822.rst ============================================================================== --- python/branches/py3k/Doc/library/rfc822.rst (original) +++ python/branches/py3k/Doc/library/rfc822.rst Sun Sep 2 01:34:30 2007 @@ -260,7 +260,7 @@ :class:`Message` instances also support a limited mapping interface. In particular: ``m[name]`` is like ``m.getheader(name)`` but raises :exc:`KeyError` if there is no matching header; and ``len(m)``, ``m.get(name[, default])``, -``m.has_key(name)``, ``m.keys()``, ``m.values()`` ``m.items()``, and +``m.__contains__(name)``, ``m.keys()``, ``m.values()`` ``m.items()``, and ``m.setdefault(name[, default])`` act as expected, with the one difference that :meth:`setdefault` uses an empty string as the default value. :class:`Message` instances also support the mapping writable interface ``m[name] Modified: python/branches/py3k/Doc/library/shelve.rst ============================================================================== --- python/branches/py3k/Doc/library/shelve.rst (original) +++ python/branches/py3k/Doc/library/shelve.rst Sun Sep 2 01:34:30 2007 @@ -131,7 +131,7 @@ # such key) del d[key] # delete data stored at key (raises KeyError # if no such key) - flag = d.has_key(key) # true if the key exists + flag = key in d # true if the key exists klist = d.keys() # a list of all existing keys (slow!) # as d was opened WITHOUT writeback=True, beware: Modified: python/branches/py3k/Doc/library/shutil.rst ============================================================================== --- python/branches/py3k/Doc/library/shutil.rst (original) +++ python/branches/py3k/Doc/library/shutil.rst Sun Sep 2 01:34:30 2007 @@ -157,5 +157,5 @@ except OSError as why: errors.extend((src, dst, str(why))) if errors: - raise Error, errors + raise Error(errors) Modified: python/branches/py3k/Doc/library/signal.rst ============================================================================== --- python/branches/py3k/Doc/library/signal.rst (original) +++ python/branches/py3k/Doc/library/signal.rst Sun Sep 2 01:34:30 2007 @@ -144,7 +144,7 @@ def handler(signum, frame): print 'Signal handler called with signal', signum - raise IOError, "Couldn't open device!" + raise IOError("Couldn't open device!") # Set the signal handler and a 5-second alarm signal.signal(signal.SIGALRM, handler) Modified: python/branches/py3k/Doc/library/stat.rst ============================================================================== --- python/branches/py3k/Doc/library/stat.rst (original) +++ python/branches/py3k/Doc/library/stat.rst Sun Sep 2 01:34:30 2007 @@ -157,10 +157,10 @@ callback(pathname) else: # Unknown file type, print a message - print 'Skipping %s' % pathname + print('Skipping %s' % pathname) def visitfile(file): - print 'visiting', file + print('visiting', file) if __name__ == '__main__': walktree(sys.argv[1], visitfile) Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Sun Sep 2 01:34:30 2007 @@ -1032,8 +1032,8 @@ dictionary inserted immediately after the ``'%'`` character. The mapping key selects the value to be formatted from the mapping. For example:: - >>> print '%(language)s has %(#)03d quote types.' % \ - {'language': "Python", "#": 2} + >>> print('%(language)s has %(#)03d quote types.' % + {'language': "Python", "#": 2}) Python has 002 quote types. In this case no ``*`` specifiers may occur in a format (since they require a @@ -1805,10 +1805,6 @@ *default* is not given, it defaults to ``None``, so that this method never raises a :exc:`KeyError`. -.. method:: dict.has_key(key) - - ``d.has_key(key)`` is equivalent to ``key in d``, but deprecated. - .. method:: dict.items() Return a copy of the dictionary's list of ``(key, value)`` pairs. @@ -1923,7 +1919,7 @@ with open("hello.txt") as f: for line in f: - print line + print(line) In older versions of Python, you would have needed to do this to get the same effect:: @@ -1931,7 +1927,7 @@ f = open("hello.txt") try: for line in f: - print line + print(line) finally: f.close() Modified: python/branches/py3k/Doc/library/stringio.rst ============================================================================== --- python/branches/py3k/Doc/library/stringio.rst (original) +++ python/branches/py3k/Doc/library/stringio.rst Sun Sep 2 01:34:30 2007 @@ -45,7 +45,7 @@ output = StringIO.StringIO() output.write('First line.\n') - print >>output, 'Second line.' + print('Second line.', file=output) # Retrieve file contents -- this will be # 'First line.\nSecond line.\n' @@ -111,7 +111,7 @@ output = cStringIO.StringIO() output.write('First line.\n') - print >>output, 'Second line.' + print('Second line.', file=output) # Retrieve file contents -- this will be # 'First line.\nSecond line.\n' Modified: python/branches/py3k/Doc/library/subprocess.rst ============================================================================== --- python/branches/py3k/Doc/library/subprocess.rst (original) +++ python/branches/py3k/Doc/library/subprocess.rst Sun Sep 2 01:34:30 2007 @@ -284,11 +284,11 @@ try: retcode = call("mycmd" + " myarg", shell=True) if retcode < 0: - print >>sys.stderr, "Child was terminated by signal", -retcode + print("Child was terminated by signal", -retcode, file=sys.stderr) else: - print >>sys.stderr, "Child returned", retcode + print("Child returned", retcode, file=sys.stderr) except OSError as e: - print >>sys.stderr, "Execution failed:", e + print("Execution failed:", e, file=sys.stderr) Replacing os.spawn\* Modified: python/branches/py3k/Doc/library/tarfile.rst ============================================================================== --- python/branches/py3k/Doc/library/tarfile.rst (original) +++ python/branches/py3k/Doc/library/tarfile.rst Sun Sep 2 01:34:30 2007 @@ -601,13 +601,13 @@ import tarfile tar = tarfile.open("sample.tar.gz", "r:gz") for tarinfo in tar: - print tarinfo.name, "is", tarinfo.size, "bytes in size and is", + print(tarinfo.name, "is", tarinfo.size, "bytes in size and is", end="") if tarinfo.isreg(): - print "a regular file." + print("a regular file.") elif tarinfo.isdir(): - print "a directory." + print("a directory.") else: - print "something else." + print("something else.") tar.close() How to create a tar archive with faked information:: Modified: python/branches/py3k/Doc/library/telnetlib.rst ============================================================================== --- python/branches/py3k/Doc/library/telnetlib.rst (original) +++ python/branches/py3k/Doc/library/telnetlib.rst Sun Sep 2 01:34:30 2007 @@ -234,5 +234,5 @@ tn.write("ls\n") tn.write("exit\n") - print tn.read_all() + print(tn.read_all()) Modified: python/branches/py3k/Doc/library/test.rst ============================================================================== --- python/branches/py3k/Doc/library/test.rst (original) +++ python/branches/py3k/Doc/library/test.rst Sun Sep 2 01:34:30 2007 @@ -307,7 +307,7 @@ Example use:: with captured_stdout() as s: - print "hello" + print("hello") assert s.getvalue() == "hello" Modified: python/branches/py3k/Doc/library/textwrap.rst ============================================================================== --- python/branches/py3k/Doc/library/textwrap.rst (original) +++ python/branches/py3k/Doc/library/textwrap.rst Sun Sep 2 01:34:30 2007 @@ -64,8 +64,8 @@ hello world ''' - print repr(s) # prints ' hello\n world\n ' - print repr(dedent(s)) # prints 'hello\n world\n' + print(repr(s)) # prints ' hello\n world\n ' + print(repr(dedent(s))) # prints 'hello\n world\n' .. class:: TextWrapper(...) Modified: python/branches/py3k/Doc/library/thread.rst ============================================================================== --- python/branches/py3k/Doc/library/thread.rst (original) +++ python/branches/py3k/Doc/library/thread.rst Sun Sep 2 01:34:30 2007 @@ -135,7 +135,7 @@ a_lock = thread.allocate_lock() with a_lock: - print "a_lock is locked while this executes" + print("a_lock is locked while this executes") **Caveats:** Modified: python/branches/py3k/Doc/library/threading.rst ============================================================================== --- python/branches/py3k/Doc/library/threading.rst (original) +++ python/branches/py3k/Doc/library/threading.rst Sun Sep 2 01:34:30 2007 @@ -683,7 +683,7 @@ For example:: def hello(): - print "hello, world" + print("hello, world") t = Timer(30.0, hello) t.start() # after 30 seconds, "hello, world" will be printed @@ -721,5 +721,5 @@ some_rlock = threading.RLock() with some_rlock: - print "some_rlock is locked while this executes" + print("some_rlock is locked while this executes") Modified: python/branches/py3k/Doc/library/timeit.rst ============================================================================== --- python/branches/py3k/Doc/library/timeit.rst (original) +++ python/branches/py3k/Doc/library/timeit.rst Sun Sep 2 01:34:30 2007 @@ -196,13 +196,13 @@ ... pass ... """ >>> t = timeit.Timer(stmt=s) - >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) + >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)) 17.09 usec/pass >>> s = """\ ... if hasattr(str, '__bool__'): pass ... """ >>> t = timeit.Timer(stmt=s) - >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) + >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)) 4.85 usec/pass >>> s = """\ ... try: @@ -211,13 +211,13 @@ ... pass ... """ >>> t = timeit.Timer(stmt=s) - >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) + >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)) 1.97 usec/pass >>> s = """\ ... if hasattr(int, '__bool__'): pass ... """ >>> t = timeit.Timer(stmt=s) - >>> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) + >>> print("%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)) 3.15 usec/pass To give the :mod:`timeit` module access to functions you define, you can pass a @@ -225,12 +225,10 @@ def test(): "Stupid test function" - L = [] - for i in range(100): - L.append(i) + L = [i for i in range(100)] if __name__=='__main__': from timeit import Timer t = Timer("test()", "from __main__ import test") - print t.timeit() + print(t.timeit()) Modified: python/branches/py3k/Doc/library/tix.rst ============================================================================== --- python/branches/py3k/Doc/library/tix.rst (original) +++ python/branches/py3k/Doc/library/tix.rst Sun Sep 2 01:34:30 2007 @@ -505,7 +505,7 @@ import Tix root = Tix.Tk() - print root.tix_configure() + print(root.tix_configure()) .. method:: tixCommand.tix_configure([cnf,] **kw) Modified: python/branches/py3k/Doc/library/tkinter.rst ============================================================================== --- python/branches/py3k/Doc/library/tkinter.rst (original) +++ python/branches/py3k/Doc/library/tkinter.rst Sun Sep 2 01:34:30 2007 @@ -184,7 +184,7 @@ class Application(Frame): def say_hi(self): - print "hi there, everyone!" + print("hi there, everyone!") def createWidgets(self): self.QUIT = Button(self) @@ -441,7 +441,7 @@ Example:: - >>> print fred.config() + >>> print(fred.config()) {'relief' : ('relief', 'relief', 'Relief', 'raised', 'groove')} Of course, the dictionary printed will include all the options available and @@ -560,8 +560,8 @@ self.print_contents) def print_contents(self, event): - print "hi. contents of entry is now ---->", \ - self.contents.get() + print("hi. contents of entry is now ---->", + self.contents.get()) The Window Manager @@ -633,7 +633,7 @@ This is any Python function that takes no arguments. For example:: def print_it(): - print "hi there" + print("hi there") fred["command"] = print_it color Modified: python/branches/py3k/Doc/library/traceback.rst ============================================================================== --- python/branches/py3k/Doc/library/traceback.rst (original) +++ python/branches/py3k/Doc/library/traceback.rst Sun Sep 2 01:34:30 2007 @@ -147,12 +147,12 @@ try: exec(source, envdir) except: - print "Exception in user code:" - print '-'*60 + print("Exception in user code:") + print("-"*60) traceback.print_exc(file=sys.stdout) - print '-'*60 + print("-"*60) envdir = {} - while 1: + while True: run_user_code(envdir) Modified: python/branches/py3k/Doc/library/urllib.rst ============================================================================== --- python/branches/py3k/Doc/library/urllib.rst (original) +++ python/branches/py3k/Doc/library/urllib.rst Sun Sep 2 01:34:30 2007 @@ -438,14 +438,14 @@ >>> import urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params) - >>> print f.read() + >>> print(f.read()) The following example uses the ``POST`` method instead:: >>> import urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params) - >>> print f.read() + >>> print(f.read()) The following example uses an explicitly specified HTTP proxy, overriding environment settings:: Modified: python/branches/py3k/Doc/library/urllib2.rst ============================================================================== --- python/branches/py3k/Doc/library/urllib2.rst (original) +++ python/branches/py3k/Doc/library/urllib2.rst Sun Sep 2 01:34:30 2007 @@ -834,7 +834,7 @@ >>> import urllib2 >>> f = urllib2.urlopen('http://www.python.org/') - >>> print f.read(100) + >>> print(f.read(100)) >> req = urllib2.Request(url='https://localhost/cgi-bin/test.cgi', ... data='This data is passed to stdin of the CGI') >>> f = urllib2.urlopen(req) - >>> print f.read() + >>> print(f.read()) Got Data: "This data is passed to stdin of the CGI" The code for the sample CGI used in the above example is:: @@ -854,7 +854,7 @@ #!/usr/bin/env python import sys data = sys.stdin.read() - print 'Content-type: text-plain\n\nGot Data: "%s"' % data + print('Content-type: text-plain\n\nGot Data: "%s"' % data) Use of Basic HTTP Authentication:: Modified: python/branches/py3k/Doc/library/weakref.rst ============================================================================== --- python/branches/py3k/Doc/library/weakref.rst (original) +++ python/branches/py3k/Doc/library/weakref.rst Sun Sep 2 01:34:30 2007 @@ -236,7 +236,7 @@ :const:`None`:: >>> del o, o2 - >>> print r() + >>> print(r()) None Testing that a weak reference object is still live should be done using the @@ -247,9 +247,9 @@ o = r() if o is None: # referent has been garbage collected - print "Object has been deallocated; can't frobnicate." + print("Object has been deallocated; can't frobnicate.") else: - print "Object is still live!" + print("Object is still live!") o.do_something_useful() Using a separate test for "liveness" creates race conditions in threaded Modified: python/branches/py3k/Doc/library/wsgiref.rst ============================================================================== --- python/branches/py3k/Doc/library/wsgiref.rst (original) +++ python/branches/py3k/Doc/library/wsgiref.rst Sun Sep 2 01:34:30 2007 @@ -244,7 +244,7 @@ from wsgiref.simple_server import make_server, demo_app httpd = make_server('', 8000, demo_app) - print "Serving HTTP on port 8000..." + print("Serving HTTP on port 8000...") # Respond to requests until process is killed httpd.serve_forever() Modified: python/branches/py3k/Doc/library/xdrlib.rst ============================================================================== --- python/branches/py3k/Doc/library/xdrlib.rst (original) +++ python/branches/py3k/Doc/library/xdrlib.rst Sun Sep 2 01:34:30 2007 @@ -272,5 +272,5 @@ try: p.pack_double(8.01) except xdrlib.ConversionError as instance: - print 'packing the double failed:', instance.msg + print('packing the double failed:', instance.msg) Modified: python/branches/py3k/Doc/library/xml.etree.elementtree.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.etree.elementtree.rst (original) +++ python/branches/py3k/Doc/library/xml.etree.elementtree.rst Sun Sep 2 01:34:30 2007 @@ -278,10 +278,10 @@ element = root.find('foo') if not element: # careful! - print "element not found, or element has no subelements" + print("element not found, or element has no subelements") if element is None: - print "element not found" + print("element not found") .. _elementtree-elementtree-objects: Modified: python/branches/py3k/Doc/library/xml.sax.utils.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.sax.utils.rst (original) +++ python/branches/py3k/Doc/library/xml.sax.utils.rst Sun Sep 2 01:34:30 2007 @@ -42,7 +42,7 @@ will be wrapped in double-quotes. The resulting string can be used directly as an attribute value:: - >>> print "" % quoteattr("ab ' cd \" ef") + >>> print("" % quoteattr("ab ' cd \" ef")) This function is useful when generating attribute values for HTML or any SGML Modified: python/branches/py3k/Doc/library/xmlrpclib.rst ============================================================================== --- python/branches/py3k/Doc/library/xmlrpclib.rst (original) +++ python/branches/py3k/Doc/library/xmlrpclib.rst Sun Sep 2 01:34:30 2007 @@ -371,12 +371,12 @@ # server = ServerProxy("http://localhost:8000") # local server server = ServerProxy("http://betty.userland.com") - print server + print(server) try: - print server.examples.getStateName(41) + print(server.examples.getStateName(41)) except Error as v: - print "ERROR", v + print("ERROR", v) To access an XML-RPC server through a proxy, you need to define a custom transport. The following example, written by NoboNobo, shows how: @@ -404,5 +404,5 @@ p = ProxiedTransport() p.set_proxy('proxy-server:8080') server = xmlrpclib.Server('http://time.xmlrpc.com/RPC2', transport=p) - print server.currentTime.getCurrentTime() + print(server.currentTime.getCurrentTime()) From fdrake at acm.org Sun Sep 2 03:01:35 2007 From: fdrake at acm.org (Fred Drake) Date: Sat, 1 Sep 2007 21:01:35 -0400 Subject: [Python-3000-checkins] r57868 - python/branches/py3k/Doc/c-api/abstract.rst... In-Reply-To: <20070901123342.AE78F1E4006@bag.python.org> References: <20070901123342.AE78F1E4006@bag.python.org> Message-ID: On Sep 1, 2007, at 8:33 AM, georg.brandl wrote: > Remove versionadded and versionchanged directives, fold information > into text where necessary. Was this discussed somewhere and I just missed the discussion? Removing information from the documentation source is somewhat disturbing. The descriptions should be complete for the current version without the added/changed notes, but those are important for anyone dealing with multiple versions. I suspect that won't really change when people move to Python 3.0, so I doubt removing these is actually a good thing. (Displaying them could be made optional, though.) -Fred -- Fred Drake From guido at python.org Sun Sep 2 03:55:39 2007 From: guido at python.org (Guido van Rossum) Date: Sat, 1 Sep 2007 18:55:39 -0700 Subject: [Python-3000-checkins] r57868 - python/branches/py3k/Doc/c-api/abstract.rst... In-Reply-To: References: <20070901123342.AE78F1E4006@bag.python.org> Message-ID: I approved it, but I don't think I spent more than a minute thinking about it. Since 3.0 is fundamentally incompatible with 2.x, I don't think it's important to keep a record in the docs about when something was added during the 2.x era -- future historians can dig that out of the 2.6 docs if they care. There just isn't a use case (that I can think of) for trying to write code that works in 3.0 *and* in some other version earlier than 2.6. And even for 2.6 vs. 3.0 the best you can do is run 2to3 over the 2.6 sources. So I don't see how someone using 3.0 would be interested in which 2.x version something was added. --Guido On 9/1/07, Fred Drake wrote: > On Sep 1, 2007, at 8:33 AM, georg.brandl wrote: > > Remove versionadded and versionchanged directives, fold information > > into text where necessary. > > Was this discussed somewhere and I just missed the discussion? > Removing information from the documentation source is somewhat > disturbing. > > The descriptions should be complete for the current version without > the added/changed notes, but those are important for anyone dealing > with multiple versions. I suspect that won't really change when > people move to Python 3.0, so I doubt removing these is actually a > good thing. (Displaying them could be made optional, though.) > > > -Fred > > -- > Fred Drake > > > > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > -- --Guido van Rossum (home page: http://www.python.org/~guido/) From python-3000-checkins at python.org Sun Sep 2 17:33:44 2007 From: python-3000-checkins at python.org (eric.smith) Date: Sun, 2 Sep 2007 17:33:44 +0200 (CEST) Subject: [Python-3000-checkins] r57906 - in python/branches/py3k: Doc/library/string.rst Lib/string.py Message-ID: <20070902153344.7DF331E4006@bag.python.org> Author: eric.smith Date: Sun Sep 2 17:33:26 2007 New Revision: 57906 Modified: python/branches/py3k/Doc/library/string.rst python/branches/py3k/Lib/string.py Log: Removed used_args param from string.Formatter.get_field. It was left in by mistake from an earlier edit. Modified: python/branches/py3k/Doc/library/string.rst ============================================================================== --- python/branches/py3k/Doc/library/string.rst (original) +++ python/branches/py3k/Doc/library/string.rst Sun Sep 2 17:33:26 2007 @@ -125,7 +125,7 @@ field, then the values of *field_name*, *format_spec* and *conversion* will be ``None``. - .. method:: get_field(field_name, args, kwargs, used_args) + .. method:: get_field(field_name, args, kwargs) Given *field_name* as returned by :meth:`parse` (see above), convert it to an object to be formatted. Returns a tuple (obj, used_key). The default Modified: python/branches/py3k/Lib/string.py ============================================================================== --- python/branches/py3k/Lib/string.py (original) +++ python/branches/py3k/Lib/string.py Sun Sep 2 17:33:26 2007 @@ -217,7 +217,7 @@ # given the field_name, find the object it references # and the argument it came from - obj, arg_used = self.get_field(field_name, args, kwargs, used_args) + obj, arg_used = self.get_field(field_name, args, kwargs) used_args.add(arg_used) # do any conversion on the resulting object @@ -272,11 +272,9 @@ # or "lookup[3]" # used_args: a set of which args have been used # args, kwargs: as passed in to vformat - # also, mark it as used in 'used_args' - def get_field(self, field_name, args, kwargs, used_args): + def get_field(self, field_name, args, kwargs): first, rest = field_name._formatter_field_name_split() - used_args.add(first) obj = self.get_value(first, args, kwargs) # loop through the rest of the field_name, doing From python-3000-checkins at python.org Mon Sep 3 09:10:25 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 3 Sep 2007 09:10:25 +0200 (CEST) Subject: [Python-3000-checkins] r57923 - python/branches/py3k/Doc/tutorial/classes.rst python/branches/py3k/Doc/tutorial/controlflow.rst python/branches/py3k/Doc/tutorial/datastructures.rst python/branches/py3k/Doc/tutorial/inputoutput.rst python/branches/py3k/Doc/tutorial/introduction.rst python/branches/py3k/Doc/tutorial/modules.rst python/branches/py3k/Doc/tutorial/stdlib2.rst Message-ID: <20070903071025.82FAC1E4007@bag.python.org> Author: georg.brandl Date: Mon Sep 3 09:10:24 2007 New Revision: 57923 Modified: python/branches/py3k/Doc/tutorial/classes.rst python/branches/py3k/Doc/tutorial/controlflow.rst python/branches/py3k/Doc/tutorial/datastructures.rst python/branches/py3k/Doc/tutorial/inputoutput.rst python/branches/py3k/Doc/tutorial/introduction.rst python/branches/py3k/Doc/tutorial/modules.rst python/branches/py3k/Doc/tutorial/stdlib2.rst Log: Tutorial formatting patch by Robin Stocker. Modified: python/branches/py3k/Doc/tutorial/classes.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/classes.rst (original) +++ python/branches/py3k/Doc/tutorial/classes.rst Mon Sep 3 09:10:24 2007 @@ -769,7 +769,7 @@ >>> valedictorian = max((student.gpa, student.name) for student in graduates) >>> data = 'golf' - >>> list(data[i] for i in range(len(data)-1,-1,-1)) + >>> list(data[i] for i in range(len(data)-1, -1, -1)) ['f', 'l', 'o', 'g'] Modified: python/branches/py3k/Doc/tutorial/controlflow.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/controlflow.rst (original) +++ python/branches/py3k/Doc/tutorial/controlflow.rst Mon Sep 3 09:10:24 2007 @@ -210,7 +210,7 @@ ... """Print a Fibonacci series up to n.""" ... a, b = 0, 1 ... while b < n: - ... print(b,end=' ') + ... print(b, end=' ') ... a, b = b, a+b ... print() ... @@ -389,7 +389,7 @@ value``. For instance, the following function:: def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): - print("-- This parrot wouldn't", action, end= ' ') + print("-- This parrot wouldn't", action, end=' ') print("if you put", voltage, "volts through it.") print("-- Lovely plumage, the", type) print("-- It's", state, "!") @@ -481,7 +481,7 @@ parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the ``*args`` parameter are 'keyword-only' arguments, meaning that they can only be used as -keywords rather than positional arguments.:: +keywords rather than positional arguments. :: >>> def concat(*args, sep="/"): ... return sep.join(args) @@ -513,7 +513,7 @@ -operator:: >>> def parrot(voltage, state='a stiff', action='voom'): - ... print("-- This parrot wouldn't", action,end=' ') + ... print("-- This parrot wouldn't", action, end=' ') ... print("if you put", voltage, "volts through it.", end=' ') ... print("E's", state, "!") ... Modified: python/branches/py3k/Doc/tutorial/datastructures.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/datastructures.rst (original) +++ python/branches/py3k/Doc/tutorial/datastructures.rst Mon Sep 3 09:10:24 2007 @@ -234,7 +234,7 @@ Now we get a little fancier:: - >>> [[x,x**2] for x in vec] + >>> [[x, x**2] for x in vec] [[2, 4], [4, 16], [6, 36]] Here we apply a method call to each item in a sequence:: @@ -243,7 +243,7 @@ >>> [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit'] -Using the if-clause we can filter the stream:: +Using the :keyword:`if` clause we can filter the stream:: >>> [3*x for x in vec if x > 3] [12, 18] @@ -260,7 +260,7 @@ >>> [(x, x**2) for x in vec] [(2, 4), (4, 16), (6, 36)] -Here are some nested for's and other fancy behavior:: +Here are some nested for loops and other fancy behavior:: >>> vec1 = [2, 4, 6] >>> vec2 = [4, 3, -9] @@ -273,7 +273,7 @@ List comprehensions can be applied to complex expressions and nested functions:: - >>> [str(round(355/113.0, i)) for i in range(1,6)] + >>> [str(round(355/113.0, i)) for i in range(1, 6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159'] @@ -469,7 +469,7 @@ To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the :func:`reversed` function. :: - >>> for i in reversed(range(1,10,2)): + >>> for i in reversed(range(1, 10, 2)): ... print(i) ... 9 Modified: python/branches/py3k/Doc/tutorial/inputoutput.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/inputoutput.rst (original) +++ python/branches/py3k/Doc/tutorial/inputoutput.rst Mon Sep 3 09:10:24 2007 @@ -78,7 +78,7 @@ Here are two ways to write a table of squares and cubes:: >>> for x in range(1, 11): - ... print(repr(x).rjust(2), repr(x*x).rjust(3),end=' ') + ... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ') ... # Note use of 'end' on previous line ... print(repr(x*x*x).rjust(4)) ... @@ -93,7 +93,7 @@ 9 81 729 10 100 1000 - >>> for x in range(1,11): + >>> for x in range(1, 11): ... print('%2d %3d %4d' % (x, x*x, x*x*x)) ... 1 1 1 Modified: python/branches/py3k/Doc/tutorial/introduction.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/introduction.rst (original) +++ python/branches/py3k/Doc/tutorial/introduction.rst Mon Sep 3 09:10:24 2007 @@ -111,7 +111,7 @@ >>> 1j * 1J (-1+0j) - >>> 1j * complex(0,1) + >>> 1j * complex(0, 1) (-1+0j) >>> 3+1j*3 (3+3j) @@ -271,8 +271,9 @@ Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is -simply a string of size one. As in Icon, substrings can be specified with the -*slice notation*: two indices separated by a colon. :: +simply a string of size one. As in the Icon programming language, substrings +can be specified with the *slice notation*: two indices separated by a colon. +:: >>> word[4] 'A' @@ -523,7 +524,7 @@ You can add something to the end of the list:: - >>> p[1].append('xtra') + >>> p[1].append('xtra') >>> p [1, [2, 3, 'xtra'], 4] >>> q Modified: python/branches/py3k/Doc/tutorial/modules.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/modules.rst (original) +++ python/branches/py3k/Doc/tutorial/modules.rst Mon Sep 3 09:10:24 2007 @@ -224,9 +224,9 @@ files when :option:`-O` is used) for all modules in a directory. * If using Python in a parallel processing system with a shared file system, - you need to patch python to disable the creation of the compiled files + you need to patch Python to disable the creation of the compiled files because otherwise the multiple Python interpreters will encounter race - conditions in creating them. + conditions in creating them. .. _tut-standardmodules: Modified: python/branches/py3k/Doc/tutorial/stdlib2.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/stdlib2.rst (original) +++ python/branches/py3k/Doc/tutorial/stdlib2.rst Mon Sep 3 09:10:24 2007 @@ -184,7 +184,7 @@ f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) f.write(self.infile) f.close() - print('Finished background zip of: ', self.infile) + print('Finished background zip of:', self.infile) background = AsyncZip('mydata.txt', 'myarchive.zip') background.start() From python-3000-checkins at python.org Mon Sep 3 09:27:50 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 3 Sep 2007 09:27:50 +0200 (CEST) Subject: [Python-3000-checkins] r57926 - in python/branches/py3k: Lib/plat-mac/Carbon/ControlAccessor.py Lib/plat-mac/buildtools.py Lib/plat-mac/bundlebuilder.py Lib/plat-mac/macresource.py Mac/IDLE/Makefile.in Mac/PythonLauncher/Makefile.in Mac/Tools/fixapplepython23.py Mac/scripts/cachersrc.py Message-ID: <20070903072750.3464A1E4007@bag.python.org> Author: georg.brandl Date: Mon Sep 3 09:27:49 2007 New Revision: 57926 Modified: python/branches/py3k/Lib/plat-mac/Carbon/ControlAccessor.py python/branches/py3k/Lib/plat-mac/buildtools.py python/branches/py3k/Lib/plat-mac/bundlebuilder.py python/branches/py3k/Lib/plat-mac/macresource.py python/branches/py3k/Mac/IDLE/Makefile.in python/branches/py3k/Mac/PythonLauncher/Makefile.in python/branches/py3k/Mac/Tools/fixapplepython23.py python/branches/py3k/Mac/scripts/cachersrc.py Log: Fix Mac build, patch #1091 by Humberto Diogenes. Modified: python/branches/py3k/Lib/plat-mac/Carbon/ControlAccessor.py ============================================================================== --- python/branches/py3k/Lib/plat-mac/Carbon/ControlAccessor.py (original) +++ python/branches/py3k/Lib/plat-mac/Carbon/ControlAccessor.py Mon Sep 3 09:27:49 2007 @@ -1,6 +1,6 @@ # Accessor functions for control properties -from Controls import * +from Carbon.Controls import * import struct # These needn't go through this module, but are here for completeness Modified: python/branches/py3k/Lib/plat-mac/buildtools.py ============================================================================== --- python/branches/py3k/Lib/plat-mac/buildtools.py (original) +++ python/branches/py3k/Lib/plat-mac/buildtools.py Mon Sep 3 09:27:49 2007 @@ -17,7 +17,8 @@ warnings.warn("the buildtools module is deprecated", DeprecationWarning, 2) -BuildError = "BuildError" +class BuildError(Exception): + pass # .pyc file (and 'PYC ' resource magic number) MAGIC = imp.get_magic() Modified: python/branches/py3k/Lib/plat-mac/bundlebuilder.py ============================================================================== --- python/branches/py3k/Lib/plat-mac/bundlebuilder.py (original) +++ python/branches/py3k/Lib/plat-mac/bundlebuilder.py Mon Sep 3 09:27:49 2007 @@ -180,7 +180,7 @@ assert len(self.type) == len(self.creator) == 4, \ "type and creator must be 4-byte strings." pkginfo = pathjoin(contents, "PkgInfo") - f = open(pkginfo, "wb") + f = open(pkginfo, "w") f.write(self.type + self.creator) f.close() # Modified: python/branches/py3k/Lib/plat-mac/macresource.py ============================================================================== --- python/branches/py3k/Lib/plat-mac/macresource.py (original) +++ python/branches/py3k/Lib/plat-mac/macresource.py Mon Sep 3 09:27:49 2007 @@ -76,15 +76,15 @@ AppleSingle file""" try: refno = Res.FSpOpenResFile(pathname, 1) - except Res.Error as arg: - if arg[0] in (-37, -39): + except Res.Error as error: + if error.args[0] in (-37, -39): # No resource fork. We may be on OSX, and this may be either # a data-fork based resource file or a AppleSingle file # from the CVS repository. try: refno = Res.FSOpenResourceFile(pathname, '', 1) - except Res.Error as arg: - if arg[0] != -199: + except Res.Error as error: + if error.args[0] != -199: # -199 is "bad resource map" raise else: @@ -103,15 +103,15 @@ try: refno = Res.FSpOpenResFile(pathname, 1) Res.CloseResFile(refno) - except Res.Error as arg: - if arg[0] in (-37, -39): + except Res.Error as error: + if error.args[0] in (-37, -39): # No resource fork. We may be on OSX, and this may be either # a data-fork based resource file or a AppleSingle file # from the CVS repository. try: refno = Res.FSOpenResourceFile(pathname, '', 1) - except Res.Error as arg: - if arg[0] != -199: + except Res.Error as error: + if error.args[0] != -199: # -199 is "bad resource map" raise else: Modified: python/branches/py3k/Mac/IDLE/Makefile.in ============================================================================== --- python/branches/py3k/Mac/IDLE/Makefile.in (original) +++ python/branches/py3k/Mac/IDLE/Makefile.in Mon Sep 3 09:27:49 2007 @@ -55,5 +55,5 @@ Info.plist: $(srcdir)/Info.plist.in - sed 's/%VERSION%/'"`$(RUNSHARED) $(BUILDPYTHON) -c 'import platform; print platform.python_version()'`"'/g' < $(srcdir)/Info.plist.in > Info.plist + sed 's/%VERSION%/'"`$(RUNSHARED) $(BUILDPYTHON) -c 'import platform; print(platform.python_version())'`"'/g' < $(srcdir)/Info.plist.in > Info.plist Modified: python/branches/py3k/Mac/PythonLauncher/Makefile.in ============================================================================== --- python/branches/py3k/Mac/PythonLauncher/Makefile.in (original) +++ python/branches/py3k/Mac/PythonLauncher/Makefile.in Mon Sep 3 09:27:49 2007 @@ -78,4 +78,4 @@ $(CC) $(LDFLAGS) -o "Python Launcher" $(OBJECTS) -framework AppKit -framework Carbon Info.plist: $(srcdir)/Info.plist.in - sed 's/%VERSION%/'"`$(RUNSHARED) $(BUILDPYTHON) -c 'import platform; print platform.python_version()'`"'/g' < $(srcdir)/Info.plist.in > Info.plist + sed 's/%VERSION%/'"`$(RUNSHARED) $(BUILDPYTHON) -c 'import platform; print(platform.python_version())'`"'/g' < $(srcdir)/Info.plist.in > Info.plist Modified: python/branches/py3k/Mac/Tools/fixapplepython23.py ============================================================================== --- python/branches/py3k/Mac/Tools/fixapplepython23.py (original) +++ python/branches/py3k/Mac/Tools/fixapplepython23.py Mon Sep 3 09:27:49 2007 @@ -80,11 +80,11 @@ """Create a wrapper script for a compiler""" dirname = os.path.split(filename)[0] if not os.access(dirname, os.X_OK): - os.mkdir(dirname, 0755) + os.mkdir(dirname, 0o755) fp = open(filename, 'w') fp.write(SCRIPT % compiler) fp.close() - os.chmod(filename, 0755) + os.chmod(filename, 0o755) print('fixapplepython23: Created', filename) def main(): Modified: python/branches/py3k/Mac/scripts/cachersrc.py ============================================================================== --- python/branches/py3k/Mac/scripts/cachersrc.py (original) +++ python/branches/py3k/Mac/scripts/cachersrc.py Mon Sep 3 09:27:49 2007 @@ -12,7 +12,8 @@ class NoArgsError(Exception): pass -def handler((verbose, force), dirname, fnames): +def handler(arg1, dirname, fnames): + verbose, force = arg1 for fn in fnames: if fn[-5:] == '.rsrc' and fn[-13:] != '.rsrc.df.rsrc': if force: From python-3000-checkins at python.org Mon Sep 3 09:40:25 2007 From: python-3000-checkins at python.org (martin.v.loewis) Date: Mon, 3 Sep 2007 09:40:25 +0200 (CEST) Subject: [Python-3000-checkins] r57927 - python/branches/py3k/Python/errors.c Message-ID: <20070903074025.2699B1E4012@bag.python.org> Author: martin.v.loewis Date: Mon Sep 3 09:40:24 2007 New Revision: 57927 Modified: python/branches/py3k/Python/errors.c Log: Patch #1075: Use wide API to format error messages. Modified: python/branches/py3k/Python/errors.c ============================================================================== --- python/branches/py3k/Python/errors.c (original) +++ python/branches/py3k/Python/errors.c Mon Sep 3 09:40:24 2007 @@ -10,8 +10,8 @@ #endif #ifdef MS_WINDOWS -#include "windows.h" -#include "winbase.h" +#include +#include #endif #include @@ -270,30 +270,38 @@ PyObject * PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject) { + PyObject *message; PyObject *v; - char *s; int i = errno; #ifdef PLAN9 char errbuf[ERRMAX]; -#endif -#ifdef MS_WINDOWS - char *s_buf = NULL; - char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */ -#endif +#else +#ifndef MS_WINDOWS + char *s; +#else + WCHAR *s_buf = NULL; +#endif /* Unix/Windows */ +#endif /* PLAN 9*/ + #ifdef EINTR if (i == EINTR && PyErr_CheckSignals()) return NULL; #endif + #ifdef PLAN9 rerrstr(errbuf, sizeof errbuf); - s = errbuf; + message = PyUnicode_DecodeUTF8(errbuf, strlen(errbuf), "ignore"); #else +#ifndef MS_WINDOWS if (i == 0) s = "Error"; /* Sometimes errno didn't get set */ else -#ifndef MS_WINDOWS s = strerror(i); + message = PyUnicode_DecodeUTF8(s, strlen(s), "ignore"); #else + if (i == 0) + message = PyUnicode_FromString("Error"); /* Sometimes errno didn't get set */ + else { /* Note that the Win32 errors do not lineup with the errno error. So if the error is in the MSVC error @@ -301,10 +309,10 @@ a Win32 error code */ if (i > 0 && i < _sys_nerr) { - s = _sys_errlist[i]; + message = PyUnicode_FromString(_sys_errlist[i]); } else { - int len = FormatMessage( + int len = FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, @@ -313,29 +321,39 @@ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ - (LPTSTR) &s_buf, + (LPWSTR) &s_buf, 0, /* size not used */ NULL); /* no args */ if (len==0) { /* Only ever seen this in out-of-mem situations */ - sprintf(s_small_buf, "Windows Error 0x%X", i); - s = s_small_buf; s_buf = NULL; + message = PyUnicode_FromFormat("Windows Error 0x%X", i); } else { - s = s_buf; /* remove trailing cr/lf and dots */ - while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.')) - s[--len] = '\0'; + while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) + s_buf[--len] = L'\0'; + message = PyUnicode_FromUnicode(s_buf, len); } } } #endif /* Unix/Windows */ #endif /* PLAN 9*/ + + if (message == NULL) + { +#ifdef MS_WINDOWS + LocalFree(s_buf); +#endif + return NULL; + } + if (filenameObject != NULL) - v = Py_BuildValue("(iUO)", i, s, filenameObject); + v = Py_BuildValue("(iOO)", i, message, filenameObject); else - v = Py_BuildValue("(iU)", i, s); + v = Py_BuildValue("(iO)", i, message); + Py_DECREF(message); + if (v != NULL) { PyErr_SetObject(exc, v); Py_DECREF(v); @@ -383,13 +401,12 @@ PyObject *filenameObject) { int len; - char *s; - char *s_buf = NULL; /* Free via LocalFree */ - char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */ + WCHAR *s_buf = NULL; /* Free via LocalFree */ + PyObject *message; PyObject *v; DWORD err = (DWORD)ierr; if (err==0) err = GetLastError(); - len = FormatMessage( + len = FormatMessageW( /* Error API error */ FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | @@ -398,24 +415,32 @@ err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ - (LPTSTR) &s_buf, + (LPWSTR) &s_buf, 0, /* size not used */ NULL); /* no args */ if (len==0) { /* Only seen this in out of mem situations */ - sprintf(s_small_buf, "Windows Error 0x%X", err); - s = s_small_buf; + message = PyUnicode_FromFormat("Windows Error 0x%X", err); s_buf = NULL; } else { - s = s_buf; /* remove trailing cr/lf and dots */ - while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.')) - s[--len] = '\0'; + while (len > 0 && (s_buf[len-1] <= L' ' || s_buf[len-1] == L'.')) + s_buf[--len] = L'\0'; + message = PyUnicode_FromUnicode(s_buf, len); } + + if (message == NULL) + { + LocalFree(s_buf); + return NULL; + } + if (filenameObject != NULL) - v = Py_BuildValue("(iUO)", err, s, filenameObject); + v = Py_BuildValue("(iOO)", err, message, filenameObject); else - v = Py_BuildValue("(iU)", err, s); + v = Py_BuildValue("(iO)", err, message); + Py_DECREF(message); + if (v != NULL) { PyErr_SetObject(exc, v); Py_DECREF(v); From python-3000-checkins at python.org Mon Sep 3 09:43:06 2007 From: python-3000-checkins at python.org (martin.v.loewis) Date: Mon, 3 Sep 2007 09:43:06 +0200 (CEST) Subject: [Python-3000-checkins] r57928 - in python/branches/py3k: Lib/test/test_winreg.py PC/_winreg.c Message-ID: <20070903074306.5C1AE1E400D@bag.python.org> Author: martin.v.loewis Date: Mon Sep 3 09:43:05 2007 New Revision: 57928 Modified: python/branches/py3k/Lib/test/test_winreg.py python/branches/py3k/PC/_winreg.c Log: Use wide API for registry functions. Modified: python/branches/py3k/Lib/test/test_winreg.py ============================================================================== --- python/branches/py3k/Lib/test/test_winreg.py (original) +++ python/branches/py3k/Lib/test/test_winreg.py Mon Sep 3 09:43:05 2007 @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # Test the windows specific win32reg module. # Only win32reg functions not hit here: FlushKey, LoadKey and SaveKey @@ -17,17 +18,19 @@ ("Raw Data", b"binary\x00data", REG_BINARY), ("Big String", "x"*(2**14-1), REG_SZ), ("Big Binary", b"x"*(2**14), REG_BINARY), + # Two and three kanjis, meaning: "Japan" and "Japanese") + ("Japanese ??", "???", REG_SZ), ] class WinregTests(unittest.TestCase): remote_name = None - def WriteTestData(self, root_key): + def WriteTestData(self, root_key, subkeystr="sub_key"): # Set the default value for this key. SetValue(root_key, test_key_name, REG_SZ, "Default value") key = CreateKey(root_key, test_key_name) # Create a sub-key - sub_key = CreateKey(key, "sub_key") + sub_key = CreateKey(key, subkeystr) # Give the sub-key some named values for value_name, value_data, value_type in test_data: @@ -62,7 +65,7 @@ except EnvironmentError: pass - def ReadTestData(self, root_key): + def ReadTestData(self, root_key, subkeystr="sub_key"): # Check we can get default value for this key. val = QueryValue(root_key, test_key_name) self.assertEquals(val, "Default value", @@ -70,7 +73,7 @@ key = OpenKey(root_key, test_key_name) # Read the sub-keys - sub_key = OpenKey(key, "sub_key") + sub_key = OpenKey(key, subkeystr) # Check I can enumerate over the values. index = 0 while 1: @@ -93,7 +96,7 @@ sub_key.Close() # Enumerate our main key. read_val = EnumKey(key, 0) - self.assertEquals(read_val, "sub_key", "Read subkey value wrong") + self.assertEquals(read_val, subkeystr, "Read subkey value wrong") try: EnumKey(key, 1) self.fail("Was able to get a second key when I only have one!") @@ -102,9 +105,9 @@ key.Close() - def DeleteTestData(self, root_key): + def DeleteTestData(self, root_key, subkeystr="sub_key"): key = OpenKey(root_key, test_key_name, 0, KEY_ALL_ACCESS) - sub_key = OpenKey(key, "sub_key", 0, KEY_ALL_ACCESS) + sub_key = OpenKey(key, subkeystr, 0, KEY_ALL_ACCESS) # It is not necessary to delete the values before deleting # the key (although subkeys must not exist). We delete them # manually just to prove we can :-) @@ -115,11 +118,11 @@ self.assertEquals(nkeys, 0, "subkey not empty before delete") self.assertEquals(nvalues, 0, "subkey not empty before delete") sub_key.Close() - DeleteKey(key, "sub_key") + DeleteKey(key, subkeystr) try: # Shouldnt be able to delete it twice! - DeleteKey(key, "sub_key") + DeleteKey(key, subkeystr) self.fail("Deleting the key twice succeeded") except EnvironmentError: pass @@ -132,13 +135,14 @@ except WindowsError: # Use this error name this time pass - def TestAll(self, root_key): - self.WriteTestData(root_key) - self.ReadTestData(root_key) - self.DeleteTestData(root_key) + def TestAll(self, root_key, subkeystr="sub_key"): + self.WriteTestData(root_key, subkeystr) + self.ReadTestData(root_key, subkeystr) + self.DeleteTestData(root_key, subkeystr) def testLocalMachineRegistryWorks(self): self.TestAll(HKEY_CURRENT_USER) + self.TestAll(HKEY_CURRENT_USER, "??-subkey") def testConnectRegistryToLocalMachineWorks(self): # perform minimal ConnectRegistry test which just invokes it Modified: python/branches/py3k/PC/_winreg.c ============================================================================== --- python/branches/py3k/PC/_winreg.c (original) +++ python/branches/py3k/PC/_winreg.c Mon Sep 3 09:43:05 2007 @@ -14,7 +14,6 @@ #include "Python.h" #include "structmember.h" -#include "malloc.h" /* for alloca */ #include "windows.h" static BOOL PyHKEY_AsHKEY(PyObject *ob, HKEY *pRes, BOOL bNoneOK); @@ -391,9 +390,7 @@ PyHKEY_strFunc(PyObject *ob) { PyHKEYObject *pyhkey = (PyHKEYObject *)ob; - char resBuf[160]; - wsprintf(resBuf, "", pyhkey->hkey); - return PyUnicode_FromString(resBuf); + return PyUnicode_FromFormat("", pyhkey->hkey); } static int @@ -652,11 +649,11 @@ ** with these strings (ie only we dont!). */ static void -fixupMultiSZ(char **str, char *data, int len) +fixupMultiSZ(wchar_t **str, wchar_t *data, int len) { - char *P; + wchar_t *P; int i; - char *Q; + wchar_t *Q; Q = data + len; for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) { @@ -667,11 +664,11 @@ } static int -countStrings(char *data, int len) +countStrings(wchar_t *data, int len) { int strings; - char *P; - char *Q = data + len; + wchar_t *P; + wchar_t *Q = data + len; for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++) for (; P < Q && *P != '\0'; P++) @@ -684,8 +681,6 @@ static BOOL Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize) { - int i,j; - DWORD d; switch (typ) { case REG_DWORD: if (value != Py_None && !PyLong_Check(value)) @@ -701,30 +696,20 @@ memcpy(*retDataBuf, &zero, sizeof(DWORD)); } else { - d = PyLong_AsLong(value); + DWORD d = PyLong_AsLong(value); memcpy(*retDataBuf, &d, sizeof(DWORD)); } break; case REG_SZ: case REG_EXPAND_SZ: { - int need_decref = 0; if (value == Py_None) *retDataSize = 1; else { - if (PyUnicode_Check(value)) { - value = PyUnicode_AsEncodedString( - value, - "mbcs", - NULL); - if (value==NULL) - return FALSE; - need_decref = 1; - } - if (!PyBytes_Check(value)) + if (!PyUnicode_Check(value)) return FALSE; - *retDataSize = 1 + strlen( - PyBytes_AS_STRING(value)); + + *retDataSize = 2 + PyUnicode_GET_DATA_SIZE(value); } *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize); if (*retDataBuf==NULL){ @@ -732,19 +717,17 @@ return FALSE; } if (value == Py_None) - strcpy((char *)*retDataBuf, ""); + wcscpy((wchar_t *)*retDataBuf, L""); else - strcpy((char *)*retDataBuf, - PyBytes_AS_STRING(value)); - if (need_decref) - Py_DECREF(value); + wcscpy((wchar_t *)*retDataBuf, + PyUnicode_AS_UNICODE(value)); break; } case REG_MULTI_SZ: { DWORD size = 0; - char *P; - PyObject **obs = NULL; + wchar_t *P; + int i,j; if (value == Py_None) i = 0; @@ -753,59 +736,35 @@ return FALSE; i = PyList_Size(value); } - obs = malloc(sizeof(PyObject *) * i); - memset(obs, 0, sizeof(PyObject *) * i); for (j = 0; j < i; j++) { PyObject *t; - t = PyList_GET_ITEM( - (PyListObject *)value,j); - if (PyBytes_Check(t)) { - obs[j] = t; - Py_INCREF(t); - } else if (PyUnicode_Check(t)) { - obs[j] = PyUnicode_AsEncodedString( - t, - "mbcs", - NULL); - if (obs[j]==NULL) - goto reg_multi_fail; - } else - goto reg_multi_fail; - size += 1 + strlen( - PyBytes_AS_STRING(obs[j])); + t = PyList_GET_ITEM(value, j); + if (!PyUnicode_Check(t)) + return FALSE; + size += 2 + PyUnicode_GET_DATA_SIZE(t); } - *retDataSize = size + 1; + *retDataSize = size + 2; *retDataBuf = (BYTE *)PyMem_NEW(char, *retDataSize); if (*retDataBuf==NULL){ PyErr_NoMemory(); - goto reg_multi_fail; + return FALSE; } - P = (char *)*retDataBuf; + P = (wchar_t *)*retDataBuf; for (j = 0; j < i; j++) { PyObject *t; - t = obs[j]; - strcpy(P, PyBytes_AS_STRING(t)); - P += 1 + strlen( - PyBytes_AS_STRING(t)); - Py_DECREF(obs[j]); + t = PyList_GET_ITEM(value, j); + wcscpy(P, PyUnicode_AS_UNICODE(t)); + P += 1 + wcslen( + PyUnicode_AS_UNICODE(t)); } /* And doubly-terminate the list... */ *P = '\0'; - free(obs); break; - reg_multi_fail: - if (obs) { - for (j = 0; j < i; j++) - Py_XDECREF(obs[j]); - - free(obs); - } - return FALSE; } case REG_BINARY: /* ALSO handle ALL unknown data types here. Even if we can't @@ -844,48 +803,50 @@ /* Convert Registry data into PyObject*/ static PyObject * -Reg2Py(char *retDataBuf, DWORD retDataSize, DWORD typ) +Reg2Py(BYTE *retDataBuf, DWORD retDataSize, DWORD typ) { PyObject *obData; switch (typ) { case REG_DWORD: if (retDataSize == 0) - obData = Py_BuildValue("i", 0); + obData = PyInt_FromLong(0); else - obData = Py_BuildValue("i", - *(int *)retDataBuf); + obData = PyInt_FromLong(*(int *)retDataBuf); break; case REG_SZ: case REG_EXPAND_SZ: - /* retDataBuf may or may not have a trailing NULL in - the buffer. */ - if (retDataSize && retDataBuf[retDataSize-1] == '\0') - --retDataSize; - if (retDataSize ==0) - retDataBuf = ""; - obData = PyUnicode_DecodeMBCS(retDataBuf, - retDataSize, - NULL); - break; + { + /* the buffer may or may not have a trailing NULL */ + wchar_t *data = (wchar_t *)retDataBuf; + int len = retDataSize / 2; + if (retDataSize && data[len-1] == '\0') + retDataSize -= 2; + if (retDataSize <= 0) + data = L""; + obData = PyUnicode_FromUnicode(data, retDataSize/2); + break; + } case REG_MULTI_SZ: if (retDataSize == 0) obData = PyList_New(0); else { int index = 0; - int s = countStrings(retDataBuf, retDataSize); - char **str = (char **)malloc(sizeof(char *)*s); + wchar_t *data = (wchar_t *)retDataBuf; + int len = retDataSize / 2; + int s = countStrings(data, len); + wchar_t **str = (wchar_t **)malloc(sizeof(wchar_t *)*s); if (str == NULL) return PyErr_NoMemory(); - fixupMultiSZ(str, retDataBuf, retDataSize); + fixupMultiSZ(str, data, len); obData = PyList_New(s); if (obData == NULL) return NULL; for (index = 0; index < s; index++) { - size_t len = _mbstrlen(str[index]); + size_t len = wcslen(str[index]); if (len > INT_MAX) { PyErr_SetString(PyExc_OverflowError, "registry string is too long for a Python string"); @@ -894,11 +855,7 @@ } PyList_SetItem(obData, index, - PyUnicode_DecodeMBCS( - (const char *)str[index], - (int)len, - NULL) - ); + PyUnicode_FromUnicode(str[index], len)); } free(str); @@ -913,15 +870,11 @@ obData = Py_None; } else - obData = Py_BuildValue("y#", - (char *)retDataBuf, - retDataSize); + obData = PyBytes_FromStringAndSize( + (char *)retDataBuf, retDataSize); break; } - if (obData == NULL) - return NULL; - else - return obData; + return obData; } /* The Python methods */ @@ -943,15 +896,15 @@ { HKEY hKey; PyObject *obKey; - char *szCompName = NULL; + wchar_t *szCompName = NULL; HKEY retKey; long rc; - if (!PyArg_ParseTuple(args, "zO:ConnectRegistry", &szCompName, &obKey)) + if (!PyArg_ParseTuple(args, "ZO:ConnectRegistry", &szCompName, &obKey)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; Py_BEGIN_ALLOW_THREADS - rc = RegConnectRegistry(szCompName, hKey, &retKey); + rc = RegConnectRegistryW(szCompName, hKey, &retKey); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, @@ -964,14 +917,14 @@ { HKEY hKey; PyObject *obKey; - char *subKey; + wchar_t *subKey; HKEY retKey; long rc; - if (!PyArg_ParseTuple(args, "Oz:CreateKey", &obKey, &subKey)) + if (!PyArg_ParseTuple(args, "OZ:CreateKey", &obKey, &subKey)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - rc = RegCreateKey(hKey, subKey, &retKey); + rc = RegCreateKeyW(hKey, subKey, &retKey); if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey"); return PyHKEY_FromHKEY(retKey); @@ -982,13 +935,13 @@ { HKEY hKey; PyObject *obKey; - char *subKey; + wchar_t *subKey; long rc; - if (!PyArg_ParseTuple(args, "Os:DeleteKey", &obKey, &subKey)) + if (!PyArg_ParseTuple(args, "Ou:DeleteKey", &obKey, &subKey)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - rc = RegDeleteKey(hKey, subKey ); + rc = RegDeleteKeyW(hKey, subKey ); if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey"); Py_INCREF(Py_None); @@ -1000,14 +953,14 @@ { HKEY hKey; PyObject *obKey; - char *subKey; + wchar_t *subKey; long rc; - if (!PyArg_ParseTuple(args, "Oz:DeleteValue", &obKey, &subKey)) + if (!PyArg_ParseTuple(args, "OZ:DeleteValue", &obKey, &subKey)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; Py_BEGIN_ALLOW_THREADS - rc = RegDeleteValue(hKey, subKey); + rc = RegDeleteValueW(hKey, subKey); Py_END_ALLOW_THREADS if (rc !=ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, @@ -1024,7 +977,7 @@ int index; long rc; PyObject *retStr; - char tmpbuf[256]; /* max key name length is 255 */ + wchar_t tmpbuf[256]; /* max key name length is 255 */ DWORD len = sizeof(tmpbuf); /* includes NULL terminator */ if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index)) @@ -1033,12 +986,12 @@ return NULL; Py_BEGIN_ALLOW_THREADS - rc = RegEnumKeyEx(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL); + rc = RegEnumKeyExW(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx"); - retStr = PyUnicode_FromStringAndSize(tmpbuf, len); + retStr = PyUnicode_FromUnicode(tmpbuf, len); return retStr; /* can be NULL */ } @@ -1049,8 +1002,8 @@ PyObject *obKey; int index; long rc; - char *retValueBuf; - char *retDataBuf; + wchar_t *retValueBuf; + BYTE *retDataBuf; DWORD retValueSize; DWORD retDataSize; DWORD typ; @@ -1062,7 +1015,7 @@ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - if ((rc = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL, + if ((rc = RegQueryInfoKeyW(hKey, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &retValueSize, &retDataSize, NULL, NULL)) != ERROR_SUCCESS) @@ -1070,23 +1023,23 @@ "RegQueryInfoKey"); ++retValueSize; /* include null terminators */ ++retDataSize; - retValueBuf = (char *)PyMem_Malloc(retValueSize); + retValueBuf = (wchar_t *)PyMem_Malloc(sizeof(wchar_t) * retValueSize); if (retValueBuf == NULL) return PyErr_NoMemory(); - retDataBuf = (char *)PyMem_Malloc(retDataSize); + retDataBuf = (BYTE *)PyMem_Malloc(retDataSize); if (retDataBuf == NULL) { PyMem_Free(retValueBuf); return PyErr_NoMemory(); } Py_BEGIN_ALLOW_THREADS - rc = RegEnumValue(hKey, + rc = RegEnumValueW(hKey, index, retValueBuf, &retValueSize, NULL, &typ, - (BYTE *)retDataBuf, + retDataBuf, &retDataSize); Py_END_ALLOW_THREADS @@ -1100,7 +1053,7 @@ retVal = NULL; goto fail; } - retVal = Py_BuildValue("UOi", retValueBuf, obData, typ); + retVal = Py_BuildValue("uOi", retValueBuf, obData, typ); Py_DECREF(obData); fail: PyMem_Free(retValueBuf); @@ -1131,16 +1084,16 @@ { HKEY hKey; PyObject *obKey; - char *subKey; - char *fileName; + wchar_t *subKey; + wchar_t *fileName; long rc; - if (!PyArg_ParseTuple(args, "Oss:LoadKey", &obKey, &subKey, &fileName)) + if (!PyArg_ParseTuple(args, "Ouu:LoadKey", &obKey, &subKey, &fileName)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; Py_BEGIN_ALLOW_THREADS - rc = RegLoadKey(hKey, subKey, fileName ); + rc = RegLoadKeyW(hKey, subKey, fileName ); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey"); @@ -1154,19 +1107,19 @@ HKEY hKey; PyObject *obKey; - char *subKey; + wchar_t *subKey; int res = 0; HKEY retKey; long rc; REGSAM sam = KEY_READ; - if (!PyArg_ParseTuple(args, "Oz|ii:OpenKey", &obKey, &subKey, + if (!PyArg_ParseTuple(args, "OZ|ii:OpenKey", &obKey, &subKey, &res, &sam)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; Py_BEGIN_ALLOW_THREADS - rc = RegOpenKeyEx(hKey, subKey, res, sam, &retKey); + rc = RegOpenKeyExW(hKey, subKey, res, sam, &retKey); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx"); @@ -1208,33 +1161,33 @@ { HKEY hKey; PyObject *obKey; - char *subKey; + wchar_t *subKey; long rc; PyObject *retStr; - char *retBuf; + wchar_t *retBuf; long bufSize = 0; - if (!PyArg_ParseTuple(args, "Oz:QueryValue", &obKey, &subKey)) + if (!PyArg_ParseTuple(args, "OZ:QueryValue", &obKey, &subKey)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - if ((rc = RegQueryValue(hKey, subKey, NULL, &bufSize)) + if ((rc = RegQueryValueW(hKey, subKey, NULL, &bufSize)) != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValue"); - retBuf = (char *)PyMem_Malloc(bufSize); + retBuf = (wchar_t *)PyMem_Malloc(bufSize); if (retBuf == NULL) return PyErr_NoMemory(); - if ((rc = RegQueryValue(hKey, subKey, retBuf, &bufSize)) + if ((rc = RegQueryValueW(hKey, subKey, retBuf, &bufSize)) != ERROR_SUCCESS) { PyMem_Free(retBuf); return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValue"); } - retStr = PyUnicode_DecodeMBCS(retBuf, strlen(retBuf), NULL); + retStr = PyUnicode_FromUnicode(retBuf, wcslen(retBuf)); PyMem_Free(retBuf); return retStr; } @@ -1244,38 +1197,38 @@ { HKEY hKey; PyObject *obKey; - char *valueName; + wchar_t *valueName; long rc; - char *retBuf; + BYTE *retBuf; DWORD bufSize = 0; DWORD typ; PyObject *obData; PyObject *result; - if (!PyArg_ParseTuple(args, "Oz:QueryValueEx", &obKey, &valueName)) + if (!PyArg_ParseTuple(args, "OZ:QueryValueEx", &obKey, &valueName)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; - if ((rc = RegQueryValueEx(hKey, valueName, + if ((rc = RegQueryValueExW(hKey, valueName, NULL, NULL, NULL, &bufSize)) != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx"); - retBuf = (char *)PyMem_Malloc(bufSize); + retBuf = (BYTE *)PyMem_Malloc(bufSize); if (retBuf == NULL) return PyErr_NoMemory(); - if ((rc = RegQueryValueEx(hKey, valueName, NULL, - &typ, (BYTE *)retBuf, &bufSize)) + if ((rc = RegQueryValueExW(hKey, valueName, NULL, + &typ, retBuf, &bufSize)) != ERROR_SUCCESS) { PyMem_Free(retBuf); return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryValueEx"); } obData = Reg2Py(retBuf, bufSize, typ); - PyMem_Free((void *)retBuf); + PyMem_Free(retBuf); if (obData == NULL) return NULL; result = Py_BuildValue("Oi", obData, typ); @@ -1289,11 +1242,11 @@ { HKEY hKey; PyObject *obKey; - char *fileName; + wchar_t *fileName; LPSECURITY_ATTRIBUTES pSA = NULL; long rc; - if (!PyArg_ParseTuple(args, "Os:SaveKey", &obKey, &fileName)) + if (!PyArg_ParseTuple(args, "Ou:SaveKey", &obKey, &fileName)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; @@ -1302,7 +1255,7 @@ return NULL; */ Py_BEGIN_ALLOW_THREADS - rc = RegSaveKey(hKey, fileName, pSA ); + rc = RegSaveKeyW(hKey, fileName, pSA ); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey"); @@ -1315,18 +1268,17 @@ { HKEY hKey; PyObject *obKey; - char *subKey; - char *str; + wchar_t *subKey; + wchar_t *str; DWORD typ; DWORD len; long rc; - PyObject *obStrVal; - PyObject *obSubKey; - if (!PyArg_ParseTuple(args, "OOiO:SetValue", + if (!PyArg_ParseTuple(args, "OZiu#:SetValue", &obKey, - &obSubKey, + &subKey, &typ, - &obStrVal)) + &str, + &len)) return NULL; if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE)) return NULL; @@ -1335,20 +1287,9 @@ "Type must be _winreg.REG_SZ"); return NULL; } - /* XXX - need Unicode support */ - str = PyString_AsString(obStrVal); - if (str == NULL) - return NULL; - len = PyString_Size(obStrVal); - if (obSubKey == Py_None) - subKey = NULL; - else { - subKey = PyString_AsString(obSubKey); - if (subKey == NULL) - return NULL; - } + Py_BEGIN_ALLOW_THREADS - rc = RegSetValue(hKey, subKey, REG_SZ, str, len+1); + rc = RegSetValueW(hKey, subKey, REG_SZ, str, len+1); Py_END_ALLOW_THREADS if (rc != ERROR_SUCCESS) return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue"); @@ -1361,7 +1302,7 @@ { HKEY hKey; PyObject *obKey; - char *valueName; + Py_UNICODE *valueName; PyObject *obRes; PyObject *value; BYTE *data; @@ -1370,7 +1311,7 @@ LONG rc; - if (!PyArg_ParseTuple(args, "OzOiO:SetValueEx", + if (!PyArg_ParseTuple(args, "OZOiO:SetValueEx", &obKey, &valueName, &obRes, @@ -1387,7 +1328,7 @@ return NULL; } Py_BEGIN_ALLOW_THREADS - rc = RegSetValueEx(hKey, valueName, 0, typ, data, len); + rc = RegSetValueExW(hKey, valueName, 0, typ, data, len); Py_END_ALLOW_THREADS PyMem_DEL(data); if (rc != ERROR_SUCCESS) @@ -1511,3 +1452,4 @@ ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST); } + From python-3000-checkins at python.org Mon Sep 3 10:40:49 2007 From: python-3000-checkins at python.org (eric.smith) Date: Mon, 3 Sep 2007 10:40:49 +0200 (CEST) Subject: [Python-3000-checkins] r57929 - in python/branches/py3k: Lib/test/test_unicode.py Objects/stringlib/string_format.h Message-ID: <20070903084050.119C01E4007@bag.python.org> Author: eric.smith Date: Mon Sep 3 10:40:29 2007 New Revision: 57929 Modified: python/branches/py3k/Lib/test/test_unicode.py python/branches/py3k/Objects/stringlib/string_format.h Log: Fix segfault discovered by Ron Adam. Not checking for terminating right bracket in "'{0[}'.format(())". Fixed, and tests added. Modified: python/branches/py3k/Lib/test/test_unicode.py ============================================================================== --- python/branches/py3k/Lib/test/test_unicode.py (original) +++ python/branches/py3k/Lib/test/test_unicode.py Mon Sep 3 10:40:29 2007 @@ -458,6 +458,7 @@ # weird field names self.assertEqual("{0[foo-bar]}".format({'foo-bar':'baz'}), 'baz') self.assertEqual("{0[foo bar]}".format({'foo bar':'baz'}), 'baz') + self.assertEqual("{0[ ]}".format({' ':3}), '3') self.assertEqual('{foo._x}'.format(foo=C(20)), '20') self.assertEqual('{1}{0}'.format(D(10), D(20)), '2010') @@ -551,6 +552,7 @@ self.assertRaises(ValueError, "{0".format) self.assertRaises(ValueError, "{0.}".format) self.assertRaises(ValueError, "{0[}".format) + self.assertRaises(ValueError, "{0[}".format, []) self.assertRaises(ValueError, "{0]}".format) self.assertRaises(ValueError, "{0.[]}".format) self.assertRaises(ValueError, "{0..foo}".format, 0) Modified: python/branches/py3k/Objects/stringlib/string_format.h ============================================================================== --- python/branches/py3k/Objects/stringlib/string_format.h (original) +++ python/branches/py3k/Objects/stringlib/string_format.h Mon Sep 3 10:40:29 2007 @@ -273,6 +273,7 @@ static int _FieldNameIterator_item(FieldNameIterator *self, SubString *name) { + int bracket_seen = 0; STRINGLIB_CHAR c; name->ptr = self->ptr; @@ -281,12 +282,19 @@ while (self->ptr < self->str.end) { switch (c = *self->ptr++) { case ']': + bracket_seen = 1; break; default: continue; } break; } + /* make sure we ended with a ']' */ + if (!bracket_seen) { + PyErr_SetString(PyExc_ValueError, "Missing ']' in format string"); + return 0; + } + /* end of string is okay */ /* don't include the ']' */ name->end = self->ptr-1; @@ -305,16 +313,14 @@ switch (*self->ptr++) { case '.': *is_attribute = 1; - if (_FieldNameIterator_attr(self, name) == 0) { + if (_FieldNameIterator_attr(self, name) == 0) return 0; - } *name_idx = -1; break; case '[': *is_attribute = 0; - if (_FieldNameIterator_item(self, name) == 0) { + if (_FieldNameIterator_item(self, name) == 0) return 0; - } *name_idx = get_integer(name); break; default: From python-3000-checkins at python.org Mon Sep 3 18:44:07 2007 From: python-3000-checkins at python.org (gregory.p.smith) Date: Mon, 3 Sep 2007 18:44:07 +0200 (CEST) Subject: [Python-3000-checkins] r57931 - python/branches/py3k/configure.in python/branches/py3k/pyconfig.h.in Message-ID: <20070903164407.4572A1E4009@bag.python.org> Author: gregory.p.smith Date: Mon Sep 3 18:44:06 2007 New Revision: 57931 Modified: python/branches/py3k/configure.in python/branches/py3k/pyconfig.h.in Log: test for strlcpy (so i can use it in _bsddb.c) Modified: python/branches/py3k/configure.in ============================================================================== --- python/branches/py3k/configure.in (original) +++ python/branches/py3k/configure.in Mon Sep 3 18:44:06 2007 @@ -2256,7 +2256,7 @@ putenv readlink realpath \ select setegid seteuid setgid \ setlocale setregid setreuid setsid setpgid setpgrp setuid setvbuf snprintf \ - sigaction siginterrupt sigrelse strftime \ + sigaction siginterrupt sigrelse strftime strlcpy \ sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll _getpty) Modified: python/branches/py3k/pyconfig.h.in ============================================================================== --- python/branches/py3k/pyconfig.h.in (original) +++ python/branches/py3k/pyconfig.h.in Mon Sep 3 18:44:06 2007 @@ -538,6 +538,9 @@ /* Define to 1 if you have the header file. */ #undef HAVE_STRING_H +/* Define to 1 if you have the `strlcpy' function. */ +#undef HAVE_STRLCPY + /* Define to 1 if you have the header file. */ #undef HAVE_STROPTS_H From python-3000-checkins at python.org Mon Sep 3 18:44:56 2007 From: python-3000-checkins at python.org (gregory.p.smith) Date: Mon, 3 Sep 2007 18:44:56 +0200 (CEST) Subject: [Python-3000-checkins] r57932 - python/branches/py3k/configure Message-ID: <20070903164456.3611C1E4009@bag.python.org> Author: gregory.p.smith Date: Mon Sep 3 18:44:55 2007 New Revision: 57932 Modified: python/branches/py3k/configure Log: regenerated Modified: python/branches/py3k/configure ============================================================================== --- python/branches/py3k/configure (original) +++ python/branches/py3k/configure Mon Sep 3 18:44:55 2007 @@ -1,5 +1,5 @@ #! /bin/sh -# From configure.in Revision: 57142 . +# From configure.in Revision: 57931 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.61 for python 3.0. # @@ -14831,6 +14831,7 @@ + for ac_func in alarm bind_textdomain_codeset chflags chown clock confstr \ ctermid execv fork fpathconf ftime ftruncate \ gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \ @@ -14840,7 +14841,7 @@ putenv readlink realpath \ select setegid seteuid setgid \ setlocale setregid setreuid setsid setpgid setpgrp setuid setvbuf snprintf \ - sigaction siginterrupt sigrelse strftime \ + sigaction siginterrupt sigrelse strftime strlcpy \ sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \ truncate uname unsetenv utimes waitpid wait3 wait4 wcscoll _getpty do From python-3000-checkins at python.org Mon Sep 3 18:48:33 2007 From: python-3000-checkins at python.org (gregory.p.smith) Date: Mon, 3 Sep 2007 18:48:33 +0200 (CEST) Subject: [Python-3000-checkins] r57933 - python/branches/py3k/Lib/bsddb/test/test_compare.py Message-ID: <20070903164833.13A3B1E4009@bag.python.org> Author: gregory.p.smith Date: Mon Sep 3 18:48:32 2007 New Revision: 57933 Modified: python/branches/py3k/Lib/bsddb/test/test_compare.py Log: fix test, use bytes not unicode and let the test raise its internal exception rather than just complaining about stderr not being what we expected masking the true problem. Modified: python/branches/py3k/Lib/bsddb/test/test_compare.py ============================================================================== --- python/branches/py3k/Lib/bsddb/test/test_compare.py (original) +++ python/branches/py3k/Lib/bsddb/test/test_compare.py Mon Sep 3 18:48:32 2007 @@ -179,9 +179,9 @@ finally: temp = sys.stderr sys.stderr = stdErr - errorOut = temp.getvalue() - if not successRe.search(errorOut): - self.fail("unexpected stderr output: %r" % errorOut) + errorOut = temp.getvalue() + if not successRe.search(errorOut): + self.fail("unexpected stderr output: %r" % errorOut) def _test_compare_function_exception (self): self.startTest () @@ -192,7 +192,7 @@ raise RuntimeError("i'm a naughty comparison function") self.createDB (bad_comparator) #print "\n*** test should print 2 uncatchable tracebacks ***" - self.addDataToDB (['a', 'b', 'c']) # this should raise, but... + self.addDataToDB ([b'a', b'b', b'c']) # this should raise, but... self.finishTest () def test_compare_function_exception(self): @@ -210,7 +210,7 @@ return l self.createDB (bad_comparator) #print "\n*** test should print 2 errors about returning an int ***" - self.addDataToDB (['a', 'b', 'c']) # this should raise, but... + self.addDataToDB ([b'a', b'b', b'c']) # this should raise, but... self.finishTest () def test_compare_function_bad_return(self): From python-3000-checkins at python.org Tue Sep 4 01:39:40 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Tue, 4 Sep 2007 01:39:40 +0200 (CEST) Subject: [Python-3000-checkins] r57937 - python/branches/p3yk-noslice Message-ID: <20070903233940.E464D1E4009@bag.python.org> Author: thomas.wouters Date: Tue Sep 4 01:39:40 2007 New Revision: 57937 Removed: python/branches/p3yk-noslice/ Log: Delete old branch. From python-3000-checkins at python.org Tue Sep 4 01:44:29 2007 From: python-3000-checkins at python.org (matthias.klose) Date: Tue, 4 Sep 2007 01:44:29 +0200 (CEST) Subject: [Python-3000-checkins] r57938 - python/branches/py3k/setup.py Message-ID: <20070903234429.6322C1E4009@bag.python.org> Author: matthias.klose Date: Tue Sep 4 01:44:29 2007 New Revision: 57938 Modified: python/branches/py3k/setup.py Log: - Add support for linking the bsddb module against BerkeleyDB 4.6.x. Modified: python/branches/py3k/setup.py ============================================================================== --- python/branches/py3k/setup.py (original) +++ python/branches/py3k/setup.py Tue Sep 4 01:44:29 2007 @@ -635,7 +635,7 @@ # a release. Most open source OSes come with one or more # versions of BerkeleyDB already installed. - max_db_ver = (4, 5) + max_db_ver = (4, 6) min_db_ver = (3, 3) db_setup_debug = False # verbose debug prints from this script? @@ -653,7 +653,7 @@ '/sw/include/db3', ] # 4.x minor number specific paths - for x in (0,1,2,3,4,5): + for x in (0,1,2,3,4,5,6): db_inc_paths.append('/usr/include/db4%d' % x) db_inc_paths.append('/usr/include/db4.%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x) @@ -678,7 +678,7 @@ for dn in inc_dirs: std_variants.append(os.path.join(dn, 'db3')) std_variants.append(os.path.join(dn, 'db4')) - for x in (0,1,2,3,4): + for x in (0,1,2,3,4,5,6): std_variants.append(os.path.join(dn, "db4%d"%x)) std_variants.append(os.path.join(dn, "db4.%d"%x)) for x in (2,3): From python-3000-checkins at python.org Tue Sep 4 04:40:38 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 4 Sep 2007 04:40:38 +0200 (CEST) Subject: [Python-3000-checkins] r57939 - python/branches/py3k/Doc/whatsnew/3.0.rst Message-ID: <20070904024038.909DB1E400D@bag.python.org> Author: guido.van.rossum Date: Tue Sep 4 04:40:38 2007 New Revision: 57939 Modified: python/branches/py3k/Doc/whatsnew/3.0.rst Log: Fix sinple typo. Modified: python/branches/py3k/Doc/whatsnew/3.0.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/3.0.rst (original) +++ python/branches/py3k/Doc/whatsnew/3.0.rst Tue Sep 4 04:40:38 2007 @@ -241,7 +241,7 @@ * PEP 3104: ``nonlocal`` statement. Using ``nonlocal x`` you can now assign directly to a variable in an outer (but non-global) scope. -* PEP 3105: ``print`` is now a function. Keyword argumemts +* PEP 3105: ``print`` is now a function. Keyword arguments ``file=sys.stdout``, ``sep=" "`` and ``end="\n"`` let you customize it. From python-3000-checkins at python.org Tue Sep 4 04:48:02 2007 From: python-3000-checkins at python.org (skip.montanaro) Date: Tue, 4 Sep 2007 04:48:02 +0200 (CEST) Subject: [Python-3000-checkins] r57940 - python/branches/py3k/Doc/whatsnew/3.0.rst Message-ID: <20070904024802.43B521E4013@bag.python.org> Author: skip.montanaro Date: Tue Sep 4 04:48:01 2007 New Revision: 57940 Modified: python/branches/py3k/Doc/whatsnew/3.0.rst Log: I always think of the language when I see "ABC". Emphasize the meaning of the acronym. Modified: python/branches/py3k/Doc/whatsnew/3.0.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/3.0.rst (original) +++ python/branches/py3k/Doc/whatsnew/3.0.rst Tue Sep 4 04:48:01 2007 @@ -198,7 +198,7 @@ * PEP 3115: New Metaclass Syntax. -* PEP 3119: Abstract Base Classes; ``@abstractmethod`` and +* PEP 3119: Abstract Base Classes (ABCs); ``@abstractmethod`` and ``@abstractproperty`` decorators; collection ABCs. * PEP 3129: Class decorators. From python-3000-checkins at python.org Tue Sep 4 04:52:00 2007 From: python-3000-checkins at python.org (skip.montanaro) Date: Tue, 4 Sep 2007 04:52:00 +0200 (CEST) Subject: [Python-3000-checkins] r57941 - python/branches/py3k/Doc/whatsnew/3.0.rst Message-ID: <20070904025200.E14061E400C@bag.python.org> Author: skip.montanaro Date: Tue Sep 4 04:52:00 2007 New Revision: 57941 Modified: python/branches/py3k/Doc/whatsnew/3.0.rst Log: CVS -> Subversion Modified: python/branches/py3k/Doc/whatsnew/3.0.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/3.0.rst (original) +++ python/branches/py3k/Doc/whatsnew/3.0.rst Tue Sep 4 04:52:00 2007 @@ -311,7 +311,7 @@ and bug fixes. Here's a partial list of the most notable changes, sorted alphabetically by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more complete list of changes, or look -through the CVS logs for all the details. +through the Subversion logs for all the details. * The ``cPickle`` module is gone. Use ``pickle`` instead. Eventually we'll have a transparent accelerator module. From python-3000-checkins at python.org Tue Sep 4 07:24:49 2007 From: python-3000-checkins at python.org (martin.v.loewis) Date: Tue, 4 Sep 2007 07:24:49 +0200 (CEST) Subject: [Python-3000-checkins] r57947 - python/branches/py3k/Python/bltinmodule.c Message-ID: <20070904052449.4C3D11E4009@bag.python.org> Author: martin.v.loewis Date: Tue Sep 4 07:24:49 2007 New Revision: 57947 Modified: python/branches/py3k/Python/bltinmodule.c Log: Decode input() with stdin.encoding. Fixes #1097. Modified: python/branches/py3k/Python/bltinmodule.c ============================================================================== --- python/branches/py3k/Python/bltinmodule.c (original) +++ python/branches/py3k/Python/bltinmodule.c Tue Sep 4 07:24:49 2007 @@ -1314,7 +1314,14 @@ PyObject *po; char *prompt; char *s; + PyObject *stdin_encoding; PyObject *result; + + stdin_encoding = PyObject_GetAttrString(fin, "encoding"); + if (!stdin_encoding) + /* stdin is a text stream, so it must have an + encoding. */ + return NULL; tmp = PyObject_CallMethod(fout, "flush", ""); if (tmp == NULL) PyErr_Clear(); @@ -1322,10 +1329,13 @@ Py_DECREF(tmp); if (promptarg != NULL) { po = PyObject_Str(promptarg); - if (po == NULL) + if (po == NULL) { + Py_DECREF(stdin_encoding); return NULL; + } prompt = PyString_AsString(po); if (prompt == NULL) { + Py_DECREF(stdin_encoding); Py_DECREF(po); return NULL; } @@ -1339,6 +1349,7 @@ if (s == NULL) { if (!PyErr_Occurred()) PyErr_SetNone(PyExc_KeyboardInterrupt); + Py_DECREF(stdin_encoding); return NULL; } if (*s == '\0') { @@ -1353,9 +1364,13 @@ result = NULL; } else { - result = PyUnicode_FromStringAndSize(s, len-1); + result = PyUnicode_Decode + (s, len-1, + PyUnicode_AsString(stdin_encoding), + NULL); } } + Py_DECREF(stdin_encoding); PyMem_FREE(s); return result; } From python-3000-checkins at python.org Tue Sep 4 08:35:14 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 4 Sep 2007 08:35:14 +0200 (CEST) Subject: [Python-3000-checkins] r57948 - in python/branches/py3k/Doc: library/constants.rst library/stdtypes.rst reference/datamodel.rst reference/expressions.rst Message-ID: <20070904063514.BDF661E400E@bag.python.org> Author: georg.brandl Date: Tue Sep 4 08:35:14 2007 New Revision: 57948 Modified: python/branches/py3k/Doc/library/constants.rst python/branches/py3k/Doc/library/stdtypes.rst python/branches/py3k/Doc/reference/datamodel.rst python/branches/py3k/Doc/reference/expressions.rst Log: Doc update for __xslice__ removal. Modified: python/branches/py3k/Doc/library/constants.rst ============================================================================== --- python/branches/py3k/Doc/library/constants.rst (original) +++ python/branches/py3k/Doc/library/constants.rst Tue Sep 4 08:35:14 2007 @@ -34,7 +34,6 @@ .. data:: Ellipsis The same as ``...``. Special value used mostly in conjunction with extended - slicing syntax for user-defined container data types. - - .. % XXX Someone who understands extended slicing should fill in here. + slicing syntax for user-defined container data types, as in :: + val = container[1:5, 7:10, ...] Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Tue Sep 4 08:35:14 2007 @@ -587,7 +587,6 @@ pair: repetition; operation pair: subscript; operation pair: slice; operation - pair: extended slice; operation operator: in operator: not in @@ -948,9 +947,10 @@ .. method:: str.translate(map) Return a copy of the *s* where all characters have been mapped through the - *map* which must be a mapping of Unicode ordinals (integers) to Unicode - ordinals, strings or ``None``. Unmapped characters are left - untouched. Characters mapped to ``None`` are deleted. + *map* which must be a dictionary of characters (strings of length 1) or + Unicode ordinals (integers) to Unicode ordinals, strings or ``None``. + Unmapped characters are left untouched. Characters mapped to ``None`` are + deleted. .. note:: @@ -1244,7 +1244,6 @@ triple: operations on; list; type pair: subscript; assignment pair: slice; assignment - pair: extended slice; assignment statement: del single: append() (sequence method) single: extend() (sequence method) @@ -2389,8 +2388,8 @@ The Ellipsis Object ------------------- -This object is mostly used by extended slice notation (see :ref:`slicings`). It -supports no special operations. There is exactly one ellipsis object, named +This object is commonly used by slicing (see :ref:`slicings`). It supports no +special operations. There is exactly one ellipsis object, named :const:`Ellipsis` (a built-in name). It is written as ``Ellipsis`` or ``...``. Modified: python/branches/py3k/Doc/reference/datamodel.rst ============================================================================== --- python/branches/py3k/Doc/reference/datamodel.rst (original) +++ python/branches/py3k/Doc/reference/datamodel.rst Tue Sep 4 08:35:14 2007 @@ -265,8 +265,6 @@ sequence of the same type. This implies that the index set is renumbered so that it starts at 0. - .. index:: single: extended slicing - Some sequences also support "extended slicing" with a third "step" parameter: ``a[i:j:k]`` selects all items of *a* with index *x* where ``x = i + n*k``, *n* ``>=`` ``0`` and *i* ``<=`` *x* ``<`` *j*. @@ -997,10 +995,8 @@ Slice objects .. index:: builtin: slice - Slice objects are used to represent slices when *extended slice syntax* is used. - This is a slice using two colons, or multiple slices or ellipses separated by - commas, e.g., ``a[i:j:step]``, ``a[i:j, k:l]``, or ``a[..., i:j]``. They are - also created by the built-in :func:`slice` function. + Slice objects are used to represent slices for :meth:`__getitem__` + methods. They are also created by the built-in :func:`slice` function. .. index:: single: start (slice object attribute) @@ -1013,15 +1009,14 @@ Slice objects support one method: - .. method:: slice.indices(self, length) - This method takes a single integer argument *length* and computes information - about the extended slice that the slice object would describe if applied to a - sequence of *length* items. It returns a tuple of three integers; respectively - these are the *start* and *stop* indices and the *step* or stride length of the - slice. Missing or out-of-bounds indices are handled in a manner consistent with - regular slices. + This method takes a single integer argument *length* and computes + information about the slice that the slice object would describe if + applied to a sequence of *length* items. It returns a tuple of three + integers; respectively these are the *start* and *stop* indices and the + *step* or stride length of the slice. Missing or out-of-bounds indices + are handled in a manner consistent with regular slices. Static method objects Static method objects provide a way of defeating the transformation of function @@ -1592,31 +1587,28 @@ either to emulate a sequence or to emulate a mapping; the difference is that for a sequence, the allowable keys should be the integers *k* for which ``0 <= k < N`` where *N* is the length of the sequence, or slice objects, which define a -range of items. (For backwards compatibility, the method :meth:`__getslice__` -(see below) can also be defined to handle simple, but not extended slices.) It -is also recommended that mappings provide the methods :meth:`keys`, -:meth:`values`, :meth:`items`, :meth:`has_key`, :meth:`get`, :meth:`clear`, -:meth:`setdefault`, :meth:`iterkeys`, :meth:`itervalues`, :meth:`iteritems`, -:meth:`pop`, :meth:`popitem`, :meth:`copy`, and :meth:`update` behaving similar -to those for Python's standard dictionary objects. The :mod:`UserDict` module -provides a :class:`DictMixin` class to help create those methods from a base set -of :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__`, and -:meth:`keys`. Mutable sequences should provide methods :meth:`append`, -:meth:`count`, :meth:`index`, :meth:`extend`, :meth:`insert`, :meth:`pop`, -:meth:`remove`, :meth:`reverse` and :meth:`sort`, like Python standard list -objects. Finally, sequence types should implement addition (meaning -concatenation) and multiplication (meaning repetition) by defining the methods -:meth:`__add__`, :meth:`__radd__`, :meth:`__iadd__`, :meth:`__mul__`, -:meth:`__rmul__` and :meth:`__imul__` described below; they should not define -other numerical operators. It is recommended that both mappings and sequences -implement the :meth:`__contains__` method to allow efficient use of the ``in`` -operator; for mappings, ``in`` should be equivalent of :meth:`has_key`; for -sequences, it should search through the values. It is further recommended that -both mappings and sequences implement the :meth:`__iter__` method to allow -efficient iteration through the container; for mappings, :meth:`__iter__` should -be the same as :meth:`iterkeys`; for sequences, it should iterate through the -values. - +range of items. It is also recommended that mappings provide the methods +:meth:`keys`, :meth:`values`, :meth:`items`, :meth:`has_key`, :meth:`get`, +:meth:`clear`, :meth:`setdefault`, :meth:`iterkeys`, :meth:`itervalues`, +:meth:`iteritems`, :meth:`pop`, :meth:`popitem`, :meth:`copy`, and +:meth:`update` behaving similar to those for Python's standard dictionary +objects. The :mod:`UserDict` module provides a :class:`DictMixin` class to help +create those methods from a base set of :meth:`__getitem__`, +:meth:`__setitem__`, :meth:`__delitem__`, and :meth:`keys`. Mutable sequences +should provide methods :meth:`append`, :meth:`count`, :meth:`index`, +:meth:`extend`, :meth:`insert`, :meth:`pop`, :meth:`remove`, :meth:`reverse` and +:meth:`sort`, like Python standard list objects. Finally, sequence types should +implement addition (meaning concatenation) and multiplication (meaning +repetition) by defining the methods :meth:`__add__`, :meth:`__radd__`, +:meth:`__iadd__`, :meth:`__mul__`, :meth:`__rmul__` and :meth:`__imul__` +described below; they should not define other numerical operators. It is +recommended that both mappings and sequences implement the :meth:`__contains__` +method to allow efficient use of the ``in`` operator; for mappings, ``in`` +should be equivalent of :meth:`has_key`; for sequences, it should search through +the values. It is further recommended that both mappings and sequences +implement the :meth:`__iter__` method to allow efficient iteration through the +container; for mappings, :meth:`__iter__` should be the same as +:meth:`iterkeys`; for sequences, it should iterate through the values. .. method:: object.__len__(self) @@ -1630,6 +1622,19 @@ considered to be false in a Boolean context. +.. note:: + + Slicing is done exclusively with the following three methods. A call like :: + + a[1:2] = b + + is translated to :: + + a[slice(1, 2, None)] = b + + and so forth. Missing slice items are always filled in with ``None``. + + .. method:: object.__getitem__(self, key) .. index:: object: slice @@ -1690,98 +1695,6 @@ of the mapping rather than the values or the key-item pairs. -.. _sequence-methods: - -Additional methods for emulation of sequence types --------------------------------------------------- - -The following optional methods can be defined to further emulate sequence -objects. Immutable sequences methods should at most only define -:meth:`__getslice__`; mutable sequences might define all three methods. - - -.. method:: object.__getslice__(self, i, j) - - .. deprecated:: 2.0 - Support slice objects as parameters to the :meth:`__getitem__` method. - (However, built-in types in CPython currently still implement - :meth:`__getslice__`. Therefore, you have to override it in derived - classes when implementing slicing.) - - Called to implement evaluation of ``self[i:j]``. The returned object should be - of the same type as *self*. Note that missing *i* or *j* in the slice - expression are replaced by zero or ``sys.maxint``, respectively. If negative - indexes are used in the slice, the length of the sequence is added to that - index. If the instance does not implement the :meth:`__len__` method, an - :exc:`AttributeError` is raised. No guarantee is made that indexes adjusted this - way are not still negative. Indexes which are greater than the length of the - sequence are not modified. If no :meth:`__getslice__` is found, a slice object - is created instead, and passed to :meth:`__getitem__` instead. - - -.. method:: object.__setslice__(self, i, j, sequence) - - Called to implement assignment to ``self[i:j]``. Same notes for *i* and *j* as - for :meth:`__getslice__`. - - This method is deprecated. If no :meth:`__setslice__` is found, or for extended - slicing of the form ``self[i:j:k]``, a slice object is created, and passed to - :meth:`__setitem__`, instead of :meth:`__setslice__` being called. - - -.. method:: object.__delslice__(self, i, j) - - Called to implement deletion of ``self[i:j]``. Same notes for *i* and *j* as for - :meth:`__getslice__`. This method is deprecated. If no :meth:`__delslice__` is - found, or for extended slicing of the form ``self[i:j:k]``, a slice object is - created, and passed to :meth:`__delitem__`, instead of :meth:`__delslice__` - being called. - -Notice that these methods are only invoked when a single slice with a single -colon is used, and the slice method is available. For slice operations -involving extended slice notation, or in absence of the slice methods, -:meth:`__getitem__`, :meth:`__setitem__` or :meth:`__delitem__` is called with a -slice object as argument. - -The following example demonstrate how to make your program or module compatible -with earlier versions of Python (assuming that methods :meth:`__getitem__`, -:meth:`__setitem__` and :meth:`__delitem__` support slice objects as -arguments):: - - class MyClass: - ... - def __getitem__(self, index): - ... - def __setitem__(self, index, value): - ... - def __delitem__(self, index): - ... - - if sys.version_info < (2, 0): - # They won't be defined if version is at least 2.0 final - - def __getslice__(self, i, j): - return self[max(0, i):max(0, j):] - def __setslice__(self, i, j, seq): - self[max(0, i):max(0, j):] = seq - def __delslice__(self, i, j): - del self[max(0, i):max(0, j):] - ... - -Note the calls to :func:`max`; these are necessary because of the handling of -negative indices before the :meth:`__\*slice__` methods are called. When -negative indexes are used, the :meth:`__\*item__` methods receive them as -provided, but the :meth:`__\*slice__` methods get a "cooked" form of the index -values. For each negative index value, the length of the sequence is added to -the index before calling the method (which may still result in a negative -index); this is the customary handling of negative indexes by the built-in -sequence types, and the :meth:`__\*item__` methods are expected to do this as -well. However, since they should already be doing that, negative indexes cannot -be passed in; they must be constrained to the bounds of the sequence before -being passed to the :meth:`__\*item__` methods. Calling ``max(0, i)`` -conveniently returns the proper value. - - .. _numeric-types: Emulating numeric types Modified: python/branches/py3k/Doc/reference/expressions.rst ============================================================================== --- python/branches/py3k/Doc/reference/expressions.rst (original) +++ python/branches/py3k/Doc/reference/expressions.rst Tue Sep 4 08:35:14 2007 @@ -517,25 +517,24 @@ simple_slicing: `primary` "[" `short_slice` "]" extended_slicing: `primary` "[" `slice_list` "]" slice_list: `slice_item` ("," `slice_item`)* [","] - slice_item: `expression` | `proper_slice` | `ellipsis` + slice_item: `expression` | `proper_slice` proper_slice: `short_slice` | `long_slice` short_slice: [`lower_bound`] ":" [`upper_bound`] long_slice: `short_slice` ":" [`stride`] lower_bound: `expression` upper_bound: `expression` stride: `expression` - ellipsis: "..." - -.. index:: pair: extended; slicing There is ambiguity in the formal syntax here: anything that looks like an expression list also looks like a slice list, so any subscription can be interpreted as a slicing. Rather than further complicating the syntax, this is disambiguated by defining that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the -slice list contains no proper slice nor ellipses). Similarly, when the slice -list has exactly one short slice and no trailing comma, the interpretation as a -simple slicing takes priority over that as an extended slicing. +slice list contains no proper slice). Similarly, when the slice list has +exactly one short slice and no trailing comma, the interpretation as a simple +slicing takes priority over that as an extended slicing. + +.. XXX is the next paragraph stil correct? The semantics for a simple slicing are as follows. The primary must evaluate to a sequence object. The lower and upper bound expressions, if present, must From python-3000-checkins at python.org Tue Sep 4 09:07:56 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 4 Sep 2007 09:07:56 +0200 (CEST) Subject: [Python-3000-checkins] r57949 - in python/branches/py3k: Doc/library/pdb.rst Lib/pdb.py Message-ID: <20070904070756.70DAD1E4009@bag.python.org> Author: georg.brandl Date: Tue Sep 4 09:07:56 2007 New Revision: 57949 Modified: python/branches/py3k/Doc/library/pdb.rst python/branches/py3k/Lib/pdb.py Log: Add "print" command to pdb, "print s" previously invoked the print statement. Modified: python/branches/py3k/Doc/library/pdb.rst ============================================================================== --- python/branches/py3k/Doc/library/pdb.rst (original) +++ python/branches/py3k/Doc/library/pdb.rst Tue Sep 4 09:07:56 2007 @@ -61,11 +61,11 @@ File "./mymodule.py", line 4, in test test2() File "./mymodule.py", line 3, in test2 - print spam + print(spam) NameError: spam >>> pdb.pm() > ./mymodule.py(3)test2() - -> print spam + -> print(spam) (Pdb) The module defines the following functions; each enters the debugger in a @@ -283,14 +283,9 @@ a(rgs) Print the argument list of the current function. -p *expression* +p(rint) *expression* Evaluate the *expression* in the current context and print its value. - .. note:: - - ``print`` can also be used, but is not a debugger command --- this executes the - Python :keyword:`print` statement. - pp *expression* Like the ``p`` command, except the value of the expression is pretty-printed using the :mod:`pprint` module. @@ -312,7 +307,7 @@ :file:`.pdbrc` file):: #Print instance variables (usage "pi classInst") - alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k] + alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k]) #Print instance variables in self alias ps pi self Modified: python/branches/py3k/Lib/pdb.py ============================================================================== --- python/branches/py3k/Lib/pdb.py (original) +++ python/branches/py3k/Lib/pdb.py Tue Sep 4 09:07:56 2007 @@ -716,6 +716,8 @@ print(repr(self._getval(arg)), file=self.stdout) except: pass + # make "print" an alias of "p" since print isn't a Python statement anymore + do_print = do_p def do_pp(self, arg): try: @@ -1009,7 +1011,7 @@ Print the arguments of the current function.""", file=self.stdout) def help_p(self): - print("""p expression + print("""p(rint) expression Print the value of the expression.""", file=self.stdout) def help_pp(self): From python-3000-checkins at python.org Tue Sep 4 09:15:34 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 4 Sep 2007 09:15:34 +0200 (CEST) Subject: [Python-3000-checkins] r57950 - in python/branches/py3k/Doc: c-api/abstract.rst c-api/newtypes.rst extending/embedding.rst extending/newtypes.rst howto/doanddont.rst howto/functional.rst howto/regex.rst howto/unicode.rst howto/urllib2.rst library/_winreg.rst library/anydbm.rst library/asyncore.rst library/atexit.rst library/binascii.rst library/cgi.rst library/collections.rst library/contextlib.rst library/cookie.rst library/csv.rst library/ctypes.rst library/dbhash.rst library/decimal.rst library/difflib.rst library/doctest.rst library/email.generator.rst library/email.header.rst library/email.iterators.rst library/email.message.rst library/fnmatch.rst library/functions.rst library/functools.rst library/gdbm.rst library/getopt.rst library/gettext.rst library/heapq.rst library/htmlparser.rst library/httplib.rst library/imaplib.rst library/itertools.rst library/logging.rst library/macosa.rst library/mailbox.rst library/nntplib.rst library/optparse.rst library/os.rst library/pickle.rst library/poplib.rst library/pprint.rst library/profile.rst library/pyexpat.rst library/repr.rst library/rlcompleter.rst library/sched.rst library/signal.rst library/simplexmlrpcserver.rst library/smtplib.rst library/socket.rst library/sqlite3.rst library/ssl.rst library/stdtypes.rst library/sys.rst library/tabnanny.rst library/tokenize.rst reference/compound_stmts.rst reference/expressions.rst reference/simple_stmts.rst tutorial/errors.rst tutorial/floatingpoint.rst tutorial/inputoutput.rst tutorial/interpreter.rst tutorial/stdlib2.rst Message-ID: <20070904071534.791851E4009@bag.python.org> Author: georg.brandl Date: Tue Sep 4 09:15:32 2007 New Revision: 57950 Modified: python/branches/py3k/Doc/c-api/abstract.rst python/branches/py3k/Doc/c-api/newtypes.rst python/branches/py3k/Doc/extending/embedding.rst python/branches/py3k/Doc/extending/newtypes.rst python/branches/py3k/Doc/howto/doanddont.rst python/branches/py3k/Doc/howto/functional.rst python/branches/py3k/Doc/howto/regex.rst python/branches/py3k/Doc/howto/unicode.rst python/branches/py3k/Doc/howto/urllib2.rst python/branches/py3k/Doc/library/_winreg.rst python/branches/py3k/Doc/library/anydbm.rst python/branches/py3k/Doc/library/asyncore.rst python/branches/py3k/Doc/library/atexit.rst python/branches/py3k/Doc/library/binascii.rst python/branches/py3k/Doc/library/cgi.rst python/branches/py3k/Doc/library/collections.rst python/branches/py3k/Doc/library/contextlib.rst python/branches/py3k/Doc/library/cookie.rst python/branches/py3k/Doc/library/csv.rst python/branches/py3k/Doc/library/ctypes.rst python/branches/py3k/Doc/library/dbhash.rst python/branches/py3k/Doc/library/decimal.rst python/branches/py3k/Doc/library/difflib.rst python/branches/py3k/Doc/library/doctest.rst python/branches/py3k/Doc/library/email.generator.rst python/branches/py3k/Doc/library/email.header.rst python/branches/py3k/Doc/library/email.iterators.rst python/branches/py3k/Doc/library/email.message.rst python/branches/py3k/Doc/library/fnmatch.rst python/branches/py3k/Doc/library/functions.rst python/branches/py3k/Doc/library/functools.rst python/branches/py3k/Doc/library/gdbm.rst python/branches/py3k/Doc/library/getopt.rst python/branches/py3k/Doc/library/gettext.rst python/branches/py3k/Doc/library/heapq.rst python/branches/py3k/Doc/library/htmlparser.rst python/branches/py3k/Doc/library/httplib.rst python/branches/py3k/Doc/library/imaplib.rst python/branches/py3k/Doc/library/itertools.rst python/branches/py3k/Doc/library/logging.rst python/branches/py3k/Doc/library/macosa.rst python/branches/py3k/Doc/library/mailbox.rst python/branches/py3k/Doc/library/nntplib.rst python/branches/py3k/Doc/library/optparse.rst python/branches/py3k/Doc/library/os.rst python/branches/py3k/Doc/library/pickle.rst python/branches/py3k/Doc/library/poplib.rst python/branches/py3k/Doc/library/pprint.rst python/branches/py3k/Doc/library/profile.rst python/branches/py3k/Doc/library/pyexpat.rst python/branches/py3k/Doc/library/repr.rst python/branches/py3k/Doc/library/rlcompleter.rst python/branches/py3k/Doc/library/sched.rst python/branches/py3k/Doc/library/signal.rst python/branches/py3k/Doc/library/simplexmlrpcserver.rst python/branches/py3k/Doc/library/smtplib.rst python/branches/py3k/Doc/library/socket.rst python/branches/py3k/Doc/library/sqlite3.rst python/branches/py3k/Doc/library/ssl.rst python/branches/py3k/Doc/library/stdtypes.rst python/branches/py3k/Doc/library/sys.rst python/branches/py3k/Doc/library/tabnanny.rst python/branches/py3k/Doc/library/tokenize.rst python/branches/py3k/Doc/reference/compound_stmts.rst python/branches/py3k/Doc/reference/expressions.rst python/branches/py3k/Doc/reference/simple_stmts.rst python/branches/py3k/Doc/tutorial/errors.rst python/branches/py3k/Doc/tutorial/floatingpoint.rst python/branches/py3k/Doc/tutorial/inputoutput.rst python/branches/py3k/Doc/tutorial/interpreter.rst python/branches/py3k/Doc/tutorial/stdlib2.rst Log: Convert all print statements in the docs. Modified: python/branches/py3k/Doc/c-api/abstract.rst ============================================================================== --- python/branches/py3k/Doc/c-api/abstract.rst (original) +++ python/branches/py3k/Doc/c-api/abstract.rst Tue Sep 4 09:15:32 2007 @@ -143,8 +143,8 @@ Compute a string representation of object *o*. Returns the string representation on success, *NULL* on failure. This is the equivalent of the - Python expression ``str(o)``. Called by the :func:`str` built-in function and - by the :keyword:`print` statement. + Python expression ``str(o)``. Called by the :func:`str` built-in function + and, therefore, by the :func:`print` function. .. cfunction:: PyObject* PyObject_Unicode(PyObject *o) Modified: python/branches/py3k/Doc/c-api/newtypes.rst ============================================================================== --- python/branches/py3k/Doc/c-api/newtypes.rst (original) +++ python/branches/py3k/Doc/c-api/newtypes.rst Tue Sep 4 09:15:32 2007 @@ -645,8 +645,8 @@ The signature is the same as for :cfunc:`PyObject_Str`; it must return a string or a Unicode object. This function should return a "friendly" string - representation of the object, as this is the representation that will be used by - the print statement. + representation of the object, as this is the representation that will be used, + among other things, by the :func:`print` function. When this field is not set, :cfunc:`PyObject_Repr` is called to return a string representation. Modified: python/branches/py3k/Doc/extending/embedding.rst ============================================================================== --- python/branches/py3k/Doc/extending/embedding.rst (original) +++ python/branches/py3k/Doc/extending/embedding.rst Tue Sep 4 09:15:32 2007 @@ -64,7 +64,7 @@ { Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" - "print 'Today is',ctime(time())\n"); + "print('Today is', ctime(time()))\n"); Py_Finalize(); return 0; } @@ -141,7 +141,7 @@ :program:`call`), and use it to execute a Python script, such as:: def multiply(a,b): - print "Will compute", a, "times", b + print("Will compute", a, "times", b) c = 0 for i in range(0, a): c = c + b @@ -234,7 +234,7 @@ With these extensions, the Python script can do things like :: import emb - print "Number of arguments", emb.numargs() + print("Number of arguments", emb.numargs()) In a real application, the methods will expose an API of the application to Python. Modified: python/branches/py3k/Doc/extending/newtypes.rst ============================================================================== --- python/branches/py3k/Doc/extending/newtypes.rst (original) +++ python/branches/py3k/Doc/extending/newtypes.rst Tue Sep 4 09:15:32 2007 @@ -826,11 +826,11 @@ >>> import shoddy >>> s = shoddy.Shoddy(range(3)) >>> s.extend(s) - >>> print len(s) + >>> print(len(s)) 6 - >>> print s.increment() + >>> print(s.increment()) 1 - >>> print s.increment() + >>> print(s.increment()) 2 .. literalinclude:: ../includes/shoddy.c @@ -1063,34 +1063,6 @@ obj->obj_UnderlyingDatatypePtr->size); } -The print function will be called whenever Python needs to "print" an instance -of the type. For example, if 'node' is an instance of type TreeNode, then the -print function is called when Python code calls:: - - print node - -There is a flags argument and one flag, :const:`Py_PRINT_RAW`, and it suggests -that you print without string quotes and possibly without interpreting escape -sequences. - -The print function receives a file object as an argument. You will likely want -to write to that file object. - -Here is a sample print function:: - - static int - newdatatype_print(newdatatypeobject *obj, FILE *fp, int flags) - { - if (flags & Py_PRINT_RAW) { - fprintf(fp, "<{newdatatype object--size: %d}>", - obj->obj_UnderlyingDatatypePtr->size); - } - else { - fprintf(fp, "\"<{newdatatype object--size: %d}>\"", - obj->obj_UnderlyingDatatypePtr->size); - } - return 0; - } Attribute Management Modified: python/branches/py3k/Doc/howto/doanddont.rst ============================================================================== --- python/branches/py3k/Doc/howto/doanddont.rst (original) +++ python/branches/py3k/Doc/howto/doanddont.rst Tue Sep 4 09:15:32 2007 @@ -59,7 +59,7 @@ Remember, you can never know for sure what names a module exports, so either take what you need --- ``from module import name1, name2``, or keep them in the -module and access on a per-need basis --- ``import module;print module.name``. +module and access on a per-need basis --- ``import module; print(module.name)``. When It Is Just Fine @@ -181,7 +181,7 @@ def get_status(file): if not os.path.exists(file): - print "file not found" + print("file not found") sys.exit(1) return open(file).readline() @@ -199,7 +199,7 @@ try: return open(file).readline() except (IOError, OSError): - print "file not found" + print("file not found") sys.exit(1) In this version, \*either\* the file gets opened and the line is read (so it @@ -264,12 +264,13 @@ There are also many useful builtin functions people seem not to be aware of for some reason: :func:`min` and :func:`max` can find the minimum/maximum of any sequence with comparable semantics, for example, yet many people write their own -:func:`max`/:func:`min`. Another highly useful function is :func:`reduce`. A -classical use of :func:`reduce` is something like :: +:func:`max`/:func:`min`. Another highly useful function is +:func:`functools.reduce`. A classical use of :func:`reduce` is something like +:: - import sys, operator + import sys, operator, functools nums = map(float, sys.argv[1:]) - print reduce(operator.add, nums)/len(nums) + print(functools.reduce(operator.add, nums) / len(nums)) This cute little script prints the average of all numbers given on the command line. The :func:`reduce` adds up all the numbers, and the rest is just some Modified: python/branches/py3k/Doc/howto/functional.rst ============================================================================== --- python/branches/py3k/Doc/howto/functional.rst (original) +++ python/branches/py3k/Doc/howto/functional.rst Tue Sep 4 09:15:32 2007 @@ -201,7 +201,7 @@ >>> L = [1,2,3] >>> it = iter(L) - >>> print it + >>> it >>> it.next() 1 @@ -221,10 +221,10 @@ These two statements are equivalent:: for i in iter(obj): - print i + print(i) for i in obj: - print i + print(i) Iterators can be materialized as lists or tuples by using the :func:`list` or :func:`tuple` constructor functions:: @@ -274,7 +274,7 @@ >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12} >>> for key in m: - ... print key, m[key] + ... print(key, m[key]) Mar 3 Feb 2 Aug 8 @@ -316,7 +316,7 @@ S = set((2, 3, 5, 7, 11, 13)) for i in S: - print i + print(i) @@ -568,18 +568,18 @@ And here's an example of changing the counter: >>> it = counter(10) - >>> print it.next() + >>> it.next() 0 - >>> print it.next() + >>> it.next() 1 - >>> print it.send(8) + >>> it.send(8) 8 - >>> print it.next() + >>> it.next() 9 - >>> print it.next() + >>> it.next() Traceback (most recent call last): File ``t.py'', line 15, in ? - print it.next() + it.next() StopIteration Because ``yield`` will often be returning ``None``, you should always check for @@ -721,7 +721,7 @@ f = open('data.txt', 'r') for i, line in enumerate(f): if line.strip() == '': - print 'Blank line at line #%i' % i + print('Blank line at line #%i' % i) ``sorted(iterable, [cmp=None], [key=None], [reverse=False)`` collects all the elements of the iterable into a list, sorts the list, and returns the sorted @@ -1100,7 +1100,7 @@ def log (message, subsystem): "Write the contents of 'message' to the specified subsystem." - print '%s: %s' % (subsystem, message) + print('%s: %s' % (subsystem, message)) ... server_log = functools.partial(log, subsystem='server') @@ -1395,6 +1395,6 @@ for elem in slice[:-1]: sys.stdout.write(str(elem)) sys.stdout.write(', ') - print elem[-1] + print(elem[-1]) Modified: python/branches/py3k/Doc/howto/regex.rst ============================================================================== --- python/branches/py3k/Doc/howto/regex.rst (original) +++ python/branches/py3k/Doc/howto/regex.rst Tue Sep 4 09:15:32 2007 @@ -1,5 +1,5 @@ **************************** - Regular Expression HOWTO + Regular Expression HOWTO **************************** :Author: A.M. Kuchling @@ -263,7 +263,7 @@ >>> import re >>> p = re.compile('ab*') - >>> print p + >>> p :func:`re.compile` also accepts an optional *flags* argument, used to enable @@ -387,7 +387,7 @@ :meth:`match` to make this clear. :: >>> p.match("") - >>> print p.match("") + >>> print(p.match("")) None Now, let's try it on a string that it should match, such as ``tempo``. In this @@ -395,7 +395,7 @@ result in a variable for later use. :: >>> m = p.match('tempo') - >>> print m + >>> m <_sre.SRE_Match object at 80c4f68> Now you can query the :class:`MatchObject` for information about the matching @@ -432,9 +432,9 @@ instances scans through the string, so the match may not start at zero in that case. :: - >>> print p.match('::: message') + >>> print(p.match('::: message')) None - >>> m = p.search('::: message') ; print m + >>> m = p.search('::: message') ; print(m) >>> m.group() 'message' @@ -447,9 +447,9 @@ p = re.compile( ... ) m = p.match( 'string goes here' ) if m: - print 'Match found: ', m.group() + print('Match found: ', m.group()) else: - print 'No match' + print('No match') Two :class:`RegexObject` methods return all of the matches for a pattern. :meth:`findall` returns a list of matching strings:: @@ -466,7 +466,7 @@ >>> iterator >>> for match in iterator: - ... print match.span() + ... print(match.span()) ... (0, 2) (22, 24) @@ -483,7 +483,7 @@ the RE string added as the first argument, and still return either ``None`` or a :class:`MatchObject` instance. :: - >>> print re.match(r'From\s+', 'Fromage amk') + >>> print(re.match(r'From\s+', 'Fromage amk')) None >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998') @@ -674,9 +674,9 @@ For example, if you wish to match the word ``From`` only at the beginning of a line, the RE to use is ``^From``. :: - >>> print re.search('^From', 'From Here to Eternity') + >>> print(re.search('^From', 'From Here to Eternity')) - >>> print re.search('^From', 'Reciting From Memory') + >>> print(re.search('^From', 'Reciting From Memory')) None .. % To match a literal \character{\^}, use \regexp{\e\^} or enclose it @@ -686,11 +686,11 @@ Matches at the end of a line, which is defined as either the end of the string, or any location followed by a newline character. :: - >>> print re.search('}$', '{block}') + >>> print(re.search('}$', '{block}')) - >>> print re.search('}$', '{block} ') + >>> print(re.search('}$', '{block} ')) None - >>> print re.search('}$', '{block}\n') + >>> print(re.search('}$', '{block}\n')) To match a literal ``'$'``, use ``\$`` or enclose it inside a character class, @@ -717,11 +717,11 @@ match when it's contained inside another word. :: >>> p = re.compile(r'\bclass\b') - >>> print p.search('no class at all') + >>> print(p.search('no class at all')) - >>> print p.search('the declassified algorithm') + >>> print(p.search('the declassified algorithm')) None - >>> print p.search('one subclass is') + >>> print(p.search('one subclass is')) None There are two subtleties you should remember when using this special sequence. @@ -733,9 +733,9 @@ in front of the RE string. :: >>> p = re.compile('\bclass\b') - >>> print p.search('no class at all') + >>> print(p.search('no class at all')) None - >>> print p.search('\b' + 'class' + '\b') + >>> print(p.search('\b' + 'class' + '\b') ) Second, inside a character class, where there's no use for this assertion, @@ -773,7 +773,7 @@ ``ab``. :: >>> p = re.compile('(ab)*') - >>> print p.match('ababababab').span() + >>> print(p.match('ababababab').span()) (0, 10) Groups indicated with ``'('``, ``')'`` also capture the starting and ending @@ -1247,17 +1247,17 @@ only report a successful match which will start at 0; if the match wouldn't start at zero, :func:`match` will *not* report it. :: - >>> print re.match('super', 'superstition').span() + >>> print(re.match('super', 'superstition').span()) (0, 5) - >>> print re.match('super', 'insuperable') + >>> print(re.match('super', 'insuperable')) None On the other hand, :func:`search` will scan forward through the string, reporting the first match it finds. :: - >>> print re.search('super', 'superstition').span() + >>> print(re.search('super', 'superstition').span()) (0, 5) - >>> print re.search('super', 'insuperable').span() + >>> print(re.search('super', 'insuperable').span()) (2, 7) Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``.*`` @@ -1286,9 +1286,9 @@ >>> s = 'Title' >>> len(s) 32 - >>> print re.match('<.*>', s).span() + >>> print(re.match('<.*>', s).span()) (0, 32) - >>> print re.match('<.*>', s).group() + >>> print(re.match('<.*>', s).group()) Title The RE matches the ``'<'`` in ````, and the ``.*`` consumes the rest of @@ -1304,7 +1304,7 @@ when it fails, the engine advances a character at a time, retrying the ``'>'`` at every step. This produces just the right result:: - >>> print re.match('<.*?>', s).group() + >>> print(re.match('<.*?>', s).group()) (Note that parsing HTML or XML with regular expressions is painful. Modified: python/branches/py3k/Doc/howto/unicode.rst ============================================================================== --- python/branches/py3k/Doc/howto/unicode.rst (original) +++ python/branches/py3k/Doc/howto/unicode.rst Tue Sep 4 09:15:32 2007 @@ -7,6 +7,12 @@ This HOWTO discusses Python's support for Unicode, and explains various problems that people commonly encounter when trying to work with Unicode. +.. XXX fix it +.. warning:: + + This HOWTO has not yet been updated for Python 3000's string object changes. + + Introduction to Unicode ======================= @@ -122,8 +128,8 @@ representation, the string "Python" would look like this:: P y t h o n - 0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00 - 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 + 0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00 + 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 This representation is straightforward but using it presents a number of problems. @@ -181,7 +187,7 @@ between 128 and 255. 3. Code points >0x7ff are turned into three- or four-byte sequences, where each byte of the sequence is between 128 and 255. - + UTF-8 has several convenient properties: 1. It can handle any Unicode code point. @@ -256,7 +262,7 @@ >>> unicode('abcdef' + chr(255)) Traceback (most recent call last): File "", line 1, in ? - UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6: + UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6: ordinal not in range(128) The ``errors`` argument specifies the response when the input string can't be @@ -268,7 +274,7 @@ >>> unicode('\x80abc', errors='strict') Traceback (most recent call last): File "", line 1, in ? - UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: + UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: ordinal not in range(128) >>> unicode('\x80abc', errors='replace') u'\ufffdabc' @@ -354,7 +360,7 @@ >>> u2 = utf8_version.decode('utf-8') # Decode using UTF-8 >>> u == u2 # The two strings match True - + The low-level routines for registering and accessing the available encodings are found in the :mod:`codecs` module. However, the encoding and decoding functions returned by this module are usually more low-level than is comfortable, so I'm @@ -366,8 +372,8 @@ The most commonly used part of the :mod:`codecs` module is the :func:`codecs.open` function which will be discussed in the section on input and output. - - + + Unicode Literals in Python Source Code -------------------------------------- @@ -385,10 +391,10 @@ >>> s = u"a\xac\u1234\u20ac\U00008000" ^^^^ two-digit hex escape - ^^^^^^ four-digit Unicode escape + ^^^^^^ four-digit Unicode escape ^^^^^^^^^^ eight-digit Unicode escape - >>> for c in s: print ord(c), - ... + >>> for c in s: print(ord(c), end=" ") + ... 97 172 4660 8364 32768 Using escape sequences for code points greater than 127 is fine in small doses, @@ -408,10 +414,10 @@ #!/usr/bin/env python # -*- coding: latin-1 -*- - + u = u'abcd?' - print ord(u[-1]) - + print(ord(u[-1])) + The syntax is inspired by Emacs's notation for specifying variables local to a file. Emacs supports many different variables, but Python only supports 'coding'. The ``-*-`` symbols indicate that the comment is special; within @@ -426,15 +432,15 @@ #!/usr/bin/env python u = u'abcd?' - print ord(u[-1]) + print(ord(u[-1])) When you run it with Python 2.4, it will output the following warning:: amk:~$ python p263.py - sys:1: DeprecationWarning: Non-ASCII character '\xe9' - in file p263.py on line 2, but no encoding declared; + sys:1: DeprecationWarning: Non-ASCII character '\xe9' + in file p263.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details - + Unicode Properties ------------------ @@ -450,15 +456,15 @@ prints the numeric value of one particular character:: import unicodedata - + u = unichr(233) + unichr(0x0bf2) + unichr(3972) + unichr(6000) + unichr(13231) - + for i, c in enumerate(u): - print i, '%04x' % ord(c), unicodedata.category(c), - print unicodedata.name(c) - + print(i, '%04x' % ord(c), unicodedata.category(c), end=" ") + print(unicodedata.name(c)) + # Get numeric value of second character - print unicodedata.numeric(u[1]) + print(unicodedata.numeric(u[1])) When run, this prints:: @@ -545,7 +551,7 @@ import codecs f = codecs.open('unicode.rst', encoding='utf-8') for line in f: - print repr(line) + print(repr(line)) It's also possible to open files in update mode, allowing both reading and writing:: @@ -553,7 +559,7 @@ f = codecs.open('test', encoding='utf-8', mode='w+') f.write(u'\u4500 blah blah blah\n') f.seek(0) - print repr(f.readline()[:1]) + print(repr(f.readline()[:1])) f.close() Unicode character U+FEFF is used as a byte-order mark (BOM), and is often @@ -606,8 +612,8 @@ f.close() import os - print os.listdir('.') - print os.listdir(u'.') + print(os.listdir('.')) + print(os.listdir(u'.')) will produce the following output:: @@ -619,7 +625,7 @@ the Unicode versions. - + Tips for Writing Unicode-aware Programs --------------------------------------- @@ -665,7 +671,7 @@ unicode_name = filename.decode(encoding) f = open(unicode_name, 'r') # ... return contents of file ... - + However, if an attacker could specify the ``'base64'`` encoding, they could pass ``'L2V0Yy9wYXNzd2Q='``, which is the base-64 encoded form of the string ``'/etc/passwd'``, to read a system file. The above code looks for ``'/'`` @@ -701,7 +707,7 @@ .. comment Describe obscure -U switch somewhere? .. comment Describe use of codecs.StreamRecoder and StreamReaderWriter -.. comment +.. comment Original outline: - [ ] Unicode introduction Modified: python/branches/py3k/Doc/howto/urllib2.rst ============================================================================== --- python/branches/py3k/Doc/howto/urllib2.rst (original) +++ python/branches/py3k/Doc/howto/urllib2.rst Tue Sep 4 09:15:32 2007 @@ -134,7 +134,7 @@ >>> data['location'] = 'Northampton' >>> data['language'] = 'Python' >>> url_values = urllib.urlencode(data) - >>> print url_values + >>> print(url_values) name=Somebody+Here&language=Python&location=Northampton >>> url = 'http://www.example.com/example.cgi' >>> full_url = url + '?' + url_values @@ -202,7 +202,7 @@ >>> req = urllib2.Request('http://www.pretend_server.org') >>> try: urllib2.urlopen(req) >>> except URLError, e: - >>> print e.reason + >>> print(e.reason) >>> (4, 'getaddrinfo failed') @@ -311,8 +311,8 @@ >>> try: >>> urllib2.urlopen(req) >>> except URLError, e: - >>> print e.code - >>> print e.read() + >>> print(e.code) + >>> print(e.read()) >>> 404 0) Modified: python/branches/py3k/Doc/library/atexit.rst ============================================================================== --- python/branches/py3k/Doc/library/atexit.rst (original) +++ python/branches/py3k/Doc/library/atexit.rst Tue Sep 4 09:15:32 2007 @@ -80,7 +80,7 @@ passed along to the registered function when it is called:: def goodbye(name, adjective): - print 'Goodbye, %s, it was %s to meet you.' % (name, adjective) + print('Goodbye, %s, it was %s to meet you.' % (name, adjective)) import atexit atexit.register(goodbye, 'Donny', 'nice') @@ -94,7 +94,7 @@ @atexit.register def goodbye(): - print "You are now leaving the Python sector." + print("You are now leaving the Python sector.") This obviously only works with functions that don't take arguments. Modified: python/branches/py3k/Doc/library/binascii.rst ============================================================================== --- python/branches/py3k/Doc/library/binascii.rst (original) +++ python/branches/py3k/Doc/library/binascii.rst Tue Sep 4 09:15:32 2007 @@ -110,11 +110,11 @@ use as a checksum algorithm, it is not suitable for use as a general hash algorithm. Use as follows:: - print binascii.crc32("hello world") + print(binascii.crc32("hello world")) # Or, in two pieces: crc = binascii.crc32("hello") crc = binascii.crc32(" world", crc) - print crc + print(crc) .. function:: b2a_hex(data) Modified: python/branches/py3k/Doc/library/cgi.rst ============================================================================== --- python/branches/py3k/Doc/library/cgi.rst (original) +++ python/branches/py3k/Doc/library/cgi.rst Tue Sep 4 09:15:32 2007 @@ -46,16 +46,16 @@ kind of data is following. Python code to generate a minimal header section looks like this:: - print "Content-Type: text/html" # HTML is following - print # blank line, end of headers + print("Content-Type: text/html") # HTML is following + print() # blank line, end of headers The second section is usually HTML, which allows the client software to display nicely formatted text with header, in-line images, etc. Here's Python code that prints a simple piece of HTML:: - print "CGI script output" - print "

This is my first CGI script

" - print "Hello, world!" + print("CGI script output") + print("

This is my first CGI script

") + print("Hello, world!") .. _using-the-cgi-module: @@ -104,11 +104,11 @@ form = cgi.FieldStorage() if not ("name" in form and "addr" in form): - print "

Error

" - print "Please fill in the name and addr fields." + print("

Error

") + print("Please fill in the name and addr fields.") return - print "

name:", form["name"].value - print "

addr:", form["addr"].value + print("

name:", form["name"].value) + print("

addr:", form["addr"].value) ...further form processing here... Here the fields, accessed through ``form[key]``, are themselves instances of @@ -505,8 +505,8 @@ import sys sys.stderr = sys.stdout - print "Content-Type: text/plain" - print + print("Content-Type: text/plain") + print() ...your code here... This relies on the Python interpreter to print the traceback. The content type Modified: python/branches/py3k/Doc/library/collections.rst ============================================================================== --- python/branches/py3k/Doc/library/collections.rst (original) +++ python/branches/py3k/Doc/library/collections.rst Tue Sep 4 09:15:32 2007 @@ -105,7 +105,7 @@ >>> from collections import deque >>> d = deque('ghi') # make a new deque with three items >>> for elem in d: # iterate over the deque's elements - ... print elem.upper() + ... print(elem.upper()) G H I @@ -194,7 +194,7 @@ ... pending.append(task) ... >>> for value in roundrobin('abc', 'd', 'efgh'): - ... print value + ... print(value) a d @@ -221,7 +221,7 @@ ... d.append(pair) ... return list(d) ... - >>> print maketree('abcdefgh') + >>> print(maketree('abcdefgh')) [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]] @@ -386,14 +386,14 @@ import csv EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade') for record in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))): - print record + print(record) To cast an individual record stored as :class:`list`, :class:`tuple`, or some other iterable type, use the star-operator [#]_ to unpack the values:: >>> Color = NamedTuple('Color', 'name code') >>> m = dict(red=1, green=2, blue=3) - >>> print Color(*m.popitem()) + >>> print(Color(*m.popitem())) Color(name='blue', code=3) .. rubric:: Footnotes Modified: python/branches/py3k/Doc/library/contextlib.rst ============================================================================== --- python/branches/py3k/Doc/library/contextlib.rst (original) +++ python/branches/py3k/Doc/library/contextlib.rst Tue Sep 4 09:15:32 2007 @@ -26,12 +26,12 @@ @contextmanager def tag(name): - print "<%s>" % name + print("<%s>" % name) yield - print "" % name + print("" % name) >>> with tag("h1"): - ... print "foo" + ... print("foo") ...

foo @@ -104,7 +104,7 @@ with closing(urllib.urlopen('http://www.python.org')) as page: for line in page: - print line + print(line) without needing to explicitly close ``page``. Even if an error occurs, ``page.close()`` will be called when the :keyword:`with` block is exited. Modified: python/branches/py3k/Doc/library/cookie.rst ============================================================================== --- python/branches/py3k/Doc/library/cookie.rst (original) +++ python/branches/py3k/Doc/library/cookie.rst Tue Sep 4 09:15:32 2007 @@ -214,32 +214,32 @@ >>> C = Cookie.SmartCookie() >>> C["fig"] = "newton" >>> C["sugar"] = "wafer" - >>> print C # generate HTTP headers + >>> print(C) # generate HTTP headers Set-Cookie: sugar=wafer Set-Cookie: fig=newton - >>> print C.output() # same thing + >>> print(C.output()) # same thing Set-Cookie: sugar=wafer Set-Cookie: fig=newton >>> C = Cookie.SmartCookie() >>> C["rocky"] = "road" >>> C["rocky"]["path"] = "/cookie" - >>> print C.output(header="Cookie:") + >>> print(C.output(header="Cookie:")) Cookie: rocky=road; Path=/cookie - >>> print C.output(attrs=[], header="Cookie:") + >>> print(C.output(attrs=[], header="Cookie:")) Cookie: rocky=road >>> C = Cookie.SmartCookie() >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header) - >>> print C + >>> print(C) Set-Cookie: vienna=finger Set-Cookie: chips=ahoy >>> C = Cookie.SmartCookie() >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') - >>> print C + >>> print(C) Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" >>> C = Cookie.SmartCookie() >>> C["oreo"] = "doublestuff" >>> C["oreo"]["path"] = "/" - >>> print C + >>> print(C) Set-Cookie: oreo=doublestuff; Path=/ >>> C = Cookie.SmartCookie() >>> C["twix"] = "none for you" @@ -252,7 +252,7 @@ '7' >>> C["string"].value 'seven' - >>> print C + >>> print(C) Set-Cookie: number=7 Set-Cookie: string=seven >>> C = Cookie.SerialCookie() @@ -262,7 +262,7 @@ 7 >>> C["string"].value 'seven' - >>> print C + >>> print(C) Set-Cookie: number="I7\012." Set-Cookie: string="S'seven'\012p1\012." >>> C = Cookie.SmartCookie() @@ -272,7 +272,7 @@ 7 >>> C["string"].value 'seven' - >>> print C + >>> print(C) Set-Cookie: number="I7\012." Set-Cookie: string=seven Modified: python/branches/py3k/Doc/library/csv.rst ============================================================================== --- python/branches/py3k/Doc/library/csv.rst (original) +++ python/branches/py3k/Doc/library/csv.rst Tue Sep 4 09:15:32 2007 @@ -390,14 +390,14 @@ import csv reader = csv.reader(open("some.csv", "rb")) for row in reader: - print row + print(row) Reading a file with an alternate format:: import csv reader = csv.reader(open("passwd", "rb"), delimiter=':', quoting=csv.QUOTE_NONE) for row in reader: - print row + print(row) The corresponding simplest possible writing example is:: @@ -420,7 +420,7 @@ reader = csv.reader(open(filename, "rb")) try: for row in reader: - print row + print(row) except csv.Error as e: sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e)) @@ -429,7 +429,7 @@ import csv for row in csv.reader(['one,two,three']): - print row + print(row) The :mod:`csv` module doesn't directly support reading and writing Unicode, but it is 8-bit-clean save for some problems with ASCII NUL characters. So you can Modified: python/branches/py3k/Doc/library/ctypes.rst ============================================================================== --- python/branches/py3k/Doc/library/ctypes.rst (original) +++ python/branches/py3k/Doc/library/ctypes.rst Tue Sep 4 09:15:32 2007 @@ -48,9 +48,9 @@ convention:: >>> from ctypes import * - >>> print windll.kernel32 # doctest: +WINDOWS + >>> print(windll.kernel32) # doctest: +WINDOWS - >>> print cdll.msvcrt # doctest: +WINDOWS + >>> print(cdll.msvcrt) # doctest: +WINDOWS >>> libc = cdll.msvcrt # doctest: +WINDOWS >>> @@ -82,9 +82,9 @@ >>> from ctypes import * >>> libc.printf <_FuncPtr object at 0x...> - >>> print windll.kernel32.GetModuleHandleA # doctest: +WINDOWS + >>> print(windll.kernel32.GetModuleHandleA) # doctest: +WINDOWS <_FuncPtr object at 0x...> - >>> print windll.kernel32.MyOwnFunction # doctest: +WINDOWS + >>> print(windll.kernel32.MyOwnFunction) # doctest: +WINDOWS Traceback (most recent call last): File "", line 1, in ? File "ctypes.py", line 239, in __getattr__ @@ -145,9 +145,9 @@ This example calls both functions with a NULL pointer (``None`` should be used as the NULL pointer):: - >>> print libc.time(None) # doctest: +SKIP + >>> print(libc.time(None)) # doctest: +SKIP 1150640792 - >>> print hex(windll.kernel32.GetModuleHandleA(None)) # doctest: +WINDOWS + >>> print(hex(windll.kernel32.GetModuleHandleA(None))) # doctest: +WINDOWS 0x1d000000 >>> @@ -269,12 +269,12 @@ Since these types are mutable, their value can also be changed afterwards:: >>> i = c_int(42) - >>> print i + >>> print(i) c_long(42) - >>> print i.value + >>> print(i.value) 42 >>> i.value = -99 - >>> print i.value + >>> print(i.value) -99 >>> @@ -285,12 +285,12 @@ >>> s = "Hello, World" >>> c_s = c_char_p(s) - >>> print c_s + >>> print(c_s) c_char_p('Hello, World') >>> c_s.value = "Hi, there" - >>> print c_s + >>> print(c_s) c_char_p('Hi, there') - >>> print s # first string is unchanged + >>> print(s) # first string is unchanged Hello, World >>> @@ -303,18 +303,18 @@ >>> from ctypes import * >>> p = create_string_buffer(3) # create a 3 byte buffer, initialized to NUL bytes - >>> print sizeof(p), repr(p.raw) + >>> print(sizeof(p), repr(p.raw)) 3 '\x00\x00\x00' >>> p = create_string_buffer("Hello") # create a buffer containing a NUL terminated string - >>> print sizeof(p), repr(p.raw) + >>> print(sizeof(p), repr(p.raw)) 6 'Hello\x00' - >>> print repr(p.value) + >>> print(repr(p.value)) 'Hello' >>> p = create_string_buffer("Hello", 10) # create a 10 byte buffer - >>> print sizeof(p), repr(p.raw) + >>> print(sizeof(p), repr(p.raw)) 10 'Hello\x00\x00\x00\x00\x00' >>> p.value = "Hi" - >>> print sizeof(p), repr(p.raw) + >>> print(sizeof(p), repr(p.raw)) 10 'Hi\x00lo\x00\x00\x00\x00\x00' >>> @@ -444,7 +444,7 @@ >>> strchr.restype = c_char_p # c_char_p is a pointer to a string >>> strchr("abcdef", ord("d")) 'def' - >>> print strchr("abcdef", ord("x")) + >>> print(strchr("abcdef", ord("x"))) None >>> @@ -460,7 +460,7 @@ Traceback (most recent call last): File "", line 1, in ? ArgumentError: argument 2: exceptions.TypeError: one character string expected - >>> print strchr("abcdef", "x") + >>> print(strchr("abcdef", "x")) None >>> strchr("abcdef", "d") 'def' @@ -516,12 +516,12 @@ >>> i = c_int() >>> f = c_float() >>> s = create_string_buffer('\000' * 32) - >>> print i.value, f.value, repr(s.value) + >>> print(i.value, f.value, repr(s.value)) 0 0.0 '' >>> libc.sscanf("1 3.14 Hello", "%d %f %s", ... byref(i), byref(f), s) 3 - >>> print i.value, f.value, repr(s.value) + >>> print(i.value, f.value, repr(s.value)) 1 3.1400001049 'Hello' >>> @@ -549,10 +549,10 @@ ... ("y", c_int)] ... >>> point = POINT(10, 20) - >>> print point.x, point.y + >>> print(point.x, point.y) 10 20 >>> point = POINT(y=5) - >>> print point.x, point.y + >>> print(point.x, point.y) 0 5 >>> POINT(1, 2, 3) Traceback (most recent call last): @@ -571,9 +571,9 @@ ... ("lowerright", POINT)] ... >>> rc = RECT(point) - >>> print rc.upperleft.x, rc.upperleft.y + >>> print(rc.upperleft.x, rc.upperleft.y) 0 5 - >>> print rc.lowerright.x, rc.lowerright.y + >>> print(rc.lowerright.x, rc.lowerright.y) 0 0 >>> @@ -585,9 +585,9 @@ Fields descriptors can be retrieved from the *class*, they are useful for debugging because they can provide useful information:: - >>> print POINT.x + >>> print(POINT.x) - >>> print POINT.y + >>> print(POINT.y) >>> @@ -622,9 +622,9 @@ ... _fields_ = [("first_16", c_int, 16), ... ("second_16", c_int, 16)] ... - >>> print Int.first_16 + >>> print(Int.first_16) - >>> print Int.second_16 + >>> print(Int.second_16) >>> @@ -653,7 +653,7 @@ ... ("b", c_float), ... ("point_array", POINT * 4)] >>> - >>> print len(MyStruct().point_array) + >>> print(len(MyStruct().point_array)) 4 >>> @@ -661,7 +661,7 @@ arr = TenPointsArrayType() for pt in arr: - print pt.x, pt.y + print(pt.x, pt.y) The above code print a series of ``0 0`` lines, because the array contents is initialized to zeros. @@ -671,9 +671,9 @@ >>> from ctypes import * >>> TenIntegers = c_int * 10 >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) - >>> print ii + >>> print(ii) - >>> for i in ii: print i, + >>> for i in ii: print(i, end=" ") ... 1 2 3 4 5 6 7 8 9 10 >>> @@ -725,10 +725,10 @@ Assigning to an integer index changes the pointed to value:: - >>> print i + >>> print(i) c_long(99) >>> pi[0] = 22 - >>> print i + >>> print(i) c_long(22) >>> @@ -758,7 +758,7 @@ ``NULL`` pointers have a ``False`` boolean value:: >>> null_ptr = POINTER(c_int)() - >>> print bool(null_ptr) + >>> print(bool(null_ptr)) False >>> @@ -797,7 +797,7 @@ >>> bar.values = (c_int * 3)(1, 2, 3) >>> bar.count = 3 >>> for i in range(bar.count): - ... print bar.values[i] + ... print(bar.values[i]) ... 1 2 @@ -841,7 +841,7 @@ >>> bar = Bar() >>> bar.values = cast((c_byte * 4)(), POINTER(c_int)) - >>> print bar.values[0] + >>> print(bar.values[0]) 0 >>> @@ -898,7 +898,7 @@ >>> c2.next = pointer(c1) >>> p = c1 >>> for i in range(8): - ... print p.name, + ... print(p.name, end=" ") ... p = p.next[0] ... foo bar foo bar foo bar foo bar @@ -952,7 +952,7 @@ arguments we get, and return 0 (incremental development ;-):: >>> def py_cmp_func(a, b): - ... print "py_cmp_func", a, b + ... print("py_cmp_func", a, b) ... return 0 ... >>> @@ -980,7 +980,7 @@ We know how to access the contents of a pointer, so lets redefine our callback:: >>> def py_cmp_func(a, b): - ... print "py_cmp_func", a[0], b[0] + ... print("py_cmp_func", a[0], b[0]) ... return 0 ... >>> cmp_func = CMPFUNC(py_cmp_func) @@ -1016,7 +1016,7 @@ return a useful result:: >>> def py_cmp_func(a, b): - ... print "py_cmp_func", a[0], b[0] + ... print("py_cmp_func", a[0], b[0]) ... return a[0] - b[0] ... >>> @@ -1051,7 +1051,7 @@ As we can easily check, our array is sorted now:: - >>> for i in ia: print i, + >>> for i in ia: print(i, end=" ") ... 1 5 7 33 99 >>> @@ -1078,7 +1078,7 @@ api:: >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag") - >>> print opt_flag + >>> print(opt_flag) c_long(0) >>> @@ -1121,7 +1121,7 @@ hit the NULL entry:: >>> for item in table: - ... print item.name, item.size + ... print(item.name, item.size) ... if item.name is None: ... break ... @@ -1156,11 +1156,11 @@ >>> p1 = POINT(1, 2) >>> p2 = POINT(3, 4) >>> rc = RECT(p1, p2) - >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y + >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y) 1 2 3 4 >>> # now swap the two points >>> rc.a, rc.b = rc.b, rc.a - >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y + >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y) 3 4 3 4 >>> @@ -1214,7 +1214,7 @@ ``ValueError`` is raised if this is tried:: >>> short_array = (c_short * 4)() - >>> print sizeof(short_array) + >>> print(sizeof(short_array)) 8 >>> resize(short_array, 4) Traceback (most recent call last): Modified: python/branches/py3k/Doc/library/dbhash.rst ============================================================================== --- python/branches/py3k/Doc/library/dbhash.rst (original) +++ python/branches/py3k/Doc/library/dbhash.rst Tue Sep 4 09:15:32 2007 @@ -96,9 +96,9 @@ prints every key in the database ``db``, without having to create a list in memory that contains them all:: - print db.first() + print(db.first()) for i in range(1, len(db)): - print db.next() + print(db.next()) .. method:: dbhash.previous() Modified: python/branches/py3k/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k/Doc/library/decimal.rst (original) +++ python/branches/py3k/Doc/library/decimal.rst Tue Sep 4 09:15:32 2007 @@ -1052,7 +1052,7 @@ def pi(): """Compute Pi to the current precision. - >>> print pi() + >>> print(pi()) 3.141592653589793238462643383 """ @@ -1071,13 +1071,13 @@ def exp(x): """Return e raised to the power of x. Result type matches input type. - >>> print exp(Decimal(1)) + >>> print(exp(Decimal(1))) 2.718281828459045235360287471 - >>> print exp(Decimal(2)) + >>> print(exp(Decimal(2))) 7.389056098930650227230427461 - >>> print exp(2.0) + >>> print(exp(2.0)) 7.38905609893 - >>> print exp(2+0j) + >>> print(exp(2+0j)) (7.38905609893+0j) """ @@ -1095,11 +1095,11 @@ def cos(x): """Return the cosine of x as measured in radians. - >>> print cos(Decimal('0.5')) + >>> print(cos(Decimal('0.5'))) 0.8775825618903727161162815826 - >>> print cos(0.5) + >>> print(cos(0.5)) 0.87758256189 - >>> print cos(0.5+0j) + >>> print(cos(0.5+0j)) (0.87758256189+0j) """ @@ -1118,11 +1118,11 @@ def sin(x): """Return the sine of x as measured in radians. - >>> print sin(Decimal('0.5')) + >>> print(sin(Decimal('0.5'))) 0.4794255386042030002732879352 - >>> print sin(0.5) + >>> print(sin(0.5)) 0.479425538604 - >>> print sin(0.5+0j) + >>> print(sin(0.5+0j)) (0.479425538604+0j) """ Modified: python/branches/py3k/Doc/library/difflib.rst ============================================================================== --- python/branches/py3k/Doc/library/difflib.rst (original) +++ python/branches/py3k/Doc/library/difflib.rst Tue Sep 4 09:15:32 2007 @@ -194,7 +194,7 @@ >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) - >>> print ''.join(diff), + >>> print(''.join(diff), end="") - one ? ^ + ore @@ -219,11 +219,11 @@ >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ... 'ore\ntree\nemu\n'.splitlines(1)) >>> diff = list(diff) # materialize the generated delta into a list - >>> print ''.join(restore(diff, 1)), + >>> print(''.join(restore(diff, 1)), end="") one two three - >>> print ''.join(restore(diff, 2)), + >>> print(''.join(restore(diff, 2)), end="") ore tree emu @@ -412,8 +412,8 @@ >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): - ... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % - ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])) + ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % + ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) delete a[0:1] (q) b[0:0] () equal a[1:3] (ab) b[0:2] (ab) replace a[3:4] (x) b[2:3] (y) @@ -488,14 +488,14 @@ sequences. As a rule of thumb, a :meth:`ratio` value over 0.6 means the sequences are close matches:: - >>> print round(s.ratio(), 3) + >>> print(round(s.ratio(), 3)) 0.866 If you're only interested in where the sequences match, :meth:`get_matching_blocks` is handy:: >>> for block in s.get_matching_blocks(): - ... print "a[%d] and b[%d] match for %d elements" % block + ... print("a[%d] and b[%d] match for %d elements" % block) a[0] and b[0] match for 8 elements a[8] and b[17] match for 6 elements a[14] and b[23] match for 15 elements @@ -509,7 +509,7 @@ :meth:`get_opcodes`:: >>> for opcode in s.get_opcodes(): - ... print "%6s a[%d:%d] b[%d:%d]" % opcode + ... print("%6s a[%d:%d] b[%d:%d]" % opcode) equal a[0:8] b[0:8] insert a[8:8] b[8:17] equal a[8:14] b[17:23] Modified: python/branches/py3k/Doc/library/doctest.rst ============================================================================== --- python/branches/py3k/Doc/library/doctest.rst (original) +++ python/branches/py3k/Doc/library/doctest.rst Tue Sep 4 09:15:32 2007 @@ -309,11 +309,11 @@ >>> x 12 >>> if x == 13: - ... print "yes" + ... print("yes") ... else: - ... print "no" - ... print "NO" - ... print "NO!!!" + ... print("no") + ... print("NO") + ... print("NO!!!") ... no NO @@ -340,7 +340,7 @@ >>> def f(x): ... r'''Backslashes in a raw docstring: m\n''' - >>> print f.__doc__ + >>> print(f.__doc__) Backslashes in a raw docstring: m\n Otherwise, the backslash will be interpreted as part of the string. For example, @@ -349,7 +349,7 @@ >>> def f(x): ... '''Backslashes in a raw docstring: m\\n''' - >>> print f.__doc__ + >>> print(f.__doc__) Backslashes in a raw docstring: m\n * The starting column doesn't matter:: @@ -639,7 +639,7 @@ For example, this test passes:: - >>> print range(20) #doctest: +NORMALIZE_WHITESPACE + >>> print(range(20)) #doctest: +NORMALIZE_WHITESPACE [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] @@ -648,18 +648,18 @@ is on a single line. This test also passes, and also requires a directive to do so:: - >>> print range(20) # doctest: +ELLIPSIS + >>> print(range(20)) # doctest: +ELLIPSIS [0, 1, ..., 18, 19] Multiple directives can be used on a single physical line, separated by commas:: - >>> print range(20) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + >>> print(range(20)) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE [0, 1, ..., 18, 19] If multiple directive comments are used for a single example, then they are combined:: - >>> print range(20) # doctest: +ELLIPSIS + >>> print(range(20)) # doctest: +ELLIPSIS ... # doctest: +NORMALIZE_WHITESPACE [0, 1, ..., 18, 19] @@ -667,7 +667,7 @@ containing only directives. This can be useful when an example is too long for a directive to comfortably fit on the same line:: - >>> print range(5) + range(10,20) + range(30,40) + range(50,60) + >>> print(range(5) + range(10,20) + range(30,40) + range(50,60)) ... # doctest: +ELLIPSIS [0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59] @@ -746,9 +746,9 @@ >>> 1./7 # risky 0.14285714285714285 - >>> print 1./7 # safer + >>> print(1./7) # safer 0.142857142857 - >>> print round(1./7, 6) # much safer + >>> print(round(1./7, 6)) # much safer 0.142857 Numbers of the form ``I/2.**J`` are safe across all platforms, and I often @@ -1518,7 +1518,7 @@ >>> def f(x): ... g(x*2) >>> def g(x): - ... print x+3 + ... print(x+3) ... import pdb; pdb.set_trace() >>> f(3) 9 @@ -1533,10 +1533,10 @@ -> import pdb; pdb.set_trace() (Pdb) list 1 def g(x): - 2 print x+3 + 2 print(x+3) 3 -> import pdb; pdb.set_trace() [EOF] - (Pdb) print x + (Pdb) p x 6 (Pdb) step --Return-- @@ -1546,7 +1546,7 @@ 1 def f(x): 2 -> g(x*2) [EOF] - (Pdb) print x + (Pdb) p x 3 (Pdb) step --Return-- @@ -1571,14 +1571,14 @@ returned as a string. For example, :: import doctest - print doctest.script_from_examples(r""" + print(doctest.script_from_examples(r""" Set x and y to 1 and 2. >>> x, y = 1, 2 Print their sum: - >>> print x+y + >>> print(x+y) 3 - """) + """)) displays:: @@ -1586,7 +1586,7 @@ x, y = 1, 2 # # Print their sum: - print x+y + print(x+y) # Expected: ## 3 @@ -1607,7 +1607,7 @@ contains a top-level function :func:`f`, then :: import a, doctest - print doctest.testsource(a, "a.f") + print(doctest.testsource(a, "a.f")) prints a script version of function :func:`f`'s docstring, with doctests converted to code, and the rest placed in comments. Modified: python/branches/py3k/Doc/library/email.generator.rst ============================================================================== --- python/branches/py3k/Doc/library/email.generator.rst (original) +++ python/branches/py3k/Doc/library/email.generator.rst Tue Sep 4 09:15:32 2007 @@ -27,7 +27,7 @@ The constructor for the :class:`Generator` class takes a file-like object called *outfp* for an argument. *outfp* must support the :meth:`write` method and be - usable as the output file in a Python extended print statement. + usable as the output file for the :func:`print` function. Optional *mangle_from_* is a flag that, when ``True``, puts a ``>`` character in front of any line in the body that starts exactly as ``From``, i.e. ``From`` @@ -72,7 +72,7 @@ Write the string *s* to the underlying file object, i.e. *outfp* passed to :class:`Generator`'s constructor. This provides just enough file-like API for - :class:`Generator` instances to be used in extended print statements. + :class:`Generator` instances to be used in the :func:`print` function. As a convenience, see the methods :meth:`Message.as_string` and ``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation Modified: python/branches/py3k/Doc/library/email.header.rst ============================================================================== --- python/branches/py3k/Doc/library/email.header.rst (original) +++ python/branches/py3k/Doc/library/email.header.rst Tue Sep 4 09:15:32 2007 @@ -31,7 +31,7 @@ >>> msg = Message() >>> h = Header('p\xf6stal', 'iso-8859-1') >>> msg['Subject'] = h - >>> print msg.as_string() + >>> print(msg.as_string()) Subject: =?iso-8859-1?q?p=F6stal?= Modified: python/branches/py3k/Doc/library/email.iterators.rst ============================================================================== --- python/branches/py3k/Doc/library/email.iterators.rst (original) +++ python/branches/py3k/Doc/library/email.iterators.rst Tue Sep 4 09:15:32 2007 @@ -60,6 +60,6 @@ text/plain text/plain - Optional *fp* is a file-like object to print the output to. It must be suitable - for Python's extended print statement. *level* is used internally. + Optional *fp* is a file-like object to print the output to. It must be + suitable for Python's :func:`print` function. *level* is used internally. Modified: python/branches/py3k/Doc/library/email.message.rst ============================================================================== --- python/branches/py3k/Doc/library/email.message.rst (original) +++ python/branches/py3k/Doc/library/email.message.rst Tue Sep 4 09:15:32 2007 @@ -167,7 +167,7 @@ the ``in`` operator, e.g.:: if 'message-id' in myMessage: - print 'Message-ID:', myMessage['message-id'] + print('Message-ID:', myMessage['message-id']) .. method:: Message.__getitem__(name) @@ -458,7 +458,7 @@ structure:: >>> for part in msg.walk(): - ... print part.get_content_type() + ... print(part.get_content_type()) multipart/report text/plain message/delivery-status Modified: python/branches/py3k/Doc/library/fnmatch.rst ============================================================================== --- python/branches/py3k/Doc/library/fnmatch.rst (original) +++ python/branches/py3k/Doc/library/fnmatch.rst Tue Sep 4 09:15:32 2007 @@ -51,7 +51,7 @@ for file in os.listdir('.'): if fnmatch.fnmatch(file, '*.txt'): - print file + print(file) .. function:: fnmatchcase(filename, pattern) @@ -78,7 +78,7 @@ >>> regex '.*\\.txt$' >>> reobj = re.compile(regex) - >>> print reobj.match('foobar.txt') + >>> print(reobj.match('foobar.txt')) <_sre.SRE_Match object at 0x...> Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Tue Sep 4 09:15:32 2007 @@ -325,7 +325,7 @@ ``(1, seq[1])``, ``(2, seq[2])``, .... For example:: >>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter')]: - >>> print i, season + >>> print(i, season) 0 Spring 1 Summer 2 Fall @@ -350,7 +350,7 @@ the evaluated expression. Syntax errors are reported as exceptions. Example:: >>> x = 1 - >>> print eval('x+1') + >>> eval('x+1') 2 This function can also be used to execute arbitrary code objects (such as those Modified: python/branches/py3k/Doc/library/functools.rst ============================================================================== --- python/branches/py3k/Doc/library/functools.rst (original) +++ python/branches/py3k/Doc/library/functools.rst Tue Sep 4 09:15:32 2007 @@ -92,14 +92,14 @@ >>> def my_decorator(f): ... @wraps(f) ... def wrapper(*args, **kwds): - ... print 'Calling decorated function' + ... print('Calling decorated function') ... return f(*args, **kwds) ... return wrapper ... >>> @my_decorator ... def example(): ... """Docstring""" - ... print 'Called example function' + ... print('Called example function') ... >>> example() Calling decorated function Modified: python/branches/py3k/Doc/library/gdbm.rst ============================================================================== --- python/branches/py3k/Doc/library/gdbm.rst (original) +++ python/branches/py3k/Doc/library/gdbm.rst Tue Sep 4 09:15:32 2007 @@ -93,7 +93,7 @@ k = db.firstkey() while k != None: - print k + print(k) k = db.nextkey(k) Modified: python/branches/py3k/Doc/library/getopt.rst ============================================================================== --- python/branches/py3k/Doc/library/getopt.rst (original) +++ python/branches/py3k/Doc/library/getopt.rst Tue Sep 4 09:15:32 2007 @@ -112,7 +112,7 @@ opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) except getopt.GetoptError as err: # print help information and exit: - print str(err) # will print something like "option -a not recognized" + print(err) # will print something like "option -a not recognized" usage() sys.exit(2) output = None Modified: python/branches/py3k/Doc/library/gettext.rst ============================================================================== --- python/branches/py3k/Doc/library/gettext.rst (original) +++ python/branches/py3k/Doc/library/gettext.rst Tue Sep 4 09:15:32 2007 @@ -126,7 +126,7 @@ gettext.textdomain('myapplication') _ = gettext.gettext # ... - print _('This is a translatable string.') + print(_('This is a translatable string.')) Class-based API @@ -201,7 +201,7 @@ candidates for translation, by wrapping them in a call to the :func:`_` function, like this:: - print _('This string will be translated.') + print(_('This string will be translated.')) For convenience, you want the :func:`_` function to be installed in Python's builtin namespace, so it is easily accessible in all modules of your @@ -446,7 +446,7 @@ import gettext cat = gettext.Catalog(domain, localedir) _ = cat.gettext - print _('hello world') + print(_('hello world')) For compatibility with this older module, the function :func:`Catalog` is an alias for the :func:`translation` function described above. @@ -604,7 +604,7 @@ ] # ... for a in animals: - print a + print(a) Here, you want to mark the strings in the ``animals`` list as being translatable, but you don't actually want to translate them until they are @@ -625,7 +625,7 @@ # ... for a in animals: - print _(a) + print(_(a)) This works because the dummy definition of :func:`_` simply returns the string unchanged. And this dummy definition will temporarily override any definition @@ -649,7 +649,7 @@ # ... for a in animals: - print _(a) + print(_(a)) In this case, you are marking translatable strings with the function :func:`N_`, [#]_ which won't conflict with any definition of :func:`_`. However, you will Modified: python/branches/py3k/Doc/library/heapq.rst ============================================================================== --- python/branches/py3k/Doc/library/heapq.rst (original) +++ python/branches/py3k/Doc/library/heapq.rst Tue Sep 4 09:15:32 2007 @@ -77,10 +77,10 @@ >>> while heap: ... ordered.append(heappop(heap)) ... - >>> print ordered + >>> ordered [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> data.sort() - >>> print data == ordered + >>> data == ordered True >>> Modified: python/branches/py3k/Doc/library/htmlparser.rst ============================================================================== --- python/branches/py3k/Doc/library/htmlparser.rst (original) +++ python/branches/py3k/Doc/library/htmlparser.rst Tue Sep 4 09:15:32 2007 @@ -171,8 +171,8 @@ class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): - print "Encountered the beginning of a %s tag" % tag + print("Encountered the beginning of a %s tag" % tag) def handle_endtag(self, tag): - print "Encountered the end of a %s tag" % tag + print("Encountered the end of a %s tag" % tag) Modified: python/branches/py3k/Doc/library/httplib.rst ============================================================================== --- python/branches/py3k/Doc/library/httplib.rst (original) +++ python/branches/py3k/Doc/library/httplib.rst Tue Sep 4 09:15:32 2007 @@ -475,12 +475,12 @@ >>> conn = httplib.HTTPConnection("www.python.org") >>> conn.request("GET", "/index.html") >>> r1 = conn.getresponse() - >>> print r1.status, r1.reason + >>> print(r1.status, r1.reason) 200 OK >>> data1 = r1.read() >>> conn.request("GET", "/parrot.spam") >>> r2 = conn.getresponse() - >>> print r2.status, r2.reason + >>> print(r2.status, r2.reason) 404 Not Found >>> data2 = r2.read() >>> conn.close() @@ -494,7 +494,7 @@ >>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80") >>> conn.request("POST", "/cgi-bin/query", params, headers) >>> response = conn.getresponse() - >>> print response.status, response.reason + >>> print(response.status, response.reason) 200 OK >>> data = response.read() >>> conn.close() Modified: python/branches/py3k/Doc/library/imaplib.rst ============================================================================== --- python/branches/py3k/Doc/library/imaplib.rst (original) +++ python/branches/py3k/Doc/library/imaplib.rst Tue Sep 4 09:15:32 2007 @@ -511,7 +511,7 @@ typ, data = M.search(None, 'ALL') for num in data[0].split(): typ, data = M.fetch(num, '(RFC822)') - print 'Message %s\n%s\n' % (num, data[0][1]) + print('Message %s\n%s\n' % (num, data[0][1])) M.close() M.logout() Modified: python/branches/py3k/Doc/library/itertools.rst ============================================================================== --- python/branches/py3k/Doc/library/itertools.rst (original) +++ python/branches/py3k/Doc/library/itertools.rst Tue Sep 4 09:15:32 2007 @@ -385,7 +385,7 @@ >>> amounts = [120.15, 764.05, 823.14] >>> for checknum, amount in izip(count(1200), amounts): - ... print 'Check %d is for $%.2f' % (checknum, amount) + ... print('Check %d is for $%.2f' % (checknum, amount)) ... Check 1200 is for $120.15 Check 1201 is for $764.05 @@ -393,7 +393,7 @@ >>> import operator >>> for cube in imap(operator.pow, range(1,5), repeat(3)): - ... print cube + ... print(cube) ... 1 8 @@ -403,7 +403,7 @@ >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', ... '', 'martin', '', 'walter', '', 'mark'] >>> for name in islice(reportlines, 3, None, 2): - ... print name.title() + ... print(name.title()) ... Alex Laura @@ -416,7 +416,7 @@ >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) >>> di = sorted(d.iteritems(), key=itemgetter(1)) >>> for k, g in groupby(di, key=itemgetter(1)): - ... print k, map(itemgetter(0), g) + ... print(k, map(itemgetter(0), g)) ... 1 ['a', 'c', 'e'] 2 ['b', 'd', 'f'] @@ -427,7 +427,7 @@ # same group. >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]): - ... print map(operator.itemgetter(1), g) + ... print(map(operator.itemgetter(1), g)) ... [1] [4, 5, 6] Modified: python/branches/py3k/Doc/library/logging.rst ============================================================================== --- python/branches/py3k/Doc/library/logging.rst (original) +++ python/branches/py3k/Doc/library/logging.rst Tue Sep 4 09:15:32 2007 @@ -841,7 +841,7 @@ logging.basicConfig( format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s") tcpserver = LogRecordSocketReceiver() - print "About to start TCP server..." + print("About to start TCP server...") tcpserver.serve_until_stopped() if __name__ == "__main__": Modified: python/branches/py3k/Doc/library/macosa.rst ============================================================================== --- python/branches/py3k/Doc/library/macosa.rst (original) +++ python/branches/py3k/Doc/library/macosa.rst Tue Sep 4 09:15:32 2007 @@ -31,7 +31,7 @@ import Finder f = Finder.Finder() - print f.get(f.window(1).name) + print(f.get(f.window(1).name)) As distributed the Python library includes packages that implement the standard suites, plus packages that interface to a small number of common applications. Modified: python/branches/py3k/Doc/library/mailbox.rst ============================================================================== --- python/branches/py3k/Doc/library/mailbox.rst (original) +++ python/branches/py3k/Doc/library/mailbox.rst Tue Sep 4 09:15:32 2007 @@ -1620,7 +1620,7 @@ for message in mailbox.mbox('~/mbox'): subject = message['subject'] # Could possibly be None. if subject and 'python' in subject.lower(): - print subject + print(subject) To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the format-specific information that can be converted:: Modified: python/branches/py3k/Doc/library/nntplib.rst ============================================================================== --- python/branches/py3k/Doc/library/nntplib.rst (original) +++ python/branches/py3k/Doc/library/nntplib.rst Tue Sep 4 09:15:32 2007 @@ -20,10 +20,10 @@ >>> s = NNTP('news.cwi.nl') >>> resp, count, first, last, name = s.group('comp.lang.python') - >>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last + >>> print('Group', name, 'has', count, 'articles, range', first, 'to', last) Group comp.lang.python has 59 articles, range 3742 to 3803 >>> resp, subs = s.xhdr('subject', first + '-' + last) - >>> for id, sub in subs[-10:]: print id, sub + >>> for id, sub in subs[-10:]: print(id, sub) ... 3792 Re: Removing elements from a list while iterating... 3793 Re: Who likes Info files? Modified: python/branches/py3k/Doc/library/optparse.rst ============================================================================== --- python/branches/py3k/Doc/library/optparse.rst (original) +++ python/branches/py3k/Doc/library/optparse.rst Tue Sep 4 09:15:32 2007 @@ -348,7 +348,7 @@ ``"-n 42"`` (two arguments), the code :: (options, args) = parser.parse_args(["-n42"]) - print options.num + print(options.num) will print ``"42"``. @@ -646,7 +646,7 @@ if len(args) != 1: parser.error("incorrect number of arguments") if options.verbose: - print "reading %s..." % options.filename + print("reading %s..." % options.filename) [...] if __name__ == "__main__": Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Tue Sep 4 09:15:32 2007 @@ -1215,9 +1215,9 @@ import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): - print root, "consumes", - print sum(getsize(join(root, name)) for name in files), - print "bytes in", len(files), "non-directory files" + print(root, "consumes", end=" ") + print(sum(getsize(join(root, name)) for name in files), end=" ") + print("bytes in", len(files), "non-directory files") if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories Modified: python/branches/py3k/Doc/library/pickle.rst ============================================================================== --- python/branches/py3k/Doc/library/pickle.rst (original) +++ python/branches/py3k/Doc/library/pickle.rst Tue Sep 4 09:15:32 2007 @@ -574,11 +574,11 @@ return 'My name is integer %d' % self.x i = Integer(7) - print i + print(i) p.dump(i) datastream = src.getvalue() - print repr(datastream) + print(repr(datastream)) dst = StringIO(datastream) up = pickle.Unpickler(dst) @@ -597,7 +597,7 @@ up.persistent_load = persistent_load j = up.load() - print j + print(j) In the :mod:`cPickle` module, the unpickler's :attr:`persistent_load` attribute can also be set to a Python list, in which case, when the unpickler reaches a Modified: python/branches/py3k/Doc/library/poplib.rst ============================================================================== --- python/branches/py3k/Doc/library/poplib.rst (original) +++ python/branches/py3k/Doc/library/poplib.rst Tue Sep 4 09:15:32 2007 @@ -191,7 +191,7 @@ numMessages = len(M.list()[1]) for i in range(numMessages): for j in M.retr(i+1)[1]: - print j + print(j) At the end of the module, there is a test section that contains a more extensive example of usage. Modified: python/branches/py3k/Doc/library/pprint.rst ============================================================================== --- python/branches/py3k/Doc/library/pprint.rst (original) +++ python/branches/py3k/Doc/library/pprint.rst Tue Sep 4 09:15:32 2007 @@ -85,9 +85,10 @@ .. function:: pprint(object[, stream[, indent[, width[, depth]]]]) Prints the formatted representation of *object* on *stream*, followed by a - newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used in - the interactive interpreter instead of a :keyword:`print` statement for - inspecting values. *indent*, *width* and *depth* will be passed to the + newline. If *stream* is omitted, ``sys.stdout`` is used. This may be used + in the interactive interpreter instead of the :func:`print` function for + inspecting values (you can even reassign ``print = pprint.pprint`` for use + within a scope). *indent*, *width* and *depth* will be passed to the :class:`PrettyPrinter` constructor as formatting parameters. :: >>> stuff = sys.path[:] Modified: python/branches/py3k/Doc/library/profile.rst ============================================================================== --- python/branches/py3k/Doc/library/profile.rst (original) +++ python/branches/py3k/Doc/library/profile.rst Tue Sep 4 09:15:32 2007 @@ -577,7 +577,7 @@ import profile pr = profile.Profile() for i in range(5): - print pr.calibrate(10000) + print(pr.calibrate(10000)) The method executes the number of Python calls given by the argument, directly and again under the profiler, measuring the time for both. It then computes the Modified: python/branches/py3k/Doc/library/pyexpat.rst ============================================================================== --- python/branches/py3k/Doc/library/pyexpat.rst (original) +++ python/branches/py3k/Doc/library/pyexpat.rst Tue Sep 4 09:15:32 2007 @@ -494,11 +494,11 @@ # 3 handler functions def start_element(name, attrs): - print 'Start element:', name, attrs + print('Start element:', name, attrs) def end_element(name): - print 'End element:', name + print('End element:', name) def char_data(data): - print 'Character data:', repr(data) + print('Character data:', repr(data)) p = xml.parsers.expat.ParserCreate() Modified: python/branches/py3k/Doc/library/repr.rst ============================================================================== --- python/branches/py3k/Doc/library/repr.rst (original) +++ python/branches/py3k/Doc/library/repr.rst Tue Sep 4 09:15:32 2007 @@ -129,5 +129,5 @@ return `obj` aRepr = MyRepr() - print aRepr.repr(sys.stdin) # prints '' + print(aRepr.repr(sys.stdin)) # prints '' Modified: python/branches/py3k/Doc/library/rlcompleter.rst ============================================================================== --- python/branches/py3k/Doc/library/rlcompleter.rst (original) +++ python/branches/py3k/Doc/library/rlcompleter.rst Tue Sep 4 09:15:32 2007 @@ -33,7 +33,7 @@ try: import readline except ImportError: - print "Module readline not available." + print("Module readline not available.") else: import rlcompleter readline.parse_and_bind("tab: complete") Modified: python/branches/py3k/Doc/library/sched.rst ============================================================================== --- python/branches/py3k/Doc/library/sched.rst (original) +++ python/branches/py3k/Doc/library/sched.rst Tue Sep 4 09:15:32 2007 @@ -30,14 +30,14 @@ >>> import sched, time >>> s=sched.scheduler(time.time, time.sleep) - >>> def print_time(): print "From print_time", time.time() + >>> def print_time(): print("From print_time", time.time()) ... >>> def print_some_times(): - ... print time.time() + ... print(time.time()) ... s.enter(5, 1, print_time, ()) ... s.enter(10, 1, print_time, ()) ... s.run() - ... print time.time() + ... print(time.time()) ... >>> print_some_times() 930343690.257 Modified: python/branches/py3k/Doc/library/signal.rst ============================================================================== --- python/branches/py3k/Doc/library/signal.rst (original) +++ python/branches/py3k/Doc/library/signal.rst Tue Sep 4 09:15:32 2007 @@ -143,7 +143,7 @@ import signal, os def handler(signum, frame): - print 'Signal handler called with signal', signum + print('Signal handler called with signal', signum) raise IOError("Couldn't open device!") # Set the signal handler and a 5-second alarm Modified: python/branches/py3k/Doc/library/simplexmlrpcserver.rst ============================================================================== --- python/branches/py3k/Doc/library/simplexmlrpcserver.rst (original) +++ python/branches/py3k/Doc/library/simplexmlrpcserver.rst Tue Sep 4 09:15:32 2007 @@ -143,12 +143,12 @@ import xmlrpclib s = xmlrpclib.Server('http://localhost:8000') - print s.pow(2,3) # Returns 2**3 = 8 - print s.add(2,3) # Returns 5 - print s.div(5,2) # Returns 5//2 = 2 + print(s.pow(2,3)) # Returns 2**3 = 8 + print(s.add(2,3)) # Returns 5 + print(s.div(5,2)) # Returns 5//2 = 2 # Print list of available methods - print s.system.listMethods() + print(s.system.listMethods()) CGIXMLRPCRequestHandler Modified: python/branches/py3k/Doc/library/smtplib.rst ============================================================================== --- python/branches/py3k/Doc/library/smtplib.rst (original) +++ python/branches/py3k/Doc/library/smtplib.rst Tue Sep 4 09:15:32 2007 @@ -317,7 +317,7 @@ fromaddr = prompt("From: ") toaddrs = prompt("To: ").split() - print "Enter message, end with ^D (Unix) or ^Z (Windows):" + print("Enter message, end with ^D (Unix) or ^Z (Windows):") # Add the From: and To: headers at the start! msg = ("From: %s\r\nTo: %s\r\n\r\n" @@ -331,7 +331,7 @@ break msg = msg + line - print "Message length is " + repr(len(msg)) + print("Message length is", len(msg)) server = smtplib.SMTP('localhost') server.set_debuglevel(1) Modified: python/branches/py3k/Doc/library/socket.rst ============================================================================== --- python/branches/py3k/Doc/library/socket.rst (original) +++ python/branches/py3k/Doc/library/socket.rst Tue Sep 4 09:15:32 2007 @@ -730,7 +730,7 @@ s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() - print 'Connected by', addr + print('Connected by', addr) while 1: data = conn.recv(1024) if not data: break @@ -749,7 +749,7 @@ s.send('Hello, world') data = s.recv(1024) s.close() - print 'Received', repr(data) + print('Received', repr(data)) The next two examples are identical to the above two, but support both IPv4 and IPv6. The server side will listen to the first address family available (it @@ -781,10 +781,10 @@ continue break if s is None: - print 'could not open socket' + print('could not open socket') sys.exit(1) conn, addr = s.accept() - print 'Connected by', addr + print('Connected by', addr) while 1: data = conn.recv(1024) if not data: break @@ -815,10 +815,10 @@ continue break if s is None: - print 'could not open socket' + print('could not open socket') sys.exit(1) s.send('Hello, world') data = s.recv(1024) s.close() - print 'Received', repr(data) + print('Received', repr(data)) Modified: python/branches/py3k/Doc/library/sqlite3.rst ============================================================================== --- python/branches/py3k/Doc/library/sqlite3.rst (original) +++ python/branches/py3k/Doc/library/sqlite3.rst Tue Sep 4 09:15:32 2007 @@ -79,7 +79,7 @@ >>> c = conn.cursor() >>> c.execute('select * from stocks order by price') >>> for row in c: - ... print row + ... print(row) ... (u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001) (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0) Modified: python/branches/py3k/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k/Doc/library/ssl.rst (original) +++ python/branches/py3k/Doc/library/ssl.rst Tue Sep 4 09:15:32 2007 @@ -297,8 +297,8 @@ ssl_sock.connect(('www.verisign.com', 443)) - print repr(ssl_sock.getpeername()) - print pprint.pformat(ssl_sock.getpeercert()) + print(repr(ssl_sock.getpeername())) + pprint.pprint(ssl_sock.getpeercert()) # Set a simple HTTP request -- use httplib in actual code. ssl_sock.write("""GET / HTTP/1.0\r Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Tue Sep 4 09:15:32 2007 @@ -22,8 +22,6 @@ The principal built-in types are numerics, sequences, mappings, files, classes, instances and exceptions. -.. index:: statement: print - Some operations are supported by several object types; in particular, practically all objects can be compared, tested for truth value, and converted to a string (with the :func:`repr` function or the slightly different @@ -1976,7 +1974,7 @@ A file object is its own iterator, for example ``iter(f)`` returns *f* (unless *f* is closed). When a file is used as an iterator, typically in a - :keyword:`for` loop (for example, ``for line in f: print line``), the + :keyword:`for` loop (for example, ``for line in f: print(line)``), the :meth:`__next__` method is called repeatedly. This method returns the next input line, or raises :exc:`StopIteration` when EOF is hit when the file is open for reading (behavior is undefined when the file is open for writing). In order @@ -2133,23 +2131,6 @@ mode the value of this attribute will be ``None``. -.. attribute:: file.softspace - - Boolean that indicates whether a space character needs to be printed before - another value when using the :keyword:`print` statement. Classes that are trying - to simulate a file object should also have a writable :attr:`softspace` - attribute, which should be initialized to zero. This will be automatic for most - classes implemented in Python (care may be needed for objects that override - attribute access); types implemented in C will have to provide a writable - :attr:`softspace` attribute. - - .. note:: - - This attribute is not used to control the :keyword:`print` statement, but to - allow the implementation of :keyword:`print` to keep track of its internal - state. - - .. _typecontextmanager: Context Manager Types Modified: python/branches/py3k/Doc/library/sys.rst ============================================================================== --- python/branches/py3k/Doc/library/sys.rst (original) +++ python/branches/py3k/Doc/library/sys.rst Tue Sep 4 09:15:32 2007 @@ -495,7 +495,7 @@ File objects corresponding to the interpreter's standard input, output and error streams. ``stdin`` is used for all interpreter input except for scripts. - ``stdout`` is used for the output of :keyword:`print` and expression statements. + ``stdout`` is used for the output of :func:`print` and expression statements. The interpreter's own prompts and (almost all of) its error messages go to ``stderr``. ``stdout`` and ``stderr`` needn't be built-in file objects: any object is acceptable as long as it has a :meth:`write` method that takes a Modified: python/branches/py3k/Doc/library/tabnanny.rst ============================================================================== --- python/branches/py3k/Doc/library/tabnanny.rst (original) +++ python/branches/py3k/Doc/library/tabnanny.rst Tue Sep 4 09:15:32 2007 @@ -26,9 +26,9 @@ If *file_or_dir* is a directory and not a symbolic link, then recursively descend the directory tree named by *file_or_dir*, checking all :file:`.py` - files along the way. If *file_or_dir* is an ordinary Python source file, it is - checked for whitespace related problems. The diagnostic messages are written to - standard output using the print statement. + files along the way. If *file_or_dir* is an ordinary Python source file, it + is checked for whitespace related problems. The diagnostic messages are + written to standard output using the :func:`print` function. .. data:: verbose Modified: python/branches/py3k/Doc/library/tokenize.rst ============================================================================== --- python/branches/py3k/Doc/library/tokenize.rst (original) +++ python/branches/py3k/Doc/library/tokenize.rst Tue Sep 4 09:15:32 2007 @@ -90,9 +90,9 @@ """Substitute Decimals for floats in a string of statements. >>> from decimal import Decimal - >>> s = 'print +21.3e-5*-.1234/81.7' + >>> s = 'print(+21.3e-5*-.1234/81.7)' >>> decistmt(s) - "print +Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7')" + "print(+Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7'))" >>> exec(s) -3.21716034272e-007 Modified: python/branches/py3k/Doc/reference/compound_stmts.rst ============================================================================== --- python/branches/py3k/Doc/reference/compound_stmts.rst (original) +++ python/branches/py3k/Doc/reference/compound_stmts.rst Tue Sep 4 09:15:32 2007 @@ -32,13 +32,13 @@ mostly because it wouldn't be clear to which :keyword:`if` clause a following :keyword:`else` clause would belong: :: - if test1: if test2: print x + if test1: if test2: print(x) Also note that the semicolon binds tighter than the colon in this context, so -that in the following example, either all or none of the :keyword:`print` -statements are executed:: +that in the following example, either all or none of the :func:`print` calls are +executed:: - if x < y < z: print x; print y; print z + if x < y < z: print(x); print(y); print(z) Summarizing: Modified: python/branches/py3k/Doc/reference/expressions.rst ============================================================================== --- python/branches/py3k/Doc/reference/expressions.rst (original) +++ python/branches/py3k/Doc/reference/expressions.rst Tue Sep 4 09:15:32 2007 @@ -376,7 +376,7 @@ generator functions:: >>> def echo(value=None): - ... print "Execution starts when 'next()' is called for the first time." + ... print("Execution starts when 'next()' is called for the first time.") ... try: ... while True: ... try: @@ -387,15 +387,15 @@ ... except Exception, e: ... value = e ... finally: - ... print "Don't forget to clean up when 'close()' is called." + ... print("Don't forget to clean up when 'close()' is called.") ... >>> generator = echo(1) - >>> print generator.next() + >>> print(generator.next()) Execution starts when 'next()' is called for the first time. 1 - >>> print generator.next() + >>> print(generator.next()) None - >>> print generator.send(2) + >>> print(generator.send(2)) 2 >>> generator.throw(TypeError, "spam") TypeError('spam',) @@ -640,7 +640,7 @@ (and the ``**expression`` argument, if any -- see below). So:: >>> def f(a, b): - ... print a, b + ... print(a, b) ... >>> f(b=1, *(2,)) 2 1 Modified: python/branches/py3k/Doc/reference/simple_stmts.rst ============================================================================== --- python/branches/py3k/Doc/reference/simple_stmts.rst (original) +++ python/branches/py3k/Doc/reference/simple_stmts.rst Tue Sep 4 09:15:32 2007 @@ -254,7 +254,7 @@ x = [0, 1] i = 0 i, x[i] = 1, 2 - print x + print(x) .. _augassign: Modified: python/branches/py3k/Doc/tutorial/errors.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/errors.rst (original) +++ python/branches/py3k/Doc/tutorial/errors.rst Tue Sep 4 09:15:32 2007 @@ -26,7 +26,7 @@ The parser repeats the offending line and displays a little 'arrow' pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token *preceding* the arrow: in the -example, the error is detected at the keyword :keyword:`print`, since a colon +example, the error is detected at the function :func:`print`, since a colon (``':'``) is missing before it. File name and line number are printed so you know where to look in case the input came from a script. @@ -181,8 +181,8 @@ ... print(inst.args) # arguments stored in .args ... print(inst) # __str__ allows args to be printed directly ... x, y = inst # __getitem__ allows args to be unpacked directly - ... print 'x =', x - ... print 'y =', y + ... print('x =', x) + ... print('y =', y) ... ('spam', 'eggs') @@ -260,7 +260,7 @@ >>> try: ... raise MyError(2*2) ... except MyError as e: - ... print 'My exception occurred, value:', e.value + ... print('My exception occurred, value:', e.value) ... My exception occurred, value: 4 >>> raise MyError, 'oops!' Modified: python/branches/py3k/Doc/tutorial/floatingpoint.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/floatingpoint.rst (original) +++ python/branches/py3k/Doc/tutorial/floatingpoint.rst Tue Sep 4 09:15:32 2007 @@ -85,7 +85,7 @@ you may wish to use that instead. It's unusual for ``eval(str(x))`` to reproduce *x*, but the output may be more pleasant to look at:: - >>> print str(0.1) + >>> print(str(0.1)) 0.1 It's important to realize that this is, in a real sense, an illusion: the value Modified: python/branches/py3k/Doc/tutorial/inputoutput.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/inputoutput.rst (original) +++ python/branches/py3k/Doc/tutorial/inputoutput.rst Tue Sep 4 09:15:32 2007 @@ -132,7 +132,7 @@ Using the ``%`` operator looks like this:: >>> import math - >>> print 'The value of PI is approximately %5.3f.' % math.pi + >>> print('The value of PI is approximately %5.3f.' % math.pi) The value of PI is approximately 3.142. If there is more than one format in the string, you need to pass a tuple as @@ -140,7 +140,7 @@ >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} >>> for name, phone in table.items(): - ... print '%-10s ==> %10d' % (name, phone) + ... print('%-10s ==> %10d' % (name, phone)) ... Jack ==> 4098 Dcab ==> 7678 @@ -159,7 +159,7 @@ shown here:: >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} - >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table + >>> print('Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table) Jack: 4098; Sjoerd: 4127; Dcab: 8637678 This is particularly useful in combination with the new built-in :func:`vars` Modified: python/branches/py3k/Doc/tutorial/interpreter.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/interpreter.rst (original) +++ python/branches/py3k/Doc/tutorial/interpreter.rst Tue Sep 4 09:15:32 2007 @@ -111,7 +111,7 @@ >>> the_world_is_flat = 1 >>> if the_world_is_flat: - ... print "Be careful not to fall off!" + ... print("Be careful not to fall off!") ... Be careful not to fall off! @@ -170,6 +170,8 @@ Source Code Encoding -------------------- +.. XXX out of date! + It is possible to use encodings different than ASCII in Python source files. The best way to do it is to put one more special comment line right after the ``#!`` line to define the source file encoding:: @@ -191,7 +193,7 @@ # -*- coding: iso-8859-15 -*- currency = u"?" - print ord(currency) + print(ord(currency)) If your editor supports saving files as ``UTF-8`` with a UTF-8 *byte order mark* (aka BOM), you can use that instead of an encoding declaration. IDLE supports Modified: python/branches/py3k/Doc/tutorial/stdlib2.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/stdlib2.rst (original) +++ python/branches/py3k/Doc/tutorial/stdlib2.rst Tue Sep 4 09:15:32 2007 @@ -44,7 +44,7 @@ ... a list of strings instead of one big string with newlines to separate ... the wrapped lines.""" ... - >>> print textwrap.fill(doc, width=40) + >>> print(textwrap.fill(doc, width=40)) The wrap() method is just like fill() except that it returns a list of strings instead of one big string with newlines @@ -121,7 +121,7 @@ >>> for i, filename in enumerate(photofiles): ... base, ext = os.path.splitext(filename) ... newname = t.substitute(d=date, n=i, f=ext) - ... print '%s --> %s' % (filename, newname) + ... print('%s --> %s' % (filename, newname)) img_1074.jpg --> Ashley_0.jpg img_1076.jpg --> Ashley_1.jpg @@ -155,7 +155,7 @@ filename = data[start:start+filenamesize] start += filenamesize extra = data[start:start+extra_size] - print filename, hex(crc32), comp_size, uncomp_size + print(filename, hex(crc32), comp_size, uncomp_size) start += extra_size + comp_size # skip to the next header From python-3000-checkins at python.org Tue Sep 4 09:23:09 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 4 Sep 2007 09:23:09 +0200 (CEST) Subject: [Python-3000-checkins] r57951 - python/branches/py3k/Doc/library/types.rst Message-ID: <20070904072309.E4E1C1E4009@bag.python.org> Author: georg.brandl Date: Tue Sep 4 09:23:09 2007 New Revision: 57951 Modified: python/branches/py3k/Doc/library/types.rst Log: Fix up the types module docs. Modified: python/branches/py3k/Doc/library/types.rst ============================================================================== --- python/branches/py3k/Doc/library/types.rst (original) +++ python/branches/py3k/Doc/library/types.rst Tue Sep 4 09:23:09 2007 @@ -42,11 +42,17 @@ .. data:: TypeType + ClassType .. index:: builtin: type - The type of type objects (such as returned by :func:`type`); alias of the - built-in :class:`type`. + The type of type objects (such as returned by :func:`type`) and user-defined + classes without metaclass; alias of the built-in :class:`type`. + + +.. data:: ObjectType + + Alias of the built-in :func:`object`. .. data:: BooleanType @@ -56,15 +62,11 @@ .. data:: IntType + LongType The type of integers (e.g. ``1``); alias of the built-in :class:`int`. -.. data:: LongType - - The type of long integers (e.g. ``1L``); alias of the built-in :class:`long`. - - .. data:: FloatType The type of floating point numbers (e.g. ``1.0``); alias of the built-in @@ -73,8 +75,9 @@ .. data:: ComplexType - The type of complex numbers (e.g. ``1.0j``). This is not defined if Python was - built without complex number support. + The type of complex numbers (e.g. ``1.0j``); alias of the built-in + :class:`complex`. This is not defined if Python was built without complex + number support. .. data:: StringType @@ -96,26 +99,18 @@ .. data:: DictType + DictionaryType The type of dictionaries (e.g. ``{'Bacon': 1, 'Ham': 0}``); alias of the built-in :class:`dict`. -.. data:: DictionaryType - - An alternate name for ``DictType``. - - .. data:: FunctionType + LambdaType The type of user-defined functions and lambdas. -.. data:: LambdaType - - An alternate name for ``FunctionType``. - - .. data:: GeneratorType The type of generator-iterator objects, produced by calling a generator @@ -129,50 +124,23 @@ The type for code objects such as returned by :func:`compile`. -.. data:: ClassType - - The type of user-defined classes. - - .. data:: MethodType + UnboundMethdType The type of methods of user-defined class instances. -.. data:: UnboundMethodType - - An alternate name for ``MethodType``. - - .. data:: BuiltinFunctionType + BuiltinMethodType The type of built-in functions like :func:`len` or :func:`sys.exit`. -.. data:: BuiltinMethodType - - An alternate name for ``BuiltinFunction``. - - .. data:: ModuleType The type of modules. -.. data:: FileType - - The type of open file objects such as ``sys.stdout``; alias of the built-in - :class:`file`. - - -.. data:: RangeType - - .. index:: builtin: range - - The type of range objects returned by :func:`range`; alias of the built-in - :class:`range`. - - .. data:: SliceType .. index:: builtin: slice @@ -197,6 +165,7 @@ traceback object. +.. XXX! .. data:: BufferType .. index:: builtin: buffer @@ -228,12 +197,3 @@ ``datetime.timedelta.days``. This constant is not defined in implementations of Python that do not have such extension types, so for portable code use ``hasattr(types, 'MemberDescriptorType')``. - - -.. data:: StringTypes - - A sequence containing ``StringType`` and ``UnicodeType`` used to facilitate - easier checking for any string object. Using this is more portable than using a - sequence of the two string types constructed elsewhere since it only contains - ``UnicodeType`` if it has been built in the running version of Python. For - example: ``isinstance(s, types.StringTypes)``. From python-3000-checkins at python.org Tue Sep 4 09:27:55 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 4 Sep 2007 09:27:55 +0200 (CEST) Subject: [Python-3000-checkins] r57952 - python/branches/py3k/Doc/library/string.rst Message-ID: <20070904072755.052DB1E4009@bag.python.org> Author: georg.brandl Date: Tue Sep 4 09:27:54 2007 New Revision: 57952 Modified: python/branches/py3k/Doc/library/string.rst Log: Fix the string formatting docs for now; if the feature is changed again, the docs can be changed too. Modified: python/branches/py3k/Doc/library/string.rst ============================================================================== --- python/branches/py3k/Doc/library/string.rst (original) +++ python/branches/py3k/Doc/library/string.rst Tue Sep 4 09:27:54 2007 @@ -416,8 +416,7 @@ | ``'%'`` | Percentage. Multiplies the number by 100 and displays | | | in fixed (``'f'``) format, followed by a percent sign. | +---------+----------------------------------------------------------+ - | None | similar to ``'g'``, except that it prints at least one | - | | digit after the decimal point. | + | None | the same as ``'g'`` | +---------+----------------------------------------------------------+ From python-3000-checkins at python.org Tue Sep 4 10:11:04 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 4 Sep 2007 10:11:04 +0200 (CEST) Subject: [Python-3000-checkins] r57953 - python/branches/py3k/Doc/library/abc.rst python/branches/py3k/Doc/library/python.rst Message-ID: <20070904081104.1F7111E4009@bag.python.org> Author: georg.brandl Date: Tue Sep 4 10:11:03 2007 New Revision: 57953 Added: python/branches/py3k/Doc/library/abc.rst Modified: python/branches/py3k/Doc/library/python.rst Log: Initial documentation for the `abc` module. Added: python/branches/py3k/Doc/library/abc.rst ============================================================================== --- (empty file) +++ python/branches/py3k/Doc/library/abc.rst Tue Sep 4 10:11:03 2007 @@ -0,0 +1,142 @@ + +:mod:`abc` --- Abstract Base Classes +==================================== + +.. module:: abc + :synopsis: Abstract base classes according to PEP 3119. +.. moduleauthor:: Guido van Rossum +.. sectionauthor:: Georg Brandl +.. much of the content adapted from docstrings + +This module provides the infrastructure for defining abstract base classes +(ABCs) in Python, as outlined in :pep:`3119`. + +Concrete base ABCs to derive from can be found in the :mod:`collections` module. + + +The module provides the following class: + +.. class:: ABCMeta + + Metaclass for defining Abstract Base Classes (ABCs). + + Use this metaclass to create an ABC. An ABC can be subclassed directly, and + then acts as a mix-in class. You can also register unrelated concrete + classes (even built-in classes) and unrelated ABCs as "virtual subclasses" -- + these and their descendants will be considered subclasses of the registering + ABC by the built-in :func:`issubclass` function, but the registering ABC + won't show up in their MRO (Method Resolution Order) nor will method + implementations defined by the registering ABC be callable (not even via + :func:`super`). + + Classes created with a metaclass of :class:`ABCMeta` have the following method: + + .. method:: register(subclass) + + Register *subclass* as a "virtual subclass" of this ABC. From now on, + ``issubclass(subclass, ABC)`` is true. + + + You can also override this method in an abstract base class: + + .. method:: __subclasshook__(subclass) + + (Must be defined as a class method.) + + Check whether *subclass* is considered a subclass of this ABC. This means + that you can customize the behavior of ``issubclass`` further without the + need to call :meth:`register` on every class you want to consider a + subclass of the ABC. + + This method should return ``True``, ``False`` or ``NotImplemented``. If + it returns ``True``, the *subclass* is considered a subclass of this ABC. + If it returns ``False``, the *subclass* is not considered a subclass of + this ABC, even if it would normally be one. If it returns + ``NotImplemented``, the subclass check is continued with the usual + mechanism. + + + To demonstrate these concepts, look at this example ABC definition:: + + class MyIterator: + pass + + class Iterator(metaclass=ABCMeta): + + @abstractmethod + def __next__(self): + raise StopIteration + + def __iter__(self): + return self + + @classmethod + def __subclasshook__(cls, C): + if cls is Iterator: + if any("__next__" in B.__dict__ for B in C.__mro__): + return True + return NotImplemented + + Iterator.register(MyIterator) + + The ABC ``Iterator`` defines the two standard iterator methods: + :meth:`__iter__` and :meth:`__next__`. The :meth:`__iter__` method is given + a default implementation, while the :meth:`__next__` method is abstract. + + .. XXX why is an implementation given then? + + The :meth:`__subclasshook__` class method defined here says that any class + that has a :meth:`__next__` method in its :attr:`__dict__` (or in that of one + of its subclasses, accessed via the :attr:`__mro__`) is considered an + ``Iterator`` too. + + Finally, the last line makes ``MyIterator`` a virtual subclass of + ``Iterator``, even though it does not define a :meth:`__next__` method. + (Of course, this doesn't make much sense in this context.) + + .. XXX perhaps find better example + + +It also provides the following decorators: + +.. function:: abstractmethod(function) + + A decorator indicating abstract methods. + + Requires that the metaclass is :class:`ABCMeta` or derived from it. A class + that has a metaclass derived from :class:`ABCMeta` cannot be instantiated + unless all of its abstract methods are overridden. The abstract methods can + be called using any of the the normal 'super' call mechanisms. + + Usage:: + + class C(metaclass=ABCMeta): + @abstractmethod + def my_abstract_method(self, ...): + ... + + +.. function:: abstractproperty(property) + + A decorator indicating abstract properties. + + Requires that the metaclass is :class:`ABCMeta` or derived from it. A class + that has a metaclass derived from :class:`ABCMeta` cannot be instantiated + unless all of its abstract properties are overridden. The abstract + properties can be called using any of the the normal 'super' call mechanisms. + + Usage:: + + class C(metaclass=ABCMeta): + @abstractproperty + def my_abstract_property(self): + ... + + This defines a read-only property; you can also define a read-write abstract + property using the 'long' form of property declaration:: + + class C(metaclass=ABCMeta): + def getx(self): ... + def setx(self, value): ... + x = abstractproperty(getx, setx) + Modified: python/branches/py3k/Doc/library/python.rst ============================================================================== --- python/branches/py3k/Doc/library/python.rst (original) +++ python/branches/py3k/Doc/library/python.rst Tue Sep 4 10:11:03 2007 @@ -17,6 +17,7 @@ __main__.rst warnings.rst contextlib.rst + abc.rst atexit.rst traceback.rst __future__.rst From python-3000-checkins at python.org Tue Sep 4 11:04:00 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Tue, 4 Sep 2007 11:04:00 +0200 (CEST) Subject: [Python-3000-checkins] r57956 - python/branches/py3k/Doc/reference/expressions.rst Message-ID: <20070904090400.364161E4018@bag.python.org> Author: thomas.wouters Date: Tue Sep 4 11:03:59 2007 New Revision: 57956 Modified: python/branches/py3k/Doc/reference/expressions.rst Log: Update ref docs on slicing. Modified: python/branches/py3k/Doc/reference/expressions.rst ============================================================================== --- python/branches/py3k/Doc/reference/expressions.rst (original) +++ python/branches/py3k/Doc/reference/expressions.rst Tue Sep 4 11:03:59 2007 @@ -513,14 +513,10 @@ :keyword:`del` statements. The syntax for a slicing: .. productionlist:: - slicing: `simple_slicing` | `extended_slicing` - simple_slicing: `primary` "[" `short_slice` "]" - extended_slicing: `primary` "[" `slice_list` "]" + slicing: `primary` "[" `slice_list` "]" slice_list: `slice_item` ("," `slice_item`)* [","] slice_item: `expression` | `proper_slice` - proper_slice: `short_slice` | `long_slice` - short_slice: [`lower_bound`] ":" [`upper_bound`] - long_slice: `short_slice` ":" [`stride`] + proper_slice: [`lower_bound`] ":" [`upper_bound`] [ ":" [`stride`] ] lower_bound: `expression` upper_bound: `expression` stride: `expression` @@ -530,36 +526,23 @@ interpreted as a slicing. Rather than further complicating the syntax, this is disambiguated by defining that in this case the interpretation as a subscription takes priority over the interpretation as a slicing (this is the case if the -slice list contains no proper slice). Similarly, when the slice list has -exactly one short slice and no trailing comma, the interpretation as a simple -slicing takes priority over that as an extended slicing. - -.. XXX is the next paragraph stil correct? - -The semantics for a simple slicing are as follows. The primary must evaluate to -a sequence object. The lower and upper bound expressions, if present, must -evaluate to plain integers; defaults are zero and the ``sys.maxint``, -respectively. If either bound is negative, the sequence's length is added to -it. The slicing now selects all items with index *k* such that ``i <= k < j`` -where *i* and *j* are the specified lower and upper bounds. This may be an -empty sequence. It is not an error if *i* or *j* lie outside the range of valid -indexes (such items don't exist so they aren't selected). +slice list contains no proper slice). .. index:: single: start (slice object attribute) single: stop (slice object attribute) single: step (slice object attribute) -The semantics for an extended slicing are as follows. The primary must evaluate -to a mapping object, and it is indexed with a key that is constructed from the -slice list, as follows. If the slice list contains at least one comma, the key -is a tuple containing the conversion of the slice items; otherwise, the -conversion of the lone slice item is the key. The conversion of a slice item -that is an expression is that expression. The conversion of a proper slice is a -slice object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and -:attr:`step` attributes are the values of the expressions given as lower bound, -upper bound and stride, respectively, substituting ``None`` for missing -expressions. +The semantics for a slicing are as follows. The primary must evaluate to a +mapping object, and it is indexed with a key that is constructed from the +slice list, as follows. If the slice list contains at least one comma, the +key is a tuple containing the conversion of the slice items; otherwise, the +conversion of the lone slice item is the key. The conversion of a slice +item that is an expression is that expression. The conversion of a proper +slice is a slice object (see section :ref:`types`) whose :attr:`start`, +:attr:`stop` and :attr:`step` attributes are the values of the expressions +given as lower bound, upper bound and stride, respectively, substituting +``None`` for missing expressions. .. _calls: From python-3000-checkins at python.org Tue Sep 4 11:18:07 2007 From: python-3000-checkins at python.org (martin.v.loewis) Date: Tue, 4 Sep 2007 11:18:07 +0200 (CEST) Subject: [Python-3000-checkins] r57957 - in python/branches/py3k: Include/parsetok.h Include/pythonrun.h Parser/parsetok.c Parser/tokenizer.c Parser/tokenizer.h Python/import.c Python/pythonrun.c Message-ID: <20070904091807.677021E400A@bag.python.org> Author: martin.v.loewis Date: Tue Sep 4 11:18:06 2007 New Revision: 57957 Modified: python/branches/py3k/Include/parsetok.h python/branches/py3k/Include/pythonrun.h python/branches/py3k/Parser/parsetok.c python/branches/py3k/Parser/tokenizer.c python/branches/py3k/Parser/tokenizer.h python/branches/py3k/Python/import.c python/branches/py3k/Python/pythonrun.c Log: Convert code from sys.stdin.encoding to UTF-8 in interactive mode. Fixes #1100. Modified: python/branches/py3k/Include/parsetok.h ============================================================================== --- python/branches/py3k/Include/parsetok.h (original) +++ python/branches/py3k/Include/parsetok.h Tue Sep 4 11:18:06 2007 @@ -34,7 +34,8 @@ PyAPI_FUNC(node *) PyParser_ParseStringFlags(const char *, grammar *, int, perrdetail *, int); -PyAPI_FUNC(node *) PyParser_ParseFileFlags(FILE *, const char *, grammar *, +PyAPI_FUNC(node *) PyParser_ParseFileFlags(FILE *, const char *, + const char*, grammar *, int, char *, char *, perrdetail *, int); Modified: python/branches/py3k/Include/pythonrun.h ============================================================================== --- python/branches/py3k/Include/pythonrun.h (original) +++ python/branches/py3k/Include/pythonrun.h Tue Sep 4 11:18:06 2007 @@ -40,7 +40,8 @@ PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *, int, PyCompilerFlags *flags, PyArena *); -PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *, int, +PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *, + const char*, int, char *, char *, PyCompilerFlags *, int *, PyArena *); Modified: python/branches/py3k/Parser/parsetok.c ============================================================================== --- python/branches/py3k/Parser/parsetok.c (original) +++ python/branches/py3k/Parser/parsetok.c Tue Sep 4 11:18:06 2007 @@ -59,19 +59,20 @@ PyParser_ParseFile(FILE *fp, const char *filename, grammar *g, int start, char *ps1, char *ps2, perrdetail *err_ret) { - return PyParser_ParseFileFlags(fp, filename, g, start, ps1, ps2, - err_ret, 0); + return PyParser_ParseFileFlags(fp, filename, NULL, + g, start, ps1, ps2, err_ret, 0); } node * -PyParser_ParseFileFlags(FILE *fp, const char *filename, grammar *g, int start, +PyParser_ParseFileFlags(FILE *fp, const char *filename, const char* enc, + grammar *g, int start, char *ps1, char *ps2, perrdetail *err_ret, int flags) { struct tok_state *tok; initerr(err_ret, filename); - if ((tok = PyTokenizer_FromFile(fp, ps1, ps2)) == NULL) { + if ((tok = PyTokenizer_FromFile(fp, enc, ps1, ps2)) == NULL) { err_ret->error = E_NOMEM; return NULL; } Modified: python/branches/py3k/Parser/tokenizer.c ============================================================================== --- python/branches/py3k/Parser/tokenizer.c (original) +++ python/branches/py3k/Parser/tokenizer.c Tue Sep 4 11:18:06 2007 @@ -677,7 +677,7 @@ /* Set up tokenizer for file */ struct tok_state * -PyTokenizer_FromFile(FILE *fp, char *ps1, char *ps2) +PyTokenizer_FromFile(FILE *fp, char* enc, char *ps1, char *ps2) { struct tok_state *tok = tok_new(); if (tok == NULL) @@ -691,6 +691,17 @@ tok->fp = fp; tok->prompt = ps1; tok->nextprompt = ps2; + if (enc != NULL) { + /* Must copy encoding declaration since it + gets copied into the parse tree. */ + tok->encoding = PyMem_MALLOC(strlen(enc)+1); + if (!tok->encoding) { + PyTokenizer_Free(tok); + return NULL; + } + strcpy(tok->encoding, enc); + tok->decoding_state = -1; + } return tok; } @@ -742,6 +753,29 @@ } if (tok->prompt != NULL) { char *newtok = PyOS_Readline(stdin, stdout, tok->prompt); +#ifndef PGEN + if (tok->encoding && newtok && *newtok) { + /* Recode to UTF-8 */ + Py_ssize_t buflen; + const char* buf; + PyObject *u = translate_into_utf8(newtok, tok->encoding); + PyMem_FREE(newtok); + if (!u) { + tok->done = E_DECODE; + return EOF; + } + buflen = PyBytes_Size(u); + buf = PyBytes_AsString(u); + if (!buf) { + Py_DECREF(u); + tok->done = E_DECODE; + return EOF; + } + newtok = PyMem_MALLOC(buflen+1); + strcpy(newtok, buf); + Py_DECREF(u); + } +#endif if (tok->nextprompt != NULL) tok->prompt = tok->nextprompt; if (newtok == NULL) Modified: python/branches/py3k/Parser/tokenizer.h ============================================================================== --- python/branches/py3k/Parser/tokenizer.h (original) +++ python/branches/py3k/Parser/tokenizer.h Tue Sep 4 11:18:06 2007 @@ -55,7 +55,8 @@ }; extern struct tok_state *PyTokenizer_FromString(const char *); -extern struct tok_state *PyTokenizer_FromFile(FILE *, char *, char *); +extern struct tok_state *PyTokenizer_FromFile(FILE *, char*, + char *, char *); extern void PyTokenizer_Free(struct tok_state *); extern int PyTokenizer_Get(struct tok_state *, char **, char **); Modified: python/branches/py3k/Python/import.c ============================================================================== --- python/branches/py3k/Python/import.c (original) +++ python/branches/py3k/Python/import.c Tue Sep 4 11:18:06 2007 @@ -809,7 +809,8 @@ if (arena == NULL) return NULL; - mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, 0, + mod = PyParser_ASTFromFile(fp, pathname, NULL, + Py_file_input, 0, 0, 0, NULL, arena); if (mod) { co = PyAST_Compile(mod, pathname, NULL, arena); Modified: python/branches/py3k/Python/pythonrun.c ============================================================================== --- python/branches/py3k/Python/pythonrun.c (original) +++ python/branches/py3k/Python/pythonrun.c Tue Sep 4 11:18:06 2007 @@ -744,12 +744,22 @@ int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) { - PyObject *m, *d, *v, *w; + PyObject *m, *d, *v, *w, *oenc = NULL; mod_ty mod; PyArena *arena; - char *ps1 = "", *ps2 = ""; + char *ps1 = "", *ps2 = "", *enc = NULL; int errcode = 0; + if (fp == stdin) { + /* Fetch encoding from sys.stdin */ + v = PySys_GetObject("stdin"); + if (!v) + return -1; + oenc = PyObject_GetAttrString(v, "encoding"); + if (!oenc) + return -1; + enc = PyUnicode_AsString(oenc); + } v = PySys_GetObject("ps1"); if (v != NULL) { v = PyObject_Str(v); @@ -770,13 +780,15 @@ if (arena == NULL) { Py_XDECREF(v); Py_XDECREF(w); + Py_XDECREF(oenc); return -1; } - mod = PyParser_ASTFromFile(fp, filename, + mod = PyParser_ASTFromFile(fp, filename, enc, Py_single_input, ps1, ps2, flags, &errcode, arena); Py_XDECREF(v); Py_XDECREF(w); + Py_XDECREF(oenc); if (mod == NULL) { PyArena_Free(arena); if (errcode == E_EOF) { @@ -1254,7 +1266,7 @@ if (arena == NULL) return NULL; - mod = PyParser_ASTFromFile(fp, filename, start, 0, 0, + mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0, flags, NULL, arena); if (closeit) fclose(fp); @@ -1379,13 +1391,15 @@ } mod_ty -PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1, +PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc, + int start, char *ps1, char *ps2, PyCompilerFlags *flags, int *errcode, PyArena *arena) { mod_ty mod; perrdetail err; - node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, + node *n = PyParser_ParseFileFlags(fp, filename, enc, + &_PyParser_Grammar, start, ps1, ps2, &err, PARSER_FLAGS(flags)); if (n) { mod = PyAST_FromNode(n, flags, filename, arena); @@ -1406,7 +1420,8 @@ PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags) { perrdetail err; - node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar, + node *n = PyParser_ParseFileFlags(fp, filename, NULL, + &_PyParser_Grammar, start, NULL, NULL, &err, flags); if (n == NULL) err_input(&err); From python-3000-checkins at python.org Tue Sep 4 13:27:48 2007 From: python-3000-checkins at python.org (thomas.heller) Date: Tue, 4 Sep 2007 13:27:48 +0200 (CEST) Subject: [Python-3000-checkins] r57959 - python/branches/py3k/Lib/os.py Message-ID: <20070904112748.123931E4002@bag.python.org> Author: thomas.heller Date: Tue Sep 4 13:27:47 2007 New Revision: 57959 Modified: python/branches/py3k/Lib/os.py Log: Make the _wrap_close type (which is returned by os.popen) iterable. This should fix the Lib\test\test_uuid.py test on Windows. Modified: python/branches/py3k/Lib/os.py ============================================================================== --- python/branches/py3k/Lib/os.py (original) +++ python/branches/py3k/Lib/os.py Tue Sep 4 13:27:47 2007 @@ -664,6 +664,8 @@ return self._proc.wait() << 8 # Shift left to match old behavior def __getattr__(self, name): return getattr(self._stream, name) + def __iter__(self): + return iter(self._stream) # Supply os.fdopen() (used by subprocess!) def fdopen(fd, mode="r", buffering=-1): From python-3000-checkins at python.org Tue Sep 4 17:45:26 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 4 Sep 2007 17:45:26 +0200 (CEST) Subject: [Python-3000-checkins] r57963 - python/branches/py3k/Doc/library/abc.rst python/branches/py3k/Doc/library/os.rst Message-ID: <20070904154526.413A81E4010@bag.python.org> Author: georg.brandl Date: Tue Sep 4 17:45:25 2007 New Revision: 57963 Modified: python/branches/py3k/Doc/library/abc.rst python/branches/py3k/Doc/library/os.rst Log: More abc docs. Modified: python/branches/py3k/Doc/library/abc.rst ============================================================================== --- python/branches/py3k/Doc/library/abc.rst (original) +++ python/branches/py3k/Doc/library/abc.rst Tue Sep 4 17:45:25 2007 @@ -9,7 +9,8 @@ .. much of the content adapted from docstrings This module provides the infrastructure for defining abstract base classes -(ABCs) in Python, as outlined in :pep:`3119`. +(ABCs) in Python, as outlined in :pep:`3119`; see there for a rationale why this +was added to Python. Concrete base ABCs to derive from can be found in the :mod:`collections` module. @@ -46,7 +47,8 @@ Check whether *subclass* is considered a subclass of this ABC. This means that you can customize the behavior of ``issubclass`` further without the need to call :meth:`register` on every class you want to consider a - subclass of the ABC. + subclass of the ABC. (This class method is called from the + :meth:`__subclasscheck__` method of the ABC.) This method should return ``True``, ``False`` or ``NotImplemented``. If it returns ``True``, the *subclass* is considered a subclass of this ABC. @@ -55,46 +57,54 @@ ``NotImplemented``, the subclass check is continued with the usual mechanism. + .. XXX explain the "usual mechanism" - To demonstrate these concepts, look at this example ABC definition:: - class MyIterator: - pass + For a demonstration of these concepts, look at this example ABC definition:: - class Iterator(metaclass=ABCMeta): + class Foo: + def __getitem__(self, index): + ... + def __len__(self): + ... + def get_iterator(self): + return iter(self) - @abstractmethod - def __next__(self): - raise StopIteration + class MyIterable(metaclass=ABCMeta): + @abstractmethod def __iter__(self): - return self + while False: + yield None + + def get_iterator(self): + return self.__iter__() @classmethod def __subclasshook__(cls, C): - if cls is Iterator: - if any("__next__" in B.__dict__ for B in C.__mro__): + if cls is MyIterable: + if any("__iter__" in B.__dict__ for B in C.__mro__): return True return NotImplemented - Iterator.register(MyIterator) - - The ABC ``Iterator`` defines the two standard iterator methods: - :meth:`__iter__` and :meth:`__next__`. The :meth:`__iter__` method is given - a default implementation, while the :meth:`__next__` method is abstract. + MyIterable.register(Foo) - .. XXX why is an implementation given then? + The ABC ``MyIterable`` defines the standard iterable method, + :meth:`__iter__`, as an abstract method. The implementation given here can + still be called from subclasses. The :meth:`get_iterator` method is also + part of the ``MyIterable`` abstract base class, but it does not have to be + overridden in a non-abstract child. The :meth:`__subclasshook__` class method defined here says that any class - that has a :meth:`__next__` method in its :attr:`__dict__` (or in that of one - of its subclasses, accessed via the :attr:`__mro__`) is considered an - ``Iterator`` too. - - Finally, the last line makes ``MyIterator`` a virtual subclass of - ``Iterator``, even though it does not define a :meth:`__next__` method. - (Of course, this doesn't make much sense in this context.) - - .. XXX perhaps find better example + that has an :meth:`__iter__` method in its :attr:`__dict__` (or in that of + one of its subclasses, accessed via the :attr:`__mro__`) is considered a + ``MyIterable`` too. + + Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``, + even though it does not define a :meth:`__iter__` method (it uses the + old-style iterable protocol, defined in terms of :meth:`__len__` and + :meth:`__getitem__`). Note that this will not make ``get_iterator`` + available as a method of ``Foo``, so it is provided separately. It also provides the following decorators: @@ -103,10 +113,17 @@ A decorator indicating abstract methods. - Requires that the metaclass is :class:`ABCMeta` or derived from it. A class - that has a metaclass derived from :class:`ABCMeta` cannot be instantiated - unless all of its abstract methods are overridden. The abstract methods can - be called using any of the the normal 'super' call mechanisms. + Using this decorator requires that the metaclass is :class:`ABCMeta` or + derived from it. A class that has a metaclass derived from :class:`ABCMeta` + cannot be instantiated unless all of its abstract methods are overridden. + The abstract methods can be called using any of the the normal 'super' call + mechanisms. + + Dynamically adding abstract methods to a class, or attempting to modify the + abstraction status of a method or class once it is created, are not + supported. The :func:`abstractmethod` only affects subclasses derived using + regular inheritance; "virtual subclasses" registered with the ABC's + :meth:`register` method are not affected. Usage:: @@ -115,10 +132,17 @@ def my_abstract_method(self, ...): ... + .. note:: + + Unlike C++ or Java, these abstract methods may have an implementation. + This implementation can be called via the :func:`super` mechanism from the + class that overrides it. This could be useful as an end-point for a + super-call in framework using a cooperative multiple-inheritance + -.. function:: abstractproperty(property) +.. function:: abstractproperty(fget[, fset[, fdel[, doc]]]) - A decorator indicating abstract properties. + A subclass of the built-in :func:`property`, indicating an abstract property. Requires that the metaclass is :class:`ABCMeta` or derived from it. A class that has a metaclass derived from :class:`ABCMeta` cannot be instantiated Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Tue Sep 4 17:45:25 2007 @@ -32,14 +32,6 @@ and in the following sub-sections are all available directly from the :mod:`os` module. -.. % Frank Stajano complained that it -.. % wasn't clear that the entries described in the subsections were all -.. % available at the module level (most uses of subsections are -.. % different); I think this is only a problem for the HTML version, -.. % where the relationship may not be as clear. -.. % - - .. exception:: error .. index:: module: errno From python-3000-checkins at python.org Tue Sep 4 18:23:16 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 4 Sep 2007 18:23:16 +0200 (CEST) Subject: [Python-3000-checkins] r57966 - python/branches/py3k/Doc/whatsnew/3.0.rst Message-ID: <20070904162316.9729E1E4002@bag.python.org> Author: guido.van.rossum Date: Tue Sep 4 18:23:16 2007 New Revision: 57966 Modified: python/branches/py3k/Doc/whatsnew/3.0.rst Log: Correction an issue reported by Mark Summerfeld. Modified: python/branches/py3k/Doc/whatsnew/3.0.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/3.0.rst (original) +++ python/branches/py3k/Doc/whatsnew/3.0.rst Tue Sep 4 18:23:16 2007 @@ -111,8 +111,8 @@ * The ``print()`` function doesn't support the "softspace" feature of the old ``print`` statement. For example, in Python 2.x, - ``print "A\n", "B\n"`` would write ``"A\nB\n"``; but in Python 3.0, - ``print("A\n", "B\n")`` writes ``"A\n B\n"``. + ``print "A\n", "B"`` would write ``"A\nB\n"``; but in Python 3.0, + ``print("A\n", "B")`` writes ``"A\n B\n"``. * Also, ``print`` and ``print (x, y)`` behave differently without warning: the former used to add a newline in 2.x, but does nothing From python-3000-checkins at python.org Tue Sep 4 19:33:11 2007 From: python-3000-checkins at python.org (fred.drake) Date: Tue, 4 Sep 2007 19:33:11 +0200 (CEST) Subject: [Python-3000-checkins] r57968 - in python/branches/py3k/Doc: howto/functional.rst library/itertools.rst library/stdtypes.rst library/userdict.rst reference/datamodel.rst Message-ID: <20070904173311.83A5E1E4002@bag.python.org> Author: fred.drake Date: Tue Sep 4 19:33:11 2007 New Revision: 57968 Modified: python/branches/py3k/Doc/howto/functional.rst python/branches/py3k/Doc/library/itertools.rst python/branches/py3k/Doc/library/stdtypes.rst python/branches/py3k/Doc/library/userdict.rst python/branches/py3k/Doc/reference/datamodel.rst Log: remove/update many of the references to dict.iter*() Modified: python/branches/py3k/Doc/howto/functional.rst ============================================================================== --- python/branches/py3k/Doc/howto/functional.rst (original) +++ python/branches/py3k/Doc/howto/functional.rst Tue Sep 4 19:33:11 2007 @@ -291,10 +291,10 @@ Note that the order is essentially random, because it's based on the hash ordering of the objects in the dictionary. -Applying ``iter()`` to a dictionary always loops over the keys, but dictionaries -have methods that return other iterators. If you want to iterate over keys, -values, or key/value pairs, you can explicitly call the ``iterkeys()``, -``itervalues()``, or ``iteritems()`` methods to get an appropriate iterator. +Applying :func:`iter` to a dictionary always loops over the keys, but +dictionaries have methods that return other iterators. If you want to iterate +over values or key/value pairs, you can explicitly call the +:meth:`values` or :meth:`items` methods to get an appropriate iterator. The :func:`dict` constructor can accept an iterator that returns a finite stream of ``(key, value)`` tuples:: Modified: python/branches/py3k/Doc/library/itertools.rst ============================================================================== --- python/branches/py3k/Doc/library/itertools.rst (original) +++ python/branches/py3k/Doc/library/itertools.rst Tue Sep 4 19:33:11 2007 @@ -414,7 +414,7 @@ # Show a dictionary sorted and grouped by value >>> from operator import itemgetter >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) - >>> di = sorted(d.iteritems(), key=itemgetter(1)) + >>> di = sorted(d.items(), key=itemgetter(1)) >>> for k, g in groupby(di, key=itemgetter(1)): ... print(k, map(itemgetter(0), g)) ... @@ -464,9 +464,6 @@ "Return function(0), function(1), ..." return imap(function, count()) - def iteritems(mapping): - return izip(mapping.iterkeys(), mapping.itervalues()) - def nth(iterable, n): "Returns the nth item or raise StopIteration" return islice(iterable, n, None).next() Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Tue Sep 4 19:33:11 2007 @@ -1804,39 +1804,24 @@ .. method:: dict.items() - Return a copy of the dictionary's list of ``(key, value)`` pairs. + Return an iterator over the dictionary's ``(key, value)`` pairs. .. note:: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of - insertions and deletions. If :meth:`items`, :meth:`keys`, :meth:`values`, - :meth:`iteritems`, :meth:`iterkeys`, and :meth:`itervalues` are called with no + insertions and deletions. If :meth:`items`, :meth:`keys`, and + :meth:`values` are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. The same relationship holds for the :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs = zip(d.itervalues(), d.iterkeys())`` provides the same value for ``pairs``. Another way to create the - same list is ``pairs = [(v, k) for (k, v) in d.iteritems()]``. - -.. method:: dict.iteritems() - - Return an iterator over the dictionary's ``(key, value)`` pairs. - See the note for :meth:`dict.items`. - -.. method:: dict.iterkeys() - - Return an iterator over the dictionary's keys. See the note for - :meth:`dict.items`. - -.. method:: dict.itervalues() - - Return an iterator over the dictionary's values. See the note for - :meth:`dict.items`. + same list is ``pairs = [(v, k) for (k, v) in d.items()]``. .. method:: dict.keys() - Return a copy of the dictionary's list of keys. See the note for + Return an iterator over the dictionary's keys. See the note for :meth:`dict.items`. .. method:: dict.pop(key[, default]) @@ -1855,13 +1840,13 @@ .. method:: dict.setdefault(key[, default]) - If *key* is in the dictionary, return its value. If not, insert *key* with a - value of *default* and return *default*. *default* defaults to ``None``. + If *key* is in the dictionary, return its value. If not, insert *key* with + a value of *default* and return *default*. *default* defaults to ``None``. .. method:: dict.update([other]) - Update the dictionary with the key/value pairs from *other*, overwriting existing - keys. Return ``None``. + Update the dictionary with the key/value pairs from *other*, overwriting + existing keys. Return ``None``. :func:`update` accepts either another dictionary object or an iterable of key/value pairs (as a tuple or other iterable of length two). If keyword @@ -1870,8 +1855,8 @@ .. method:: dict.values() - Return a copy of the dictionary's list of values. See the note for - :meth:`mapping.items`. + Return an iterator over the dictionary's values. See the note for + :meth:`dict.items`. .. _bltin-file-objects: Modified: python/branches/py3k/Doc/library/userdict.rst ============================================================================== --- python/branches/py3k/Doc/library/userdict.rst (original) +++ python/branches/py3k/Doc/library/userdict.rst Tue Sep 4 19:33:11 2007 @@ -33,7 +33,8 @@ .. note:: - For backward compatibility, instances of :class:`UserDict` are not iterable. + For backward compatibility, instances of :class:`UserDict` are not + iterable. .. class:: IterableUserDict([initialdata]) @@ -62,8 +63,8 @@ :meth:`__delitem__` will preclude only :meth:`pop` and :meth:`popitem` from the full interface. - In addition to the four base methods, progressively more efficiency comes with - defining :meth:`__contains__`, :meth:`__iter__`, and :meth:`iteritems`. + In addition to the four base methods, progressively more efficiency comes + with defining :meth:`__contains__` and :meth:`__iter__`. Since the mixin has no knowledge of the subclass constructor, it does not define :meth:`__init__` or :meth:`copy`. @@ -93,10 +94,11 @@ .. class:: UserList([list]) Class that simulates a list. The instance's contents are kept in a regular - list, which is accessible via the :attr:`data` attribute of :class:`UserList` + list, which is accessible via the :attr:`data` attribute of + :class:`UserList` instances. The instance's contents are initially set to a copy of *list*, - defaulting to the empty list ``[]``. *list* can be any iterable, e.g. a - real Python list or a :class:`UserList` object. + defaulting to the empty list ``[]``. *list* can be any iterable, for + example a real Python list or a :class:`UserList` object. In addition to supporting the methods and operations of mutable sequences (see section :ref:`typesseq`), :class:`UserList` instances provide the following Modified: python/branches/py3k/Doc/reference/datamodel.rst ============================================================================== --- python/branches/py3k/Doc/reference/datamodel.rst (original) +++ python/branches/py3k/Doc/reference/datamodel.rst Tue Sep 4 19:33:11 2007 @@ -1589,8 +1589,8 @@ N`` where *N* is the length of the sequence, or slice objects, which define a range of items. It is also recommended that mappings provide the methods :meth:`keys`, :meth:`values`, :meth:`items`, :meth:`has_key`, :meth:`get`, -:meth:`clear`, :meth:`setdefault`, :meth:`iterkeys`, :meth:`itervalues`, -:meth:`iteritems`, :meth:`pop`, :meth:`popitem`, :meth:`copy`, and +:meth:`clear`, :meth:`setdefault`, +:meth:`pop`, :meth:`popitem`, :meth:`copy`, and :meth:`update` behaving similar to those for Python's standard dictionary objects. The :mod:`UserDict` module provides a :class:`DictMixin` class to help create those methods from a base set of :meth:`__getitem__`, @@ -1608,7 +1608,7 @@ the values. It is further recommended that both mappings and sequences implement the :meth:`__iter__` method to allow efficient iteration through the container; for mappings, :meth:`__iter__` should be the same as -:meth:`iterkeys`; for sequences, it should iterate through the values. +:meth:`keys`; for sequences, it should iterate through the values. .. method:: object.__len__(self) @@ -1677,7 +1677,7 @@ This method is called when an iterator is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container, and - should also be made available as the method :meth:`iterkeys`. + should also be made available as the method :meth:`keys`. Iterator objects also need to implement this method; they are required to return themselves. For more information on iterator objects, see :ref:`typeiter`. From python-3000-checkins at python.org Tue Sep 4 19:43:38 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 4 Sep 2007 19:43:38 +0200 (CEST) Subject: [Python-3000-checkins] r57969 - python/branches/py3k/Doc/library/stdtypes.rst Message-ID: <20070904174338.180EB1E4002@bag.python.org> Author: georg.brandl Date: Tue Sep 4 19:43:37 2007 New Revision: 57969 Modified: python/branches/py3k/Doc/library/stdtypes.rst Log: Docs on dictviews. Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Tue Sep 4 19:43:37 2007 @@ -1699,14 +1699,13 @@ :class:`set`, and :class:`tuple` classes, and the :mod:`collections` module.) -A dictionary's keys are *almost* arbitrary values. Only -values containing lists, dictionaries or other mutable types (that are compared -by value rather than by object identity) may not be used as keys. Numeric types -used for keys obey the normal rules for numeric comparison: if two numbers -compare equal (such as ``1`` and ``1.0``) then they can be used interchangeably -to index the same dictionary entry. (Note however, that since computers -store floating-point numbers as approximations it is usually unwise to -use them as dictionary keys.) +A dictionary's keys are *almost* arbitrary values. Only values containing +lists, dictionaries or other mutable types (that are compared by value rather +than by object identity) may not be used as keys. Numeric types used for keys +obey the normal rules for numeric comparison: if two numbers compare equal (such +as ``1`` and ``1.0``) then they can be used interchangeably to index the same +dictionary entry. (Note however, that since computers store floating-point +numbers as approximations it is usually unwise to use them as dictionary keys.) Dictionaries can be created by placing a comma-separated list of ``key: value`` pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098: @@ -1714,33 +1713,31 @@ .. class:: dict([arg]) - Return a new dictionary initialized from an optional positional argument or from - a set of keyword arguments. If no arguments are given, return a new empty - dictionary. If the positional argument *arg* is a mapping object, return a - dictionary mapping the same keys to the same values as does the mapping object. - Otherwise the positional argument must be a sequence, a container that supports - iteration, or an iterator object. The elements of the argument must each also - be of one of those kinds, and each must in turn contain exactly two objects. - The first is used as a key in the new dictionary, and the second as the key's - value. If a given key is seen more than once, the last value associated with it - is retained in the new dictionary. + Return a new dictionary initialized from an optional positional argument or + from a set of keyword arguments. If no arguments are given, return a new + empty dictionary. If the positional argument *arg* is a mapping object, + return a dictionary mapping the same keys to the same values as does the + mapping object. Otherwise the positional argument must be a sequence, a + container that supports iteration, or an iterator object. The elements of + the argument must each also be of one of those kinds, and each must in turn + contain exactly two objects. The first is used as a key in the new + dictionary, and the second as the key's value. If a given key is seen more + than once, the last value associated with it is retained in the new + dictionary. If keyword arguments are given, the keywords themselves with their associated - values are added as items to the dictionary. If a key is specified both in the - positional argument and as a keyword argument, the value associated with the - keyword is retained in the dictionary. For example, these all return a + values are added as items to the dictionary. If a key is specified both in + the positional argument and as a keyword argument, the value associated with + the keyword is retained in the dictionary. For example, these all return a dictionary equal to ``{"one": 2, "two": 3}``: * ``dict(one=2, two=3)`` - * ``dict({'one': 2, 'two': 3})`` - * ``dict(zip(('one', 'two'), (2, 3)))`` - * ``dict([['two', 3], ['one', 2]])`` - The first example only works for keys that are valid Python - identifiers; the others work with any valid keys. + The first example only works for keys that are valid Python identifiers; the + others work with any valid keys. These are the operations that dictionaries support (and therefore, custom mapping @@ -1804,25 +1801,13 @@ .. method:: dict.items() - Return an iterator over the dictionary's ``(key, value)`` pairs. - - .. note:: - - Keys and values are listed in an arbitrary order which is non-random, varies - across Python implementations, and depends on the dictionary's history of - insertions and deletions. If :meth:`items`, :meth:`keys`, and - :meth:`values` are called with no - intervening modifications to the dictionary, the lists will directly correspond. - This allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs = - zip(d.values(), d.keys())``. The same relationship holds for the - :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs = zip(d.itervalues(), - d.iterkeys())`` provides the same value for ``pairs``. Another way to create the - same list is ``pairs = [(v, k) for (k, v) in d.items()]``. + Return a new view of the dictionary's items (``(key, value)`` pairs). See + below for documentation of view objects. .. method:: dict.keys() - Return an iterator over the dictionary's keys. See the note for - :meth:`dict.items`. + Return a new view of the dictionary's keys. See below for documentation of + view objects. .. method:: dict.pop(key[, default]) @@ -1855,8 +1840,70 @@ .. method:: dict.values() - Return an iterator over the dictionary's values. See the note for - :meth:`dict.items`. + Return a new view of the dictionary's values. See below for documentation of + view objects. + + +Dictionary view objects +----------------------- + +The objects returned by :meth:`dict.keys`, :meth:`dict.values` and +:meth:`dict.items` are *view objects*. They provide a dynamic view on the +dictionary's entries, which means that when the dictionary changes, the view +reflects these changes. The keys and items views have a set-like character +since their entries + +Dictionary views can be iterated over to yield their respective data, and +support membership tests: + +.. describe:: len(dictview) + + Return the number of entries in the dictionary. + +.. describe:: iter(dictview) + + Return an iterator over the keys, values or items (represented as tuples of + ``(key, value)``) in the dictionary. + + Keys and values are iterated over in an arbitrary order which is non-random, + varies across Python implementations, and depends on the dictionary's history + of insertions and deletions. If keys, values and items views are iterated + over with no intervening modifications to the dictionary, the order of items + will directly correspond. This allows the creation of ``(value, key)`` pairs + using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to + create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``. + +.. describe:: x in dictview + + Return ``True`` if *x* is in the underlying dictionary's keys, values or + items (in the latter case, *x* should be a ``(key, value)`` tuple). + + +The keys and items views also provide set-like operations ("other" here refers +to another dictionary view or a set): + +.. describe:: dictview & other + + Return the intersection of the dictview and the other object as a new set. + +.. describe:: dictview | other + + Return the union of the dictview and the other object as a new set. + +.. describe:: dictview - other + + Return the difference between the dictview and the other object (all elements + in *dictview* that aren't in *other*) as a new set. + +.. describe:: dictview ^ other + + Return the symmetric difference (all elements either in *dictview* or + *other*, but not in both) of the dictview and the other object as a new set. + +.. warning:: + + Since a dictionary's values are not required to be hashable, any of these + four operations will fail if an involved dictionary contains such a value. .. _bltin-file-objects: From python-3000-checkins at python.org Tue Sep 4 19:50:40 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 4 Sep 2007 19:50:40 +0200 (CEST) Subject: [Python-3000-checkins] r57970 - python/branches/py3k/Doc/library/functions.rst Message-ID: <20070904175040.C847D1E4002@bag.python.org> Author: georg.brandl Date: Tue Sep 4 19:50:40 2007 New Revision: 57970 Modified: python/branches/py3k/Doc/library/functions.rst Log: Change docs for builtins that now return iterators. Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Tue Sep 4 19:50:40 2007 @@ -406,16 +406,17 @@ .. function:: filter(function, iterable) - Construct a list from those elements of *iterable* for which *function* returns - true. *iterable* may be either a sequence, a container which supports - iteration, or an iterator, If *iterable* is a string or a tuple, the result - also has that type; otherwise it is always a list. If *function* is ``None``, - the identity function is assumed, that is, all elements of *iterable* that are - false are removed. - - Note that ``filter(function, iterable)`` is equivalent to ``[item for item in - iterable if function(item)]`` if function is not ``None`` and ``[item for item - in iterable if item]`` if function is ``None``. + Construct an iterator from those elements of *iterable* for which *function* + returns true. *iterable* may be either a sequence, a container which + supports iteration, or an iterator, If *iterable* is a string or a tuple, the + result also has that type; otherwise it is always a list. If *function* is + ``None``, the identity function is assumed, that is, all elements of + *iterable* that are false are removed. + + Note that ``filter(function, iterable)`` is equivalent to the generator + expression ``(item for item in iterable if function(item))`` if function is + not ``None`` and ``(item for item in iterable if item)`` if function is + ``None``. .. function:: float([x]) @@ -608,15 +609,19 @@ .. function:: map(function, iterable, ...) - Apply *function* to every item of *iterable* and return a list of the results. - If additional *iterable* arguments are passed, *function* must take that many - arguments and is applied to the items from all iterables in parallel. If one - iterable is shorter than another it is assumed to be extended with ``None`` - items. If *function* is ``None``, the identity function is assumed; if there - are multiple arguments, :func:`map` returns a list consisting of tuples - containing the corresponding items from all iterables (a kind of transpose - operation). The *iterable* arguments may be a sequence or any iterable object; - the result is always a list. + Return an iterator that applies *function* to every item of *iterable*, + yielding the results. If additional *iterable* arguments are passed, + *function* must take that many arguments and is applied to the items from all + iterables in parallel. If one iterable is shorter than another it is assumed + to be extended with ``None`` items. If *function* is ``None``, the identity + function is assumed; if there are multiple arguments, :func:`map` returns a + list consisting of tuples containing the corresponding items from all + iterables (a kind of transpose operation). The *iterable* arguments may be a + sequence or any iterable object; the result is always a list. + + Note that for only one *iterable* argument, ``map(function, iterable)`` is + equivalent to the generator expression ``(function(item) for item in + iterable)`` if *function* is not ``None``. .. function:: max(iterable[, args...], *[, key]) @@ -793,17 +798,18 @@ the same name. +.. XXX does accept objects with __index__ too .. function:: range([start,] stop[, step]) - This is a versatile function to create sequences containing arithmetic + This is a versatile function to create iterators containing arithmetic progressions. It is most often used in :keyword:`for` loops. The arguments - must be plain integers. If the *step* argument is omitted, it defaults to - ``1``. If the *start* argument is omitted, it defaults to ``0``. The full form - returns a list of plain integers ``[start, start + step, start + 2 * step, - ...]``. If *step* is positive, the last element is the largest ``start + i * - step`` less than *stop*; if *step* is negative, the last element is the smallest - ``start + i * step`` greater than *stop*. *step* must not be zero (or else - :exc:`ValueError` is raised). Example:: + must be integers. If the *step* argument is omitted, it defaults to ``1``. + If the *start* argument is omitted, it defaults to ``0``. The full form + returns an iterator of plain integers ``[start, start + step, start + 2 * + step, ...]``. If *step* is positive, the last element is the largest ``start + + i * step`` less than *stop*; if *step* is negative, the last element is the + smallest ``start + i * step`` greater than *stop*. *step* must not be zero + (or else :exc:`ValueError` is raised). Example:: >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] @@ -1045,13 +1051,13 @@ .. function:: zip([iterable, ...]) - This function returns a list of tuples, where the *i*-th tuple contains the - *i*-th element from each of the argument sequences or iterables. The returned - list is truncated in length to the length of the shortest argument sequence. - When there are multiple arguments which are all of the same length, :func:`zip` - is similar to :func:`map` with an initial argument of ``None``. With a single - sequence argument, it returns a list of 1-tuples. With no arguments, it returns - an empty list. + This function returns an iterator of tuples, where the *i*-th tuple contains + the *i*-th element from each of the argument sequences or iterables. The + iterator stops when the shortest argument sequence is exhausted. When there + are multiple arguments which are all of the same length, :func:`zip` is + similar to :func:`map` with an initial argument of ``None``. With a single + sequence argument, it returns an iterator of 1-tuples. With no arguments, it + returns an empty iterator. .. % --------------------------------------------------------------------------- From python-3000-checkins at python.org Tue Sep 4 19:58:03 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Tue, 4 Sep 2007 19:58:03 +0200 (CEST) Subject: [Python-3000-checkins] r57971 - python/branches/py3k/Doc/library/stdtypes.rst Message-ID: <20070904175803.36E271E4002@bag.python.org> Author: georg.brandl Date: Tue Sep 4 19:58:02 2007 New Revision: 57971 Modified: python/branches/py3k/Doc/library/stdtypes.rst Log: Add a dict view usage example. Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Tue Sep 4 19:58:02 2007 @@ -1906,6 +1906,36 @@ four operations will fail if an involved dictionary contains such a value. +An example of dictionary view usage:: + + >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500} + >>> keys = dishes.keys() + >>> values = dishes.values() + + >>> # iteration + >>> n = 0 + >>> for val in values: + ... n += val + >>> print(n) + 504 + + >>> # keys and values are iterated over in the same order + >>> list(keys) + ['eggs', 'bacon', 'sausage', 'spam'] + >>> list(values) + [2, 1, 1, 500] + + >>> # view objects are dynamic and reflect dict changes + >>> del dishes['eggs'] + >>> del dishes['sausage'] + >>> list(keys) + ['spam', 'bacon'] + + >>> # set operations + >>> keys & {'eggs', 'bacon', 'salad'} + {'eggs', 'bacon'} + + .. _bltin-file-objects: File Objects From python-3000-checkins at python.org Tue Sep 4 21:43:20 2007 From: python-3000-checkins at python.org (fred.drake) Date: Tue, 4 Sep 2007 21:43:20 +0200 (CEST) Subject: [Python-3000-checkins] r57974 - python/branches/py3k/setup.py Message-ID: <20070904194320.045E31E4002@bag.python.org> Author: fred.drake Date: Tue Sep 4 21:43:19 2007 New Revision: 57974 Modified: python/branches/py3k/setup.py Log: fix typo Modified: python/branches/py3k/setup.py ============================================================================== --- python/branches/py3k/setup.py (original) +++ python/branches/py3k/setup.py Tue Sep 4 21:43:19 2007 @@ -503,7 +503,7 @@ if sys.platform == 'darwin': # In every directory on the search path search for a dynamic # library and then a static library, instead of first looking - # for dynamic libraries on the entiry path. + # for dynamic libraries on the entire path. # This way a staticly linked custom readline gets picked up # before the (broken) dynamic library in /usr/lib. readline_extra_link_args = ('-Wl,-search_paths_first',) From python-3000-checkins at python.org Wed Sep 5 01:04:22 2007 From: python-3000-checkins at python.org (eric.smith) Date: Wed, 5 Sep 2007 01:04:22 +0200 (CEST) Subject: [Python-3000-checkins] r57976 - in python/branches/py3k: Lib/string.py Lib/test/test_unicode.py Objects/stringlib/string_format.h Message-ID: <20070904230422.6F31F1E4002@bag.python.org> Author: eric.smith Date: Wed Sep 5 01:04:22 2007 New Revision: 57976 Modified: python/branches/py3k/Lib/string.py python/branches/py3k/Lib/test/test_unicode.py python/branches/py3k/Objects/stringlib/string_format.h Log: Changed some ValueError's to KeyError and IndexError. Corrected code for invalid conversion specifier. Added tests to verify. Modified string.Formatter to correctly expand format_spec's, and added a limit to recursion depth. Added _vformat() method to support both of these. Modified: python/branches/py3k/Lib/string.py ============================================================================== --- python/branches/py3k/Lib/string.py (original) +++ python/branches/py3k/Lib/string.py Wed Sep 5 01:04:22 2007 @@ -202,6 +202,13 @@ def vformat(self, format_string, args, kwargs): used_args = set() + result = self._vformat(format_string, args, kwargs, used_args, 2) + self.check_unused_args(used_args, args, kwargs) + return result + + def _vformat(self, format_string, args, kwargs, used_args, recursion_depth): + if recursion_depth < 0: + raise ValueError('Max string recursion exceeded') result = [] for literal_text, field_name, format_spec, conversion in \ self.parse(format_string): @@ -223,10 +230,13 @@ # do any conversion on the resulting object obj = self.convert_field(obj, conversion) + # expand the format spec, if needed + format_spec = self._vformat(format_spec, args, kwargs, + used_args, recursion_depth-1) + # format the object and append to the result result.append(self.format_field(obj, format_spec)) - self.check_unused_args(used_args, args, kwargs) return ''.join(result) @@ -251,9 +261,9 @@ return repr(value) elif conversion == 's': return str(value) - else: - assert conversion is None + elif conversion is None: return value + raise ValueError("Unknown converion specifier {0!s}".format(conversion)) # returns an iterable that contains tuples of the form: Modified: python/branches/py3k/Lib/test/test_unicode.py ============================================================================== --- python/branches/py3k/Lib/test/test_unicode.py (original) +++ python/branches/py3k/Lib/test/test_unicode.py Wed Sep 5 01:04:22 2007 @@ -542,29 +542,30 @@ self.assertRaises(ValueError, 'a}'.format) self.assertRaises(ValueError, '{a'.format) self.assertRaises(ValueError, '}a'.format) - self.assertRaises(ValueError, '{0}'.format) - self.assertRaises(ValueError, '{1}'.format, 'abc') - self.assertRaises(ValueError, '{x}'.format) + self.assertRaises(IndexError, '{0}'.format) + self.assertRaises(IndexError, '{1}'.format, 'abc') + self.assertRaises(KeyError, '{x}'.format) self.assertRaises(ValueError, "}{".format) self.assertRaises(ValueError, "{".format) self.assertRaises(ValueError, "}".format) self.assertRaises(ValueError, "abc{0:{}".format) self.assertRaises(ValueError, "{0".format) - self.assertRaises(ValueError, "{0.}".format) - self.assertRaises(ValueError, "{0[}".format) + self.assertRaises(IndexError, "{0.}".format) + self.assertRaises(ValueError, "{0.}".format, 0) + self.assertRaises(IndexError, "{0[}".format) self.assertRaises(ValueError, "{0[}".format, []) - self.assertRaises(ValueError, "{0]}".format) - self.assertRaises(ValueError, "{0.[]}".format) + self.assertRaises(KeyError, "{0]}".format) + self.assertRaises(ValueError, "{0.[]}".format, 0) self.assertRaises(ValueError, "{0..foo}".format, 0) - self.assertRaises(ValueError, "{0[0}".format) - self.assertRaises(ValueError, "{0[0:foo}".format) - self.assertRaises(ValueError, "{c]}".format) - self.assertRaises(ValueError, "{{ {{{0}}".format) - self.assertRaises(ValueError, "{0}}".format) - self.assertRaises(ValueError, "{foo}".format, bar=3) + self.assertRaises(ValueError, "{0[0}".format, 0) + self.assertRaises(ValueError, "{0[0:foo}".format, 0) + self.assertRaises(KeyError, "{c]}".format) + self.assertRaises(ValueError, "{{ {{{0}}".format, 0) + self.assertRaises(ValueError, "{0}}".format, 0) + self.assertRaises(KeyError, "{foo}".format, bar=3) self.assertRaises(ValueError, "{0!x}".format, 3) - self.assertRaises(ValueError, "{0!}".format) - self.assertRaises(ValueError, "{0!rs}".format) + self.assertRaises(ValueError, "{0!}".format, 0) + self.assertRaises(ValueError, "{0!rs}".format, 0) self.assertRaises(ValueError, "{!}".format) self.assertRaises(ValueError, "{:}".format) self.assertRaises(ValueError, "{:s}".format) Modified: python/branches/py3k/Objects/stringlib/string_format.h ============================================================================== --- python/branches/py3k/Objects/stringlib/string_format.h (original) +++ python/branches/py3k/Objects/stringlib/string_format.h Wed Sep 5 01:04:22 2007 @@ -414,8 +414,7 @@ if (key == NULL) goto error; if ((kwargs == NULL) || (obj = PyDict_GetItem(kwargs, key)) == NULL) { - PyErr_SetString(PyExc_ValueError, "Keyword argument not found " - "in format string"); + PyErr_SetObject(PyExc_KeyError, key); Py_DECREF(key); goto error; } @@ -425,12 +424,8 @@ else { /* look up in args */ obj = PySequence_GetItem(args, index); - if (obj == NULL) { - /* translate IndexError to a ValueError */ - PyErr_SetString(PyExc_ValueError, "Not enough positional arguments " - "in format string"); + if (obj == NULL) goto error; - } } /* iterate over the rest of the field_name */ From python-3000-checkins at python.org Wed Sep 5 04:02:43 2007 From: python-3000-checkins at python.org (eric.smith) Date: Wed, 5 Sep 2007 04:02:43 +0200 (CEST) Subject: [Python-3000-checkins] r57982 - python/branches/py3k/Objects/stringlib/string_format.h Message-ID: <20070905020243.80E331E4002@bag.python.org> Author: eric.smith Date: Wed Sep 5 04:02:43 2007 New Revision: 57982 Modified: python/branches/py3k/Objects/stringlib/string_format.h Log: Simplified recursion logic. Modified variable name to match string.Formatter. Modified: python/branches/py3k/Objects/stringlib/string_format.h ============================================================================== --- python/branches/py3k/Objects/stringlib/string_format.h (original) +++ python/branches/py3k/Objects/stringlib/string_format.h Wed Sep 5 04:02:43 2007 @@ -29,7 +29,7 @@ /* forward declaration for recursion */ static PyObject * build_string(SubString *input, PyObject *args, PyObject *kwargs, - int *recursion_level); + int recursion_depth); @@ -792,7 +792,7 @@ output_markup(SubString *field_name, SubString *format_spec, int format_spec_needs_expanding, STRINGLIB_CHAR conversion, OutputString *output, PyObject *args, PyObject *kwargs, - int *recursion_level) + int recursion_depth) { PyObject *tmp = NULL; PyObject *fieldobj = NULL; @@ -818,7 +818,7 @@ /* if needed, recurively compute the format_spec */ if (format_spec_needs_expanding) { - tmp = build_string(format_spec, args, kwargs, recursion_level); + tmp = build_string(format_spec, args, kwargs, recursion_depth-1); if (tmp == NULL) goto done; @@ -852,7 +852,7 @@ */ static int do_markup(SubString *input, PyObject *args, PyObject *kwargs, - OutputString *output, int *recursion_level) + OutputString *output, int recursion_depth) { MarkupIterator iter; int format_spec_needs_expanding; @@ -871,7 +871,7 @@ if (field_name.ptr != field_name.end) if (!output_markup(&field_name, &format_spec, format_spec_needs_expanding, conversion, output, - args, kwargs, recursion_level)) + args, kwargs, recursion_depth)) return 0; } return result; @@ -884,7 +884,7 @@ */ static PyObject * build_string(SubString *input, PyObject *args, PyObject *kwargs, - int *recursion_level) + int recursion_depth) { OutputString output; PyObject *result = NULL; @@ -893,8 +893,7 @@ output.obj = NULL; /* needed so cleanup code always works */ /* check the recursion level */ - (*recursion_level)--; - if (*recursion_level < 0) { + if (recursion_depth <= 0) { PyErr_SetString(PyExc_ValueError, "Max string recursion exceeded"); goto done; @@ -907,7 +906,7 @@ INITIAL_SIZE_INCREMENT)) goto done; - if (!do_markup(input, args, kwargs, &output, recursion_level)) { + if (!do_markup(input, args, kwargs, &output, recursion_depth)) { goto done; } @@ -921,7 +920,6 @@ output.obj = NULL; done: - (*recursion_level)++; Py_XDECREF(output.obj); return result; } @@ -940,10 +938,10 @@ "{0:{1}}".format('abc', 's') # works "{0:{1:{2}}}".format('abc', 's', '') # fails */ - int recursion_level = 2; + int recursion_depth = 2; SubString_init(&input, STRINGLIB_STR(self), STRINGLIB_LEN(self)); - return build_string(&input, args, kwargs, &recursion_level); + return build_string(&input, args, kwargs, recursion_depth); } From python-3000-checkins at python.org Wed Sep 5 05:26:38 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 5 Sep 2007 05:26:38 +0200 (CEST) Subject: [Python-3000-checkins] r57983 - python/branches/py3k/Lib/test/test_doctest.py Message-ID: <20070905032638.B40771E4002@bag.python.org> Author: guido.van.rossum Date: Wed Sep 5 05:26:38 2007 New Revision: 57983 Modified: python/branches/py3k/Lib/test/test_doctest.py Log: Fix doctest failure introduced by r57949. The formatting of errors from pdb's own print command is different from the formatting of errors when pdb exec's an arbitrary command; the introduction of print as a pdb command caused this test to use the former instead of the latter, causing the test to fail. Modified: python/branches/py3k/Lib/test/test_doctest.py ============================================================================== --- python/branches/py3k/Lib/test/test_doctest.py (original) +++ python/branches/py3k/Lib/test/test_doctest.py Wed Sep 5 05:26:38 2007 @@ -1792,7 +1792,7 @@ > (1)() -> calls_set_trace() (Pdb) print(foo) - *** NameError: name 'foo' is not defined + *** NameError: NameError("name 'foo' is not defined",) (Pdb) continue (0, 2) """ From python-3000-checkins at python.org Wed Sep 5 10:43:04 2007 From: python-3000-checkins at python.org (mark.summerfield) Date: Wed, 5 Sep 2007 10:43:04 +0200 (CEST) Subject: [Python-3000-checkins] r57988 - python/branches/py3k/Doc/library/abc.rst python/branches/py3k/Doc/library/collections.rst Message-ID: <20070905084304.F1AD01E400A@bag.python.org> Author: mark.summerfield Date: Wed Sep 5 10:43:04 2007 New Revision: 57988 Modified: python/branches/py3k/Doc/library/abc.rst python/branches/py3k/Doc/library/collections.rst Log: Proof read/editing of abc. Added table of collections.Hashable etc. to collections with some brief notes. Modified: python/branches/py3k/Doc/library/abc.rst ============================================================================== --- python/branches/py3k/Doc/library/abc.rst (original) +++ python/branches/py3k/Doc/library/abc.rst Wed Sep 5 10:43:04 2007 @@ -9,13 +9,18 @@ .. much of the content adapted from docstrings This module provides the infrastructure for defining abstract base classes -(ABCs) in Python, as outlined in :pep:`3119`; see there for a rationale why this -was added to Python. +(ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this +was added to Python. (See also, :pep:`3141` regarding a type hierarchy +for numbers based on ABCs.) + +The :mod:`collections` module has some concrete classes that derive from +ABCs; these can, of course, be further derived. In addition the +:mod:`collections` module has some ABCs that can be used to test whether +a class or instance provides a particular interface, for example, is it +hashable or a mapping. -Concrete base ABCs to derive from can be found in the :mod:`collections` module. - -The module provides the following class: +This module provides the following class: .. class:: ABCMeta @@ -28,15 +33,24 @@ ABC by the built-in :func:`issubclass` function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via - :func:`super`). + :func:`super`). [#]_ Classes created with a metaclass of :class:`ABCMeta` have the following method: .. method:: register(subclass) - Register *subclass* as a "virtual subclass" of this ABC. From now on, - ``issubclass(subclass, ABC)`` is true. + Register *subclass* as a "virtual subclass" of this ABC. For + example:: + + from abc import ABCMeta + + class MyABC(metaclass=ABCMeta): + pass + MyABC.register(tuple) + + assert issubclass(tuple, MyABC) + assert isinstance((), MyABC) You can also override this method in an abstract base class: @@ -93,15 +107,15 @@ :meth:`__iter__`, as an abstract method. The implementation given here can still be called from subclasses. The :meth:`get_iterator` method is also part of the ``MyIterable`` abstract base class, but it does not have to be - overridden in a non-abstract child. + overridden in non-abstract derived classes. The :meth:`__subclasshook__` class method defined here says that any class that has an :meth:`__iter__` method in its :attr:`__dict__` (or in that of - one of its subclasses, accessed via the :attr:`__mro__`) is considered a - ``MyIterable`` too. + one of its base classes, accessed via the :attr:`__mro__` list) is + considered a ``MyIterable`` too. Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``, - even though it does not define a :meth:`__iter__` method (it uses the + even though it does not define an :meth:`__iter__` method (it uses the old-style iterable protocol, defined in terms of :meth:`__len__` and :meth:`__getitem__`). Note that this will not make ``get_iterator`` available as a method of ``Foo``, so it is provided separately. @@ -113,9 +127,11 @@ A decorator indicating abstract methods. - Using this decorator requires that the metaclass is :class:`ABCMeta` or - derived from it. A class that has a metaclass derived from :class:`ABCMeta` - cannot be instantiated unless all of its abstract methods are overridden. + Using this decorator requires that the class's metaclass is :class:`ABCMeta` or + is derived from it. + A class that has a metaclass derived from :class:`ABCMeta` + cannot be instantiated unless all of its abstract methods and + properties are overridden. The abstract methods can be called using any of the the normal 'super' call mechanisms. @@ -134,20 +150,24 @@ .. note:: - Unlike C++ or Java, these abstract methods may have an implementation. - This implementation can be called via the :func:`super` mechanism from the - class that overrides it. This could be useful as an end-point for a - super-call in framework using a cooperative multiple-inheritance + Unlike C++'s pure virtual functions, or Java abstract methods, these abstract + methods may have an implementation. This implementation can be + called via the :func:`super` mechanism from the class that + overrides it. This could be useful as an end-point for a + super-call in a framework that uses cooperative + multiple-inheritance. .. function:: abstractproperty(fget[, fset[, fdel[, doc]]]) A subclass of the built-in :func:`property`, indicating an abstract property. - Requires that the metaclass is :class:`ABCMeta` or derived from it. A class - that has a metaclass derived from :class:`ABCMeta` cannot be instantiated - unless all of its abstract properties are overridden. The abstract - properties can be called using any of the the normal 'super' call mechanisms. + Using this function requires that the class's metaclass is :class:`ABCMeta` or + is derived from it. + A class that has a metaclass derived from :class:`ABCMeta` cannot be + instantiated unless all of its abstract methods and properties are overridden. + The abstract properties can be called using any of the normal + 'super' call mechanisms. Usage:: @@ -164,3 +184,7 @@ def setx(self, value): ... x = abstractproperty(getx, setx) +.. rubric:: Footnotes + +.. [#] C++ programmers should note that Python's virtual base class + concept is not the same as C++'s. Modified: python/branches/py3k/Doc/library/collections.rst ============================================================================== --- python/branches/py3k/Doc/library/collections.rst (original) +++ python/branches/py3k/Doc/library/collections.rst Wed Sep 5 10:43:04 2007 @@ -19,6 +19,55 @@ Future editions of the standard library may include balanced trees and ordered dictionaries. +In addition to containers, the collections module provides some ABCs +(abstract base classes) that can be used to test whether +a class provides a particular interface, for example, is it hashable or +a mapping. The ABCs provided include those in the following table: + +===================================== ======================================== +ABC Notes +===================================== ======================================== +:class:`collections.Container` Defines ``__contains__()`` +:class:`collections.Hashable` Defines ``__hash__()`` +:class:`collections.Iterable` Defines ``__iter__()`` +:class:`collections.Iterator` Derived from :class:`Iterable` and in + addition defines ``__next__()`` +:class:`collections.Mapping` Derived from :class:`Container`, + :class:`Iterable`, + and :class:`Sized`, and in addition + defines ``__getitem__()``, ``get()``, + ``__contains__()``, ``__len__()``, + ``__iter__()``, ``keys()``, + ``items()``, and ``values()`` +:class:`collections.MutableMapping` Derived from :class:`Mapping` +:class:`collections.MutableSequence` Derived from :class:`Sequence` +:class:`collections.MutableSet` Derived from :class:`Set` and in + addition defines ``add()``, + ``clear()``, ``discard()``, ``pop()``, + and ``toggle()`` +:class:`collections.Sequence` Derived from :class:`Container`, + :class:`Iterable`, and :class:`Sized`, + and in addition defines + ``__getitem__()`` +:class:`collections.Set` Derived from :class:`Container`, :class:`Iterable`, and :class:`Sized` +:class:`collections.Sized` Defines ``__len__()`` +===================================== ======================================== + +.. XXX Have not included them all and the notes are imcomplete +.. Deliberately did one row wide to get a neater output + +These ABCs allow us to ask classes or instances if they provide +particular functionality, for example:: + + from collections import Sized + + size = None + if isinstance(myvar, Sized): + size = len(myvar) + +(For more about ABCs, see the :mod:`abc` module and :pep:`3119`.) + + .. _deque-objects: From python-3000-checkins at python.org Wed Sep 5 15:36:27 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 5 Sep 2007 15:36:27 +0200 (CEST) Subject: [Python-3000-checkins] r57992 - python/branches/py3k/Doc/reference/datamodel.rst Message-ID: <20070905133627.8CA571E4011@bag.python.org> Author: georg.brandl Date: Wed Sep 5 15:36:27 2007 New Revision: 57992 Modified: python/branches/py3k/Doc/reference/datamodel.rst Log: Bug #1684991: explain __special__ lookup semantics. Modified: python/branches/py3k/Doc/reference/datamodel.rst ============================================================================== --- python/branches/py3k/Doc/reference/datamodel.rst (original) +++ python/branches/py3k/Doc/reference/datamodel.rst Wed Sep 5 15:36:27 2007 @@ -1060,6 +1060,20 @@ .. XXX above translation is not correct for new-style classes! +Special methods are only guaranteed to work if defined in an object's class, not +in the object's instance dictionary. That explains why this won't work:: + + >>> class C: + ... pass + ... + >>> c = C() + >>> c.__len__ = lambda: 5 + >>> len(c) + Traceback (most recent call last): + File "", line 1, in + TypeError: object of type 'C' has no len() + + When implementing a class that emulates any built-in type, it is important that the emulation only be implemented to the degree that it makes sense for the object being modelled. For example, some sequences may work well with retrieval From python-3000-checkins at python.org Wed Sep 5 22:35:46 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Wed, 5 Sep 2007 22:35:46 +0200 (CEST) Subject: [Python-3000-checkins] r57995 - python/branches/py3k/Parser/parsetok.c Message-ID: <20070905203546.53FA11E401A@bag.python.org> Author: brett.cannon Date: Wed Sep 5 22:35:46 2007 New Revision: 57995 Modified: python/branches/py3k/Parser/parsetok.c Log: Cast away const qualifier to silence a compiler warning about it. Modified: python/branches/py3k/Parser/parsetok.c ============================================================================== --- python/branches/py3k/Parser/parsetok.c (original) +++ python/branches/py3k/Parser/parsetok.c Wed Sep 5 22:35:46 2007 @@ -72,7 +72,7 @@ initerr(err_ret, filename); - if ((tok = PyTokenizer_FromFile(fp, enc, ps1, ps2)) == NULL) { + if ((tok = PyTokenizer_FromFile(fp, (char *)enc, ps1, ps2)) == NULL) { err_ret->error = E_NOMEM; return NULL; } From python-3000-checkins at python.org Thu Sep 6 05:57:24 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 6 Sep 2007 05:57:24 +0200 (CEST) Subject: [Python-3000-checkins] r57997 - python/branches/py3k/Lib/test/test_ftplib.py Message-ID: <20070906035724.47B2B1E400A@bag.python.org> Author: guido.van.rossum Date: Thu Sep 6 05:57:23 2007 New Revision: 57997 Modified: python/branches/py3k/Lib/test/test_ftplib.py Log: Use an event variable to wait for the server to be ready, not time.sleep(). Modified: python/branches/py3k/Lib/test/test_ftplib.py ============================================================================== --- python/branches/py3k/Lib/test/test_ftplib.py (original) +++ python/branches/py3k/Lib/test/test_ftplib.py Thu Sep 6 05:57:23 2007 @@ -6,12 +6,13 @@ from unittest import TestCase from test import test_support -def server(evt): +def server(evt, ready): serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serv.settimeout(3) serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serv.bind(("", 9091)) serv.listen(5) + ready.set() try: conn, addr = serv.accept() except socket.timeout: @@ -28,8 +29,9 @@ def setUp(self): ftplib.FTP.port = 9091 self.evt = threading.Event() - threading.Thread(target=server, args=(self.evt,)).start() - time.sleep(.1) + ready = threading.Event() + threading.Thread(target=server, args=(self.evt, ready)).start() + ready.wait() def tearDown(self): self.evt.wait() From python-3000-checkins at python.org Thu Sep 6 06:03:04 2007 From: python-3000-checkins at python.org (kurt.kaiser) Date: Thu, 6 Sep 2007 06:03:04 +0200 (CEST) Subject: [Python-3000-checkins] r57998 - python/branches/py3k/Lib/idlelib/EditorWindow.py python/branches/py3k/Lib/idlelib/FileList.py Message-ID: <20070906040304.6A2791E4004@bag.python.org> Author: kurt.kaiser Date: Thu Sep 6 06:03:04 2007 New Revision: 57998 Modified: python/branches/py3k/Lib/idlelib/EditorWindow.py python/branches/py3k/Lib/idlelib/FileList.py Log: 1. Fail gracefully if the file fails to decode when loaded. 2. If the load fails, close the half-built edit window. 3. Don't reopen the file to check the shebang. 4. Clarify that we're setting tabs in Tk. M EditorWindow.py M FileList.py Modified: python/branches/py3k/Lib/idlelib/EditorWindow.py ============================================================================== --- python/branches/py3k/Lib/idlelib/EditorWindow.py (original) +++ python/branches/py3k/Lib/idlelib/EditorWindow.py Thu Sep 6 06:03:04 2007 @@ -224,42 +224,32 @@ # conceivable file). # Making the initial values larger slows things down more often. self.num_context_lines = 50, 500, 5000000 - self.per = per = self.Percolator(text) - if self.ispythonsource(filename): - self.color = color = self.ColorDelegator() - per.insertfilter(color) - else: - self.color = None - + self.color = None self.undo = undo = self.UndoDelegator() per.insertfilter(undo) text.undo_block_start = undo.undo_block_start text.undo_block_stop = undo.undo_block_stop undo.set_saved_change_hook(self.saved_change_hook) - # IOBinding implements file I/O and printing functionality self.io = io = self.IOBinding(self) io.set_filename_change_hook(self.filename_change_hook) - - # Create the recent files submenu - self.recent_files_menu = Menu(self.menubar) - self.menudict['file'].insert_cascade(3, label='Recent Files', - underline=0, - menu=self.recent_files_menu) - self.update_recent_files_list() - + self.good_load = False + self.set_indentation_params(False) if filename: if os.path.exists(filename) and not os.path.isdir(filename): - io.loadfile(filename) + if io.loadfile(filename): + self.good_load = True + is_py_src = self.ispythonsource(filename) + self.set_indentation_params(is_py_src) + if is_py_src: + self.color = color = self.ColorDelegator() + per.insertfilter(color) else: io.set_filename(filename) self.saved_change_hook() - - self.set_indentation_params(self.ispythonsource(filename)) - + self.update_recent_files_list() self.load_extensions() - menu = self.menudict.get('windows') if menu: end = menu.index("end") @@ -337,13 +327,15 @@ underline, label = prepstr(label) menudict[name] = menu = Menu(mbar, name=name) mbar.add_cascade(label=label, menu=menu, underline=underline) - if sys.platform == 'darwin' and '.framework' in sys.executable: # Insert the application menu menudict['application'] = menu = Menu(mbar, name='apple') mbar.add_cascade(label='IDLE', menu=menu) - self.fill_menus() + self.recent_files_menu = Menu(self.menubar) + self.menudict['file'].insert_cascade(3, label='Recent Files', + underline=0, + menu=self.recent_files_menu) self.base_helpmenu_length = self.menudict['help'].index(END) self.reset_help_menu_entries() @@ -489,7 +481,7 @@ text.see("insert") def open_module(self, event=None): - # XXX Shouldn't this be in IOBinding or in FileList? + # XXX Shouldn't this be in IOBinding? try: name = self.text.get("sel.first", "sel.last") except TclError: @@ -552,13 +544,8 @@ base, ext = os.path.splitext(os.path.basename(filename)) if os.path.normcase(ext) in (".py", ".pyw"): return True - try: - f = open(filename) - line = f.readline() - f.close() - except IOError: - return False - return line.startswith('#!') and line.find('python') >= 0 + line = self.text.get('1.0', '1.0 lineend') + return line.startswith('#!') and 'python' in line def close_hook(self): if self.flist: @@ -1003,15 +990,16 @@ # Return the text widget's current view of what a tab stop means # (equivalent width in spaces). - def get_tabwidth(self): + def get_tk_tabwidth(self): current = self.text['tabs'] or TK_TABWIDTH_DEFAULT return int(current) # Set the text widget's current view of what a tab stop means. - def set_tabwidth(self, newtabwidth): + def set_tk_tabwidth(self, newtabwidth): text = self.text - if self.get_tabwidth() != newtabwidth: + if self.get_tk_tabwidth() != newtabwidth: + # Set text widget tab width pixels = text.tk.call("font", "measure", text["font"], "-displayof", text.master, "n" * newtabwidth) @@ -1019,20 +1007,14 @@ ### begin autoindent code ### (configuration was moved to beginning of class) - # If ispythonsource and guess are true, guess a good value for - # indentwidth based on file content (if possible), and if - # indentwidth != tabwidth set usetabs false. - # In any case, adjust the Text widget's view of what a tab - # character means. - - def set_indentation_params(self, ispythonsource, guess=True): - if guess and ispythonsource: + def set_indentation_params(self, is_py_src, guess=True): + if is_py_src and guess: i = self.guess_indent() if 2 <= i <= 8: self.indentwidth = i if self.indentwidth != self.tabwidth: self.usetabs = False - self.set_tabwidth(self.tabwidth) + self.set_tk_tabwidth(self.tabwidth) def smart_backspace_event(self, event): text = self.text Modified: python/branches/py3k/Lib/idlelib/FileList.py ============================================================================== --- python/branches/py3k/Lib/idlelib/FileList.py (original) +++ python/branches/py3k/Lib/idlelib/FileList.py Thu Sep 6 06:03:04 2007 @@ -33,7 +33,12 @@ # Don't create window, perform 'action', e.g. open in same window return action(filename) else: - return self.EditorWindow(self, filename, key) + edit = self.EditorWindow(self, filename, key) + if edit.good_load: + return edit + else: + edit._close() + return None def gotofileline(self, filename, lineno=None): edit = self.open(filename) From python-3000-checkins at python.org Thu Sep 6 16:03:41 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Thu, 6 Sep 2007 16:03:41 +0200 (CEST) Subject: [Python-3000-checkins] r58007 - python/branches/py3k/Doc/reference/compound_stmts.rst Message-ID: <20070906140341.BA58A1E4005@bag.python.org> Author: georg.brandl Date: Thu Sep 6 16:03:41 2007 New Revision: 58007 Modified: python/branches/py3k/Doc/reference/compound_stmts.rst Log: New exception catching syntax. Modified: python/branches/py3k/Doc/reference/compound_stmts.rst ============================================================================== --- python/branches/py3k/Doc/reference/compound_stmts.rst (original) +++ python/branches/py3k/Doc/reference/compound_stmts.rst Thu Sep 6 16:03:41 2007 @@ -219,13 +219,13 @@ .. productionlist:: try_stmt: try1_stmt | try2_stmt try1_stmt: "try" ":" `suite` - : ("except" [`expression` ["," `target`]] ":" `suite`)+ + : ("except" [`expression` ["as" `target`]] ":" `suite`)+ : ["else" ":" `suite`] : ["finally" ":" `suite`] try2_stmt: "try" ":" `suite` : "finally" ":" `suite` -The :keyword:`except` clause(s) specify one or more exception handlers. When no +The :keyword:`except` clause(s) specify one or more exception handlers. When no exception occurs in the :keyword:`try` clause, no exception handler is executed. When an exception occurs in the :keyword:`try` suite, a search for an exception handler is started. This search inspects the except clauses in turn until one @@ -245,12 +245,12 @@ as if the entire :keyword:`try` statement raised the exception). When a matching except clause is found, the exception is assigned to the target -specified in that except clause, if present, and the except clause's suite is -executed. All except clauses must have an executable block. When the end of -this block is reached, execution continues normally after the entire try -statement. (This means that if two nested handlers exist for the same -exception, and the exception occurs in the try clause of the inner handler, the -outer handler will not handle the exception.) +specified after the ``as`` keyword in that except clause, if present, and the +except clause's suite is executed. All except clauses must have an executable +block. When the end of this block is reached, execution continues normally +after the entire try statement. (This means that if two nested handlers exist +for the same exception, and the exception occurs in the try clause of the inner +handler, the outer handler will not handle the exception.) .. index:: module: sys @@ -545,4 +545,3 @@ .. [#] Currently, control "flows off the end" except in the case of an exception or the execution of a :keyword:`return`, :keyword:`continue`, or :keyword:`break` statement. - From python-3000-checkins at python.org Thu Sep 6 16:09:10 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Thu, 6 Sep 2007 16:09:10 +0200 (CEST) Subject: [Python-3000-checkins] r58008 - python/branches/py3k/Doc/library/hashlib.rst Message-ID: <20070906140910.58DDD1E4005@bag.python.org> Author: georg.brandl Date: Thu Sep 6 16:09:10 2007 New Revision: 58008 Modified: python/branches/py3k/Doc/library/hashlib.rst Log: hashlib operates on bytes, not strings. Modified: python/branches/py3k/Doc/library/hashlib.rst ============================================================================== --- python/branches/py3k/Doc/library/hashlib.rst (original) +++ python/branches/py3k/Doc/library/hashlib.rst Thu Sep 6 16:09:10 2007 @@ -15,9 +15,9 @@ This module implements a common interface to many different secure hash and message digest algorithms. Included are the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA's MD5 -algorithm (defined in Internet :rfc:`1321`). The terms secure hash and message -digest are interchangeable. Older algorithms were called message digests. The -modern term is secure hash. +algorithm (defined in Internet :rfc:`1321`). The terms "secure hash" and +"message digest" are interchangeable. Older algorithms were called message +digests. The modern term is secure hash. .. warning:: @@ -25,10 +25,16 @@ There is one constructor method named for each type of :dfn:`hash`. All return a hash object with the same simple interface. For example: use :func:`sha1` to -create a SHA1 hash object. You can now feed this object with arbitrary strings -using the :meth:`update` method. At any point you can ask it for the -:dfn:`digest` of the concatenation of the strings fed to it so far using the -:meth:`digest` or :meth:`hexdigest` methods. +create a SHA1 hash object. You can now feed this object with objects conforming +to the buffer interface (normally :class:`bytes` objects) using the +:meth:`update` method. At any point you can ask it for the :dfn:`digest` of the +concatenation of the data fed to it so far using the :meth:`digest` or +:meth:`hexdigest` methods. + +.. note:: + + Feeding string objects is to :meth:`update` is not supported, as hashes work + on bytes, not on characters. .. index:: single: OpenSSL @@ -37,20 +43,20 @@ :func:`sha512`. Additional algorithms may also be available depending upon the OpenSSL library that Python uses on your platform. -For example, to obtain the digest of the string ``'Nobody inspects the spammish -repetition'``:: +For example, to obtain the digest of the byte string ``b'Nobody inspects the +spammish repetition'``:: >>> import hashlib >>> m = hashlib.md5() - >>> m.update("Nobody inspects") - >>> m.update(" the spammish repetition") + >>> m.update(b"Nobody inspects") + >>> m.update(b" the spammish repetition") >>> m.digest() - '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9' + b'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9' More condensed:: - >>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest() - 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' + >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest() + b'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2' A generic :func:`new` constructor that takes the string name of the desired algorithm as its first parameter also exists to allow access to the above listed @@ -60,9 +66,9 @@ Using :func:`new` with an algorithm provided by OpenSSL:: >>> h = hashlib.new('ripemd160') - >>> h.update("Nobody inspects the spammish repetition") + >>> h.update(b"Nobody inspects the spammish repetition") >>> h.hexdigest() - 'cc4a5ce1b3df48aec5d22d1f16b894a0b894eccc' + b'cc4a5ce1b3df48aec5d22d1f16b894a0b894eccc' The following values are provided as constant attributes of the hash objects returned by the constructors: @@ -77,29 +83,30 @@ .. method:: hash.update(arg) - Update the hash object with the string *arg*. Repeated calls are equivalent to - a single call with the concatenation of all the arguments: ``m.update(a); - m.update(b)`` is equivalent to ``m.update(a+b)``. + Update the hash object with the object *arg*, which must be interpretable as + a buffer of bytes. Repeated calls are equivalent to a single call with the + concatenation of all the arguments: ``m.update(a); m.update(b)`` is + equivalent to ``m.update(a+b)``. .. method:: hash.digest() - Return the digest of the strings passed to the :meth:`update` method so far. - This is a string of :attr:`digest_size` bytes which may contain non-ASCII - characters, including null bytes. + Return the digest of the data passed to the :meth:`update` method so far. + This is a bytes array of size :attr:`digest_size` which may contain bytes in + the whole range from 0 to 255. .. method:: hash.hexdigest() - Like :meth:`digest` except the digest is returned as a string of double length, - containing only hexadecimal digits. This may be used to exchange the value - safely in email or other non-binary environments. + Like :meth:`digest` except the digest is returned as a string object of + double length, containing only hexadecimal digits. This may be used to + exchange the value safely in email or other non-binary environments. .. method:: hash.copy() Return a copy ("clone") of the hash object. This can be used to efficiently - compute the digests of strings that share a common initial substring. + compute the digests of data sharing a common initial substring. .. seealso:: From python-3000-checkins at python.org Thu Sep 6 16:46:41 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 6 Sep 2007 16:46:41 +0200 (CEST) Subject: [Python-3000-checkins] r58011 - python/branches/py3k/Doc/whatsnew/3.0.rst Message-ID: <20070906144641.6053F1E401A@bag.python.org> Author: guido.van.rossum Date: Thu Sep 6 16:46:41 2007 New Revision: 58011 Modified: python/branches/py3k/Doc/whatsnew/3.0.rst Log: In response to issue 1101, place vastly more emphasis on the new print() function. Modified: python/branches/py3k/Doc/whatsnew/3.0.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/3.0.rst (original) +++ python/branches/py3k/Doc/whatsnew/3.0.rst Thu Sep 6 16:46:41 2007 @@ -79,6 +79,48 @@ remains syntactically valid that trips people up. I'm also omitting changes to rarely used features.) +* The ``print`` statement has been replaced with a ``print()`` function, + with keyword arguments to replace most of the special syntax of the + old ``print`` statement (PEP 3105). Examples:: + + Old: print "The answer is", 2*2 + New: print("The answer is", 2*2) + + Old: print x, # Trailing comma suppresses newline + New: print(x, end=" ") # Appends a space instead of a newline + + Old: print # Prints a newline + New: print() # You must call the function! + + Old: print >>sys.stderr, "fatal error" + New: print("fatal error", file=sys.stderr) + + Old: print (x, y) # prints repr((x, y)) + New: print((x, y)) # Not the same as print(x, y)! + + You can also customize the separator between items, e.g.:: + + print("There are <", 2**32, "> possibilities!", sep="") + + which produces:: + + There are <4294967296> possibilities! + + Notes about the ``print()`` function: + + * The ``print()`` function doesn't support the "softspace" feature of + the old ``print`` statement. For example, in Python 2.x, + ``print "A\n", "B"`` would write ``"A\nB\n"``; but in Python 3.0, + ``print("A\n", "B")`` writes ``"A\n B\n"``. + + * Initially, you'll be finding yourself typing the old ``print x`` + a lot in interactive mode. Time to retrain your fingers to type + ``print(x)`` instead! + + * When using the ``2to3`` source-to-source conversion tool, all + ``print`` statements are autmatically converted to ``print()`` + function calls, so this is mostly a non-issue for larger projects. + * Python 3.0 uses strings and bytes instead of the Unicode strings and 8-bit strings. This means that pretty much all code that uses Unicode, encodings or binary data in any way has to change. The @@ -109,19 +151,6 @@ * Code that unconditionally strips the trailing ``L`` from the ``repr()`` of a long integer will chop off the last digit instead. -* The ``print()`` function doesn't support the "softspace" feature of - the old ``print`` statement. For example, in Python 2.x, - ``print "A\n", "B"`` would write ``"A\nB\n"``; but in Python 3.0, - ``print("A\n", "B")`` writes ``"A\n B\n"``. - -* Also, ``print`` and ``print (x, y)`` behave differently without - warning: the former used to add a newline in 2.x, but does nothing - in 3.0; the latter used to print the ``repr()`` of a tuple in 2.x, - but prints the individual values in 3.0. - -* You'll be finding yourself typing ``print x`` a lot in interactive - mode. Time to retrain your fingers. :-) - Strings and Bytes ================= @@ -241,10 +270,6 @@ * PEP 3104: ``nonlocal`` statement. Using ``nonlocal x`` you can now assign directly to a variable in an outer (but non-global) scope. -* PEP 3105: ``print`` is now a function. Keyword arguments - ``file=sys.stdout``, ``sep=" "`` and ``end="\n"`` let you customize - it. - * PEP 3111: ``raw_input()`` renamed to ``input()``. That is, the new ``input()`` function reads a line from ``sys.stdin`` and returns it with the trailing newline stripped. It raises ``EOFError`` if the From python-3000-checkins at python.org Thu Sep 6 16:49:02 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Thu, 6 Sep 2007 16:49:02 +0200 (CEST) Subject: [Python-3000-checkins] r58012 - python/branches/py3k/Doc/extending/extending.rst Message-ID: <20070906144902.597C91E4008@bag.python.org> Author: georg.brandl Date: Thu Sep 6 16:49:02 2007 New Revision: 58012 Modified: python/branches/py3k/Doc/extending/extending.rst Log: #1116: reference to old filename fixed. Modified: python/branches/py3k/Doc/extending/extending.rst ============================================================================== --- python/branches/py3k/Doc/extending/extending.rst (original) +++ python/branches/py3k/Doc/extending/extending.rst Thu Sep 6 16:49:02 2007 @@ -418,7 +418,7 @@ standard interface to call a Python function. (I won't dwell on how to call the Python parser with a particular string as input --- if you're interested, have a look at the implementation of the :option:`-c` command line option in -:file:`Python/pythonmain.c` from the Python source code.) +:file:`Modules/main.c` from the Python source code.) Calling a Python function is easy. First, the Python program must somehow pass you the Python function object. You should provide a function (or some other From python-3000-checkins at python.org Thu Sep 6 18:30:31 2007 From: python-3000-checkins at python.org (skip.montanaro) Date: Thu, 6 Sep 2007 18:30:31 +0200 (CEST) Subject: [Python-3000-checkins] r58016 - python/branches/py3k/setup.py Message-ID: <20070906163031.4F4E11E400B@bag.python.org> Author: skip.montanaro Date: Thu Sep 6 18:30:31 2007 New Revision: 58016 Modified: python/branches/py3k/setup.py Log: I think we can just dump the else clause, per the comment I just deleted. Modified: python/branches/py3k/setup.py ============================================================================== --- python/branches/py3k/setup.py (original) +++ python/branches/py3k/setup.py Thu Sep 6 18:30:31 2007 @@ -617,9 +617,6 @@ # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash exts.append( Extension('_sha256', ['sha256module.c']) ) exts.append( Extension('_sha512', ['sha512module.c']) ) - else: - # these aren't strictly missing since they are unneeded. - missing.extend(['_sha256', '_sha512']) # Modules that provide persistent dictionary-like semantics. You will # probably want to arrange for at least one of them to be available on From guido at python.org Thu Sep 6 19:15:38 2007 From: guido at python.org (Guido van Rossum) Date: Thu, 6 Sep 2007 10:15:38 -0700 Subject: [Python-3000-checkins] r58012 - python/branches/py3k/Doc/extending/extending.rst In-Reply-To: <20070906144902.597C91E4008@bag.python.org> References: <20070906144902.597C91E4008@bag.python.org> Message-ID: I'm guessing this is also wrong on the trunk then? On 9/6/07, georg.brandl wrote: > Author: georg.brandl > Date: Thu Sep 6 16:49:02 2007 > New Revision: 58012 > > Modified: > python/branches/py3k/Doc/extending/extending.rst > Log: > #1116: reference to old filename fixed. > > > Modified: python/branches/py3k/Doc/extending/extending.rst > ============================================================================== > --- python/branches/py3k/Doc/extending/extending.rst (original) > +++ python/branches/py3k/Doc/extending/extending.rst Thu Sep 6 16:49:02 2007 > @@ -418,7 +418,7 @@ > standard interface to call a Python function. (I won't dwell on how to call the > Python parser with a particular string as input --- if you're interested, have a > look at the implementation of the :option:`-c` command line option in > -:file:`Python/pythonmain.c` from the Python source code.) > +:file:`Modules/main.c` from the Python source code.) > > Calling a Python function is easy. First, the Python program must somehow pass > you the Python function object. You should provide a function (or some other > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > -- --Guido van Rossum (home page: http://www.python.org/~guido/) From g.brandl at gmx.net Thu Sep 6 19:43:01 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Thu, 06 Sep 2007 19:43:01 +0200 Subject: [Python-3000-checkins] r58012 - python/branches/py3k/Doc/extending/extending.rst In-Reply-To: References: <20070906144902.597C91E4008@bag.python.org> Message-ID: Guido van Rossum schrieb: > I'm guessing this is also wrong on the trunk then? Yes - it's already fixed there :) Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. From python-3000-checkins at python.org Thu Sep 6 20:55:17 2007 From: python-3000-checkins at python.org (jeffrey.yasskin) Date: Thu, 6 Sep 2007 20:55:17 +0200 (CEST) Subject: [Python-3000-checkins] r58017 - python/branches/py3k/Lib/unittest.py Message-ID: <20070906185517.DC86F1E4013@bag.python.org> Author: jeffrey.yasskin Date: Thu Sep 6 20:55:17 2007 New Revision: 58017 Modified: python/branches/py3k/Lib/unittest.py Log: Extend unittest's fail*AlmostEqual methods to work on complex numbers. Modified: python/branches/py3k/Lib/unittest.py ============================================================================== --- python/branches/py3k/Lib/unittest.py (original) +++ python/branches/py3k/Lib/unittest.py Thu Sep 6 20:55:17 2007 @@ -339,7 +339,7 @@ Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). """ - if round(second-first, places) != 0: + if round(abs(second-first), places) != 0: raise self.failureException(msg or '%r != %r within %r places' % (first, second, places)) @@ -351,7 +351,7 @@ Note that decimal places (from zero) are usually not the same as significant digits (measured from the most signficant digit). """ - if round(second-first, places) == 0: + if round(abs(second-first), places) == 0: raise self.failureException(msg or '%r == %r within %r places' % (first, second, places)) From python-3000-checkins at python.org Fri Sep 7 01:06:50 2007 From: python-3000-checkins at python.org (gregory.p.smith) Date: Fri, 7 Sep 2007 01:06:50 +0200 (CEST) Subject: [Python-3000-checkins] r58025 - python/branches/py3k/Lib/bsddb/test/test_1413192.py Message-ID: <20070906230650.6ACF21E401A@bag.python.org> Author: gregory.p.smith Date: Fri Sep 7 01:06:50 2007 New Revision: 58025 Modified: python/branches/py3k/Lib/bsddb/test/test_1413192.py Log: merge r58023 to fix issue1112 on windows. make this test more robust and deterministic. Modified: python/branches/py3k/Lib/bsddb/test/test_1413192.py ============================================================================== --- python/branches/py3k/Lib/bsddb/test/test_1413192.py (original) +++ python/branches/py3k/Lib/bsddb/test/test_1413192.py Fri Sep 7 01:06:50 2007 @@ -1,7 +1,6 @@ - -# http://python.org/sf/1413192 +# http://bugs.python.org/issue1413192 # -# This test relies on the variable names, see the bug report for details. +# See the bug report for details. # The problem was that the env was deallocated prior to the txn. import shutil @@ -15,15 +14,28 @@ env_name = tempfile.mkdtemp() -env = db.DBEnv() -env.open(env_name, db.DB_CREATE | db.DB_INIT_TXN | db.DB_INIT_MPOOL) -the_txn = env.txn_begin() - -map = db.DB(env) -map.open('xxx.db', - "p", db.DB_HASH, db.DB_CREATE, 0o666, txn=the_txn) +# Wrap test operation in a class so we can control destruction rather than +# waiting for the controlling Python executable to exit + +class Context: + + def __init__(self): + self.env = db.DBEnv() + self.env.open(env_name, + db.DB_CREATE | db.DB_INIT_TXN | db.DB_INIT_MPOOL) + self.the_txn = self.env.txn_begin() + + self.map = db.DB(self.env) + self.map.open('xxx.db', "p", + db.DB_HASH, db.DB_CREATE, 0o666, txn=self.the_txn) + del self.env + del self.the_txn + + +context = Context() +del context -# try not to leave a turd (won't help Windows since files are still open) +# try not to leave a turd try: shutil.rmtree(env_name) except EnvironmentError: From python-3000-checkins at python.org Fri Sep 7 04:12:14 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 7 Sep 2007 04:12:14 +0200 (CEST) Subject: [Python-3000-checkins] r58026 - python/branches/py3k/Lib/inspect.py Message-ID: <20070907021214.94B8A1E4027@bag.python.org> Author: brett.cannon Date: Fri Sep 7 04:12:14 2007 New Revision: 58026 Modified: python/branches/py3k/Lib/inspect.py Log: Fix docstring for getfullargspec(). Modified: python/branches/py3k/Lib/inspect.py ============================================================================== --- python/branches/py3k/Lib/inspect.py (original) +++ python/branches/py3k/Lib/inspect.py Fri Sep 7 04:12:14 2007 @@ -731,8 +731,8 @@ def getfullargspec(func): """Get the names and default values of a function's arguments. - A tuple of seven things is returned: (args, varargs, kwonlyargs, - kwonlydefaults, varkw, defaults, annotations). + A tuple of seven things is returned: + (args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. From python-3000-checkins at python.org Fri Sep 7 07:06:21 2007 From: python-3000-checkins at python.org (kurt.kaiser) Date: Fri, 7 Sep 2007 07:06:21 +0200 (CEST) Subject: [Python-3000-checkins] r58033 - python/branches/py3k/Lib/idlelib/IOBinding.py Message-ID: <20070907050622.306DA1E400A@bag.python.org> Author: kurt.kaiser Date: Fri Sep 7 07:06:21 2007 New Revision: 58033 Modified: python/branches/py3k/Lib/idlelib/IOBinding.py Log: Make IDLE's file decode more robust. 1. coding_spec() only looks at first two lines of bytes to avoid a UnicodeDecodeError if rest of file is e.g. latin-1 2. coding_spec() handles \n or \r 3. Clarify that locale_encoding is used by calling it that. However, it's still called IOBinding.encoding in other parts of IDLE and that usage needs to be checked to verify that's still what is desired. 4. Return None from _decode() if decoding fails. 5. Name the vars representing bytes and strings or chars appropriately. Modified: python/branches/py3k/Lib/idlelib/IOBinding.py ============================================================================== --- python/branches/py3k/Lib/idlelib/IOBinding.py (original) +++ python/branches/py3k/Lib/idlelib/IOBinding.py Fri Sep 7 07:06:21 2007 @@ -22,15 +22,15 @@ pass # Encoding for file names -filesystemencoding = sys.getfilesystemencoding() +filesystemencoding = sys.getfilesystemencoding() ### currently unused -encoding = "ascii" +locale_encoding = 'ascii' if sys.platform == 'win32': # On Windows, we could use "mbcs". However, to give the user # a portable encoding name, we need to find the code page try: - encoding = locale.getdefaultlocale()[1] - codecs.lookup(encoding) + locale_encoding = locale.getdefaultlocale()[1] + codecs.lookup(locale_encoding) except LookupError: pass else: @@ -39,25 +39,28 @@ # loaded, it may not offer nl_langinfo, or CODESET, or the # resulting codeset may be unknown to Python. We ignore all # these problems, falling back to ASCII - encoding = locale.nl_langinfo(locale.CODESET) - if encoding is None or encoding is '': + locale_encoding = locale.nl_langinfo(locale.CODESET) + if locale_encoding is None or locale_encoding is '': # situation occurs on Mac OS X - encoding = 'ascii' - codecs.lookup(encoding) + locale_encoding = 'ascii' + codecs.lookup(locale_encoding) except (NameError, AttributeError, LookupError): - # Try getdefaultlocale well: it parses environment variables, + # Try getdefaultlocale: it parses environment variables, # which may give a clue. Unfortunately, getdefaultlocale has # bugs that can cause ValueError. try: - encoding = locale.getdefaultlocale()[1] - if encoding is None or encoding is '': + locale_encoding = locale.getdefaultlocale()[1] + if locale_encoding is None or locale_encoding is '': # situation occurs on Mac OS X - encoding = 'ascii' - codecs.lookup(encoding) + locale_encoding = 'ascii' + codecs.lookup(locale_encoding) except (ValueError, LookupError): pass -encoding = encoding.lower() +locale_encoding = locale_encoding.lower() + +encoding = locale_encoding ### KBK 07Sep07 This is used all over IDLE, check! + ### 'encoding' is used below in encode(), check! coding_re = re.compile("coding[:=]\s*([-\w_.]+)") @@ -110,26 +113,36 @@ def coding_spec(data): """Return the encoding declaration according to PEP 263. - Raise LookupError if the encoding is declared but unknown. + When checking encoded data, only the first two lines should be passed + in to avoid a UnicodeDecodeError if the rest of the data is not unicode. + The first two lines would contain the encoding specification. + + Raise a LookupError if the encoding is declared but unknown. """ if isinstance(data, bytes): - str = data.decode('utf-8') + try: + lines = data.decode('utf-8') + except UnicodeDecodeError: + return None else: - str = data - # Only consider the first two lines - str = str.split("\n")[:2] - str = "\n".join(str) + lines = data + # consider only the first two lines + if '\n' in lines: + lst = lines.split('\n')[:2] + elif '\r' in lines: + lst = lines.split('\r')[:2] + else: + lst = list(lines) + str = '\n'.join(lst) match = coding_re.search(str) if not match: return None name = match.group(1) - # Check whether the encoding is known - import codecs try: codecs.lookup(name) except LookupError: # The standard encoding error does not indicate the encoding - raise LookupError("Unknown encoding "+name) + raise LookupError("Unknown encoding: "+name) return name @@ -236,12 +249,19 @@ # open the file in binary mode so that we can handle # end-of-line convention ourselves. f = open(filename,'rb') + two_lines = f.readline() + f.readline() + f.seek(0) bytes = f.read() f.close() except IOError as msg: tkMessageBox.showerror("I/O Error", str(msg), master=self.text) return False - chars = self.decode(bytes) + chars = self._decode(two_lines, bytes) + if chars is None: + tkMessageBox.showerror("Decoding Error", + "File %s\nFailed to Decode" % filename, + parent=self.text) + return False # We now convert all end-of-lines to '\n's firsteol = self.eol_re.search(chars) if firsteol: @@ -257,25 +277,23 @@ self.updaterecentfileslist(filename) return True - def decode(self, chars): - """Create a Unicode string - - If that fails, let Tcl try its best - """ + def _decode(self, two_lines, bytes): + "Create a Unicode string." + chars = None # Check presence of a UTF-8 signature first - if chars.startswith(BOM_UTF8): + if bytes.startswith(BOM_UTF8): try: - chars = chars[3:].decode("utf-8") - except UnicodeError: + chars = bytes[3:].decode("utf-8") + except UnicodeDecodeError: # has UTF-8 signature, but fails to decode... - return chars + return None else: # Indicates that this file originally had a BOM self.fileencoding = 'BOM' return chars # Next look for coding specification try: - enc = coding_spec(chars) + enc = coding_spec(two_lines) except LookupError as name: tkMessageBox.showerror( title="Error loading the file", @@ -283,24 +301,37 @@ "installation. The file may not display correctly" % name, master = self.text) enc = None + except UnicodeDecodeError: + return None if enc: try: - return str(chars, enc) - except UnicodeError: + chars = str(bytes, enc) + self.fileencoding = enc + return chars + except UnicodeDecodeError: pass - # If it is ASCII, we need not to record anything + # Try ascii: try: - return str(chars, 'ascii') - except UnicodeError: + chars = str(bytes, 'ascii') + self.fileencoding = None + return chars + except UnicodeDecodeError: + pass + # Try utf-8: + try: + chars = str(bytes, 'utf-8') + self.fileencoding = 'utf-8' + return chars + except UnicodeDecodeError: pass # Finally, try the locale's encoding. This is deprecated; # the user should declare a non-ASCII encoding try: - chars = str(chars, encoding) - self.fileencoding = encoding - except UnicodeError: + chars = str(bytes, locale_encoding) + self.fileencoding = locale_encoding + except UnicodeDecodeError: pass - return chars + return chars # None on failure def maybesave(self): if self.get_saved(): @@ -383,8 +414,9 @@ return chars.encode('ascii') except UnicodeError: pass - # If there is an encoding declared, try this first. + # Check if there is an encoding declared try: + # a string, let coding_spec slice it to the first two lines enc = coding_spec(chars) failed = None except LookupError as msg: @@ -509,7 +541,6 @@ self.opendialog = tkFileDialog.Open(master=self.text, filetypes=self.filetypes) filename = self.opendialog.show(initialdir=dir, initialfile=base) - assert isinstance(filename, str) return filename def defaultfilename(self, mode="open"): From python-3000-checkins at python.org Fri Sep 7 16:15:41 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Fri, 7 Sep 2007 16:15:41 +0200 (CEST) Subject: [Python-3000-checkins] r58038 - in python/branches/py3k/Doc: library/constants.rst library/fileinput.rst library/new.rst library/readline.rst reference/executionmodel.rst reference/expressions.rst reference/toplevel_components.rst Message-ID: <20070907141541.B8ECD1E401B@bag.python.org> Author: georg.brandl Date: Fri Sep 7 16:15:41 2007 New Revision: 58038 Modified: python/branches/py3k/Doc/library/constants.rst python/branches/py3k/Doc/library/fileinput.rst python/branches/py3k/Doc/library/new.rst python/branches/py3k/Doc/library/readline.rst python/branches/py3k/Doc/reference/executionmodel.rst python/branches/py3k/Doc/reference/expressions.rst python/branches/py3k/Doc/reference/toplevel_components.rst Log: Continue going through the language reference, bringing it up-to-date. In particular, document the new comprehensions and remove mentions of long integers. Fix a bunch of related things in the lib ref. Modified: python/branches/py3k/Doc/library/constants.rst ============================================================================== --- python/branches/py3k/Doc/library/constants.rst (original) +++ python/branches/py3k/Doc/library/constants.rst Fri Sep 7 16:15:41 2007 @@ -5,6 +5,11 @@ A small number of constants live in the built-in namespace. They are: +.. note:: + + :data:`None`, :data:`False`, :data:`True` and :data:`__debug__` cannot be + reassigned, so they can be considered "true" constants. + .. XXX False, True, None are keywords too .. data:: False @@ -37,3 +42,10 @@ slicing syntax for user-defined container data types, as in :: val = container[1:5, 7:10, ...] + + +.. data:: __debug__ + + A boolean value that is :data:`True` if Python was not started with the + ``-O`` command line option. Its value is used indirectly by the + :keyword:`assert` statement, but it can also be used directly in code. Modified: python/branches/py3k/Doc/library/fileinput.rst ============================================================================== --- python/branches/py3k/Doc/library/fileinput.rst (original) +++ python/branches/py3k/Doc/library/fileinput.rst Fri Sep 7 16:15:41 2007 @@ -19,10 +19,10 @@ This iterates over the lines of all files listed in ``sys.argv[1:]``, defaulting to ``sys.stdin`` if the list is empty. If a filename is ``'-'``, it is also replaced by ``sys.stdin``. To specify an alternative list of filenames, pass it -as the first argument to :func:`input`. A single file name is also allowed. +as the first argument to :func:`.input`. A single file name is also allowed. All files are opened in text mode by default, but you can override this by -specifying the *mode* parameter in the call to :func:`input` or +specifying the *mode* parameter in the call to :func:`.input` or :class:`FileInput()`. If an I/O error occurs during opening or reading a file, :exc:`IOError` is raised. Modified: python/branches/py3k/Doc/library/new.rst ============================================================================== --- python/branches/py3k/Doc/library/new.rst (original) +++ python/branches/py3k/Doc/library/new.rst Fri Sep 7 16:15:41 2007 @@ -50,4 +50,4 @@ This function returns a new class object, with name *name*, derived from *baseclasses* (which should be a tuple of classes) and with namespace *dict*. - + Alias for the built-in :class:`type`. Modified: python/branches/py3k/Doc/library/readline.rst ============================================================================== --- python/branches/py3k/Doc/library/readline.rst (original) +++ python/branches/py3k/Doc/library/readline.rst Fri Sep 7 16:15:41 2007 @@ -12,8 +12,8 @@ completion and reading/writing of history files from the Python interpreter. This module can be used directly or via the :mod:`rlcompleter` module. Settings made using this module affect the behaviour of both the interpreter's -interactive prompt and the prompts offered by the :func:`raw_input` and -:func:`input` built-in functions. +interactive prompt and the prompts offered by the built-in :func:`input` +function. The :mod:`readline` module defines the following functions: Modified: python/branches/py3k/Doc/reference/executionmodel.rst ============================================================================== --- python/branches/py3k/Doc/reference/executionmodel.rst (original) +++ python/branches/py3k/Doc/reference/executionmodel.rst Fri Sep 7 16:15:41 2007 @@ -26,17 +26,16 @@ Each occurrence of a name in the program text refers to the :dfn:`binding` of that name established in the innermost function block containing the use. -.. index:: single: block +.. index:: block A :dfn:`block` is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition. Each command typed interactively is a block. A script file (a file given as standard input to the interpreter or specified on the interpreter command line the first argument) is a code block. A script command (a command specified on -the interpreter command line with the '**-c**' option) is a code block. The string -argument passed to the built-in functions :func:`eval` and :func:`exec` is a -code block. The expression read and evaluated by the built-in function -:func:`input` is a code block. +the interpreter command line with the '**-c**' option) is a code block. The +string argument passed to the built-in functions :func:`eval` and :func:`exec` +is a code block. .. index:: pair: execution; frame @@ -44,7 +43,7 @@ administrative information (used for debugging) and determines where and how execution continues after the code block's execution has completed. -.. index:: single: scope +.. index:: scope A :dfn:`scope` defines the visibility of a name within a block. If a local variable is defined in a block, its scope includes that block. If the @@ -61,10 +60,11 @@ .. index:: pair: free; variable -If a name is bound in a block, it is a local variable of that block. If a name -is bound at the module level, it is a global variable. (The variables of the -module code block are local and global.) If a variable is used in a code block -but not defined there, it is a :dfn:`free variable`. +If a name is bound in a block, it is a local variable of that block, unless +declared as :keyword:`nonlocal`. If a name is bound at the module level, it is +a global variable. (The variables of the module code block are local and +global.) If a variable is used in a code block but not defined there, it is a +:dfn:`free variable`. .. index:: single: NameError (built-in exception) @@ -96,18 +96,20 @@ If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can -lead to errors when a name is used within a block before it is bound. This rule +lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations. -If the global statement occurs within a block, all uses of the name specified in -the statement refer to the binding of that name in the top-level namespace. -Names are resolved in the top-level namespace by searching the global namespace, -i.e. the namespace of the module containing the code block, and the builtin -namespace, the namespace of the module :mod:`__builtin__`. The global namespace -is searched first. If the name is not found there, the builtin namespace is -searched. The global statement must precede all uses of the name. +If the :keyword:`global` statement occurs within a block, all uses of the name +specified in the statement refer to the binding of that name in the top-level +namespace. Names are resolved in the top-level namespace by searching the +global namespace, i.e. the namespace of the module containing the code block, +and the builtin namespace, the namespace of the module :mod:`__builtin__`. The +global namespace is searched first. If the name is not found there, the builtin +namespace is searched. The global statement must precede all uses of the name. + +.. XXX document "nonlocal" semantics here .. index:: pair: restricted; execution @@ -137,7 +139,7 @@ statement, the free variable is treated as a global. A class definition is an executable statement that may use and define names. -These references follow the normal rules for name resolution. The namespace of +These references follow the normal rules for name resolution. The namespace of the class definition becomes the attribute dictionary of the class. Names defined at the class scope are not visible in methods. @@ -157,13 +159,14 @@ the function contains or is a nested block with free variables, the compiler will raise a :exc:`SyntaxError`. -The :func:`eval` and :func:`exec` functions do -not have access to the full environment for resolving names. Names may be -resolved in the local and global namespaces of the caller. Free variables are -not resolved in the nearest enclosing namespace, but in the global namespace. -[#]_ The :func:`exec` and :func:`eval` functions have optional -arguments to override the global and local namespace. If only one namespace is -specified, it is used for both. +.. XXX from * also invalid with relative imports (at least currently) + +The :func:`eval` and :func:`exec` functions do not have access to the full +environment for resolving names. Names may be resolved in the local and global +namespaces of the caller. Free variables are not resolved in the nearest +enclosing namespace, but in the global namespace. [#]_ The :func:`exec` and +:func:`eval` functions have optional arguments to override the global and local +namespace. If only one namespace is specified, it is used for both. .. _exceptions: @@ -205,21 +208,17 @@ When an exception is not handled at all, the interpreter terminates execution of the program, or returns to its interactive main loop. In either case, it prints -a stack backtrace, except when the exception is :exc:`SystemExit`. +a stack backtrace, except when the exception is :exc:`SystemExit`. Exceptions are identified by class instances. The :keyword:`except` clause is selected depending on the class of the instance: it must reference the class of the instance or a base class thereof. The instance can be received by the handler and can carry additional information about the exceptional condition. -Exceptions can also be identified by strings, in which case the -:keyword:`except` clause is selected by object identity. An arbitrary value can -be raised along with the identifying string which can be passed to the handler. - .. warning:: - Messages to exceptions are not part of the Python API. Their contents may - change from one version of Python to the next without warning and should not be + Exception messages are not part of the Python API. Their contents may change + from one version of Python to the next without warning and should not be relied on by code which will run under multiple versions of the interpreter. See also the description of the :keyword:`try` statement in section :ref:`try` @@ -227,6 +226,6 @@ .. rubric:: Footnotes -.. [#] This limitation occurs because the code that is executed by these operations is - not available at the time the module is compiled. +.. [#] This limitation occurs because the code that is executed by these operations + is not available at the time the module is compiled. Modified: python/branches/py3k/Doc/reference/expressions.rst ============================================================================== --- python/branches/py3k/Doc/reference/expressions.rst (original) +++ python/branches/py3k/Doc/reference/expressions.rst Fri Sep 7 16:15:41 2007 @@ -27,25 +27,19 @@ .. index:: pair: arithmetic; conversion -.. XXX no coercion rules are documented anymore - When a description of an arithmetic operator below uses the phrase "the numeric -arguments are converted to a common type," the arguments are coerced using the -coercion rules. If both arguments are standard -numeric types, the following coercions are applied: +arguments are converted to a common type," this means that the operator +implementation for built-in types works that way: * If either argument is a complex number, the other is converted to complex; * otherwise, if either argument is a floating point number, the other is converted to floating point; -* otherwise, if either argument is a long integer, the other is converted to - long integer; - -* otherwise, both must be plain integers and no conversion is necessary. +* otherwise, both must be integers and no conversion is necessary. Some additional rules apply for certain operators (e.g., a string left argument -to the '%' operator). Extensions can define their own coercions. +to the '%' operator). Extensions must define their own conversion behavior. .. _atoms: @@ -53,18 +47,16 @@ Atoms ===== -.. index:: single: atom +.. index:: atom Atoms are the most basic elements of expressions. The simplest atoms are -identifiers or literals. Forms enclosed in reverse quotes or in parentheses, -brackets or braces are also categorized syntactically as atoms. The syntax for -atoms is: +identifiers or literals. Forms enclosed in parentheses, brackets or braces are +also categorized syntactically as atoms. The syntax for atoms is: .. productionlist:: atom: `identifier` | `literal` | `enclosure` - enclosure: `parenth_form` | `list_display` - : | `generator_expression` | `dict_display` - : | `string_conversion` | `yield_atom` + enclosure: `parenth_form` | `list_display` | `dict_display` | `set_display` + : | `generator_expression` | `yield_atom` .. _atom-identifiers: @@ -72,9 +64,7 @@ Identifiers (Names) ------------------- -.. index:: - single: name - single: identifier +.. index:: name, identifier An identifier occurring as an atom is a name. See section :ref:`identifiers` for lexical definition and section :ref:`naming` for documentation of naming and @@ -103,9 +93,6 @@ defined truncation may happen. If the class name consists only of underscores, no transformation is done. -.. % -.. % - .. _atom-literals: @@ -114,26 +101,26 @@ .. index:: single: literal -Python supports string literals and various numeric literals: +Python supports string and bytes literals and various numeric literals: .. productionlist:: - literal: `stringliteral` | `integer` | `longinteger` - : | `floatnumber` | `imagnumber` + literal: `stringliteral` | `bytesliteral` + : | `integer` | `floatnumber` | `imagnumber` -Evaluation of a literal yields an object of the given type (string, integer, -long integer, floating point number, complex number) with the given value. The -value may be approximated in the case of floating point and imaginary (complex) +Evaluation of a literal yields an object of the given type (string, bytes, +integer, floating point number, complex number) with the given value. The value +may be approximated in the case of floating point and imaginary (complex) literals. See section :ref:`literals` for details. .. index:: triple: immutable; data; type pair: immutable; object -All literals correspond to immutable data types, and hence the object's identity -is less important than its value. Multiple evaluations of literals with the -same value (either the same occurrence in the program text or a different -occurrence) may obtain the same object or a different object with the same -value. +With the exception of bytes literals, these all correspond to immutable data +types, and hence the object's identity is less important than its value. +Multiple evaluations of literals with the same value (either the same occurrence +in the program text or a different occurrence) may obtain the same object or a +different object with the same value. .. _parenthesized: @@ -168,6 +155,35 @@ ambiguities and allow common typos to pass uncaught. +.. _comprehensions: + +Displays for lists, sets and dictionaries +----------------------------------------- + +For constructing a list, a set or a dictionary Python provides special syntax +called "displays", each of them in two flavors: + +* either the container contents are listed explicitly, or + +* they are computed via a set of looping and filtering instructions, called a + :dfn:`comprehension`. + +Common syntax elements for comprehensions are: + +.. productionlist:: + comprehension: `expression` `comp_for` + comp_for: "for" `target_list` "in" `or_test` [`comp_iter`] + comp_iter: `comp_for` | `comp_if` + comp_if: "if" `expression_nocond` [`comp_iter`] + +The comprehension consists of a single expression followed by at least one +:keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` clauses. +In this case, the elements of the new container are those that would be produced +by considering each of the :keyword:`for` or :keyword:`if` clauses a block, +nesting from left to right, and evaluating the expression to produce an element +each time the innermost block is reached. + + .. _lists: List displays @@ -176,71 +192,41 @@ .. index:: pair: list; display pair: list; comprehensions + pair: empty; list + object: list A list display is a possibly empty series of expressions enclosed in square brackets: .. productionlist:: - list_display: "[" [`expression_list` | `list_comprehension`] "]" - list_comprehension: `expression` `list_for` - list_for: "for" `target_list` "in" `old_expression_list` [`list_iter`] - old_expression_list: `old_expression` [("," `old_expression`)+ [","]] - list_iter: `list_for` | `list_if` - list_if: "if" `old_expression` [`list_iter`] + list_display: "[" [`expression_list` | `comprehension`] "]" -.. index:: - pair: list; comprehensions - object: list - pair: empty; list - -A list display yields a new list object. Its contents are specified by -providing either a list of expressions or a list comprehension. When a -comma-separated list of expressions is supplied, its elements are evaluated from -left to right and placed into the list object in that order. When a list -comprehension is supplied, it consists of a single expression followed by at -least one :keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` -clauses. In this case, the elements of the new list are those that would be -produced by considering each of the :keyword:`for` or :keyword:`if` clauses a -block, nesting from left to right, and evaluating the expression to produce a -list element each time the innermost block is reached [#]_. +A list display yields a new list object, the contents being specified by either +a list of expressions or a comprehension. When a comma-separated list of +expressions is supplied, its elements are evaluated from left to right and +placed into the list object in that order. When a comprehension is supplied, +the list is constructed from the elements resulting from the comprehension. -.. _genexpr: +.. _set: -Generator expressions ---------------------- +Set displays +------------ -.. index:: pair: generator; expression +.. index:: pair: set; display + object: set -A generator expression is a compact generator notation in parentheses: +A set display is denoted by curly braces and distinguishable from dictionary +displays by the lack of colons separating keys and values: .. productionlist:: - generator_expression: "(" `expression` `genexpr_for` ")" - genexpr_for: "for" `target_list` "in" `or_test` [`genexpr_iter`] - genexpr_iter: `genexpr_for` | `genexpr_if` - genexpr_if: "if" `old_expression` [`genexpr_iter`] - -.. index:: object: generator - -A generator expression yields a new generator object. It consists of a single -expression followed by at least one :keyword:`for` clause and zero or more -:keyword:`for` or :keyword:`if` clauses. The iterating values of the new -generator are those that would be produced by considering each of the -:keyword:`for` or :keyword:`if` clauses a block, nesting from left to right, and -evaluating the expression to yield a value that is reached the innermost block -for each iteration. - -Variables used in the generator expression are evaluated lazily when the -:meth:`__next__` method is called for generator object (in the same fashion as -normal generators). However, the leftmost :keyword:`for` clause is immediately -evaluated so that error produced by it can be seen before any other possible -error in the code that handles the generator expression. Subsequent -:keyword:`for` clauses cannot be evaluated immediately since they may depend on -the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y -in bar(x))``. + set_display: "{" [`expression_list` | `comprehension`] "}" -The parentheses can be omitted on calls with only one argument. See section -:ref:`calls` for the detail. +A set display yields a new mutable set object, the contents being specified by +either a sequence of expressions or a comprehension. When a comma-separated +list of expressions is supplied, its elements are evaluated from left to right +and added to the set object. When a comprehension is supplied, the set is +constructed from the elements resulting from the comprehension. .. _dict: @@ -249,29 +235,33 @@ ------------------- .. index:: pair: dictionary; display - -.. index:: - single: key - single: datum - single: key/datum pair + key, datum, key/datum pair + object: dictionary A dictionary display is a possibly empty series of key/datum pairs enclosed in curly braces: .. productionlist:: - dict_display: "{" [`key_datum_list`] "}" + dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}" key_datum_list: `key_datum` ("," `key_datum`)* [","] key_datum: `expression` ":" `expression` - -.. index:: object: dictionary + dict_comprehension: `expression` ":" `expression` `comp_for` A dictionary display yields a new dictionary object. -The key/datum pairs are evaluated from left to right to define the entries of -the dictionary: each key object is used as a key into the dictionary to store -the corresponding datum. +If a comma-separated sequence of key/datum pairs is given, they are evaluated +from left to right to define the entries of the dictionary: each key object is +used as a key into the dictionary to store the corresponding datum. This means +that you can specify the same key multiple times in the key/datum list, and the +final dictionary's value for that key will be the last one given. + +A dict comprehension, in contrast to list and set comprehensions, needs two +expressions separated with a colon followed by the usual "for" and "if" clauses. +When the comprehension is run, the resulting key and value elements are inserted +in the new dictionary in the order they are produced. .. index:: pair: immutable; object + hashable Restrictions on the types of the key values are listed earlier in section :ref:`types`. (To summarize, the key type should be hashable, which excludes @@ -280,6 +270,36 @@ prevails. +.. _genexpr: + +Generator expressions +--------------------- + +.. index:: pair: generator; expression + object: generator + +A generator expression is a compact generator notation in parentheses: + +.. productionlist:: + generator_expression: "(" `expression` `comp_for` ")" + +A generator expression yields a new generator object. Its syntax is the same as +for comprehensions, except that it is enclosed in parentheses instead of +brackets or curly braces. + +Variables used in the generator expression are evaluated lazily when the +:meth:`__next__` method is called for generator object (in the same fashion as +normal generators). However, the leftmost :keyword:`for` clause is immediately +evaluated, so that an error produced by it can be seen before any other possible +error in the code that handles the generator expression. Subsequent +:keyword:`for` clauses cannot be evaluated immediately since they may depend on +the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y +in bar(x))``. + +The parentheses can be omitted on calls with only one argument. See section +:ref:`calls` for the detail. + + .. _yieldexpr: Yield expressions @@ -295,7 +315,7 @@ yield_expression: "yield" [`expression_list`] The :keyword:`yield` expression is only used when defining a generator function, -and can only be used in the body of a function definition. Using a +and can only be used in the body of a function definition. Using a :keyword:`yield` expression in a function definition is sufficient to cause that definition to create a generator function instead of a normal function. @@ -308,7 +328,7 @@ including the current bindings of local variables, the instruction pointer, and the internal evaluation stack. When the execution is resumed by calling one of the generator's methods, the function can proceed exactly as if the -:keyword:`yield` expression was just another external call. The value of the +:keyword:`yield` expression was just another external call. The value of the :keyword:`yield` expression after resuming depends on the method which resumed the execution. @@ -328,16 +348,19 @@ .. index:: exception: StopIteration -.. method:: generator.next() +.. method:: generator.__next__() - Starts the execution of a generator function or resumes it at the last executed - :keyword:`yield` expression. When a generator function is resumed with a - :meth:`next` method, the current :keyword:`yield` expression always evaluates to - :const:`None`. The execution then continues to the next :keyword:`yield` - expression, where the generator is suspended again, and the value of the - :token:`expression_list` is returned to :meth:`next`'s caller. If the generator - exits without yielding another value, a :exc:`StopIteration` exception is - raised. + Starts the execution of a generator function or resumes it at the last + executed :keyword:`yield` expression. When a generator function is resumed + with a :meth:`next` method, the current :keyword:`yield` expression always + evaluates to :const:`None`. The execution then continues to the next + :keyword:`yield` expression, where the generator is suspended again, and the + value of the :token:`expression_list` is returned to :meth:`next`'s caller. + If the generator exits without yielding another value, a :exc:`StopIteration` + exception is raised. + + This method is normally called implicitly, e.g. by a :keyword:`for` loop, or + by the built-in :func:`next` function. .. method:: generator.send(value) @@ -346,8 +369,8 @@ ``value`` argument becomes the result of the current :keyword:`yield` expression. The :meth:`send` method returns the next value yielded by the generator, or raises :exc:`StopIteration` if the generator exits without - yielding another value. When :meth:`send` is called to start the generator, it - must be called with :const:`None` as the argument, because there is no + yielding another value. When :meth:`send` is called to start the generator, + it must be called with :const:`None` as the argument, because there is no :keyword:`yield` expression that could receieve the value. @@ -365,12 +388,12 @@ .. method:: generator.close() Raises a :exc:`GeneratorExit` at the point where the generator function was - paused. If the generator function then raises :exc:`StopIteration` (by exiting - normally, or due to already being closed) or :exc:`GeneratorExit` (by not - catching the exception), close returns to its caller. If the generator yields a - value, a :exc:`RuntimeError` is raised. If the generator raises any other - exception, it is propagated to the caller. :meth:`close` does nothing if the - generator has already exited due to an exception or normal exit. + paused. If the generator function then raises :exc:`StopIteration` (by + exiting normally, or due to already being closed) or :exc:`GeneratorExit` (by + not catching the exception), close returns to its caller. If the generator + yields a value, a :exc:`RuntimeError` is raised. If the generator raises any + other exception, it is propagated to the caller. :meth:`close` does nothing + if the generator has already exited due to an exception or normal exit. Here is a simple example that demonstrates the behavior of generators and generator functions:: @@ -390,10 +413,10 @@ ... print("Don't forget to clean up when 'close()' is called.") ... >>> generator = echo(1) - >>> print(generator.next()) + >>> print(next(generator)) Execution starts when 'next()' is called for the first time. 1 - >>> print(generator.next()) + >>> print(next(generator)) None >>> print(generator.send(2)) 2 @@ -406,8 +429,8 @@ .. seealso:: :pep:`0342` - Coroutines via Enhanced Generators - The proposal to enhance the API and syntax of generators, making them usable as - simple coroutines. + The proposal to enhance the API and syntax of generators, making them + usable as simple coroutines. .. _primaries: @@ -442,11 +465,12 @@ object: list The primary must evaluate to an object of a type that supports attribute -references, e.g., a module, list, or an instance. This object is then asked to -produce the attribute whose name is the identifier. If this attribute is not -available, the exception :exc:`AttributeError` is raised. Otherwise, the type -and value of the object produced is determined by the object. Multiple -evaluations of the same attribute reference may yield different objects. +references, which most objects do. This object is then asked to produce the +attribute whose name is the identifier (which can be customized by overriding +the :meth:`__getattr__` method). If this attribute is not available, the +exception :exc:`AttributeError` is raised. Otherwise, the type and value of the +object produced is determined by the object. Multiple evaluations of the same +attribute reference may yield different objects. .. _subscriptions: @@ -471,19 +495,22 @@ .. productionlist:: subscription: `primary` "[" `expression_list` "]" -The primary must evaluate to an object of a sequence or mapping type. +The primary must evaluate to an object that supports subscription, e.g. a list +or dictionary. User-defined objects can support subscription by defining a +:meth:`__getitem__` method. + +For built-in objects, there are two types of objects that support subscription: If the primary is a mapping, the expression list must evaluate to an object whose value is one of the keys of the mapping, and the subscription selects the value in the mapping that corresponds to that key. (The expression list is a tuple except if it has exactly one item.) -If the primary is a sequence, the expression (list) must evaluate to a plain -integer. If this value is negative, the length of the sequence is added to it -(so that, e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value -must be a nonnegative integer less than the number of items in the sequence, and -the subscription selects the item whose index is that value (counting from -zero). +If the primary is a sequence, the expression (list) must evaluate to an integer. +If this value is negative, the length of the sequence is added to it (so that, +e.g., ``x[-1]`` selects the last item of ``x``.) The resulting value must be a +nonnegative integer less than the number of items in the sequence, and the +subscription selects the item whose index is that value (counting from zero). .. index:: single: character @@ -534,15 +561,16 @@ single: step (slice object attribute) The semantics for a slicing are as follows. The primary must evaluate to a -mapping object, and it is indexed with a key that is constructed from the -slice list, as follows. If the slice list contains at least one comma, the -key is a tuple containing the conversion of the slice items; otherwise, the -conversion of the lone slice item is the key. The conversion of a slice -item that is an expression is that expression. The conversion of a proper -slice is a slice object (see section :ref:`types`) whose :attr:`start`, -:attr:`stop` and :attr:`step` attributes are the values of the expressions -given as lower bound, upper bound and stride, respectively, substituting -``None`` for missing expressions. +mapping object, and it is indexed (using the same :meth:`__getitem__` method as +normal subscription) with a key that is constructed from the slice list, as +follows. If the slice list contains at least one comma, the key is a tuple +containing the conversion of the slice items; otherwise, the conversion of the +lone slice item is the key. The conversion of a slice item that is an +expression is that expression. The conversion of a proper slice is a slice +object (see section :ref:`types`) whose :attr:`start`, :attr:`stop` and +:attr:`step` attributes are the values of the expressions given as lower bound, +upper bound and stride, respectively, substituting ``None`` for missing +expressions. .. _calls: @@ -576,10 +604,11 @@ The primary must evaluate to a callable object (user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class -instances, and certain class instances themselves are callable; extensions may -define additional callable object types). All argument expressions are -evaluated before the call is attempted. Please refer to section :ref:`function` -for the syntax of formal parameter lists. +instances, and all objects having a :meth:`__call__` method are callable). All +argument expressions are evaluated before the call is attempted. Please refer +to section :ref:`function` for the syntax of formal parameter lists. + +.. XXX update with kwonly args PEP If keyword arguments are present, they are first converted to positional arguments, as follows. First, a list of unfilled slots is created for the @@ -722,16 +751,12 @@ The power operator has the same semantics as the built-in :func:`pow` function, when called with two arguments: it yields its left argument raised to the power of its right argument. The numeric arguments are first converted to a common -type. The result type is that of the arguments after coercion. +type, and the result is of that type. -With mixed operand types, the coercion rules for binary arithmetic operators -apply. For int and long int operands, the result has the same type as the -operands (after coercion) unless the second argument is negative; in that case, -all arguments are converted to float and a float result is delivered. For -example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. (This last -feature was added in Python 2.2. In Python 2.1 and before, if both arguments -were of integer types and the second argument was negative, an exception was -raised). +For int operands, the result has the same type as the operands unless the second +argument is negative; in that case, all arguments are converted to float and a +float result is delivered. For example, ``10**2`` returns ``100``, but +``10**-2`` returns ``0.01``. Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`. Raising a negative number to a fractional power results in a :exc:`ValueError`. @@ -763,9 +788,9 @@ .. index:: single: inversion -The unary ``~`` (invert) operator yields the bit-wise inversion of its plain or -long integer argument. The bit-wise inversion of ``x`` is defined as -``-(x+1)``. It only applies to integral numbers. +The unary ``~`` (invert) operator yields the bit-wise inversion of its integer +argument. The bit-wise inversion of ``x`` is defined as ``-(x+1)``. It only +applies to integral numbers. .. index:: exception: TypeError @@ -793,11 +818,10 @@ .. index:: single: multiplication The ``*`` (multiplication) operator yields the product of its arguments. The -arguments must either both be numbers, or one argument must be an integer (plain -or long) and the other must be a sequence. In the former case, the numbers are -converted to a common type and then multiplied together. In the latter case, -sequence repetition is performed; a negative repetition factor yields an empty -sequence. +arguments must either both be numbers, or one argument must be an integer and +the other must be a sequence. In the former case, the numbers are converted to a +common type and then multiplied together. In the latter case, sequence +repetition is performed; a negative repetition factor yields an empty sequence. .. index:: exception: ZeroDivisionError @@ -805,9 +829,10 @@ The ``/`` (division) and ``//`` (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. -Plain or long integer division yields an integer of the same type; the result is -that of mathematical division with the 'floor' function applied to the result. -Division by zero raises the :exc:`ZeroDivisionError` exception. +Integer division yields a float, while floor division of integers results in an +integer; the result is that of mathematical division with the 'floor' function +applied to the result. Division by zero raises the :exc:`ZeroDivisionError` +exception. .. index:: single: modulo @@ -820,25 +845,23 @@ the result is strictly smaller than the absolute value of the second operand [#]_. -The integer division and modulo operators are connected by the following -identity: ``x == (x/y)*y + (x%y)``. Integer division and modulo are also -connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y, -x%y)``. These identities don't hold for floating point numbers; there similar -identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or -``floor(x/y) - 1`` [#]_. +The floor division and modulo operators are connected by the following +identity: ``x == (x//y)*y + (x%y)``. Floor division and modulo are also +connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x//y, +x%y)``. [#]_. In addition to performing the modulo operation on numbers, the ``%`` operator is -also overloaded by string objects to perform string formatting (also -known as interpolation). The syntax for string formatting is described in the +also overloaded by string objects to perform old-style string formatting (also +known as interpolation). The syntax for string formatting is described in the Python Library Reference, section :ref:`old-string-formatting`. The floor division operator, the modulo operator, and the :func:`divmod` -function are not defined for complex numbers. Instead, convert to a -floating point number using the :func:`abs` function if appropriate. +function are not defined for complex numbers. Instead, convert to a floating +point number using the :func:`abs` function if appropriate. .. index:: single: addition -The ``+`` (addition) operator yields the sum of its arguments. The arguments +The ``+`` (addition) operator yields the sum of its arguments. The arguments must either both be numbers or both sequences of the same type. In the former case, the numbers are converted to a common type and then added together. In the latter case, the sequences are concatenated. @@ -861,17 +884,13 @@ .. productionlist:: shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr` -These operators accept plain or long integers as arguments. The arguments are -converted to a common type. They shift the first argument to the left or right -by the number of bits given by the second argument. +These operators accept integers as arguments. They shift the first argument to +the left or right by the number of bits given by the second argument. .. index:: exception: ValueError A right shift by *n* bits is defined as division by ``pow(2,n)``. A left shift -by *n* bits is defined as multiplication with ``pow(2,n)``; for plain integers -there is no overflow check so in that case the operation drops bits and flips -the sign if the result is not less than ``pow(2,31)`` in absolute value. -Negative shift counts raise a :exc:`ValueError` exception. +by *n* bits is defined as multiplication with ``pow(2,n)``. .. _bitwise: @@ -890,22 +909,22 @@ .. index:: pair: bit-wise; and -The ``&`` operator yields the bitwise AND of its arguments, which must be plain -or long integers. The arguments are converted to a common type. +The ``&`` operator yields the bitwise AND of its arguments, which must be +integers. .. index:: pair: bit-wise; xor pair: exclusive; or The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which -must be plain or long integers. The arguments are converted to a common type. +must be integers. .. index:: pair: bit-wise; or pair: inclusive; or The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which -must be plain or long integers. The arguments are converted to a common type. +must be integers. .. _comparisons: @@ -949,8 +968,8 @@ numbers, they are converted to a common type. Otherwise, objects of different types *always* compare unequal, and are ordered consistently but arbitrarily. You can control comparison behavior of objects of non-builtin types by defining -a ``__cmp__`` method or rich comparison methods like ``__gt__``, described in -section :ref:`specialnames`. +a :meth:`__cmp__` method or rich comparison methods like :meth:`__gt__`, +described in section :ref:`specialnames`. (This unusual definition of comparison was used to simplify the definition of operations like sorting and the :keyword:`in` and :keyword:`not in` operators. @@ -961,12 +980,12 @@ * Numbers are compared arithmetically. -* Bytes objects are compared lexicographically using the numeric values of - their elements. +* Bytes objects are compared lexicographically using the numeric values of their + elements. * Strings are compared lexicographically using the numeric equivalents (the - result of the built-in function :func:`ord`) of their characters. [#]_ - String and bytes object can't be compared! + result of the built-in function :func:`ord`) of their characters. [#]_ String + and bytes object can't be compared! * Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must @@ -975,11 +994,11 @@ If not equal, the sequences are ordered the same as their first differing elements. For example, ``cmp([1,2,x], [1,2,y])`` returns the same as - ``cmp(x,y)``. If the corresponding element does not exist, the shorter sequence - is ordered first (for example, ``[1,2] < [1,2,3]``). + ``cmp(x,y)``. If the corresponding element does not exist, the shorter + sequence is ordered first (for example, ``[1,2] < [1,2,3]``). -* Mappings (dictionaries) compare equal if and only if their sorted (key, value) - lists compare equal. [#]_ Outcomes other than equality are resolved +* Mappings (dictionaries) compare equal if and only if their sorted ``(key, + value)`` lists compare equal. [#]_ Outcomes other than equality are resolved consistently, but are not otherwise defined. [#]_ * Most other objects of builtin types compare unequal unless they are the same @@ -987,14 +1006,11 @@ another one is made arbitrarily but consistently within one execution of a program. -The operators :keyword:`in` and :keyword:`not in` test for set membership. ``x -in s`` evaluates to true if *x* is a member of the set *s*, and false otherwise. -``x not in s`` returns the negation of ``x in s``. The set membership test has -traditionally been bound to sequences; an object is a member of a set if the set -is a sequence and contains an element equal to that object. However, it is -possible for an object to support membership tests without being a sequence. In -particular, dictionaries support membership testing as a nicer way of spelling -``key in dict``; other mapping types may follow suit. +The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in +s`` evaluates to true if *x* is a member of *s*, and false otherwise. ``x not +in s`` returns the negation of ``x in s``. All built-in sequences and set types +support this as well as dictionary, for which :keyword:`in` tests whether a the +dictionary has a given key. For the list and tuple types, ``x in y`` is true if and only if there exists an index *i* such that ``x == y[i]`` is true. @@ -1010,7 +1026,7 @@ For user-defined classes which do not define :meth:`__contains__` and do define :meth:`__getitem__`, ``x in y`` is true if and only if there is a non-negative integer index *i* such that ``x == y[i]``, and all lower integer indices do not -raise :exc:`IndexError` exception. (If any other exception is raised, it is as +raise :exc:`IndexError` exception. (If any other exception is raised, it is as if :keyword:`in` raised that exception). .. index:: @@ -1045,7 +1061,7 @@ .. productionlist:: expression: `conditional_expression` | `lambda_form` - old_expression: `or_test` | `old_lambda_form` + expression_nocond: `or_test` | `lambda_form_nocond` conditional_expression: `or_test` ["if" `or_test` "else" `expression`] or_test: `and_test` | `or_test` "or" `and_test` and_test: `not_test` | `and_test` "and" `not_test` @@ -1055,7 +1071,8 @@ control flow statements, the following values are interpreted as false: ``False``, ``None``, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All -other values are interpreted as true. +other values are interpreted as true. User-defined objects can customize their +truth value by providing a :meth:`__bool__` method. .. index:: operator: not @@ -1078,7 +1095,7 @@ (Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type they return to ``False`` and ``True``, but rather return the last evaluated -argument. This is sometimes useful, e.g., if ``s`` is a string that should be +argument. This is sometimes useful, e.g., if ``s`` is a string that should be replaced by a default value if it is empty, the expression ``s or 'foo'`` yields the desired value. Because :keyword:`not` has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g., ``not @@ -1097,14 +1114,14 @@ .. productionlist:: lambda_form: "lambda" [`parameter_list`]: `expression` - old_lambda_form: "lambda" [`parameter_list`]: `old_expression` + lambda_form_nocond: "lambda" [`parameter_list`]: `expression_nocond` Lambda forms (lambda expressions) have the same syntactic position as expressions. They are a shorthand to create anonymous functions; the expression ``lambda arguments: expression`` yields a function object. The unnamed object behaves like a function object defined with :: - def name(arguments): + def (arguments): return expression See section :ref:`function` for the syntax of parameter lists. Note that @@ -1145,8 +1162,8 @@ .. index:: pair: evaluation; order -Python evaluates expressions from left to right. Notice that while evaluating an -assignment, the right-hand side is evaluated before the left-hand side. +Python evaluates expressions from left to right. Notice that while evaluating +an assignment, the right-hand side is evaluated before the left-hand side. In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:: @@ -1167,7 +1184,7 @@ .. index:: pair: operator; precedence The following table summarizes the operator precedences in Python, from lowest -precedence (least binding) to highest precedence (most binding). Operators in +precedence (least binding) to highest precedence (most binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for comparisons, including tests, which all have the same precedence and chain from @@ -1201,7 +1218,7 @@ +----------------------------------------------+-------------------------------------+ | ``+``, ``-`` | Addition and subtraction | +----------------------------------------------+-------------------------------------+ -| ``*``, ``/``, ``%`` | Multiplication, division, remainder | +| ``*``, ``/``, ``//``, ``%`` | Multiplication, division, remainder | +----------------------------------------------+-------------------------------------+ | ``+x``, ``-x`` | Positive, negative | +----------------------------------------------+-------------------------------------+ @@ -1217,20 +1234,16 @@ +----------------------------------------------+-------------------------------------+ | ``f(arguments...)`` | Function call | +----------------------------------------------+-------------------------------------+ -| ``(expressions...)`` | Binding or tuple display | +| ``(expressions...)`` | Binding, tuple display, generator | +| | expressions | +----------------------------------------------+-------------------------------------+ | ``[expressions...]`` | List display | +----------------------------------------------+-------------------------------------+ -| ``{key:datum...}`` | Dictionary display | +| ``{expressions...}`` | Dictionary or set display | +----------------------------------------------+-------------------------------------+ .. rubric:: Footnotes -.. [#] In Python 2.3, a list comprehension "leaks" the control variables of each - ``for`` it contains into the containing scope. However, this behavior is - deprecated, and relying on it will not work once this bug is fixed in a future - release - .. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be true numerically due to roundoff. For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 % @@ -1241,22 +1254,21 @@ is more appropriate depends on the application. .. [#] If x is very close to an exact integer multiple of y, it's possible for - ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding. In such + ``x//y`` to be one larger than ``(x-x%y)//y`` due to rounding. In such cases, Python returns the latter result, in order to preserve that ``divmod(x,y)[0] * y + x % y`` be very close to ``x``. -.. [#] While comparisons between strings make sense at the byte - level, they may be counter-intuitive to users. For example, the - strings ``"\u00C7"`` and ``"\u0327\u0043"`` compare differently, - even though they both represent the same unicode character (LATIN - CAPTITAL LETTER C WITH CEDILLA). +.. [#] While comparisons between strings make sense at the byte level, they may + be counter-intuitive to users. For example, the strings ``"\u00C7"`` and + ``"\u0327\u0043"`` compare differently, even though they both represent the + same unicode character (LATIN CAPTITAL LETTER C WITH CEDILLA). -.. [#] The implementation computes this efficiently, without constructing lists or - sorting. +.. [#] The implementation computes this efficiently, without constructing lists + or sorting. .. [#] Earlier versions of Python used lexicographic comparison of the sorted (key, - value) lists, but this was very expensive for the common case of comparing for - equality. An even earlier version of Python compared dictionaries by identity - only, but this caused surprises because people expected to be able to test a - dictionary for emptiness by comparing it to ``{}``. + value) lists, but this was very expensive for the common case of comparing + for equality. An even earlier version of Python compared dictionaries by + identity only, but this caused surprises because people expected to be able + to test a dictionary for emptiness by comparing it to ``{}``. Modified: python/branches/py3k/Doc/reference/toplevel_components.rst ============================================================================== --- python/branches/py3k/Doc/reference/toplevel_components.rst (original) +++ python/branches/py3k/Doc/reference/toplevel_components.rst Fri Sep 7 16:15:41 2007 @@ -106,13 +106,6 @@ .. productionlist:: eval_input: `expression_list` NEWLINE* -.. index:: builtin: input - -The input line read by :func:`input` must have the following form: - -.. productionlist:: - input_input: `expression_list` NEWLINE - .. index:: object: file single: input; raw From python-3000-checkins at python.org Fri Sep 7 17:00:39 2007 From: python-3000-checkins at python.org (jeffrey.yasskin) Date: Fri, 7 Sep 2007 17:00:39 +0200 (CEST) Subject: [Python-3000-checkins] r58039 - in python/branches/py3k/Lib: test/test_unittest.py unittest.py Message-ID: <20070907150040.040531E4012@bag.python.org> Author: jeffrey.yasskin Date: Fri Sep 7 17:00:39 2007 New Revision: 58039 Modified: python/branches/py3k/Lib/test/test_unittest.py python/branches/py3k/Lib/unittest.py Log: Add a test for fail*AlmostEqual, including the new support for complex numbers. Modified: python/branches/py3k/Lib/test/test_unittest.py ============================================================================== --- python/branches/py3k/Lib/test/test_unittest.py (original) +++ python/branches/py3k/Lib/test/test_unittest.py Fri Sep 7 17:00:39 2007 @@ -2292,13 +2292,34 @@ expected = ['startTest', 'test', 'stopTest'] self.assertEqual(events, expected) +class Test_Assertions(TestCase): + def test_AlmostEqual(self): + self.failUnlessAlmostEqual(1.00000001, 1.0) + self.failIfAlmostEqual(1.0000001, 1.0) + self.assertRaises(AssertionError, + self.failUnlessAlmostEqual, 1.0000001, 1.0) + self.assertRaises(AssertionError, + self.failIfAlmostEqual, 1.00000001, 1.0) + + self.failUnlessAlmostEqual(1.1, 1.0, places=0) + self.assertRaises(AssertionError, + self.failUnlessAlmostEqual, 1.1, 1.0, places=1) + + self.failUnlessAlmostEqual(0, .1+.1j, places=0) + self.failIfAlmostEqual(0, .1+.1j, places=1) + self.assertRaises(AssertionError, + self.failUnlessAlmostEqual, 0, .1+.1j, places=1) + self.assertRaises(AssertionError, + self.failIfAlmostEqual, 0, .1+.1j, places=0) + ###################################################################### ## Main ###################################################################### def test_main(): test_support.run_unittest(Test_TestCase, Test_TestLoader, - Test_TestSuite, Test_TestResult, Test_FunctionTestCase) + Test_TestSuite, Test_TestResult, Test_FunctionTestCase, + Test_Assertions) if __name__ == "__main__": test_main() Modified: python/branches/py3k/Lib/unittest.py ============================================================================== --- python/branches/py3k/Lib/unittest.py (original) +++ python/branches/py3k/Lib/unittest.py Fri Sep 7 17:00:39 2007 @@ -331,7 +331,7 @@ if first == second: raise self.failureException(msg or '%r == %r' % (first, second)) - def failUnlessAlmostEqual(self, first, second, places=7, msg=None): + def failUnlessAlmostEqual(self, first, second, *, places=7, msg=None): """Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero. @@ -343,7 +343,7 @@ raise self.failureException(msg or '%r != %r within %r places' % (first, second, places)) - def failIfAlmostEqual(self, first, second, places=7, msg=None): + def failIfAlmostEqual(self, first, second, *, places=7, msg=None): """Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero. From python-3000-checkins at python.org Fri Sep 7 17:15:49 2007 From: python-3000-checkins at python.org (jeffrey.yasskin) Date: Fri, 7 Sep 2007 17:15:49 +0200 (CEST) Subject: [Python-3000-checkins] r58040 - in python/branches/py3k: Lib/numbers.py Lib/test/test_builtin.py Lib/test/test_complex.py Lib/test/test_descr.py Objects/floatobject.c Message-ID: <20070907151549.F056A1E400D@bag.python.org> Author: jeffrey.yasskin Date: Fri Sep 7 17:15:49 2007 New Revision: 58040 Modified: python/branches/py3k/Lib/numbers.py python/branches/py3k/Lib/test/test_builtin.py python/branches/py3k/Lib/test/test_complex.py python/branches/py3k/Lib/test/test_descr.py python/branches/py3k/Objects/floatobject.c Log: Check in some documentation tweaks for PEP 3141, add some tests, and implement the promotion to complex on pow(negative, fraction). Modified: python/branches/py3k/Lib/numbers.py ============================================================================== --- python/branches/py3k/Lib/numbers.py (original) +++ python/branches/py3k/Lib/numbers.py Fri Sep 7 17:15:49 2007 @@ -1,7 +1,9 @@ # Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. -"""Abstract Base Classes (ABCs) for numbers, according to PEP 3141.""" +"""Abstract Base Classes (ABCs) for numbers, according to PEP 3141. + +TODO: Fill out more detailed documentation on the operators.""" from abc import ABCMeta, abstractmethod, abstractproperty @@ -56,10 +58,10 @@ @abstractmethod def __complex__(self): - """Return a builtin complex instance.""" + """Return a builtin complex instance. Called for complex(self).""" def __bool__(self): - """True if self != 0.""" + """True if self != 0. Called for bool(self).""" return self != 0 @abstractproperty @@ -80,53 +82,64 @@ @abstractmethod def __add__(self, other): + """self + other""" raise NotImplementedError @abstractmethod def __radd__(self, other): + """other + self""" raise NotImplementedError @abstractmethod def __neg__(self): + """-self""" raise NotImplementedError def __pos__(self): + """+self""" return self def __sub__(self, other): + """self - other""" return self + -other def __rsub__(self, other): + """other - self""" return -self + other @abstractmethod def __mul__(self, other): + """self * other""" raise NotImplementedError @abstractmethod def __rmul__(self, other): + """other * self""" raise NotImplementedError @abstractmethod def __div__(self, other): + """self / other""" raise NotImplementedError @abstractmethod def __rdiv__(self, other): + """other / self""" raise NotImplementedError @abstractmethod def __pow__(self, exponent): - """Like division, a**b should promote to complex when necessary.""" + """Like division, self**exponent should promote to complex when necessary.""" raise NotImplementedError @abstractmethod def __rpow__(self, base): + """base ** self""" raise NotImplementedError @abstractmethod def __abs__(self): - """Returns the Real distance from 0.""" + """Returns the Real distance from 0. Called for abs(self).""" raise NotImplementedError @abstractmethod @@ -136,9 +149,11 @@ @abstractmethod def __eq__(self, other): + """self == other""" raise NotImplementedError def __ne__(self, other): + """self != other""" return not (self == other) Complex.register(complex) @@ -155,12 +170,14 @@ @abstractmethod def __float__(self): - """Any Real can be converted to a native float object.""" + """Any Real can be converted to a native float object. + + Called for float(self).""" raise NotImplementedError @abstractmethod def __trunc__(self): - """Truncates self to an Integral. + """trunc(self): Truncates self to an Integral. Returns an Integral i such that: * i>0 iff self>0 @@ -169,7 +186,7 @@ raise NotImplementedError def __divmod__(self, other): - """The pair (self // other, self % other). + """divmod(self, other): The pair (self // other, self % other). Sometimes this can be computed faster than the pair of operations. @@ -177,7 +194,7 @@ return (self // other, self % other) def __rdivmod__(self, other): - """The pair (self // other, self % other). + """divmod(other, self): The pair (self // other, self % other). Sometimes this can be computed faster than the pair of operations. @@ -186,40 +203,49 @@ @abstractmethod def __floordiv__(self, other): - """The floor() of self/other.""" + """self // other: The floor() of self/other.""" raise NotImplementedError @abstractmethod def __rfloordiv__(self, other): - """The floor() of other/self.""" + """other // self: The floor() of other/self.""" raise NotImplementedError @abstractmethod def __mod__(self, other): + """self % other""" raise NotImplementedError @abstractmethod def __rmod__(self, other): + """other % self""" raise NotImplementedError @abstractmethod def __lt__(self, other): - """< on Reals defines a total ordering, except perhaps for NaN.""" + """self < other + + < on Reals defines a total ordering, except perhaps for NaN.""" raise NotImplementedError + @abstractmethod def __le__(self, other): + """self <= other""" raise NotImplementedError # Concrete implementations of Complex abstract methods. def __complex__(self): + """complex(self) == complex(float(self), 0)""" return complex(float(self)) @property def real(self): + """Real numbers are their real component.""" return self @property def imag(self): + """Real numbers have no imaginary component.""" return 0 def conjugate(self): @@ -242,6 +268,7 @@ # Concrete implementation of Real's conversion to float. def __float__(self): + """float(self) = self.numerator / self.denominator""" return self.numerator / self.denominator @@ -250,76 +277,92 @@ @abstractmethod def __int__(self): + """int(self)""" raise NotImplementedError def __index__(self): + """index(self)""" return int(self) @abstractmethod - def __pow__(self, exponent, modulus): + def __pow__(self, exponent, modulus=None): """self ** exponent % modulus, but maybe faster. - Implement this if you want to support the 3-argument version - of pow(). Otherwise, just implement the 2-argument version - described in Complex. Raise a TypeError if exponent < 0 or any - argument isn't Integral. + Accept the modulus argument if you want to support the + 3-argument version of pow(). Raise a TypeError if exponent < 0 + or any argument isn't Integral. Otherwise, just implement the + 2-argument version described in Complex. """ raise NotImplementedError @abstractmethod def __lshift__(self, other): + """self << other""" raise NotImplementedError @abstractmethod def __rlshift__(self, other): + """other << self""" raise NotImplementedError @abstractmethod def __rshift__(self, other): + """self >> other""" raise NotImplementedError @abstractmethod def __rrshift__(self, other): + """other >> self""" raise NotImplementedError @abstractmethod def __and__(self, other): + """self & other""" raise NotImplementedError @abstractmethod def __rand__(self, other): + """other & self""" raise NotImplementedError @abstractmethod def __xor__(self, other): + """self ^ other""" raise NotImplementedError @abstractmethod def __rxor__(self, other): + """other ^ self""" raise NotImplementedError @abstractmethod def __or__(self, other): + """self | other""" raise NotImplementedError @abstractmethod def __ror__(self, other): + """other | self""" raise NotImplementedError @abstractmethod def __invert__(self): + """~self""" raise NotImplementedError # Concrete implementations of Rational and Real abstract methods. def __float__(self): + """float(self) == float(int(self))""" return float(int(self)) @property def numerator(self): + """Integers are their own numerators.""" return self @property def denominator(self): + """Integers have a denominator of 1.""" return 1 Integral.register(int) Modified: python/branches/py3k/Lib/test/test_builtin.py ============================================================================== --- python/branches/py3k/Lib/test/test_builtin.py (original) +++ python/branches/py3k/Lib/test/test_builtin.py Fri Sep 7 17:15:49 2007 @@ -1358,11 +1358,13 @@ else: self.assertAlmostEqual(pow(x, y, z), 24.0) + self.assertAlmostEqual(pow(-1, 0.5), 1j) + self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j) + self.assertRaises(TypeError, pow, -1, -2, 3) self.assertRaises(ValueError, pow, 1, 2, 0) self.assertRaises(TypeError, pow, -1, -2, 3) self.assertRaises(ValueError, pow, 1, 2, 0) - self.assertRaises(ValueError, pow, -342.43, 0.234) self.assertRaises(TypeError, pow) Modified: python/branches/py3k/Lib/test/test_complex.py ============================================================================== --- python/branches/py3k/Lib/test/test_complex.py (original) +++ python/branches/py3k/Lib/test/test_complex.py Fri Sep 7 17:15:49 2007 @@ -1,13 +1,6 @@ import unittest, os from test import test_support -import warnings -warnings.filterwarnings( - "ignore", - category=DeprecationWarning, - message=".*complex divmod.*are deprecated" -) - from random import random # These tests ensure that complex math does the right thing @@ -108,6 +101,7 @@ # % is no longer supported on complex numbers self.assertRaises(TypeError, (1+1j).__mod__, 0+0j) self.assertRaises(TypeError, lambda: (3.33+4.43j) % 0) + self.assertRaises(TypeError, (1+1j).__mod__, 4.3j) def test_divmod(self): self.assertRaises(TypeError, divmod, 1+1j, 1+0j) Modified: python/branches/py3k/Lib/test/test_descr.py ============================================================================== --- python/branches/py3k/Lib/test/test_descr.py (original) +++ python/branches/py3k/Lib/test/test_descr.py Fri Sep 7 17:15:49 2007 @@ -3,13 +3,8 @@ from test.test_support import verify, vereq, verbose, TestFailed, TESTFN from test.test_support import get_original_stdout from copy import deepcopy -import warnings import types -warnings.filterwarnings("ignore", - r'complex divmod\(\), // and % are deprecated$', - DeprecationWarning, r'(|%s)$' % __name__) - def veris(a, b): if a is not b: raise TestFailed("%r is %r" % (a, b)) Modified: python/branches/py3k/Objects/floatobject.c ============================================================================== --- python/branches/py3k/Objects/floatobject.c (original) +++ python/branches/py3k/Objects/floatobject.c Fri Sep 7 17:15:49 2007 @@ -680,9 +680,10 @@ * bugs so we have to figure it out ourselves. */ if (iw != floor(iw)) { - PyErr_SetString(PyExc_ValueError, "negative number " - "cannot be raised to a fractional power"); - return NULL; + /* Negative numbers raised to fractional powers + * become complex. + */ + return PyComplex_Type.tp_as_number->nb_power(v, w, z); } /* iw is an exact integer, albeit perhaps a very large one. * -1 raised to an exact integer should never be exceptional. From python-3000-checkins at python.org Fri Sep 7 17:45:05 2007 From: python-3000-checkins at python.org (jeffrey.yasskin) Date: Fri, 7 Sep 2007 17:45:05 +0200 (CEST) Subject: [Python-3000-checkins] r58041 - in python/branches/py3k/Lib: ctypes/test/test_byteswap.py test/test_cmath.py test/test_random.py Message-ID: <20070907154505.D0D281E401A@bag.python.org> Author: jeffrey.yasskin Date: Fri Sep 7 17:45:05 2007 New Revision: 58041 Modified: python/branches/py3k/Lib/ctypes/test/test_byteswap.py python/branches/py3k/Lib/test/test_cmath.py python/branches/py3k/Lib/test/test_random.py Log: Forgot to run the tests after making the places and msg argument keyword-only. This fixes the tests that broke. Modified: python/branches/py3k/Lib/ctypes/test/test_byteswap.py ============================================================================== --- python/branches/py3k/Lib/ctypes/test/test_byteswap.py (original) +++ python/branches/py3k/Lib/ctypes/test/test_byteswap.py Fri Sep 7 17:45:05 2007 @@ -114,12 +114,12 @@ s = c_float(math.pi) self.failUnlessEqual(bin(struct.pack("f", math.pi)), bin(s)) # Hm, what's the precision of a float compared to a double? - self.failUnlessAlmostEqual(s.value, math.pi, 6) + self.failUnlessAlmostEqual(s.value, math.pi, places=6) s = c_float.__ctype_le__(math.pi) - self.failUnlessAlmostEqual(s.value, math.pi, 6) + self.failUnlessAlmostEqual(s.value, math.pi, places=6) self.failUnlessEqual(bin(struct.pack("f", math.pi)), bin(s)) def test_endian_double(self): Modified: python/branches/py3k/Lib/test/test_cmath.py ============================================================================== --- python/branches/py3k/Lib/test/test_cmath.py (original) +++ python/branches/py3k/Lib/test/test_cmath.py Fri Sep 7 17:45:05 2007 @@ -27,10 +27,10 @@ def test_constants(self): e_expected = 2.71828182845904523536 pi_expected = 3.14159265358979323846 - self.assertAlmostEqual(cmath.pi, pi_expected, 9, - "cmath.pi is %s; should be %s" % (cmath.pi, pi_expected)) - self.assertAlmostEqual(cmath.e, e_expected, 9, - "cmath.e is %s; should be %s" % (cmath.e, e_expected)) + self.assertAlmostEqual(cmath.pi, pi_expected, places=9, + msg="cmath.pi is %s; should be %s" % (cmath.pi, pi_expected)) + self.assertAlmostEqual(cmath.e, e_expected, places=9, + msg="cmath.e is %s; should be %s" % (cmath.e, e_expected)) def test_user_object(self): # Test automatic calling of __complex__ and __float__ by cmath Modified: python/branches/py3k/Lib/test/test_random.py ============================================================================== --- python/branches/py3k/Lib/test/test_random.py (original) +++ python/branches/py3k/Lib/test/test_random.py Fri Sep 7 17:45:05 2007 @@ -505,8 +505,8 @@ s1 += e s2 += (e - mu) ** 2 N = len(y) - self.assertAlmostEqual(s1/N, mu, 2) - self.assertAlmostEqual(s2/(N-1), sigmasqrd, 2) + self.assertAlmostEqual(s1/N, mu, places=2) + self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2) class TestModule(unittest.TestCase): def testMagicConstants(self): From python-3000-checkins at python.org Fri Sep 7 19:52:54 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Fri, 7 Sep 2007 19:52:54 +0200 (CEST) Subject: [Python-3000-checkins] r58042 - in python/branches/py3k/Doc: library/exceptions.rst reference/compound_stmts.rst reference/expressions.rst reference/simple_stmts.rst reference/toplevel_components.rst Message-ID: <20070907175254.18E221E400D@bag.python.org> Author: georg.brandl Date: Fri Sep 7 19:52:53 2007 New Revision: 58042 Modified: python/branches/py3k/Doc/library/exceptions.rst python/branches/py3k/Doc/reference/compound_stmts.rst python/branches/py3k/Doc/reference/expressions.rst python/branches/py3k/Doc/reference/simple_stmts.rst python/branches/py3k/Doc/reference/toplevel_components.rst Log: Finish the first pass of the language reference update. Document extended iterable unpacking, raising and catching exceptions, class decorators, etc. A few notable things are not documented yet, I've added XXX comments about that. Modified: python/branches/py3k/Doc/library/exceptions.rst ============================================================================== --- python/branches/py3k/Doc/library/exceptions.rst (original) +++ python/branches/py3k/Doc/library/exceptions.rst Fri Sep 7 19:52:53 2007 @@ -46,6 +46,7 @@ The following exceptions are only used as base classes for other exceptions. +.. XXX document with_traceback() .. exception:: BaseException Modified: python/branches/py3k/Doc/reference/compound_stmts.rst ============================================================================== --- python/branches/py3k/Doc/reference/compound_stmts.rst (original) +++ python/branches/py3k/Doc/reference/compound_stmts.rst Fri Sep 7 19:52:53 2007 @@ -14,8 +14,10 @@ The :keyword:`if`, :keyword:`while` and :keyword:`for` statements implement traditional control flow constructs. :keyword:`try` specifies exception -handlers and/or cleanup code for a group of statements. Function and class -definitions are also syntactically compound statements. +handlers and/or cleanup code for a group of statements, while the +:keyword:`with` statement allows the execution of initialization and +finalization code around a block of code. Function and class definitions are +also syntactically compound statements. .. index:: single: clause @@ -30,7 +32,7 @@ can be one or more indented statements on subsequent lines. Only the latter form of suite can contain nested compound statements; the following is illegal, mostly because it wouldn't be clear to which :keyword:`if` clause a following -:keyword:`else` clause would belong: :: +:keyword:`else` clause would belong:: if test1: if test2: print(x) @@ -60,7 +62,7 @@ pair: dangling; else Note that statements always end in a ``NEWLINE`` possibly followed by a -``DEDENT``. Also note that optional continuation clauses always begin with a +``DEDENT``. Also note that optional continuation clauses always begin with a keyword that cannot start a statement, thus there are no ambiguities (the 'dangling :keyword:`else`' problem is solved in Python by requiring nested :keyword:`if` statements to be indented). @@ -75,6 +77,8 @@ =========================== .. index:: statement: if + keyword: elif + keyword: else The :keyword:`if` statement is used for conditional execution: @@ -83,10 +87,6 @@ : ( "elif" `expression` ":" `suite` )* : ["else" ":" `suite`] -.. index:: - keyword: elif - keyword: else - It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section :ref:`booleans` for the definition of true and false); then that suite is executed (and no other part of the @@ -101,6 +101,7 @@ .. index:: statement: while + keyword: else pair: loop; statement The :keyword:`while` statement is used for repeated execution as long as an @@ -110,8 +111,6 @@ while_stmt: "while" `expression` ":" `suite` : ["else" ":" `suite`] -.. index:: keyword: else - This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the :keyword:`else` clause, if present, is executed and the loop @@ -134,9 +133,11 @@ .. index:: statement: for + keyword: in + keyword: else + pair: target; list pair: loop; statement - -.. index:: object: sequence + object: sequence The :keyword:`for` statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object: @@ -145,17 +146,13 @@ for_stmt: "for" `target_list` "in" `expression_list` ":" `suite` : ["else" ":" `suite`] -.. index:: - keyword: in - keyword: else - pair: target; list - The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the ``expression_list``. The suite is then executed once for each item provided by the iterator, in the order of ascending indices. Each item in turn is assigned to the target list using the -standard rules for assignments, and then the suite is executed. When the items -are exhausted (which is immediately when the sequence is empty), the suite in +standard rules for assignments (see :ref:`assignment`), and then the suite is +executed. When the items are exhausted (which is immediately when the sequence +is empty or an iterator raises a :exc:`StopIteration` exception), the suite in the :keyword:`else` clause, if present, is executed, and the loop terminates. .. index:: @@ -173,13 +170,12 @@ .. index:: builtin: range - pair: Pascal; language -The target list is not deleted when the loop is finished, but if the sequence is -empty, it will not have been assigned to at all by the loop. Hint: the built-in -function :func:`range` returns a sequence of integers suitable to emulate the -effect of Pascal's ``for i := a to b do``; e.g., ``range(3)`` returns the list -``[0, 1, 2]``. +Names in the target list are not deleted when the loop is finished, but if the +sequence is empty, it will not have been assigned to at all by the loop. Hint: +the built-in function :func:`range` returns an iterator of integers suitable to +emulate the effect of Pascal's ``for i := a to b do``; e.g., ``range(3)`` +returns the list ``[0, 1, 2]``. .. warning:: @@ -188,21 +184,19 @@ single: mutable sequence; loop over There is a subtlety when the sequence is being modified by the loop (this can - only occur for mutable sequences, i.e. lists). An internal counter is used to - keep track of which item is used next, and this is incremented on each + only occur for mutable sequences, i.e. lists). An internal counter is used + to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) - item from the sequence, the next item will be skipped (since it gets the index - of the current item which has already been treated). Likewise, if the suite - inserts an item in the sequence before the current item, the current item will - be treated again the next time through the loop. This can lead to nasty bugs - that can be avoided by making a temporary copy using a slice of the whole - sequence, e.g., - -:: + item from the sequence, the next item will be skipped (since it gets the + index of the current item which has already been treated). Likewise, if the + suite inserts an item in the sequence before the current item, the current + item will be treated again the next time through the loop. This can lead to + nasty bugs that can be avoided by making a temporary copy using a slice of + the whole sequence, e.g., :: - for x in a[:]: - if x < 0: a.remove(x) + for x in a[:]: + if x < 0: a.remove(x) .. _try: @@ -245,12 +239,33 @@ as if the entire :keyword:`try` statement raised the exception). When a matching except clause is found, the exception is assigned to the target -specified after the ``as`` keyword in that except clause, if present, and the -except clause's suite is executed. All except clauses must have an executable -block. When the end of this block is reached, execution continues normally -after the entire try statement. (This means that if two nested handlers exist -for the same exception, and the exception occurs in the try clause of the inner -handler, the outer handler will not handle the exception.) +specified after the :keyword:`as` keyword in that except clause, if present, and +the except clause's suite is executed. All except clauses must have an +executable block. When the end of this block is reached, execution continues +normally after the entire try statement. (This means that if two nested +handlers exist for the same exception, and the exception occurs in the try +clause of the inner handler, the outer handler will not handle the exception.) + +When an exception has been assigned using ``as target``, it is cleared at the +end of the except clause. This is as if :: + + except E as N: + foo + +was translated to :: + + except E as N: + try: + foo + finally: + N = None + del N + +That means that you have to assign the exception to a different name if you want +to be able to refer to it after the except clause. The reason for this is that +with the traceback attached to them, exceptions will form a reference cycle with +the stack frame, keeping all locals in that frame alive until the next garbage +collection occurs. .. index:: module: sys @@ -258,12 +273,12 @@ Before an except clause's suite is executed, details about the exception are stored in the :mod:`sys` module and can be access via :func:`sys.exc_info`. -:func:`sys.exc_info` returns a 3-tuple consisting of: ``exc_type`` receives the -object identifying the exception; ``exc_value`` receives the exception's -parameter; ``exc_traceback`` receives a traceback object (see section -:ref:`types`) identifying the point in the program where the exception -occurred. :func:`sys.exc_info` values are restored to their previous values -(before the call) when returning from a function that handled an exception. +:func:`sys.exc_info` returns a 3-tuple consisting of: ``exc_type``, the +exception class; ``exc_value``, the exception instance; ``exc_traceback``, a +traceback object (see section :ref:`types`) identifying the point in the program +where the exception occurred. :func:`sys.exc_info` values are restored to their +previous values (before the call) when returning from a function that handled an +exception. .. index:: keyword: else @@ -303,6 +318,12 @@ and information on using the :keyword:`raise` statement to generate exceptions may be found in section :ref:`raise`. +.. seealso:: + + :pep:`3110` - Catching exceptions in Python 3000 + Describes the differences in :keyword:`try` statements between Python 2.x + and 3.0. + .. _with: @@ -312,9 +333,9 @@ .. index:: statement: with The :keyword:`with` statement is used to wrap the execution of a block with -methods defined by a context manager (see section :ref:`context-managers`). This -allows common :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` usage -patterns to be encapsulated for convenient reuse. +methods defined by a context manager (see section :ref:`context-managers`). +This allows common :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` +usage patterns to be encapsulated for convenient reuse. .. productionlist:: with_stmt: "with" `expression` ["as" `target`] ":" `suite` @@ -330,35 +351,27 @@ .. note:: - The :keyword:`with` statement guarantees that if the :meth:`__enter__` method - returns without an error, then :meth:`__exit__` will always be called. Thus, if - an error occurs during the assignment to the target list, it will be treated the - same as an error occurring within the suite would be. See step 5 below. + The :keyword:`with` statement guarantees that if the :meth:`__enter__` + method returns without an error, then :meth:`__exit__` will always be + called. Thus, if an error occurs during the assignment to the target + list, it will be treated the same as an error occurring within the suite + would be. See step 5 below. #. The suite is executed. -#. The context manager's :meth:`__exit__` method is invoked. If an exception +#. The context manager's :meth:`__exit__` method is invoked. If an exception caused the suite to be exited, its type, value, and traceback are passed as arguments to :meth:`__exit__`. Otherwise, three :const:`None` arguments are supplied. If the suite was exited due to an exception, and the return value from the - :meth:`__exit__` method was false, the exception is reraised. If the return + :meth:`__exit__` method was false, the exception is reraised. If the return value was true, the exception is suppressed, and execution continues with the statement following the :keyword:`with` statement. - If the suite was exited for any reason other than an exception, the return value - from :meth:`__exit__` is ignored, and execution proceeds at the normal location - for the kind of exit that was taken. - -.. note:: - - In Python 2.5, the :keyword:`with` statement is only allowed when the - ``with_statement`` feature has been enabled. It will always be enabled in - Python 2.6. This ``__future__`` import statement can be used to enable the - feature:: - - from __future__ import with_statement + If the suite was exited for any reason other than an exception, the return + value from :meth:`__exit__` is ignored, and execution proceeds at the normal + location for the kind of exit that was taken. .. seealso:: @@ -376,10 +389,10 @@ .. index:: pair: function; definition statement: def - -.. index:: object: user-defined function object: function + pair: function; name + pair: name; binding A function definition defines a user-defined function object (see section :ref:`types`): @@ -398,9 +411,6 @@ defparameter: `parameter` ["=" `expression`] funcname: `identifier` -.. index:: - pair: function; name - pair: name; binding A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper @@ -416,13 +426,13 @@ that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators -are applied in nested fashion. For example, the following code:: +are applied in nested fashion. For example, the following code :: @f1(arg) @f2 def func(): pass -is equivalent to:: +is equivalent to :: def func(): pass func = f1(arg)(f2(func)) @@ -433,16 +443,16 @@ function is said to have "default parameter values." For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter's default value is substituted. If a parameter has a default -value, all following parameters up until the "``*``" must also have a default -value --- this is a syntactic restriction that is not expressed by the grammar. +value, all following parameters up until the "``*``" must also have a default +value --- this is a syntactic restriction that is not expressed by the grammar. **Default parameter values are evaluated when the function definition is -executed.** This means that the expression is evaluated once, when the function +executed.** This means that the expression is evaluated once, when the function is defined, and that that same "pre-computed" value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. -This is generally not what was intended. A way around this is to use ``None`` +This is generally not what was intended. A way around this is to use ``None`` as the default, and explicitly test for it in the body of the function, e.g.:: def whats_on_the_telly(penguin=None): @@ -451,7 +461,7 @@ penguin.append("property of the zoo") return penguin -Function call semantics are described in more detail in section :ref:`calls`. A +Function call semantics are described in more detail in section :ref:`calls`. A function call always assigns values to all parameters mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form "``*identifier``" is present, it is initialized to a tuple @@ -464,13 +474,13 @@ .. index:: pair: function; annotations Parameters may have annotations of the form "``: expression``" following the -parameter name. Any parameter may have an annotation even those of the form -``*identifier`` or ``**identifier``. Functions may have "return" annotation of -the form "``-> expression``" after the parameter list. These annotations can be +parameter name. Any parameter may have an annotation even those of the form +``*identifier`` or ``**identifier``. Functions may have "return" annotation of +the form "``-> expression``" after the parameter list. These annotations can be any valid Python expression and are evaluated when the function definition is -executed. Annotations may be evaluated in a different order than they appear in -the source code. The presence of annotations does not change the semantics of a -function. The annotation values are available as values of a dictionary keyed +executed. Annotations may be evaluated in a different order than they appear in +the source code. The presence of annotations does not change the semantics of a +function. The annotation values are available as values of a dictionary keyed by the parameters' names in the :attr:`__annotations__` attribute of the function object. @@ -499,21 +509,21 @@ .. index:: pair: class; definition statement: class - -.. index:: object: class + object: class + single: inheritance + pair: class; name + pair: name; binding + pair: execution; frame A class definition defines a class object (see section :ref:`types`): +.. XXX need to document PEP 3115 changes here (new metaclasses) + .. productionlist:: - classdef: "class" `classname` [`inheritance`] ":" `suite` + classdef: [`decorators`] "class" `classname` [`inheritance`] ":" `suite` inheritance: "(" [`expression_list`] ")" classname: `identifier` -.. index:: - single: inheritance - pair: class; name - pair: name; binding - pair: execution; frame A class definition is an executable statement. It first evaluates the inheritance list, if present. Each item in the inheritance list should evaluate @@ -526,6 +536,17 @@ the saved local namespace for the attribute dictionary. The class name is bound to this class object in the original local namespace. +Classes can also be decorated; as with functions, :: + + @f1(arg) + @f2 + class Foo: pass + +is equivalent to :: + + class Foo: pass + Foo = f1(arg)(f2(Foo)) + **Programmer's note:** Variables defined in the class definition are class variables; they are shared by all instances. To define instance variables, they must be given a value in the :meth:`__init__` method or in another method. Both @@ -537,6 +558,12 @@ .. XXX add link to descriptor docs above +.. seealso:: + + :pep:`3129` - Class Decorators + + + .. rubric:: Footnotes .. [#] The exception is propogated to the invocation stack only if there is no Modified: python/branches/py3k/Doc/reference/expressions.rst ============================================================================== --- python/branches/py3k/Doc/reference/expressions.rst (original) +++ python/branches/py3k/Doc/reference/expressions.rst Fri Sep 7 19:52:53 2007 @@ -183,6 +183,9 @@ nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached. +Note that the comprehension is executed in a separate scope, so names assigned +to in the target list don't "leak" in the enclosing scope. + .. _lists: @@ -340,6 +343,12 @@ where should the execution continue after it yields; the control is always transfered to the generator's caller. +The :keyword:`yield` statement is allowed in the :keyword:`try` clause of a +:keyword:`try` ... :keyword:`finally` construct. If the generator is not +resumed before it is finalized (by reaching a zero reference count or by being +garbage collected), the generator-iterator's :meth:`close` method will be +called, allowing any pending :keyword:`finally` clauses to execute. + .. index:: object: generator The following generator's methods can be used to control the execution of a @@ -428,6 +437,9 @@ .. seealso:: + :pep:`0255` - Simple Generators + The proposal for adding generators and the :keyword:`yield` statement to Python. + :pep:`0342` - Coroutines via Enhanced Generators The proposal to enhance the API and syntax of generators, making them usable as simple coroutines. Modified: python/branches/py3k/Doc/reference/simple_stmts.rst ============================================================================== --- python/branches/py3k/Doc/reference/simple_stmts.rst (original) +++ python/branches/py3k/Doc/reference/simple_stmts.rst Fri Sep 7 19:52:53 2007 @@ -25,6 +25,7 @@ : | `continue_stmt` : | `import_stmt` : | `global_stmt` + : | `nonlocal_stmt` .. _exprstmts: @@ -33,6 +34,7 @@ ===================== .. index:: pair: expression; statement +.. index:: pair: expression; list Expression statements are used (mostly interactively) to compute and write a value, or (usually) to call a procedure (a function that returns no meaningful @@ -43,8 +45,6 @@ .. productionlist:: expression_stmt: `expression_list` -.. index:: pair: expression; list - An expression statement evaluates the expression list (which may be a single expression). @@ -59,9 +59,8 @@ In interactive mode, if the value is not ``None``, it is converted to a string using the built-in :func:`repr` function and the resulting string is written to -standard output (see :func:`print`) on a line by itself. (Expression -statements yielding ``None`` are not written, so that procedure calls do not -cause any output.) +standard output on a line by itself (except if the result is ``None``, so that +procedure calls do not cause any output.) .. _assert: @@ -72,6 +71,8 @@ .. index:: statement: assert pair: debugging; assertions + single: __debug__ + exception: AssertionError Assert statements are a convenient way to insert debugging assertions into a program: @@ -87,23 +88,19 @@ The extended form, ``assert expression1, expression2``, is equivalent to :: if __debug__: - if not expression1: raise AssertionError, expression2 - -.. index:: - single: __debug__ - exception: AssertionError + if not expression1: raise AssertionError(expression2) -These equivalences assume that ``__debug__`` and :exc:`AssertionError` refer to -the built-in variables with those names. In the current implementation, the -built-in variable ``__debug__`` is ``True`` under normal circumstances, -``False`` when optimization is requested (command line option -O). The current -code generator emits no code for an assert statement when optimization is -requested at compile time. Note that it is unnecessary to include the source +These equivalences assume that :data:`__debug__` and :exc:`AssertionError` refer +to the built-in variables with those names. In the current implementation, the +built-in variable :data:`__debug__` is ``True`` under normal circumstances, +``False`` when optimization is requested (command line option ``-O``). The +current code generator emits no code for an assert statement when optimization +is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace. -Assignments to ``__debug__`` are illegal. The value for the built-in variable -is determined when the interpreter starts. +Assignments to :data:`__debug__` are illegal. The value for the built-in +variable is determined when the interpreter starts. .. _assignment: @@ -130,12 +127,11 @@ : | `attributeref` : | `subscription` : | `slicing` + : | "*" `target` (See section :ref:`primaries` for the syntax definitions for the last three symbols.) -.. index:: pair: expression; list - An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to @@ -154,48 +150,45 @@ .. index:: triple: target; list; assignment -Assignment of an object to a target list is recursively defined as follows. +Assignment of an object to a target list, optionally enclosed in parentheses or +square brackets, is recursively defined as follows. * If the target list is a single target: The object is assigned to that target. -* If the target list is a comma-separated list of targets: The object must be a - sequence with the same number of items as there are targets in the target list, - and the items are assigned, from left to right, to the corresponding targets. - (This rule is relaxed as of Python 1.5; in earlier versions, the object had to - be a tuple. Since strings are sequences, an assignment like ``a, b = "xy"`` is - now legal as long as the string has the right length.) +* If the target list is a comma-separated list of targets: + + * If the target list contains one target prefixed with an asterisk, called a + "starred" target: The object must be a sequence with at least as many items + as there are targets in the target list, minus one. The first items of the + sequence are assigned, from left to right, to the targets before the starred + target. The final items of the sequence are assigned to the targets after + the starred target. A list of the remaining items in the sequence is then + assigned to the starred target (the list can be empty). + + * Else: The object must be a sequence with the same number of items as there + are targets in the target list, and the items are assigned, from left to + right, to the corresponding targets. Assignment of an object to a single target is recursively defined as follows. * If the target is an identifier (name): - .. index:: statement: global - -* If the name does not occur in a :keyword:`global` statement in the current - code block: the name is bound to the object in the current local namespace. - -* Otherwise: the name is bound to the object in the current global namespace. - - .. index:: single: destructor - - The name is rebound if it was already bound. This may cause the reference count - for the object previously bound to the name to reach zero, causing the object to - be deallocated and its destructor (if it has one) to be called. - - .. % nested - -* If the target is a target list enclosed in parentheses or in square brackets: - The object must be a sequence with the same number of items as there are targets - in the target list, and its items are assigned, from left to right, to the - corresponding targets. - - .. index:: pair: attribute; assignment + * If the name does not occur in a :keyword:`global` or :keyword:`nonlocal` + statement in the current code block: the name is bound to the object in the + current local namespace. + + * Otherwise: the name is bound to the object in the global namespace or the + outer namespace determined by :keyword:`nonlocal`, respectively. + + The name is rebound if it was already bound. This may cause the reference + count for the object previously bound to the name to reach zero, causing the + object to be deallocated and its destructor (if it has one) to be called. * If the target is an attribute reference: The primary expression in the reference is evaluated. It should yield an object with assignable attributes; - if this is not the case, :exc:`TypeError` is raised. That object is then asked - to assign the assigned object to the given attribute; if it cannot perform the - assignment, it raises an exception (usually but not necessarily + if this is not the case, :exc:`TypeError` is raised. That object is then + asked to assign the assigned object to the given attribute; if it cannot + perform the assignment, it raises an exception (usually but not necessarily :exc:`AttributeError`). .. index:: @@ -203,20 +196,20 @@ object: mutable * If the target is a subscription: The primary expression in the reference is - evaluated. It should yield either a mutable sequence object (such as a list) or - a mapping object (such as a dictionary). Next, the subscript expression is + evaluated. It should yield either a mutable sequence object (such as a list) + or a mapping object (such as a dictionary). Next, the subscript expression is evaluated. .. index:: object: sequence object: list - If the primary is a mutable sequence object (such as a list), the subscript must - yield a plain integer. If it is negative, the sequence's length is added to it. - The resulting value must be a nonnegative integer less than the sequence's - length, and the sequence is asked to assign the assigned object to its item with - that index. If the index is out of range, :exc:`IndexError` is raised - (assignment to a subscripted sequence cannot add new items to a list). + If the primary is a mutable sequence object (such as a list), the subscript + must yield an integer. If it is negative, the sequence's length is added to + it. The resulting value must be a nonnegative integer less than the + sequence's length, and the sequence is asked to assign the assigned object to + its item with that index. If the index is out of range, :exc:`IndexError` is + raised (assignment to a subscripted sequence cannot add new items to a list). .. index:: object: mapping @@ -228,19 +221,22 @@ object. This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed). + For user-defined objects, the :meth:`__setitem__` method is called with + appropriate arguments. + .. index:: pair: slicing; assignment * If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults - are zero and the sequence's length. The bounds should evaluate to (small) - integers. If either bound is negative, the sequence's length is added to it. - The resulting bounds are clipped to lie between zero and the sequence's length, - inclusive. Finally, the sequence object is asked to replace the slice with the - items of the assigned sequence. The length of the slice may be different from - the length of the assigned sequence, thus changing the length of the target - sequence, if the object allows it. + are zero and the sequence's length. The bounds should evaluate to integers. + If either bound is negative, the sequence's length is added to it. The + resulting bounds are clipped to lie between zero and the sequence's length, + inclusive. Finally, the sequence object is asked to replace the slice with + the items of the assigned sequence. The length of the slice may be different + from the length of the assigned sequence, thus changing the length of the + target sequence, if the object allows it. (In the current implementation, the syntax for targets is taken to be the same as for expressions, and invalid syntax is rejected during the code generation @@ -257,6 +253,12 @@ print(x) +.. seealso:: + + :pep:`3132` - Extended Iterable Unpacking + The specification for the ``*target`` feature. + + .. _augassign: Augmented assignment statements @@ -312,12 +314,11 @@ ============================= .. index:: statement: pass + pair: null; operation .. productionlist:: pass_stmt: "pass" -.. index:: pair: null; operation - :keyword:`pass` is a null operation --- when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:: @@ -333,14 +334,12 @@ ============================ .. index:: statement: del + pair: deletion; target + triple: deletion; target; list .. productionlist:: del_stmt: "del" `target_list` -.. index:: - pair: deletion; target - triple: deletion; target; list - Deletion is recursively defined very similar to the way assignment is defined. Rather that spelling it out in full details, here are some hints. @@ -350,7 +349,7 @@ statement: global pair: unbinding; name -Deletion of a name removes the binding of that name from the local or global +Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a :keyword:`global` statement in the same code block. If the name is unbound, a :exc:`NameError` exception will be raised. @@ -374,14 +373,12 @@ =============================== .. index:: statement: return + pair: function; definition + pair: class; definition .. productionlist:: return_stmt: "return" [`expression_list`] -.. index:: - pair: function; definition - pair: class; definition - :keyword:`return` may only occur syntactically nested in a function definition, not within a nested class definition. @@ -407,59 +404,11 @@ The :keyword:`yield` statement ============================== -.. index:: statement: yield - .. productionlist:: yield_stmt: `yield_expression` -.. index:: - single: generator; function - single: generator; iterator - single: function; generator - exception: StopIteration - -The :keyword:`yield` statement is only used when defining a generator function, -and is only used in the body of the generator function. Using a :keyword:`yield` -statement in a function definition is sufficient to cause that definition to -create a generator function instead of a normal function. - -When a generator function is called, it returns an iterator known as a generator -iterator, or more commonly, a generator. The body of the generator function is -executed by calling the generator's :meth:`__next__` method repeatedly until it -raises an exception. - -When a :keyword:`yield` statement is executed, the state of the generator is -frozen and the value of :token:`expression_list` is returned to -:meth:`__next__`'s caller. By "frozen" we mean that all local state is -retained, including the current bindings of local variables, the instruction -pointer, and the internal evaluation stack: enough information is saved so that -the next time :meth:`__next__` is invoked, the function can proceed exactly as -if the :keyword:`yield` statement were just another external call. - -As of Python version 2.5, the :keyword:`yield` statement is now allowed in the -:keyword:`try` clause of a :keyword:`try` ... :keyword:`finally` construct. If -the generator is not resumed before it is finalized (by reaching a zero -reference count or by being garbage collected), the generator-iterator's -:meth:`close` method will be called, allowing any pending :keyword:`finally` -clauses to execute. - -.. note:: - - In Python 2.2, the :keyword:`yield` statement is only allowed when the - ``generators`` feature has been enabled. It will always be enabled in Python - 2.3. This ``__future__`` import statement can be used to enable the feature:: - - from __future__ import generators - - -.. seealso:: - - :pep:`0255` - Simple Generators - The proposal for adding generators and the :keyword:`yield` statement to Python. - - :pep:`0342` - Coroutines via Enhanced Generators - The proposal that, among other generator enhancements, proposed allowing - :keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block. +The yield statement is nothing but a yield expression used as a statement, +see :ref:`yieldexpr`. .. _raise: @@ -468,49 +417,45 @@ ============================== .. index:: statement: raise + pair: raising; exception .. productionlist:: - raise_stmt: "raise" [`expression` ["," `expression` ["," `expression`]]] - -.. index:: - single: exception - pair: raising; exception + raise_stmt: "raise" [`expression` ["from" `expression`]] If no expressions are present, :keyword:`raise` re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a :exc:`TypeError` exception is raised indicating that this is an error (if running under IDLE, a :exc:`Queue.Empty` exception is raised instead). -Otherwise, :keyword:`raise` evaluates the expressions to get three objects, -using ``None`` as the value of omitted expressions. The first two objects are -used to determine the *type* and *value* of the exception. - -If the first object is an instance, the type of the exception is the class of -the instance, the instance itself is the value, and the second object must be -``None``. - -If the first object is a class, it becomes the type of the exception. The second -object is used to determine the exception value: If it is an instance of the -class, the instance becomes the exception value. If the second object is a -tuple, it is used as the argument list for the class constructor; if it is -``None``, an empty argument list is used, and any other object is treated as a -single argument to the constructor. The instance so created by calling the -constructor is used as the exception value. +Otherwise, :keyword:`raise` evaluates the first expression as the exception +object. It must be either a subclass or an instance of :class:`BaseException`. +If it is a class, the exception instance will be obtained when needed by +instantiating the class with no arguments. + +The :dfn:`type` of the exception is the exception instance's class, the +:dfn:`value` is the instance itself. .. index:: object: traceback -If a third object is present and not ``None``, it must be a traceback object -(see section :ref:`types`), and it is substituted instead of the current -location as the place where the exception occurred. If the third object is -present and not a traceback object or ``None``, a :exc:`TypeError` exception is -raised. The three-expression form of :keyword:`raise` is useful to re-raise an -exception transparently in an except clause, but :keyword:`raise` with no -expressions should be preferred if the exception to be re-raised was the most -recently active exception in the current scope. +A traceback object is normally created automatically when an exception is raised +and attached to it as the :attr:`__traceback__` attribute; however, you can set +your own traceback using the :meth:`with_traceback` exception method, like so:: + + raise RuntimeError("foo occurred").with_traceback(tracebackobj) + +.. XXX document exception chaining + +The "from" clause is used for exception chaining, which is not documented yet. Additional information on exceptions can be found in section :ref:`exceptions`, and information about handling exceptions is in section :ref:`try`. +.. seealso:: + + :pep:`3109` - Raising exceptions in Python 3000 + Describes the differences in :keyword:`raise` statements between Python + 2.x and 3.0. + .. _break: @@ -518,26 +463,23 @@ ============================== .. index:: statement: break + statement: for + statement: while + pair: loop; statement .. productionlist:: break_stmt: "break" -.. index:: - statement: for - statement: while - pair: loop; statement - :keyword:`break` may only occur syntactically nested in a :keyword:`for` or :keyword:`while` loop, but not nested in a function or class definition within that loop. .. index:: keyword: else + pair: loop control; target It terminates the nearest enclosing loop, skipping the optional :keyword:`else` clause if the loop has one. -.. index:: pair: loop control; target - If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control target keeps its current value. @@ -554,16 +496,14 @@ ================================= .. index:: statement: continue + statement: for + statement: while + pair: loop; statement + keyword: finally .. productionlist:: continue_stmt: "continue" -.. index:: - statement: for - statement: while - pair: loop; statement - keyword: finally - :keyword:`continue` may only occur syntactically nested in a :keyword:`for` or :keyword:`while` loop, but not nested in a function or class definition or :keyword:`finally` statement within that loop. [#]_ It continues with the next @@ -594,7 +534,7 @@ Import statements are executed in two steps: (1) find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope -where the :keyword:`import` statement occurs). The first form (without +where the :keyword:`import` statement occurs). The first form (without :keyword:`from`) repeats these steps for each identifier in the list. The form with :keyword:`from` performs step (1) once, and then performs step (2) repeatedly. @@ -611,9 +551,9 @@ pair: module; name pair: built-in; module pair: user-defined; module - module: sys pair: filename; extension triple: module; search; path + module: sys The system maintains a table of modules that have been or are being initialized, indexed by module name. This table is accessible as ``sys.modules``. When a @@ -676,9 +616,6 @@ .. index:: keyword: from - statement: from - -.. index:: triple: hierarchical; module; names single: packages single: __init__.py @@ -692,8 +629,6 @@ http://www.python.org/doc/essays/packages.html for more details, also about how the module search works from inside a package.] -.. % - .. index:: builtin: __import__ The built-in function :func:`__import__` is provided to support applications @@ -731,10 +666,12 @@ * blank lines, and * other future statements. -The features recognized by Python 2.5 are ``absolute_import``, ``division``, -``generators``, ``nested_scopes`` and ``with_statement``. ``generators`` and -``nested_scopes`` are redundant in Python version 2.3 and above because they -are always enabled. +.. XXX change this if future is cleaned out + +The features recognized by Python 3.0 are ``absolute_import``, ``division``, +``generators``, ``nested_scopes`` and ``with_statement``. They are all +redundant because they are always enabled, and only kept for backwards +compatibility. A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating @@ -762,11 +699,10 @@ special semantics or syntax restrictions. Code compiled by calls to the builtin functions :func:`exec` and :func:`compile` -that occur in a module :mod:`M` containing a future -statement will, by default, use the new syntax or semantics associated with the -future statement. This can, starting with Python 2.2 be controlled by optional -arguments to :func:`compile` --- see the documentation of that function -for details. +that occur in a module :mod:`M` containing a future statement will, by default, +use the new syntax or semantics associated with the future statement. This can +be controlled by optional arguments to :func:`compile` --- see the documentation +of that function for details. A future statement typed at an interactive interpreter prompt will take effect for the rest of the interpreter session. If an interpreter is started with the @@ -817,6 +753,20 @@ unaffected by :keyword:`global` statements in the code containing the function call. The same applies to the :func:`eval` and :func:`compile` functions. + +.. _nonlocal: + +The :keyword:`nonlocal` statement +================================= + +.. index:: statement: nonlocal + +.. productionlist:: + nonlocal_stmt: "nonlocal" `identifier` ("," `identifier`)* + +XXX: To be documented. + + .. rubric:: Footnotes .. [#] It may occur within an :keyword:`except` or :keyword:`else` clause. The Modified: python/branches/py3k/Doc/reference/toplevel_components.rst ============================================================================== --- python/branches/py3k/Doc/reference/toplevel_components.rst (original) +++ python/branches/py3k/Doc/reference/toplevel_components.rst Fri Sep 7 19:52:53 2007 @@ -53,9 +53,9 @@ Under Unix, a complete program can be passed to the interpreter in three forms: with the :option:`-c` *string* command line option, as a file passed as the -first command line argument, or as standard input. If the file or standard input -is a tty device, the interpreter enters interactive mode; otherwise, it executes -the file as a complete program. +first command line argument, or as standard input. If the file or standard +input is a tty device, the interpreter enters interactive mode; otherwise, it +executes the file as a complete program. .. _file-input: From python-3000-checkins at python.org Fri Sep 7 22:49:04 2007 From: python-3000-checkins at python.org (neil.schemenauer) Date: Fri, 7 Sep 2007 22:49:04 +0200 (CEST) Subject: [Python-3000-checkins] r58047 - python/branches/py3k/Objects/unicodeobject.c Message-ID: <20070907204904.A6AD21E400D@bag.python.org> Author: neil.schemenauer Date: Fri Sep 7 22:49:04 2007 New Revision: 58047 Modified: python/branches/py3k/Objects/unicodeobject.c Log: Restore caching of unicode hash value. This apparently was broken during some refactoring. Modified: python/branches/py3k/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k/Objects/unicodeobject.c (original) +++ python/branches/py3k/Objects/unicodeobject.c Fri Sep 7 22:49:04 2007 @@ -6588,12 +6588,19 @@ } static long -unicode_hash(PyObject *self) +unicode_hash(PyUnicodeObject *self) { - /* Since Unicode objects compare equal to their UTF-8 string - counterparts, we hash the UTF-8 string. */ - PyObject *v = _PyUnicode_AsDefaultEncodedString(self, NULL); - return PyObject_Hash(v); + if (self->hash != -1) { + return self->hash; + } + else { + /* Since Unicode objects compare equal to their UTF-8 string + counterparts, we hash the UTF-8 string. */ + PyObject *v = _PyUnicode_AsDefaultEncodedString((PyObject*)self, NULL); + long x = PyObject_Hash(v); + self->hash = x; + return x; + } } PyDoc_STRVAR(index__doc__, From python-3000-checkins at python.org Sat Sep 8 18:05:25 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 8 Sep 2007 18:05:25 +0200 (CEST) Subject: [Python-3000-checkins] r58053 - python/branches/py3k/Lib/test/test_doctest.py Message-ID: <20070908160525.CAA561E4006@bag.python.org> Author: guido.van.rossum Date: Sat Sep 8 18:05:25 2007 New Revision: 58053 Modified: python/branches/py3k/Lib/test/test_doctest.py Log: Add REPORT_NDIFF option to o test that was hard to debug recently. Modified: python/branches/py3k/Lib/test/test_doctest.py ============================================================================== --- python/branches/py3k/Lib/test/test_doctest.py (original) +++ python/branches/py3k/Lib/test/test_doctest.py Sat Sep 8 18:05:25 2007 @@ -1752,6 +1752,7 @@ ... runner.run(test) ... finally: ... sys.stdin = real_stdin + ... # doctest: +REPORT_NDIFF > (5)calls_set_trace() -> self.f1() (Pdb) print(y) From python-3000-checkins at python.org Sat Sep 8 19:39:31 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Sat, 8 Sep 2007 19:39:31 +0200 (CEST) Subject: [Python-3000-checkins] r58054 - in python/branches/py3k: Doc/documenting/markup.rst Doc/library/codecs.rst Doc/library/copy.rst Doc/library/ctypes.rst Doc/library/mutex.rst Doc/library/queue.rst Doc/library/re.rst Doc/library/readline.rst Doc/library/smtplib.rst Doc/library/socket.rst Doc/library/ssl.rst Doc/library/thread.rst Doc/library/threading.rst Doc/whatsnew/2.6.rst Include/pyerrors.h Lib/ctypes/__init__.py Lib/ctypes/test/test_arrays.py Lib/ctypes/test/test_callbacks.py Lib/ctypes/test/test_cfuncs.py Lib/ctypes/test/test_functions.py Lib/ctypes/test/test_repr.py Lib/distutils/dep_util.py Lib/httplib.py Lib/imaplib.py Lib/smtplib.py Lib/test/crashers/infinite_rec_1.py Lib/test/crashers/infinite_rec_2.py Lib/test/test_descr.py Lib/test/test_ssl.py Lib/test/test_uuid.py Makefile.pre.in Misc/ACKS Modules/_ctypes/_ctypes.c Modules/_ctypes/_ctypes_test.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_ctypes/ctypes.h Modules/_ctypes/libffi/configure Modules/_ctypes/libffi/configure.ac Modules/_lsprof.c Modules/_ssl.c Modules/makesetup Modules/posixmodule.c Modules/readline.c Objects/abstract.c Objects/exceptions.c Objects/typeobject.c PCbuild8/readme.txt Parser/parsetok.c Parser/tokenizer.c Parser/tokenizer.h Python/errors.c configure configure.in pyconfig.h.in Message-ID: <20070908173931.074251E4007@bag.python.org> Author: thomas.wouters Date: Sat Sep 8 19:39:28 2007 New Revision: 58054 Removed: python/branches/py3k/Lib/test/crashers/infinite_rec_1.py python/branches/py3k/Lib/test/crashers/infinite_rec_2.py Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/documenting/markup.rst python/branches/py3k/Doc/library/codecs.rst python/branches/py3k/Doc/library/copy.rst python/branches/py3k/Doc/library/ctypes.rst python/branches/py3k/Doc/library/mutex.rst python/branches/py3k/Doc/library/queue.rst python/branches/py3k/Doc/library/re.rst python/branches/py3k/Doc/library/readline.rst python/branches/py3k/Doc/library/smtplib.rst python/branches/py3k/Doc/library/socket.rst python/branches/py3k/Doc/library/ssl.rst python/branches/py3k/Doc/library/thread.rst python/branches/py3k/Doc/library/threading.rst python/branches/py3k/Doc/whatsnew/2.6.rst python/branches/py3k/Include/pyerrors.h python/branches/py3k/Lib/ctypes/__init__.py python/branches/py3k/Lib/ctypes/test/test_arrays.py python/branches/py3k/Lib/ctypes/test/test_callbacks.py python/branches/py3k/Lib/ctypes/test/test_cfuncs.py python/branches/py3k/Lib/ctypes/test/test_functions.py python/branches/py3k/Lib/ctypes/test/test_repr.py python/branches/py3k/Lib/distutils/dep_util.py python/branches/py3k/Lib/httplib.py python/branches/py3k/Lib/imaplib.py python/branches/py3k/Lib/smtplib.py python/branches/py3k/Lib/test/test_descr.py python/branches/py3k/Lib/test/test_ssl.py python/branches/py3k/Lib/test/test_uuid.py python/branches/py3k/Makefile.pre.in python/branches/py3k/Misc/ACKS python/branches/py3k/Modules/_ctypes/_ctypes.c python/branches/py3k/Modules/_ctypes/_ctypes_test.c python/branches/py3k/Modules/_ctypes/callproc.c python/branches/py3k/Modules/_ctypes/cfield.c python/branches/py3k/Modules/_ctypes/ctypes.h python/branches/py3k/Modules/_ctypes/libffi/configure python/branches/py3k/Modules/_ctypes/libffi/configure.ac python/branches/py3k/Modules/_lsprof.c python/branches/py3k/Modules/_ssl.c python/branches/py3k/Modules/makesetup python/branches/py3k/Modules/posixmodule.c python/branches/py3k/Modules/readline.c python/branches/py3k/Objects/abstract.c python/branches/py3k/Objects/exceptions.c python/branches/py3k/Objects/typeobject.c python/branches/py3k/PCbuild8/readme.txt python/branches/py3k/Parser/parsetok.c python/branches/py3k/Parser/tokenizer.c python/branches/py3k/Parser/tokenizer.h python/branches/py3k/Python/errors.c python/branches/py3k/configure python/branches/py3k/configure.in python/branches/py3k/pyconfig.h.in Log: Merged revisions 57778-58052 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r57820 | georg.brandl | 2007-08-31 08:59:27 +0200 (Fri, 31 Aug 2007) | 2 lines Document new shorthand notation for index entries. ........ r57827 | georg.brandl | 2007-08-31 10:47:51 +0200 (Fri, 31 Aug 2007) | 2 lines Fix subitem markup. ........ r57833 | martin.v.loewis | 2007-08-31 12:01:07 +0200 (Fri, 31 Aug 2007) | 1 line Mark registry components as 64-bit on Win64. ........ r57854 | bill.janssen | 2007-08-31 21:02:23 +0200 (Fri, 31 Aug 2007) | 1 line deprecate use of FakeSocket ........ r57855 | bill.janssen | 2007-08-31 21:02:46 +0200 (Fri, 31 Aug 2007) | 1 line remove mentions of socket.ssl in comments ........ r57856 | bill.janssen | 2007-08-31 21:03:31 +0200 (Fri, 31 Aug 2007) | 1 line remove use of non-existent SSLFakeSocket in apparently untested code ........ r57859 | martin.v.loewis | 2007-09-01 08:36:03 +0200 (Sat, 01 Sep 2007) | 3 lines Bug #1737210: Change Manufacturer of Windows installer to PSF. Will backport to 2.5. ........ r57865 | georg.brandl | 2007-09-01 09:51:24 +0200 (Sat, 01 Sep 2007) | 2 lines Fix RST link (backport from Py3k). ........ r57876 | georg.brandl | 2007-09-01 17:49:49 +0200 (Sat, 01 Sep 2007) | 2 lines Document sets' ">" and "<" operations (backport from py3k). ........ r57878 | skip.montanaro | 2007-09-01 19:40:03 +0200 (Sat, 01 Sep 2007) | 4 lines Added a note and examples to explain that re.split does not split on an empty pattern match. (issue 852532). ........ r57879 | walter.doerwald | 2007-09-01 20:18:09 +0200 (Sat, 01 Sep 2007) | 2 lines Fix wrong function names. ........ r57880 | walter.doerwald | 2007-09-01 20:34:05 +0200 (Sat, 01 Sep 2007) | 2 lines Fix typo. ........ r57889 | andrew.kuchling | 2007-09-01 22:31:59 +0200 (Sat, 01 Sep 2007) | 1 line Markup fix ........ r57892 | andrew.kuchling | 2007-09-01 22:43:36 +0200 (Sat, 01 Sep 2007) | 1 line Add various items ........ r57895 | andrew.kuchling | 2007-09-01 23:17:58 +0200 (Sat, 01 Sep 2007) | 1 line Wording change ........ r57896 | andrew.kuchling | 2007-09-01 23:18:31 +0200 (Sat, 01 Sep 2007) | 1 line Add more items ........ r57904 | ronald.oussoren | 2007-09-02 11:46:07 +0200 (Sun, 02 Sep 2007) | 3 lines Macosx: this patch ensures that the value of MACOSX_DEPLOYMENT_TARGET used by the Makefile is also used at configure-time. ........ r57925 | georg.brandl | 2007-09-03 09:16:46 +0200 (Mon, 03 Sep 2007) | 2 lines Fix #883466: don't allow Unicode as arguments to quopri and uu codecs. ........ r57936 | matthias.klose | 2007-09-04 01:33:04 +0200 (Tue, 04 Sep 2007) | 2 lines - Added support for linking the bsddb module against BerkeleyDB 4.6.x. ........ r57954 | mark.summerfield | 2007-09-04 10:16:15 +0200 (Tue, 04 Sep 2007) | 3 lines Added cross-references plus a note about dict & list shallow copying. ........ r57958 | martin.v.loewis | 2007-09-04 11:51:57 +0200 (Tue, 04 Sep 2007) | 3 lines Document that we rely on the OS to release the crypto context. Fixes #1626801. ........ r57960 | martin.v.loewis | 2007-09-04 15:13:14 +0200 (Tue, 04 Sep 2007) | 3 lines Patch #1388440: Add set_completion_display_matches_hook and get_completion_type to readline. ........ r57961 | martin.v.loewis | 2007-09-04 16:19:28 +0200 (Tue, 04 Sep 2007) | 3 lines Patch #1031213: Decode source line in SyntaxErrors back to its original source encoding. Will backport to 2.5. ........ r57972 | matthias.klose | 2007-09-04 20:17:36 +0200 (Tue, 04 Sep 2007) | 3 lines - Makefile.pre.in(buildbottest): Run an optional script pybuildbot.identify to include some information about the build environment. ........ r57973 | matthias.klose | 2007-09-04 21:05:38 +0200 (Tue, 04 Sep 2007) | 2 lines - Makefile.pre.in(buildbottest): Remove whitespace at eol. ........ r57975 | matthias.klose | 2007-09-04 22:46:02 +0200 (Tue, 04 Sep 2007) | 2 lines - Fix libffi configure for hppa*-*-linux* | parisc*-*-linux*. ........ r57980 | bill.janssen | 2007-09-05 02:46:27 +0200 (Wed, 05 Sep 2007) | 1 line SSL certificate distinguished names should be represented by tuples ........ r57985 | martin.v.loewis | 2007-09-05 08:39:17 +0200 (Wed, 05 Sep 2007) | 3 lines Patch #1105: Explain that one needs to build the solution to get dependencies right. ........ r57987 | armin.rigo | 2007-09-05 09:51:21 +0200 (Wed, 05 Sep 2007) | 4 lines PyDict_GetItem() returns a borrowed reference. There are probably a number of places that are open to attacks such as the following one, in bltinmodule.c:min_max(). ........ r57991 | martin.v.loewis | 2007-09-05 13:47:34 +0200 (Wed, 05 Sep 2007) | 3 lines Patch #786737: Allow building in a tree of symlinks pointing to a readonly source. ........ r57993 | georg.brandl | 2007-09-05 15:36:44 +0200 (Wed, 05 Sep 2007) | 2 lines Backport from Py3k: Bug #1684991: explain lookup semantics for __special__ methods (new-style classes only). ........ r58004 | armin.rigo | 2007-09-06 10:30:51 +0200 (Thu, 06 Sep 2007) | 4 lines Patch #1733973 by peaker: ptrace_enter_call() assumes no exception is currently set. This assumption is broken when throwing into a generator. ........ r58006 | armin.rigo | 2007-09-06 11:30:38 +0200 (Thu, 06 Sep 2007) | 4 lines PyDict_GetItem() returns a borrowed reference. This attack is against ceval.c:IMPORT_NAME, which calls an object (__builtin__.__import__) without holding a reference to it. ........ r58013 | georg.brandl | 2007-09-06 16:49:56 +0200 (Thu, 06 Sep 2007) | 2 lines Backport from 3k: #1116: fix reference to old filename. ........ r58021 | thomas.heller | 2007-09-06 22:26:20 +0200 (Thu, 06 Sep 2007) | 1 line Fix typo: c_float represents to C float type. ........ r58022 | skip.montanaro | 2007-09-07 00:29:06 +0200 (Fri, 07 Sep 2007) | 3 lines If this is correct for py3k branch and it's already in the release25-maint branch, seems like it ought to be on the trunk as well. ........ r58023 | gregory.p.smith | 2007-09-07 00:59:59 +0200 (Fri, 07 Sep 2007) | 4 lines Apply the fix from Issue1112 to make this test more robust and keep windows happy. ........ r58031 | brett.cannon | 2007-09-07 05:17:50 +0200 (Fri, 07 Sep 2007) | 4 lines Make uuid1 and uuid4 tests conditional on whether ctypes can be imported; implementation of either function depends on ctypes but uuid as a whole does not. ........ r58032 | brett.cannon | 2007-09-07 06:18:30 +0200 (Fri, 07 Sep 2007) | 6 lines Fix a crasher where Python code managed to infinitely recurse in C code without ever going back out to Python code in PyObject_Call(). Required introducing a static RuntimeError instance so that normalizing an exception there is no reliance on a recursive call that would put the exception system over the recursion check itself. ........ r58034 | thomas.heller | 2007-09-07 08:32:17 +0200 (Fri, 07 Sep 2007) | 1 line Add a 'c_longdouble' type to the ctypes module. ........ r58035 | thomas.heller | 2007-09-07 11:30:40 +0200 (Fri, 07 Sep 2007) | 1 line Remove unneeded #include. ........ r58036 | thomas.heller | 2007-09-07 11:33:24 +0200 (Fri, 07 Sep 2007) | 6 lines Backport from py3k branch: Add a workaround for a strange bug on win64, when _ctypes is compiled with the SDK compiler. This should fix the failing Lib\ctypes\test\test_as_parameter.py test. ........ r58037 | georg.brandl | 2007-09-07 16:14:40 +0200 (Fri, 07 Sep 2007) | 2 lines Fix a wrong indentation for sublists. ........ r58043 | georg.brandl | 2007-09-07 22:10:49 +0200 (Fri, 07 Sep 2007) | 2 lines #1095: ln -f doesn't work portably, fix in Makefile. ........ r58049 | skip.montanaro | 2007-09-08 02:34:17 +0200 (Sat, 08 Sep 2007) | 1 line be explicit about the actual location of the missing file ........ Modified: python/branches/py3k/Doc/documenting/markup.rst ============================================================================== --- python/branches/py3k/Doc/documenting/markup.rst (original) +++ python/branches/py3k/Doc/documenting/markup.rst Sat Sep 8 19:39:28 2007 @@ -707,7 +707,7 @@ For example:: .. index:: - single: execution!context + single: execution; context module: __main__ module: sys triple: module; search; path @@ -720,8 +720,8 @@ single Creates a single index entry. Can be made a subentry by separating the - subentry text with a semicolon (this is also used below to describe what - entries are created). + subentry text with a semicolon (this notation is also used below to describe + what entries are created). pair ``pair: loop; statement`` is a shortcut that creates two index entries, namely ``loop; statement`` and ``statement; loop``. @@ -733,6 +733,13 @@ These all create two index entries. For example, ``module: hashlib`` creates the entries ``module; hashlib`` and ``hashlib; module``. +For index directives containing only "single" entries, there is a shorthand +notation:: + + .. index:: BNF, grammar, syntax, notation + +This creates four index entries. + Grammar production displays --------------------------- Modified: python/branches/py3k/Doc/library/codecs.rst ============================================================================== --- python/branches/py3k/Doc/library/codecs.rst (original) +++ python/branches/py3k/Doc/library/codecs.rst Sat Sep 8 19:39:28 2007 @@ -186,12 +186,12 @@ Implements the ``ignore`` error handling. -.. function:: xmlcharrefreplace_errors_errors(exception) +.. function:: xmlcharrefreplace_errors(exception) Implements the ``xmlcharrefreplace`` error handling. -.. function:: backslashreplace_errors_errors(exception) +.. function:: backslashreplace_errors(exception) Implements the ``backslashreplace`` error handling. @@ -833,7 +833,7 @@ encoding was used for encoding a Unicode string. Each charmap encoding can decode any random byte sequence. However that's not possible with UTF-8, as UTF-8 byte sequences have a structure that doesn't allow arbitrary byte -sequence. To increase the reliability with which a UTF-8 encoding can be +sequences. To increase the reliability with which a UTF-8 encoding can be detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls ``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters is written to the file, a UTF-8 encoded BOM (which looks like this as a byte Modified: python/branches/py3k/Doc/library/copy.rst ============================================================================== --- python/branches/py3k/Doc/library/copy.rst (original) +++ python/branches/py3k/Doc/library/copy.rst Sat Sep 8 19:39:28 2007 @@ -54,6 +54,10 @@ classes (shallow and deeply), by returning the original object unchanged; this is compatible with the way these are treated by the :mod:`pickle` module. +Shallow copies of dictionaries can be made using :meth:`dict.copy`, and +of lists by assigning a slice of the entire list, for example, +``copied_list = original_list[:]``. + .. index:: module: pickle Classes can use the same interfaces to control copying that they use to control Modified: python/branches/py3k/Doc/library/ctypes.rst ============================================================================== --- python/branches/py3k/Doc/library/ctypes.rst (original) +++ python/branches/py3k/Doc/library/ctypes.rst Sat Sep 8 19:39:28 2007 @@ -247,6 +247,8 @@ +----------------------+--------------------------------+----------------------------+ | :class:`c_double` | ``double`` | float | +----------------------+--------------------------------+----------------------------+ + | :class:`c_longdouble`| ``long double`` | float | + +----------------------+--------------------------------+----------------------------+ | :class:`c_char_p` | ``char *`` (NUL terminated) | string or ``None`` | +----------------------+--------------------------------+----------------------------+ | :class:`c_wchar_p` | ``wchar_t *`` (NUL terminated) | unicode or ``None`` | @@ -2065,9 +2067,16 @@ initializer. +.. class:: c_longdouble + + Represents the C long double datatype. The constructor accepts an + optional float initializer. On platforms where ``sizeof(long + double) == sizeof(double)`` it is an alias to :class:`c_double`. + + .. class:: c_float - Represents the C double datatype. The constructor accepts an optional float + Represents the C float datatype. The constructor accepts an optional float initializer. Modified: python/branches/py3k/Doc/library/mutex.rst ============================================================================== --- python/branches/py3k/Doc/library/mutex.rst (original) +++ python/branches/py3k/Doc/library/mutex.rst Sat Sep 8 19:39:28 2007 @@ -8,8 +8,9 @@ The :mod:`mutex` module defines a class that allows mutual-exclusion via -acquiring and releasing locks. It does not require (or imply) threading or -multi-tasking, though it could be useful for those purposes. +acquiring and releasing locks. It does not require (or imply) +:mod:`threading` or multi-tasking, though it could be useful for those +purposes. The :mod:`mutex` module defines the following class: Modified: python/branches/py3k/Doc/library/queue.rst ============================================================================== --- python/branches/py3k/Doc/library/queue.rst (original) +++ python/branches/py3k/Doc/library/queue.rst Sat Sep 8 19:39:28 2007 @@ -7,10 +7,11 @@ The :mod:`Queue` module implements a multi-producer, multi-consumer FIFO queue. -It is especially useful in threads programming when information must be +It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The :class:`Queue` class in this module implements all the required locking semantics. It depends on the -availability of thread support in Python. +availability of thread support in Python; see the :mod:`threading` +module. The :mod:`Queue` module defines the following class and exception: Modified: python/branches/py3k/Doc/library/re.rst ============================================================================== --- python/branches/py3k/Doc/library/re.rst (original) +++ python/branches/py3k/Doc/library/re.rst Sat Sep 8 19:39:28 2007 @@ -546,6 +546,13 @@ >>> re.split('\W+', 'Words, words, words.', 1) ['Words', 'words, words.'] + Note that *split* will never split a string on an empty pattern match. + For example :: + + >>> re.split('x*', 'foo') + ['foo'] + >>> re.split("(?m)^$", "foo\n\nbar\n") + ['foo\n\nbar\n'] .. function:: findall(pattern, string[, flags]) Modified: python/branches/py3k/Doc/library/readline.rst ============================================================================== --- python/branches/py3k/Doc/library/readline.rst (original) +++ python/branches/py3k/Doc/library/readline.rst Sat Sep 8 19:39:28 2007 @@ -128,6 +128,12 @@ Get the completer function, or ``None`` if no completer function has been set. +.. function:: get_completion_type() + + Get the type of completion being attempted. + + .. versionadded:: 2.6 + .. function:: get_begidx() Get the beginning index of the readline tab-completion scope. @@ -147,6 +153,16 @@ Get the readline word delimiters for tab-completion. +.. function:: set_completion_display_matches_hook([function]) + + Set or remove the completion display function. If *function* is + specified, it will be used as the new completion display function; + if omitted or ``None``, any completion display function already + installed is removed. The completion display function is called as + ``function(substitution, [matches], longest_match_length)`` once + each time matches need to be displayed. + + .. versionadded:: 2.6 .. function:: add_history(line) Modified: python/branches/py3k/Doc/library/smtplib.rst ============================================================================== --- python/branches/py3k/Doc/library/smtplib.rst (original) +++ python/branches/py3k/Doc/library/smtplib.rst Sat Sep 8 19:39:28 2007 @@ -47,7 +47,7 @@ .. class:: LMTP([host[, port[, local_hostname]]]) The LMTP protocol, which is very similar to ESMTP, is heavily based on the - standard SMTP client. It's common to use Unix sockets for LMTP, so our connect() + standard SMTP client. It's common to use Unix sockets for LMTP, so our :meth:`connect` method must support that as well as a regular host:port server. To specify a Unix socket, you must use an absolute path for *host*, starting with a '/'. Modified: python/branches/py3k/Doc/library/socket.rst ============================================================================== --- python/branches/py3k/Doc/library/socket.rst (original) +++ python/branches/py3k/Doc/library/socket.rst Sat Sep 8 19:39:28 2007 @@ -165,7 +165,7 @@ .. function:: create_connection(address[, timeout]) Connects to the *address* received (as usual, a ``(host, port)`` pair), with an - optional timeout for the connection. Specially useful for higher-level + optional timeout for the connection. Especially useful for higher-level protocols, it is not normally used directly from application-level code. Passing the optional *timeout* parameter will set the timeout on the socket instance (if it is not given or ``None``, the global default timeout setting is Modified: python/branches/py3k/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k/Doc/library/ssl.rst (original) +++ python/branches/py3k/Doc/library/ssl.rst Sat Sep 8 19:39:28 2007 @@ -170,6 +170,8 @@ Some "standard" root certificates are available at http://www.thawte.com/roots/ (for Thawte roots) and http://www.verisign.com/support/roots.html (for Verisign roots). +See also :rfc:`4158` for more discussion of the way in which +certification chains can be built. sslsocket Objects @@ -239,23 +241,23 @@ the certificate), ``notBefore`` (the time before which the certificate should not be trusted), and ``notAfter`` (the time after which the certificate should not be trusted) filled in. - The "subject" and "issuer" fields are themselves dictionaries containing the fields given - in the certificate's data structure for each principal:: + The "subject" and "issuer" fields are tuples containing the name-value fields + given in the certificate's data structure for each principal:: - {'issuer': {'commonName': u'somemachine.python.org', - 'countryName': u'US', - 'localityName': u'Wilmington', - 'organizationName': u'Python Software Foundation', - 'organizationalUnitName': u'SSL', - 'stateOrProvinceName': u'Delaware'}, - 'subject': {'commonName': u'somemachine.python.org', - 'countryName': u'US', - 'localityName': u'Wilmington', - 'organizationName': u'Python Software Foundation', - 'organizationalUnitName': u'SSL', - 'stateOrProvinceName': u'Delaware'}, - 'notAfter': 'Sep 4 21:54:26 2007 GMT', - 'notBefore': 'Aug 25 21:54:26 2007 GMT', + {'issuer': (('countryName', u'US'), + ('stateOrProvinceName', u'Delaware'), + ('localityName', u'Wilmington'), + ('organizationName', u'Python Software Foundation'), + ('organizationalUnitName', u'SSL'), + ('commonName', u'somemachine.python.org')), + 'notAfter': 'Feb 16 16:54:50 2013 GMT', + 'notBefore': 'Aug 27 16:54:50 2007 GMT', + 'subject': (('countryName', u'US'), + ('stateOrProvinceName', u'Delaware'), + ('localityName', u'Wilmington'), + ('organizationName', u'Python Software Foundation'), + ('organizationalUnitName', u'SSL'), + ('commonName', u'somemachine.python.org')), 'version': 2} This certificate is said to be *self-signed*, because the subject @@ -311,27 +313,32 @@ # note that closing the sslsocket will also close the underlying socket ssl_sock.close() -As of August 25, 2007, the certificate printed by this program +As of September 4, 2007, the certificate printed by this program looked like this:: - {'issuer': {'commonName': u'VeriSign Class 3 Extended Validation SSL SGC CA', - 'countryName': u'US', - 'organizationName': u'VeriSign, Inc.', - 'organizationalUnitName': u'Terms of use at https://www.verisign.com/rpa (c)06'}, - 'subject': {'1.3.6.1.4.1.311.60.2.1.2': u'Delaware', - '1.3.6.1.4.1.311.60.2.1.3': u'US', - 'commonName': u'www.verisign.com', - 'countryName': u'US', - 'localityName': u'Mountain View', - 'organizationName': u'VeriSign, Inc.', - 'organizationalUnitName': u'Terms of use at www.verisign.com/rpa (c)06', - 'postalCode': u'94043', - 'serialNumber': u'2497886', - 'stateOrProvinceName': u'California', - 'streetAddress': u'487 East Middlefield Road'}, - 'notAfter': 'May 8 23:59:59 2009 GMT', - 'notBefore': 'May 9 00:00:00 2007 GMT', - 'version': 2} + {'issuer': (('countryName', u'US'), + ('organizationName', u'VeriSign, Inc.'), + ('organizationalUnitName', u'VeriSign Trust Network'), + ('organizationalUnitName', + u'Terms of use at https://www.verisign.com/rpa (c)06'), + ('commonName', + u'VeriSign Class 3 Extended Validation SSL SGC CA')), + 'notAfter': 'May 8 23:59:59 2009 GMT', + 'notBefore': 'May 9 00:00:00 2007 GMT', + 'subject': (('serialNumber', u'2497886'), + ('1.3.6.1.4.1.311.60.2.1.3', u'US'), + ('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'), + ('countryName', u'US'), + ('postalCode', u'94043'), + ('stateOrProvinceName', u'California'), + ('localityName', u'Mountain View'), + ('streetAddress', u'487 East Middlefield Road'), + ('organizationName', u'VeriSign, Inc.'), + ('organizationalUnitName', u'Production Security Services'), + ('organizationalUnitName', + u'Terms of use at www.verisign.com/rpa (c)06'), + ('commonName', u'www.verisign.com')), + 'version': 2} Server-side operation ^^^^^^^^^^^^^^^^^^^^^ @@ -383,3 +390,5 @@ `Introducing SSL and Certificates using OpenSSL `_, by Frederick J. Hirsch `Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management`, :rfc:`1422`, by Steve Kent + +`Internet X.509 Public Key Infrastructure Certificate and CRL Profile`, :rfc:`3280`, Housley et. al. Modified: python/branches/py3k/Doc/library/thread.rst ============================================================================== --- python/branches/py3k/Doc/library/thread.rst (original) +++ python/branches/py3k/Doc/library/thread.rst Sat Sep 8 19:39:28 2007 @@ -13,9 +13,11 @@ single: semaphores, binary This module provides low-level primitives for working with multiple threads -(a.k.a. :dfn:`light-weight processes` or :dfn:`tasks`) --- multiple threads of +(also called :dfn:`light-weight processes` or :dfn:`tasks`) --- multiple threads of control sharing their global data space. For synchronization, simple locks -(a.k.a. :dfn:`mutexes` or :dfn:`binary semaphores`) are provided. +(also called :dfn:`mutexes` or :dfn:`binary semaphores`) are provided. +The :mod:`threading` module provides an easier to use and higher-level +threading API built on top of this module. .. index:: single: pthreads Modified: python/branches/py3k/Doc/library/threading.rst ============================================================================== --- python/branches/py3k/Doc/library/threading.rst (original) +++ python/branches/py3k/Doc/library/threading.rst Sat Sep 8 19:39:28 2007 @@ -8,6 +8,7 @@ This module constructs higher-level threading interfaces on top of the lower level :mod:`thread` module. +See also the :mod:`mutex` and :mod:`Queue` modules. The :mod:`dummy_threading` module is provided for situations where :mod:`threading` cannot be used because :mod:`thread` is missing. Modified: python/branches/py3k/Doc/whatsnew/2.6.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/2.6.rst (original) +++ python/branches/py3k/Doc/whatsnew/2.6.rst Sat Sep 8 19:39:28 2007 @@ -73,6 +73,20 @@ Here are all of the changes that Python 2.6 makes to the core Python language. +* The :func:`complex` constructor now accepts strings containing + parenthesized complex numbers, letting ``complex(repr(cmplx))`` + will now round-trip values. For example, ``complex('(3+4j)')`` + now returns the value (3+4j). + + .. % Patch 1491866 + +* The string :meth:`translate` method now accepts ``None`` as the + translation table parameter, which is treated as the identity + transformation. This makes it easier to carry out operations + that only delete characters. (Contributed by Bengt Richter.) + + .. % Patch 1193128 + * An obscure change: when you use the the :func:`locals` function inside a :keyword:`class` statement, the resulting dictionary no longer returns free variables. (Free variables, in this case, are variables referred to in the @@ -124,6 +138,11 @@ (Contributed by Fabian Kreutz.) +* An optional ``timeout`` parameter was added to the + :class:`ftplib.FTP` class constructor as well as the :meth:`connect` + method, specifying a timeout measured in seconds. (Added by Facundo + Batista.) + * The :func:`glob.glob` function can now return Unicode filenames if a Unicode path was used and Unicode filenames are matched within the directory. @@ -157,6 +176,21 @@ .. % Patch #1490190 +* In the :mod:`os.path` module, the :func:`splitext` function + has been changed to not split on leading period characters. + This produces better results when operating on Unix's dot-files. + For example, ``os.path.splitext('.ipython')`` + now returns ``('.ipython', '')`` instead of ``('', '.ipython')``. + + .. % Bug #115886 + + A new function, :func:`relpath(path, start)` returns a relative path + from the ``start`` path, if it's supplied, or from the current + working directory to the destination ``path``. (Contributed by + Richard Barran.) + + .. % Patch 1339796 + * New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags` are wrappers for the corresponding system calls (where they're available). Constants for the flag values are defined in the :mod:`stat` module; some @@ -166,14 +200,41 @@ * The :mod:`rgbimg` module has been removed. -* The :mod:`smtplib` module now supports SMTP over SSL thanks to the addition - of the :class:`SMTP_SSL` class. This class supports an interface identical to - the existing :class:`SMTP` class. (Contributed by Monty Taylor.) +* The :mod:`smtplib` module now supports SMTP over SSL thanks to the + addition of the :class:`SMTP_SSL` class. This class supports an + interface identical to the existing :class:`SMTP` class. Both + class constructors also have an optional ``timeout`` parameter + that specifies a timeout for the initial connection attempt, measured in + seconds. + + An implementation of the LMTP protocol (:rfc:`2033`) was also added to + the module. LMTP is used in place of SMTP when transferring e-mail + between agents that don't manage a mail queue. + + (SMTP over SSL contributed by Monty Taylor; timeout parameter + added by Facundo Batista; LMTP implemented by Leif + Hedstrom.) + + .. % Patch #957003 + +* An optional ``timeout`` parameter was added to the + :class:`telnetlib.Telnet` class constructor, specifying a timeout + measured in seconds. (Added by Facundo Batista.) * The :mod:`test.test_support` module now contains a :func:`EnvironmentVarGuard` context manager that supports temporarily changing environment variables and automatically restores them to their old values. (Contributed by Brett Cannon.) +* The :mod:`timeit` module now accepts callables as well as strings + for the statement being timed and for the setup code. + Two convenience functions were added for creating + :class:`Timer` instances: + ``repeat(stmt, setup, time, repeat, number)`` and + ``timeit(stmt, setup, time, number)`` create an instance and call + the corresponding method. (Contributed by Erik Demaine.) + + .. % Patch #1533909 + .. % ====================================================================== .. % whole new modules get described in \subsections here Modified: python/branches/py3k/Include/pyerrors.h ============================================================================== --- python/branches/py3k/Include/pyerrors.h (original) +++ python/branches/py3k/Include/pyerrors.h Sat Sep 8 19:39:28 2007 @@ -153,6 +153,7 @@ #endif PyAPI_DATA(PyObject *) PyExc_MemoryErrorInst; +PyAPI_DATA(PyObject *) PyExc_RecursionErrorInst; /* Predefined warning categories */ PyAPI_DATA(PyObject *) PyExc_Warning; Modified: python/branches/py3k/Lib/ctypes/__init__.py ============================================================================== --- python/branches/py3k/Lib/ctypes/__init__.py (original) +++ python/branches/py3k/Lib/ctypes/__init__.py Sat Sep 8 19:39:28 2007 @@ -188,6 +188,11 @@ _type_ = "d" _check_size(c_double) +class c_longdouble(_SimpleCData): + _type_ = "D" +if sizeof(c_longdouble) == sizeof(c_double): + c_longdouble = c_double + if _calcsize("l") == _calcsize("q"): # if long and long long have the same size, make c_longlong an alias for c_long c_longlong = c_long Modified: python/branches/py3k/Lib/ctypes/test/test_arrays.py ============================================================================== --- python/branches/py3k/Lib/ctypes/test/test_arrays.py (original) +++ python/branches/py3k/Lib/ctypes/test/test_arrays.py Sat Sep 8 19:39:28 2007 @@ -4,7 +4,7 @@ formats = "bBhHiIlLqQfd" formats = c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint, \ - c_long, c_ulonglong, c_float, c_double + c_long, c_ulonglong, c_float, c_double, c_longdouble class ArrayTestCase(unittest.TestCase): def test_simple(self): Modified: python/branches/py3k/Lib/ctypes/test/test_callbacks.py ============================================================================== --- python/branches/py3k/Lib/ctypes/test/test_callbacks.py (original) +++ python/branches/py3k/Lib/ctypes/test/test_callbacks.py Sat Sep 8 19:39:28 2007 @@ -77,6 +77,10 @@ self.check_type(c_double, 3.14) self.check_type(c_double, -3.14) + def test_longdouble(self): + self.check_type(c_longdouble, 3.14) + self.check_type(c_longdouble, -3.14) + def test_char(self): self.check_type(c_char, b"x") self.check_type(c_char, b"a") Modified: python/branches/py3k/Lib/ctypes/test/test_cfuncs.py ============================================================================== --- python/branches/py3k/Lib/ctypes/test/test_cfuncs.py (original) +++ python/branches/py3k/Lib/ctypes/test/test_cfuncs.py Sat Sep 8 19:39:28 2007 @@ -158,6 +158,18 @@ self.failUnlessEqual(self._dll.tf_bd(0, 42.), 14.) self.failUnlessEqual(self.S(), 42) + def test_longdouble(self): + self._dll.tf_D.restype = c_longdouble + self._dll.tf_D.argtypes = (c_longdouble,) + self.failUnlessEqual(self._dll.tf_D(42.), 14.) + self.failUnlessEqual(self.S(), 42) + + def test_longdouble_plus(self): + self._dll.tf_bD.restype = c_longdouble + self._dll.tf_bD.argtypes = (c_byte, c_longdouble) + self.failUnlessEqual(self._dll.tf_bD(0, 42.), 14.) + self.failUnlessEqual(self.S(), 42) + def test_callwithresult(self): def process_result(result): return result * 2 Modified: python/branches/py3k/Lib/ctypes/test/test_functions.py ============================================================================== --- python/branches/py3k/Lib/ctypes/test/test_functions.py (original) +++ python/branches/py3k/Lib/ctypes/test/test_functions.py Sat Sep 8 19:39:28 2007 @@ -143,6 +143,18 @@ self.failUnlessEqual(result, -21) self.failUnlessEqual(type(result), float) + def test_longdoubleresult(self): + f = dll._testfunc_D_bhilfD + f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_longdouble] + f.restype = c_longdouble + result = f(1, 2, 3, 4, 5.0, 6.0) + self.failUnlessEqual(result, 21) + self.failUnlessEqual(type(result), float) + + result = f(-1, -2, -3, -4, -5.0, -6.0) + self.failUnlessEqual(result, -21) + self.failUnlessEqual(type(result), float) + def test_longlongresult(self): try: c_longlong Modified: python/branches/py3k/Lib/ctypes/test/test_repr.py ============================================================================== --- python/branches/py3k/Lib/ctypes/test/test_repr.py (original) +++ python/branches/py3k/Lib/ctypes/test/test_repr.py Sat Sep 8 19:39:28 2007 @@ -4,7 +4,7 @@ subclasses = [] for base in [c_byte, c_short, c_int, c_long, c_longlong, c_ubyte, c_ushort, c_uint, c_ulong, c_ulonglong, - c_float, c_double, c_bool]: + c_float, c_double, c_longdouble, c_bool]: class X(base): pass subclasses.append(X) Modified: python/branches/py3k/Lib/distutils/dep_util.py ============================================================================== --- python/branches/py3k/Lib/distutils/dep_util.py (original) +++ python/branches/py3k/Lib/distutils/dep_util.py Sat Sep 8 19:39:28 2007 @@ -17,7 +17,8 @@ Raise DistutilsFileError if 'source' does not exist. """ if not os.path.exists(source): - raise DistutilsFileError("file '%s' does not exist" % source) + raise DistutilsFileError("file '%s' does not exist" % + os.path.abspath(source)) if not os.path.exists(target): return 1 Modified: python/branches/py3k/Lib/httplib.py ============================================================================== --- python/branches/py3k/Lib/httplib.py (original) +++ python/branches/py3k/Lib/httplib.py Sat Sep 8 19:39:28 2007 @@ -71,6 +71,7 @@ import mimetools import socket from urlparse import urlsplit +import warnings __all__ = ["HTTPResponse", "HTTPConnection", "HTTPException", "NotConnected", "UnknownProtocol", @@ -988,6 +989,9 @@ def FakeSocket (sock, sslobj): + warnings.warn("FakeSocket is deprecated, and won't be in 3.x. " + + "Use the result of ssl.sslsocket directly instead.", + DeprecationWarning, stacklevel=2) return sslobj __all__.append("HTTPSConnection") Modified: python/branches/py3k/Lib/imaplib.py ============================================================================== --- python/branches/py3k/Lib/imaplib.py (original) +++ python/branches/py3k/Lib/imaplib.py Sat Sep 8 19:39:28 2007 @@ -1165,7 +1165,6 @@ def readline(self): """Read line from remote.""" - # NB: socket.ssl needs a "readline" method, or perhaps a "makefile" method. line = [] while 1: char = self.sslobj.read(1) @@ -1175,7 +1174,6 @@ def send(self, data): """Send data to remote.""" - # NB: socket.ssl needs a "sendall" method to match socket objects. bytes = len(data) while bytes > 0: sent = self.sslobj.write(data) @@ -1201,7 +1199,7 @@ def ssl(self): """Return SSLObject instance used to communicate with the IMAP4 server. - ssl = .socket.ssl() + ssl = ssl.sslsocket(.socket) """ return self.sslobj Modified: python/branches/py3k/Lib/smtplib.py ============================================================================== --- python/branches/py3k/Lib/smtplib.py (original) +++ python/branches/py3k/Lib/smtplib.py Sat Sep 8 19:39:28 2007 @@ -161,7 +161,6 @@ except ImportError: _have_ssl = False else: - class SSLFakeFile: """A fake file like object that really wraps a SSLObject. @@ -722,9 +721,8 @@ def _get_socket(self, host, port, timeout): if self.debuglevel > 0: print('connect:', (host, port), file=stderr) self.sock = socket.create_connection((host, port), timeout) - sslobj = socket.ssl(self.sock, self.keyfile, self.certfile) - self.sock = SSLFakeSocket(self.sock, sslobj) - self.file = SSLFakeFile(sslobj) + self.sock = ssl.sslsocket(self.sock, self.keyfile, self.certfile) + self.file = SSLFakeFile(self.sock) __all__.append("SMTP_SSL") Deleted: /python/branches/py3k/Lib/test/crashers/infinite_rec_1.py ============================================================================== --- /python/branches/py3k/Lib/test/crashers/infinite_rec_1.py Sat Sep 8 19:39:28 2007 +++ (empty file) @@ -1,11 +0,0 @@ - -# http://python.org/sf/1202533 - -import new, operator - -class A: - pass -A.__mul__ = new.instancemethod(operator.mul, None, A) - -if __name__ == '__main__': - A()*2 # segfault: infinite recursion in C Deleted: /python/branches/py3k/Lib/test/crashers/infinite_rec_2.py ============================================================================== --- /python/branches/py3k/Lib/test/crashers/infinite_rec_2.py Sat Sep 8 19:39:28 2007 +++ (empty file) @@ -1,10 +0,0 @@ - -# http://python.org/sf/1202533 - -class A(str): - __get__ = getattr - -if __name__ == '__main__': - a = A('a') - A.a = a - a.a # segfault: infinite recursion in C Modified: python/branches/py3k/Lib/test/test_descr.py ============================================================================== --- python/branches/py3k/Lib/test/test_descr.py (original) +++ python/branches/py3k/Lib/test/test_descr.py Sat Sep 8 19:39:28 2007 @@ -4,6 +4,7 @@ from test.test_support import get_original_stdout from copy import deepcopy import types +import new def veris(a, b): if a is not b: @@ -1834,6 +1835,10 @@ ## unsafecmp(1, 1L) ## unsafecmp(1L, 1) +def recursions(): + if verbose: + print("Testing recursion checks ...") + ## class Letter(str): ## def __new__(cls, letter): ## if letter == 'EPS': @@ -1843,7 +1848,6 @@ ## if not self: ## return 'EPS' ## return self - ## # sys.stdout needs to be the original to trigger the recursion bug ## import sys ## test_stdout = sys.stdout @@ -1857,6 +1861,17 @@ ## raise TestFailed, "expected a RuntimeError for print recursion" ## sys.stdout = test_stdout + # Bug #1202533. + class A(object): + pass + A.__mul__ = new.instancemethod(lambda self, x: self * x, None, A) + try: + A()*2 + except RuntimeError: + pass + else: + raise TestFailed("expected a RuntimeError") + def weakrefs(): if verbose: print("Testing weak references...") import weakref @@ -4153,6 +4168,7 @@ overloading() methods() specials() + recursions() weakrefs() properties() supers() Modified: python/branches/py3k/Lib/test/test_ssl.py ============================================================================== --- python/branches/py3k/Lib/test/test_ssl.py (original) +++ python/branches/py3k/Lib/test/test_ssl.py Sat Sep 8 19:39:28 2007 @@ -137,18 +137,15 @@ cert = c2.getpeercert() if not cert: raise test_support.TestFailed("Can't get peer certificate.") + if test_support.verbose: + sys.stdout.write(pprint.pformat(cert) + '\n') if not cert.has_key('subject'): raise test_support.TestFailed( "No subject field in certificate: %s." % pprint.pformat(cert)) - if not (cert['subject'].has_key('organizationName')): - raise test_support.TestFailed( - "No 'organizationName' field in certificate subject: %s." % - pprint.pformat(cert)) - if (cert['subject']['organizationName'] != - "Python Software Foundation"): + if not ('organizationName', 'Python Software Foundation') in cert['subject']: raise test_support.TestFailed( - "Invalid 'organizationName' field in certificate subject; " + "Missing or invalid 'organizationName' field in certificate subject; " "should be 'Python Software Foundation'."); c2.close() @@ -336,7 +333,7 @@ def test_main(verbose=False): if skip_expected: - raise test_support.TestSkipped("socket module has no ssl support") + raise test_support.TestSkipped("No SSL support") global CERTFILE CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, Modified: python/branches/py3k/Lib/test/test_uuid.py ============================================================================== --- python/branches/py3k/Lib/test/test_uuid.py (original) +++ python/branches/py3k/Lib/test/test_uuid.py Sat Sep 8 19:39:28 2007 @@ -364,6 +364,12 @@ self.assertEqual(node1, node2) def test_uuid1(self): + # uuid1 requires ctypes. + try: + import ctypes + except ImportError: + return + equal = self.assertEqual # Make sure uuid1() generates UUIDs that are actually version 1. @@ -417,6 +423,12 @@ equal(str(u), v) def test_uuid4(self): + # uuid4 requires ctypes. + try: + import ctypes + except ImportError: + return + equal = self.assertEqual # Make sure uuid4() generates UUIDs that are actually version 4. Modified: python/branches/py3k/Makefile.pre.in ============================================================================== --- python/branches/py3k/Makefile.pre.in (original) +++ python/branches/py3k/Makefile.pre.in Sat Sep 8 19:39:28 2007 @@ -61,7 +61,7 @@ # Both CPPFLAGS and LDFLAGS need to contain the shell's value for setup.py to # be able to build extension modules using the directories specified in the # environment variables -CPPFLAGS= -I. -I$(srcdir)/Include @CPPFLAGS@ +CPPFLAGS= -I. -IInclude -I$(srcdir)/Include @CPPFLAGS@ LDFLAGS= @LDFLAGS@ LDLAST= @LDLAST@ SGI_ABI= @SGI_ABI@ @@ -473,6 +473,7 @@ $(GRAMMAR_H) $(GRAMMAR_C): $(PGEN) $(GRAMMAR_INPUT) + -@ mkdir Include -$(PGEN) $(GRAMMAR_INPUT) $(GRAMMAR_H) $(GRAMMAR_C) $(PGEN): $(PGENOBJS) @@ -619,7 +620,11 @@ # Like testall, but with a single pass only +# run an optional script to include some information about the build environment buildbottest: all platform + - at if which pybuildbot.identify >/dev/null 2>&1; then \ + pybuildbot.identify "CC='$(CC)'" "CXX='$(CXX)'"; \ + fi $(TESTPYTHON) $(TESTPROG) $(TESTOPTS) -uall -rw QUICKTESTOPTS= $(TESTOPTS) -x test_thread test_signal test_strftime \ @@ -673,7 +678,8 @@ else true; \ fi (cd $(DESTDIR)$(BINDIR); $(LN) python$(VERSION)$(EXE) $(PYTHON)) - (cd $(DESTDIR)$(BINDIR); $(LN) -sf python$(VERSION)-config python-config) + -rm -f $(DESTDIR)$(BINDIR)/python-config + (cd $(DESTDIR)$(BINDIR); $(LN) -s python$(VERSION)-config python-config) # Install the interpreter with $(VERSION) affixed # This goes into $(exec_prefix) Modified: python/branches/py3k/Misc/ACKS ============================================================================== --- python/branches/py3k/Misc/ACKS (original) +++ python/branches/py3k/Misc/ACKS Sat Sep 8 19:39:28 2007 @@ -80,6 +80,7 @@ Peter Bosch Eric Bouck Thierry Bousch +Sebastian Boving Monty Brandenberg Georg Brandl Terrence Brannon @@ -320,6 +321,7 @@ Tony Ingraldi John Interrante Bob Ippolito +Atsuo Ishimoto Ben Jackson Paul Jackson David Jacobs Modified: python/branches/py3k/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/_ctypes.c (original) +++ python/branches/py3k/Modules/_ctypes/_ctypes.c Sat Sep 8 19:39:28 2007 @@ -1104,7 +1104,7 @@ */ -static char *SIMPLE_TYPE_CHARS = "cbBhHiIlLdfuzZqQPXOvt"; +static char *SIMPLE_TYPE_CHARS = "cbBhHiIlLdfuzZqQPXOvtD"; static PyObject * c_wchar_p_from_param(PyObject *type, PyObject *value) Modified: python/branches/py3k/Modules/_ctypes/_ctypes_test.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/_ctypes_test.c (original) +++ python/branches/py3k/Modules/_ctypes/_ctypes_test.c Sat Sep 8 19:39:28 2007 @@ -12,6 +12,29 @@ /* some functions handy for testing */ +EXPORT(long double)testfunc_Ddd(double a, double b) +{ + long double result = (long double)(a * b); + printf("testfunc_Ddd(%p, %p)\n", &a, &b); + printf("testfunc_Ddd(%g, %g)\n", a, b); + return result; +} + +EXPORT(long double)testfunc_DDD(long double a, long double b) +{ + long double result = a * b; + printf("testfunc_DDD(%p, %p)\n", &a, &b); + printf("testfunc_DDD(%Lg, %Lg)\n", a, b); + return result; +} + +EXPORT(int)testfunc_iii(int a, int b) +{ + int result = a * b; + printf("testfunc_iii(%p, %p)\n", &a, &b); + return result; +} + EXPORT(int)myprintf(char *fmt, ...) { int result; @@ -77,6 +100,14 @@ return (double)(b + h + i + l + f + d); } +EXPORT(long double) _testfunc_D_bhilfD(signed char b, short h, int i, long l, float f, long double d) +{ +/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n", + b, h, i, l, f, d); +*/ + return (long double)(b + h + i + l + f + d); +} + EXPORT(char *) _testfunc_p_p(void *s) { return (char *)s; @@ -391,6 +422,7 @@ EXPORT(unsigned PY_LONG_LONG) tf_Q(unsigned PY_LONG_LONG c) { U; return c/3; } EXPORT(float) tf_f(float c) { S; return c/3; } EXPORT(double) tf_d(double c) { S; return c/3; } +EXPORT(long double) tf_D(long double c) { S; return c/3; } #ifdef MS_WIN32 EXPORT(signed char) __stdcall s_tf_b(signed char c) { S; return c/3; } @@ -405,6 +437,7 @@ EXPORT(unsigned PY_LONG_LONG) __stdcall s_tf_Q(unsigned PY_LONG_LONG c) { U; return c/3; } EXPORT(float) __stdcall s_tf_f(float c) { S; return c/3; } EXPORT(double) __stdcall s_tf_d(double c) { S; return c/3; } +EXPORT(long double) __stdcall s_tf_D(long double c) { S; return c/3; } #endif /*******/ @@ -420,6 +453,7 @@ EXPORT(unsigned PY_LONG_LONG) tf_bQ(signed char x, unsigned PY_LONG_LONG c) { U; return c/3; } EXPORT(float) tf_bf(signed char x, float c) { S; return c/3; } EXPORT(double) tf_bd(signed char x, double c) { S; return c/3; } +EXPORT(long double) tf_bD(signed char x, long double c) { S; return c/3; } EXPORT(void) tv_i(int c) { S; return; } #ifdef MS_WIN32 @@ -435,6 +469,7 @@ EXPORT(unsigned PY_LONG_LONG) __stdcall s_tf_bQ(signed char x, unsigned PY_LONG_LONG c) { U; return c/3; } EXPORT(float) __stdcall s_tf_bf(signed char x, float c) { S; return c/3; } EXPORT(double) __stdcall s_tf_bd(signed char x, double c) { S; return c/3; } +EXPORT(long double) __stdcall s_tf_bD(signed char x, long double c) { S; return c/3; } EXPORT(void) __stdcall s_tv_i(int c) { S; return; } #endif Modified: python/branches/py3k/Modules/_ctypes/callproc.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/callproc.c (original) +++ python/branches/py3k/Modules/_ctypes/callproc.c Sat Sep 8 19:39:28 2007 @@ -444,6 +444,7 @@ #ifdef HAVE_LONG_LONG PY_LONG_LONG q; #endif + long double D; double d; float f; void *p; Modified: python/branches/py3k/Modules/_ctypes/cfield.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/cfield.c (original) +++ python/branches/py3k/Modules/_ctypes/cfield.c Sat Sep 8 19:39:28 2007 @@ -977,6 +977,29 @@ */ +static PyObject * +D_set(void *ptr, PyObject *value, Py_ssize_t size) +{ + long double x; + + x = PyFloat_AsDouble(value); + if (x == -1 && PyErr_Occurred()) { + PyErr_Format(PyExc_TypeError, + " float expected instead of %s instance", + value->ob_type->tp_name); + return NULL; + } + memcpy(ptr, &x, sizeof(long double)); + _RET(value); +} + +static PyObject * +D_get(void *ptr, Py_ssize_t size) +{ + long double val; + memcpy(&val, ptr, sizeof(long double)); + return PyFloat_FromDouble(val); +} static PyObject * d_set(void *ptr, PyObject *value, Py_ssize_t size) @@ -1591,6 +1614,7 @@ { 'B', B_set, B_get, &ffi_type_uchar}, { 'c', c_set, c_get, &ffi_type_schar}, { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw}, + { 'D', D_set, D_get, &ffi_type_longdouble}, { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw}, { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw}, { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw}, @@ -1673,6 +1697,7 @@ typedef struct { char c; long x; } s_long; typedef struct { char c; float x; } s_float; typedef struct { char c; double x; } s_double; +typedef struct { char c; long double x; } s_long_double; typedef struct { char c; char *x; } s_char_p; typedef struct { char c; void *x; } s_void_p; @@ -1684,6 +1709,8 @@ */ #define FLOAT_ALIGN (sizeof(s_float) - sizeof(float)) #define DOUBLE_ALIGN (sizeof(s_double) - sizeof(double)) +#define LONGDOUBLE_ALIGN (sizeof(s_long_double) - sizeof(long double)) + /* #define CHAR_P_ALIGN (sizeof(s_char_p) - sizeof(char*)) */ #define VOID_P_ALIGN (sizeof(s_void_p) - sizeof(void*)) @@ -1729,6 +1756,8 @@ ffi_type ffi_type_float = { sizeof(float), FLOAT_ALIGN, FFI_TYPE_FLOAT }; ffi_type ffi_type_double = { sizeof(double), DOUBLE_ALIGN, FFI_TYPE_DOUBLE }; +ffi_type ffi_type_longdouble = { sizeof(long double), LONGDOUBLE_ALIGN, + FFI_TYPE_LONGDOUBLE }; /* ffi_type ffi_type_longdouble */ Modified: python/branches/py3k/Modules/_ctypes/ctypes.h ============================================================================== --- python/branches/py3k/Modules/_ctypes/ctypes.h (original) +++ python/branches/py3k/Modules/_ctypes/ctypes.h Sat Sep 8 19:39:28 2007 @@ -30,6 +30,7 @@ #ifdef HAVE_LONG_LONG PY_LONG_LONG ll; #endif + long double D; }; /* @@ -283,6 +284,7 @@ #ifdef HAVE_LONG_LONG PY_LONG_LONG q; #endif + long double D; double d; float f; void *p; Modified: python/branches/py3k/Modules/_ctypes/libffi/configure ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi/configure (original) +++ python/branches/py3k/Modules/_ctypes/libffi/configure Sat Sep 8 19:39:28 2007 @@ -3533,7 +3533,7 @@ sh-*-linux* | sh[34]*-*-linux*) TARGET=SH; TARGETDIR=sh;; sh-*-rtems*) TARGET=SH; TARGETDIR=sh;; sh64-*-linux* | sh5*-*-linux*) TARGET=SH64; TARGETDIR=sh64;; -hppa-*-linux* | parisc-*-linux*) TARGET=PA; TARGETDIR=pa;; +hppa*-*-linux* | parisc*-*-linux*) TARGET=PA; TARGETDIR=pa;; esac if test $TARGETDIR = unknown; then Modified: python/branches/py3k/Modules/_ctypes/libffi/configure.ac ============================================================================== --- python/branches/py3k/Modules/_ctypes/libffi/configure.ac (original) +++ python/branches/py3k/Modules/_ctypes/libffi/configure.ac Sat Sep 8 19:39:28 2007 @@ -71,7 +71,7 @@ sh-*-linux* | sh[[34]]*-*-linux*) TARGET=SH; TARGETDIR=sh;; sh-*-rtems*) TARGET=SH; TARGETDIR=sh;; sh64-*-linux* | sh5*-*-linux*) TARGET=SH64; TARGETDIR=sh64;; -hppa-*-linux* | parisc-*-linux*) TARGET=PA; TARGETDIR=pa;; +hppa*-*-linux* | parisc*-*-linux*) TARGET=PA; TARGETDIR=pa;; esac if test $TARGETDIR = unknown; then Modified: python/branches/py3k/Modules/_lsprof.c ============================================================================== --- python/branches/py3k/Modules/_lsprof.c (original) +++ python/branches/py3k/Modules/_lsprof.c Sat Sep 8 19:39:28 2007 @@ -372,11 +372,20 @@ ProfilerEntry *profEntry; ProfilerContext *pContext; + /* In the case of entering a generator expression frame via a + * throw (gen_send_ex(.., 1)), we may already have an + * Exception set here. We must not mess around with this + * exception, and some of the code under here assumes that + * PyErr_* is its own to mess around with, so we have to + * save and restore any current exception. */ + PyObject *last_type, *last_value, *last_tb; + PyErr_Fetch(&last_type, &last_value, &last_tb); + profEntry = getEntry(pObj, key); if (profEntry == NULL) { profEntry = newProfilerEntry(pObj, key, userObj); if (profEntry == NULL) - return; + goto restorePyerr; } /* grab a ProfilerContext out of the free list */ pContext = pObj->freelistProfilerContext; @@ -389,10 +398,13 @@ malloc(sizeof(ProfilerContext)); if (pContext == NULL) { pObj->flags |= POF_NOMEMORY; - return; + goto restorePyerr; } } initContext(pObj, pContext, profEntry); + +restorePyerr: + PyErr_Restore(last_type, last_value, last_tb); } static void Modified: python/branches/py3k/Modules/_ssl.c ============================================================================== --- python/branches/py3k/Modules/_ssl.c (original) +++ python/branches/py3k/Modules/_ssl.c Sat Sep 8 19:39:28 2007 @@ -437,12 +437,15 @@ } static PyObject * -_create_dict_for_X509_NAME (X509_NAME *xname) +_create_tuple_for_X509_NAME (X509_NAME *xname) { - PyObject *pd = PyDict_New(); + PyObject *pt = NULL; + PyObject *entry_tuple = NULL; + int entry_count = X509_NAME_entry_count(xname); int index_counter; - if (pd == NULL) + pt = PyTuple_New(entry_count); + if (pt == NULL) return NULL; for (index_counter = 0; @@ -480,18 +483,20 @@ Py_DECREF(name_obj); goto fail0; } - if (PyDict_SetItem(pd, name_obj, value_obj) < 0) { + entry_tuple = PyTuple_New(2); + if (entry_tuple == NULL) { Py_DECREF(name_obj); Py_DECREF(value_obj); goto fail0; } - Py_DECREF(name_obj); - Py_DECREF(value_obj); + PyTuple_SET_ITEM(entry_tuple, 0, name_obj); + PyTuple_SET_ITEM(entry_tuple, 1, value_obj); + PyTuple_SET_ITEM(pt, index_counter, entry_tuple); } - return pd; + return pt; fail0: - Py_XDECREF(pd); + Py_XDECREF(pt); return NULL; } @@ -520,7 +525,7 @@ if ((verification & SSL_VERIFY_PEER) == 0) return retval; - peer = _create_dict_for_X509_NAME( + peer = _create_tuple_for_X509_NAME( X509_get_subject_name(self->peer_cert)); if (peer == NULL) goto fail0; @@ -530,7 +535,7 @@ } Py_DECREF(peer); - issuer = _create_dict_for_X509_NAME( + issuer = _create_tuple_for_X509_NAME( X509_get_issuer_name(self->peer_cert)); if (issuer == NULL) goto fail0; Modified: python/branches/py3k/Modules/makesetup ============================================================================== --- python/branches/py3k/Modules/makesetup (original) +++ python/branches/py3k/Modules/makesetup Sat Sep 8 19:39:28 2007 @@ -238,7 +238,7 @@ no) SHAREDMODS="$SHAREDMODS $file";; esac rule="$file: $objs" - rule="$rule; \$(LDSHARED) $objs $libs $ExtraLibs -o $file" + rule="$rule; \$(BLDSHARED) $objs $libs $ExtraLibs -o $file" echo "$rule" >>$rulesf done done Modified: python/branches/py3k/Modules/posixmodule.c ============================================================================== --- python/branches/py3k/Modules/posixmodule.c (original) +++ python/branches/py3k/Modules/posixmodule.c Sat Sep 8 19:39:28 2007 @@ -6540,6 +6540,8 @@ BYTE *pbBuffer ); static CRYPTGENRANDOM pCryptGenRandom = NULL; +/* This handle is never explicitly released. Instead, the operating + system will release it when the process terminates. */ static HCRYPTPROV hCryptProv = 0; static PyObject* Modified: python/branches/py3k/Modules/readline.c ============================================================================== --- python/branches/py3k/Modules/readline.c (original) +++ python/branches/py3k/Modules/readline.c Sat Sep 8 19:39:28 2007 @@ -198,6 +198,7 @@ /* Exported functions to specify hook functions in Python */ +static PyObject *completion_display_matches_hook = NULL; static PyObject *startup_hook = NULL; #ifdef HAVE_RL_PRE_INPUT_HOOK @@ -205,6 +206,20 @@ #endif static PyObject * +set_completion_display_matches_hook(PyObject *self, PyObject *args) +{ + return set_hook("completion_display_matches_hook", + &completion_display_matches_hook, args); +} + +PyDoc_STRVAR(doc_set_completion_display_matches_hook, +"set_completion_display_matches_hook([function]) -> None\n\ +Set or remove the completion display function.\n\ +The function is called as\n\ + function(substitution, [matches], longest_match_length)\n\ +once each time matches need to be displayed."); + +static PyObject * set_startup_hook(PyObject *self, PyObject *args) { return set_hook("startup_hook", &startup_hook, args); @@ -245,6 +260,18 @@ static PyObject *endidx = NULL; +/* Get the completion type for the scope of the tab-completion */ +static PyObject * +get_completion_type(PyObject *self, PyObject *noarg) +{ + return PyInt_FromLong(rl_completion_type); +} + +PyDoc_STRVAR(doc_get_completion_type, +"get_completion_type() -> int\n\ +Get the type of completion being attempted."); + + /* Get the beginning index for the scope of the tab-completion */ static PyObject * @@ -557,6 +584,8 @@ METH_NOARGS, get_history_length_doc}, {"set_completer", set_completer, METH_VARARGS, doc_set_completer}, {"get_completer", get_completer, METH_NOARGS, doc_get_completer}, + {"get_completion_type", get_completion_type, + METH_NOARGS, doc_get_completion_type}, {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx}, {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx}, @@ -568,6 +597,8 @@ {"get_completer_delims", get_completer_delims, METH_NOARGS, doc_get_completer_delims}, + {"set_completion_display_matches_hook", set_completion_display_matches_hook, + METH_VARARGS, doc_set_completion_display_matches_hook}, {"set_startup_hook", set_startup_hook, METH_VARARGS, doc_set_startup_hook}, #ifdef HAVE_RL_PRE_INPUT_HOOK @@ -631,6 +662,48 @@ #endif +/* C function to call the Python completion_display_matches */ + +static void +on_completion_display_matches_hook(char **matches, + int num_matches, int max_length) +{ + if (completion_display_matches_hook != NULL) { + int i; + PyObject *m, *s; + PyObject *r; +#ifdef WITH_THREAD + PyGILState_STATE gilstate = PyGILState_Ensure(); +#endif + m = PyList_New(num_matches); + for (i = 0; i < num_matches; i++) { + s = PyString_FromString(matches[i+1]); + PyList_SetItem(m, i, s); + } + + r = PyObject_CallFunction(completion_display_matches_hook, + "sOi", matches[0], m, max_length); + + Py_DECREF(m); + + if (r == NULL || + (r != Py_None && PyInt_AsLong(r) == -1 && PyErr_Occurred())) { + goto error; + } + + Py_DECREF(r); + goto done; + error: + PyErr_Clear(); + Py_XDECREF(r); + done: +#ifdef WITH_THREAD + PyGILState_Release(gilstate); +#endif + } +} + + /* C function to call the Python completer. */ static char * @@ -708,6 +781,10 @@ rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap); rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap); /* Set our hook functions */ +#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK + rl_completion_display_matches_hook = + (rl_compdisp_func_t *)on_completion_display_matches_hook; +#endif rl_startup_hook = (Function *)on_startup_hook; #ifdef HAVE_RL_PRE_INPUT_HOOK rl_pre_input_hook = (Function *)on_pre_input_hook; Modified: python/branches/py3k/Objects/abstract.c ============================================================================== --- python/branches/py3k/Objects/abstract.c (original) +++ python/branches/py3k/Objects/abstract.c Sat Sep 8 19:39:28 2007 @@ -2047,7 +2047,11 @@ ternaryfunc call; if ((call = func->ob_type->tp_call) != NULL) { - PyObject *result = (*call)(func, arg, kw); + PyObject *result; + if (Py_EnterRecursiveCall(" while calling a Python object")) + return NULL; + result = (*call)(func, arg, kw); + Py_LeaveRecursiveCall(); if (result == NULL && !PyErr_Occurred()) PyErr_SetString( PyExc_SystemError, Modified: python/branches/py3k/Objects/exceptions.c ============================================================================== --- python/branches/py3k/Objects/exceptions.c (original) +++ python/branches/py3k/Objects/exceptions.c Sat Sep 8 19:39:28 2007 @@ -1715,6 +1715,12 @@ */ PyObject *PyExc_MemoryErrorInst=NULL; +/* Pre-computed RuntimeError instance for when recursion depth is reached. + Meant to be used when normalizing the exception for exceeding the recursion + depth will cause its own infinite recursion. +*/ +PyObject *PyExc_RecursionErrorInst = NULL; + #define PRE_INIT(TYPE) if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \ Py_FatalError("exceptions bootstrapping error."); @@ -1867,6 +1873,29 @@ if (!PyExc_MemoryErrorInst) Py_FatalError("Cannot pre-allocate MemoryError instance\n"); + PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL); + if (!PyExc_RecursionErrorInst) + Py_FatalError("Cannot pre-allocate RuntimeError instance for " + "recursion errors"); + else { + PyBaseExceptionObject *err_inst = + (PyBaseExceptionObject *)PyExc_RecursionErrorInst; + PyObject *args_tuple; + PyObject *exc_message; + exc_message = PyString_FromString("maximum recursion depth exceeded"); + if (!exc_message) + Py_FatalError("cannot allocate argument for RuntimeError " + "pre-allocation"); + args_tuple = PyTuple_Pack(1, exc_message); + if (!args_tuple) + Py_FatalError("cannot allocate tuple for RuntimeError " + "pre-allocation"); + Py_DECREF(exc_message); + if (BaseException_init(err_inst, args_tuple, NULL)) + Py_FatalError("init of pre-allocated RuntimeError failed"); + Py_DECREF(args_tuple); + } + Py_DECREF(bltinmod); #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__) Modified: python/branches/py3k/Objects/typeobject.c ============================================================================== --- python/branches/py3k/Objects/typeobject.c (original) +++ python/branches/py3k/Objects/typeobject.c Sat Sep 8 19:39:28 2007 @@ -4647,16 +4647,7 @@ if (meth == NULL) return NULL; - /* PyObject_Call() will end up calling slot_tp_call() again if - the object returned for __call__ has __call__ itself defined - upon it. This can be an infinite recursion if you set - __call__ in a class to an instance of it. */ - if (Py_EnterRecursiveCall(" in __call__")) { - Py_DECREF(meth); - return NULL; - } res = PyObject_Call(meth, args, kwds); - Py_LeaveRecursiveCall(); Py_DECREF(meth); return res; Modified: python/branches/py3k/PCbuild8/readme.txt ============================================================================== --- python/branches/py3k/PCbuild8/readme.txt (original) +++ python/branches/py3k/PCbuild8/readme.txt Sat Sep 8 19:39:28 2007 @@ -90,6 +90,13 @@ large tables of Unicode data winsound play sounds (typically .wav files) under Windows + +Note: Check the dependencies of subprojects when building a subproject. You +need to manually build each of the dependencies, in order, first. A good +example of this is the pythoncore subproject. It is dependent on both the +make_versioninfo and the make_buildinfo subprojects. You can check the build +order by right clicking on the project name, in the solution explorer, and +selecting the project build order item. The following subprojects will generally NOT build out of the box. They wrap code Python doesn't control, and you'll need to download the base Modified: python/branches/py3k/Parser/parsetok.c ============================================================================== --- python/branches/py3k/Parser/parsetok.c (original) +++ python/branches/py3k/Parser/parsetok.c Sat Sep 8 19:39:28 2007 @@ -213,16 +213,24 @@ err_ret->error = E_EOF; err_ret->lineno = tok->lineno; if (tok->buf != NULL) { + char *text = NULL; size_t len; assert(tok->cur - tok->buf < INT_MAX); err_ret->offset = (int)(tok->cur - tok->buf); len = tok->inp - tok->buf; - err_ret->text = (char *) PyObject_MALLOC(len + 1); - if (err_ret->text != NULL) { - if (len > 0) - strncpy(err_ret->text, tok->buf, len); - err_ret->text[len] = '\0'; +#ifdef Py_USING_UNICODE + text = PyTokenizer_RestoreEncoding(tok, len, &err_ret->offset); + +#endif + if (text == NULL) { + text = (char *) PyObject_MALLOC(len + 1); + if (text != NULL) { + if (len > 0) + strncpy(text, tok->buf, len); + text[len] = '\0'; + } } + err_ret->text = text; } } else if (tok->encoding != NULL) { node* r = PyNode_New(encoding_decl); Modified: python/branches/py3k/Parser/tokenizer.c ============================================================================== --- python/branches/py3k/Parser/tokenizer.c (original) +++ python/branches/py3k/Parser/tokenizer.c Sat Sep 8 19:39:28 2007 @@ -1536,6 +1536,68 @@ return result; } +/* This function is only called from parsetok. However, it cannot live + there, as it must be empty for PGEN, and we can check for PGEN only + in this file. */ + +#ifdef PGEN +char* +PyTokenizer_RestoreEncoding(struct tok_state* tok, int len, int* offset) +{ + return NULL; +} +#else +static PyObject * +dec_utf8(const char *enc, const char *text, size_t len) { + PyObject *ret = NULL; + PyObject *unicode_text = PyUnicode_DecodeUTF8(text, len, "replace"); + if (unicode_text) { + ret = PyUnicode_AsEncodedString(unicode_text, enc, "replace"); + Py_DECREF(unicode_text); + } + if (!ret) { + PyErr_Print(); + } + return ret; +} + +char * +PyTokenizer_RestoreEncoding(struct tok_state* tok, int len, int *offset) +{ + char *text = NULL; + if (tok->encoding) { + /* convert source to original encondig */ + PyObject *lineobj = dec_utf8(tok->encoding, tok->buf, len); + if (lineobj != NULL) { + int linelen = PyString_Size(lineobj); + const char *line = PyString_AsString(lineobj); + text = PyObject_MALLOC(linelen + 1); + if (text != NULL && line != NULL) { + if (linelen) + strncpy(text, line, linelen); + text[linelen] = '\0'; + } + Py_DECREF(lineobj); + + /* adjust error offset */ + if (*offset > 1) { + PyObject *offsetobj = dec_utf8(tok->encoding, + tok->buf, *offset-1); + if (offsetobj) { + *offset = PyString_Size(offsetobj) + 1; + Py_DECREF(offsetobj); + } + } + + } + } + return text; + +} +#endif + + + #ifdef Py_DEBUG void Modified: python/branches/py3k/Parser/tokenizer.h ============================================================================== --- python/branches/py3k/Parser/tokenizer.h (original) +++ python/branches/py3k/Parser/tokenizer.h Sat Sep 8 19:39:28 2007 @@ -59,6 +59,8 @@ char *, char *); extern void PyTokenizer_Free(struct tok_state *); extern int PyTokenizer_Get(struct tok_state *, char **, char **); +extern char * PyTokenizer_RestoreEncoding(struct tok_state* tok, + int len, int *offset); #ifdef __cplusplus } Modified: python/branches/py3k/Python/errors.c ============================================================================== --- python/branches/py3k/Python/errors.c (original) +++ python/branches/py3k/Python/errors.c Sat Sep 8 19:39:28 2007 @@ -139,6 +139,7 @@ PyObject *value = *val; PyObject *inclass = NULL; PyObject *initial_tb = NULL; + PyThreadState *tstate = NULL; if (type == NULL) { /* There was no exception, so nothing to do. */ @@ -214,7 +215,14 @@ Py_DECREF(initial_tb); } /* normalize recursively */ + tstate = PyThreadState_GET(); + if (++tstate->recursion_depth > Py_GetRecursionLimit()) { + --tstate->recursion_depth; + PyErr_SetObject(PyExc_RuntimeError, PyExc_RecursionErrorInst); + return; + } PyErr_NormalizeException(exc, val, tb); + --tstate->recursion_depth; } Modified: python/branches/py3k/configure ============================================================================== --- python/branches/py3k/configure (original) +++ python/branches/py3k/configure Sat Sep 8 19:39:28 2007 @@ -12002,6 +12002,14 @@ cur_target=10.3 fi CONFIGURE_MACOSX_DEPLOYMENT_TARGET=${MACOSX_DEPLOYMENT_TARGET-${cur_target}} + + # Make sure that MACOSX_DEPLOYMENT_TARGET is set in the + # environment with a value that is the same as what we'll use + # in the Makefile to ensure that we'll get the same compiler + # environment during configure and build time. + MACOSX_DEPLOYMENT_TARGET="$CONFIGURE_MACOSX_DEPLOYMENT_TARGET" + export MACOSX_DEPLOYMENT_TARGET + EXPORT_MACOSX_DEPLOYMENT_TARGET='' if test ${MACOSX_DEPLOYMENT_TARGET-${cur_target}} '>' 10.2 then @@ -21442,6 +21450,77 @@ fi +# also in 4.0 +{ echo "$as_me:$LINENO: checking for rl_completion_display_matches_hook in -lreadline" >&5 +echo $ECHO_N "checking for rl_completion_display_matches_hook in -lreadline... $ECHO_C" >&6; } +if test "${ac_cv_lib_readline_rl_completion_display_matches_hook+set}" = set; then + echo $ECHO_N "(cached) $ECHO_C" >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lreadline $LIBS" +cat >conftest.$ac_ext <<_ACEOF +/* confdefs.h. */ +_ACEOF +cat confdefs.h >>conftest.$ac_ext +cat >>conftest.$ac_ext <<_ACEOF +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char rl_completion_display_matches_hook (); +int +main () +{ +return rl_completion_display_matches_hook (); + ; + return 0; +} +_ACEOF +rm -f conftest.$ac_objext conftest$ac_exeext +if { (ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 + (eval "$ac_link") 2>conftest.er1 + ac_status=$? + grep -v '^ *+' conftest.er1 >conftest.err + rm -f conftest.er1 + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && + $as_test_x conftest$ac_exeext; then + ac_cv_lib_readline_rl_completion_display_matches_hook=yes +else + echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_cv_lib_readline_rl_completion_display_matches_hook=no +fi + +rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ echo "$as_me:$LINENO: result: $ac_cv_lib_readline_rl_completion_display_matches_hook" >&5 +echo "${ECHO_T}$ac_cv_lib_readline_rl_completion_display_matches_hook" >&6; } +if test $ac_cv_lib_readline_rl_completion_display_matches_hook = yes; then + +cat >>confdefs.h <<\_ACEOF +#define HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK 1 +_ACEOF + +fi + + # check for readline 4.2 { echo "$as_me:$LINENO: checking for rl_completion_matches in -lreadline" >&5 echo $ECHO_N "checking for rl_completion_matches in -lreadline... $ECHO_C" >&6; } Modified: python/branches/py3k/configure.in ============================================================================== --- python/branches/py3k/configure.in (original) +++ python/branches/py3k/configure.in Sat Sep 8 19:39:28 2007 @@ -1480,6 +1480,14 @@ cur_target=10.3 fi CONFIGURE_MACOSX_DEPLOYMENT_TARGET=${MACOSX_DEPLOYMENT_TARGET-${cur_target}} + + # Make sure that MACOSX_DEPLOYMENT_TARGET is set in the + # environment with a value that is the same as what we'll use + # in the Makefile to ensure that we'll get the same compiler + # environment during configure and build time. + MACOSX_DEPLOYMENT_TARGET="$CONFIGURE_MACOSX_DEPLOYMENT_TARGET" + export MACOSX_DEPLOYMENT_TARGET + EXPORT_MACOSX_DEPLOYMENT_TARGET='' if test ${MACOSX_DEPLOYMENT_TARGET-${cur_target}} '>' 10.2 then @@ -3087,6 +3095,11 @@ AC_DEFINE(HAVE_RL_PRE_INPUT_HOOK, 1, [Define if you have readline 4.0]), , ) +# also in 4.0 +AC_CHECK_LIB(readline, rl_completion_display_matches_hook, + AC_DEFINE(HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK, 1, + [Define if you have readline 4.0]), , ) + # check for readline 4.2 AC_CHECK_LIB(readline, rl_completion_matches, AC_DEFINE(HAVE_RL_COMPLETION_MATCHES, 1, Modified: python/branches/py3k/pyconfig.h.in ============================================================================== --- python/branches/py3k/pyconfig.h.in (original) +++ python/branches/py3k/pyconfig.h.in Sat Sep 8 19:39:28 2007 @@ -429,6 +429,9 @@ /* Define if you have readline 2.2 */ #undef HAVE_RL_COMPLETION_APPEND_CHARACTER +/* Define if you have readline 4.0 */ +#undef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK + /* Define if you have readline 4.2 */ #undef HAVE_RL_COMPLETION_MATCHES From python-3000-checkins at python.org Sun Sep 9 01:25:43 2007 From: python-3000-checkins at python.org (gregory.p.smith) Date: Sun, 9 Sep 2007 01:25:43 +0200 (CEST) Subject: [Python-3000-checkins] r58058 - python/branches/py3k/Lib/bsddb/test/test_thread.py Message-ID: <20070908232543.7588D1E4007@bag.python.org> Author: gregory.p.smith Date: Sun Sep 9 01:25:43 2007 New Revision: 58058 Modified: python/branches/py3k/Lib/bsddb/test/test_thread.py Log: Cleanup test_thread. CDB (Concurrent Database) support in BerkeleyDB is only intended to have one writer and multiple readers so only run one. Modified: python/branches/py3k/Lib/bsddb/test/test_thread.py ============================================================================== --- python/branches/py3k/Lib/bsddb/test/test_thread.py (original) +++ python/branches/py3k/Lib/bsddb/test/test_thread.py Sun Sep 9 01:25:43 2007 @@ -81,6 +81,9 @@ except db.DBLockDeadlockError: if verbose: print(currentThread().getName(), 'died from', e) + else: + if verbose: + print(currentThread().getName(), "finished.") def readerThread(self, *args, **kwargs): try: @@ -88,7 +91,9 @@ except db.DBLockDeadlockError as e: if verbose: print(currentThread().getName(), 'died from', e) - + else: + if verbose: + print(currentThread().getName(), "finished.") @@ -107,14 +112,14 @@ print('\n', '-=' * 30) print("Running %s.test01_1WriterMultiReaders..." % \ self.__class__.__name__) + print('Using:', self.homeDir, self.filename) threads = [] - for x in range(self.writers): - wt = Thread(target = self.writerThread, - args = (self.d, self.records, x), - name = 'writer %d' % x, - )#verbose = verbose) - threads.append(wt) + wt = Thread(target = self.writerThread, + args = (self.d, self.records), + name = 'the writer', + )#verbose = verbose) + threads.append(wt) for x in range(self.readers): rt = Thread(target = self.readerThread, @@ -128,20 +133,18 @@ for t in threads: t.join() - def _writerThread(self, d, howMany, writerNum): - #time.sleep(0.01 * writerNum + 0.01) + def _writerThread(self, d, howMany): name = currentThread().getName() - start = howMany * writerNum - stop = howMany * (writerNum + 1) - 1 + start = 0 + stop = howMany if verbose: - print("%s: creating records %d - %d" % (name, start, stop)) + print(name+": creating records", start, "-", stop) for x in range(start, stop): key = ('%04d' % x).encode("ascii") - dbutils.DeadlockWrap(d.put, key, self.makeData(key), - max_retries=20) - if verbose and x % 100 == 0: - print("%s: records %d - %d finished" % (name, start, x)) + d.put(key, self.makeData(key)) + if verbose and x > start and x % 50 == 0: + print(name+": records", start, "-", x, "finished") if verbose: print("%s: finished creating records" % name) @@ -157,8 +160,6 @@ ## c.delete() ## c.close() - if verbose: - print("%s: thread finished" % name) def _readerThread(self, d, readerNum): time.sleep(0.01 * readerNum) @@ -174,25 +175,22 @@ self.assertEqual(self.makeData(key), data) rec = c.next() if verbose: - print("%s: found %d records" % (name, count)) + print(name+": found", count, "records") c.close() time.sleep(0.05) - if verbose: - print("%s: thread finished" % name) - class BTreeConcurrentDataStore(ConcurrentDataStoreBase): dbtype = db.DB_BTREE - writers = 2 + writers = 1 readers = 10 records = 1000 class HashConcurrentDataStore(ConcurrentDataStoreBase): dbtype = db.DB_HASH - writers = 2 - readers = 10 + writers = 1 + readers = 0 records = 1000 @@ -373,7 +371,7 @@ finished = True except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: - print("%s: Aborting transaction (%s)" % (name, val[1])) + print("%s: Aborting transaction (%s)" % (name, val)) txn.abort() time.sleep(0.05) @@ -411,7 +409,7 @@ print("%s: deleted records %s" % (name, recs)) except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: - print("%s: Aborting transaction (%s)" % (name, val[1])) + print("%s: Aborting transaction (%s)" % (name, val)) txn.abort() time.sleep(0.05) @@ -441,7 +439,7 @@ finished = True except (db.DBLockDeadlockError, db.DBLockNotGrantedError) as val: if verbose: - print("%s: Aborting transaction (%s)" % (name, val[1])) + print("%s: Aborting transaction (%s)" % (name, val)) c.close() txn.abort() time.sleep(0.05) From python-3000-checkins at python.org Sun Sep 9 08:44:35 2007 From: python-3000-checkins at python.org (gregory.p.smith) Date: Sun, 9 Sep 2007 08:44:35 +0200 (CEST) Subject: [Python-3000-checkins] r58059 - in python/branches/py3k: Lib/hashlib.py Modules/md5module.c Modules/sha1module.c Modules/sha256module.c Modules/sha512module.c setup.py Message-ID: <20070909064435.6DECC1E400F@bag.python.org> Author: gregory.p.smith Date: Sun Sep 9 08:44:34 2007 New Revision: 58059 Added: python/branches/py3k/Modules/md5module.c python/branches/py3k/Modules/sha1module.c Modified: python/branches/py3k/Lib/hashlib.py python/branches/py3k/Modules/sha256module.c python/branches/py3k/Modules/sha512module.c python/branches/py3k/setup.py Log: Adds stand alone _md5 and _sha1 modules for use by hashlib on systems when the OpenSSL library is either not present or not found by setup.py. These are derived from the public domain libtomcrypt (libtom.org) just like the existing sha256 and sha512 modules. Modified: python/branches/py3k/Lib/hashlib.py ============================================================================== --- python/branches/py3k/Lib/hashlib.py (original) +++ python/branches/py3k/Lib/hashlib.py Sun Sep 9 08:44:34 2007 @@ -10,8 +10,8 @@ given hash function; initializing the hash using the given binary data. -Named constructor functions are also available, these are much faster -than using new(): +Named constructor functions are also available, these are faster +than using new(name): md5(), sha1(), sha224(), sha256(), sha384(), and sha512() @@ -22,14 +22,13 @@ sha384 and sha512 will be slow on 32 bit platforms. Hash objects have these methods: - - update(arg): Update the hash object with the string arg. Repeated calls + - update(arg): Update the hash object with the bytes in arg. Repeated calls are equivalent to a single call with the concatenation of all the arguments. - - digest(): Return the digest of the strings passed to the update() method - so far. This may contain non-ASCII characters, including - NUL bytes. - - hexdigest(): Like digest() except the digest is returned as a string of - double length, containing only hexadecimal digits. + - digest(): Return the digest of the bytes passed to the update() method + so far. + - hexdigest(): Like digest() except the digest is returned as a unicode + object of double length, containing only hexadecimal digits. - copy(): Return a copy (clone) of the hash object. This can be used to efficiently compute the digests of strings that share a common initial substring. @@ -54,11 +53,11 @@ def __get_builtin_constructor(name): if name in ('SHA1', 'sha1'): - import _sha - return _sha.new + import _sha1 + return _sha1.sha1 elif name in ('MD5', 'md5'): import _md5 - return _md5.new + return _md5.md5 elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'): import _sha256 bs = name[3:] @@ -78,7 +77,7 @@ def __py_new(name, data=b''): - """new(name, data='') - Return a new hashing object using the named algorithm; + """new(name, data=b'') - Return a new hashing object using the named algorithm; optionally initialized with data (which must be bytes). """ return __get_builtin_constructor(name)(data) Added: python/branches/py3k/Modules/md5module.c ============================================================================== --- (empty file) +++ python/branches/py3k/Modules/md5module.c Sun Sep 9 08:44:34 2007 @@ -0,0 +1,561 @@ +/* MD5 module */ + +/* This module provides an interface to the MD5 algorithm */ + +/* See below for information about the original code this module was + based upon. Additional work performed by: + + Andrew Kuchling (amk at amk.ca) + Greg Stein (gstein at lyra.org) + Trevor Perrin (trevp at trevp.net) + + Copyright (C) 2005-2007 Gregory P. Smith (greg at krypto.org) + Licensed to PSF under a Contributor Agreement. + +*/ + +/* MD5 objects */ + +#include "Python.h" + + +/* Some useful types */ + +#if SIZEOF_INT == 4 +typedef unsigned int MD5_INT32; /* 32-bit integer */ +typedef PY_LONG_LONG MD5_INT64; /* 64-bit integer */ +#else +/* not defined. compilation will die. */ +#endif + +/* The MD5 block size and message digest sizes, in bytes */ + +#define MD5_BLOCKSIZE 64 +#define MD5_DIGESTSIZE 16 + +/* The structure for storing MD5 info */ + +struct md5_state { + MD5_INT64 length; + MD5_INT32 state[4], curlen; + unsigned char buf[MD5_BLOCKSIZE]; +}; + +typedef struct { + PyObject_HEAD + + struct md5_state hash_state; +} MD5object; + + +/* ------------------------------------------------------------------------ + * + * This code for the MD5 algorithm was noted as public domain. The + * original headers are pasted below. + * + * Several changes have been made to make it more compatible with the + * Python environment and desired interface. + * + */ + +/* LibTomCrypt, modular cryptographic library -- Tom St Denis + * + * LibTomCrypt is a library that provides various cryptographic + * algorithms in a highly modular and flexible manner. + * + * The library is free for all purposes without any express + * guarantee it works. + * + * Tom St Denis, tomstdenis at gmail.com, http://libtom.org + */ + +/* rotate the hard way (platform optimizations could be done) */ +#define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL) + +/* Endian Neutral macros that work on all platforms */ + +#define STORE32L(x, y) \ + { (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \ + (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); } + +#define LOAD32L(x, y) \ + { x = ((unsigned long)((y)[3] & 255)<<24) | \ + ((unsigned long)((y)[2] & 255)<<16) | \ + ((unsigned long)((y)[1] & 255)<<8) | \ + ((unsigned long)((y)[0] & 255)); } + +#define STORE64L(x, y) \ + { (y)[7] = (unsigned char)(((x)>>56)&255); (y)[6] = (unsigned char)(((x)>>48)&255); \ + (y)[5] = (unsigned char)(((x)>>40)&255); (y)[4] = (unsigned char)(((x)>>32)&255); \ + (y)[3] = (unsigned char)(((x)>>24)&255); (y)[2] = (unsigned char)(((x)>>16)&255); \ + (y)[1] = (unsigned char)(((x)>>8)&255); (y)[0] = (unsigned char)((x)&255); } + +#ifndef MIN + #define MIN(x, y) ( ((x)<(y))?(x):(y) ) +#endif + + +/* MD5 macros */ + +#define F(x,y,z) (z ^ (x & (y ^ z))) +#define G(x,y,z) (y ^ (z & (y ^ x))) +#define H(x,y,z) (x^y^z) +#define I(x,y,z) (y^(x|(~z))) + +#define FF(a,b,c,d,M,s,t) \ + a = (a + F(b,c,d) + M + t); a = ROLc(a, s) + b; + +#define GG(a,b,c,d,M,s,t) \ + a = (a + G(b,c,d) + M + t); a = ROLc(a, s) + b; + +#define HH(a,b,c,d,M,s,t) \ + a = (a + H(b,c,d) + M + t); a = ROLc(a, s) + b; + +#define II(a,b,c,d,M,s,t) \ + a = (a + I(b,c,d) + M + t); a = ROLc(a, s) + b; + + +static void md5_compress(struct md5_state *md5, unsigned char *buf) +{ + MD5_INT32 i, W[16], a, b, c, d; + + assert(md5 != NULL); + assert(buf != NULL); + + /* copy the state into 512-bits into W[0..15] */ + for (i = 0; i < 16; i++) { + LOAD32L(W[i], buf + (4*i)); + } + + /* copy state */ + a = md5->state[0]; + b = md5->state[1]; + c = md5->state[2]; + d = md5->state[3]; + + FF(a,b,c,d,W[0],7,0xd76aa478UL) + FF(d,a,b,c,W[1],12,0xe8c7b756UL) + FF(c,d,a,b,W[2],17,0x242070dbUL) + FF(b,c,d,a,W[3],22,0xc1bdceeeUL) + FF(a,b,c,d,W[4],7,0xf57c0fafUL) + FF(d,a,b,c,W[5],12,0x4787c62aUL) + FF(c,d,a,b,W[6],17,0xa8304613UL) + FF(b,c,d,a,W[7],22,0xfd469501UL) + FF(a,b,c,d,W[8],7,0x698098d8UL) + FF(d,a,b,c,W[9],12,0x8b44f7afUL) + FF(c,d,a,b,W[10],17,0xffff5bb1UL) + FF(b,c,d,a,W[11],22,0x895cd7beUL) + FF(a,b,c,d,W[12],7,0x6b901122UL) + FF(d,a,b,c,W[13],12,0xfd987193UL) + FF(c,d,a,b,W[14],17,0xa679438eUL) + FF(b,c,d,a,W[15],22,0x49b40821UL) + GG(a,b,c,d,W[1],5,0xf61e2562UL) + GG(d,a,b,c,W[6],9,0xc040b340UL) + GG(c,d,a,b,W[11],14,0x265e5a51UL) + GG(b,c,d,a,W[0],20,0xe9b6c7aaUL) + GG(a,b,c,d,W[5],5,0xd62f105dUL) + GG(d,a,b,c,W[10],9,0x02441453UL) + GG(c,d,a,b,W[15],14,0xd8a1e681UL) + GG(b,c,d,a,W[4],20,0xe7d3fbc8UL) + GG(a,b,c,d,W[9],5,0x21e1cde6UL) + GG(d,a,b,c,W[14],9,0xc33707d6UL) + GG(c,d,a,b,W[3],14,0xf4d50d87UL) + GG(b,c,d,a,W[8],20,0x455a14edUL) + GG(a,b,c,d,W[13],5,0xa9e3e905UL) + GG(d,a,b,c,W[2],9,0xfcefa3f8UL) + GG(c,d,a,b,W[7],14,0x676f02d9UL) + GG(b,c,d,a,W[12],20,0x8d2a4c8aUL) + HH(a,b,c,d,W[5],4,0xfffa3942UL) + HH(d,a,b,c,W[8],11,0x8771f681UL) + HH(c,d,a,b,W[11],16,0x6d9d6122UL) + HH(b,c,d,a,W[14],23,0xfde5380cUL) + HH(a,b,c,d,W[1],4,0xa4beea44UL) + HH(d,a,b,c,W[4],11,0x4bdecfa9UL) + HH(c,d,a,b,W[7],16,0xf6bb4b60UL) + HH(b,c,d,a,W[10],23,0xbebfbc70UL) + HH(a,b,c,d,W[13],4,0x289b7ec6UL) + HH(d,a,b,c,W[0],11,0xeaa127faUL) + HH(c,d,a,b,W[3],16,0xd4ef3085UL) + HH(b,c,d,a,W[6],23,0x04881d05UL) + HH(a,b,c,d,W[9],4,0xd9d4d039UL) + HH(d,a,b,c,W[12],11,0xe6db99e5UL) + HH(c,d,a,b,W[15],16,0x1fa27cf8UL) + HH(b,c,d,a,W[2],23,0xc4ac5665UL) + II(a,b,c,d,W[0],6,0xf4292244UL) + II(d,a,b,c,W[7],10,0x432aff97UL) + II(c,d,a,b,W[14],15,0xab9423a7UL) + II(b,c,d,a,W[5],21,0xfc93a039UL) + II(a,b,c,d,W[12],6,0x655b59c3UL) + II(d,a,b,c,W[3],10,0x8f0ccc92UL) + II(c,d,a,b,W[10],15,0xffeff47dUL) + II(b,c,d,a,W[1],21,0x85845dd1UL) + II(a,b,c,d,W[8],6,0x6fa87e4fUL) + II(d,a,b,c,W[15],10,0xfe2ce6e0UL) + II(c,d,a,b,W[6],15,0xa3014314UL) + II(b,c,d,a,W[13],21,0x4e0811a1UL) + II(a,b,c,d,W[4],6,0xf7537e82UL) + II(d,a,b,c,W[11],10,0xbd3af235UL) + II(c,d,a,b,W[2],15,0x2ad7d2bbUL) + II(b,c,d,a,W[9],21,0xeb86d391UL) + + md5->state[0] = md5->state[0] + a; + md5->state[1] = md5->state[1] + b; + md5->state[2] = md5->state[2] + c; + md5->state[3] = md5->state[3] + d; +} + + +/** + Initialize the hash state + @param sha1 The hash state you wish to initialize +*/ +void md5_init(struct md5_state *md5) +{ + assert(md5 != NULL); + md5->state[0] = 0x67452301UL; + md5->state[1] = 0xefcdab89UL; + md5->state[2] = 0x98badcfeUL; + md5->state[3] = 0x10325476UL; + md5->curlen = 0; + md5->length = 0; +} + +/** + Process a block of memory though the hash + @param sha1 The hash state + @param in The data to hash + @param inlen The length of the data (octets) +*/ +void md5_process(struct md5_state *md5, + const unsigned char *in, unsigned long inlen) +{ + unsigned long n; + + assert(md5 != NULL); + assert(in != NULL); + assert(md5->curlen <= sizeof(md5->buf)); + + while (inlen > 0) { + if (md5->curlen == 0 && inlen >= MD5_BLOCKSIZE) { + md5_compress(md5, (unsigned char *)in); + md5->length += MD5_BLOCKSIZE * 8; + in += MD5_BLOCKSIZE; + inlen -= MD5_BLOCKSIZE; + } else { + n = MIN(inlen, (MD5_BLOCKSIZE - md5->curlen)); + memcpy(md5->buf + md5->curlen, in, (size_t)n); + md5->curlen += n; + in += n; + inlen -= n; + if (md5->curlen == MD5_BLOCKSIZE) { + md5_compress(md5, md5->buf); + md5->length += 8*MD5_BLOCKSIZE; + md5->curlen = 0; + } + } + } +} + +/** + Terminate the hash to get the digest + @param sha1 The hash state + @param out [out] The destination of the hash (16 bytes) +*/ +void md5_done(struct md5_state *md5, unsigned char *out) +{ + int i; + + assert(md5 != NULL); + assert(out != NULL); + assert(md5->curlen < sizeof(md5->buf)); + + /* increase the length of the message */ + md5->length += md5->curlen * 8; + + /* append the '1' bit */ + md5->buf[md5->curlen++] = (unsigned char)0x80; + + /* if the length is currently above 56 bytes we append zeros + * then compress. Then we can fall back to padding zeros and length + * encoding like normal. + */ + if (md5->curlen > 56) { + while (md5->curlen < 64) { + md5->buf[md5->curlen++] = (unsigned char)0; + } + md5_compress(md5, md5->buf); + md5->curlen = 0; + } + + /* pad upto 56 bytes of zeroes */ + while (md5->curlen < 56) { + md5->buf[md5->curlen++] = (unsigned char)0; + } + + /* store length */ + STORE64L(md5->length, md5->buf+56); + md5_compress(md5, md5->buf); + + /* copy output */ + for (i = 0; i < 4; i++) { + STORE32L(md5->state[i], out+(4*i)); + } +} + +/* .Source: /cvs/libtom/libtomcrypt/src/hashes/md5.c,v $ */ +/* .Revision: 1.10 $ */ +/* .Date: 2007/05/12 14:25:28 $ */ + +/* + * End of copied MD5 code. + * + * ------------------------------------------------------------------------ + */ + +static PyTypeObject MD5type; + + +static MD5object * +newMD5object(void) +{ + return (MD5object *)PyObject_New(MD5object, &MD5type); +} + + +/* Internal methods for a hash object */ + +static void +MD5_dealloc(PyObject *ptr) +{ + PyObject_Del(ptr); +} + + +/* External methods for a hash object */ + +PyDoc_STRVAR(MD5_copy__doc__, "Return a copy of the hash object."); + +static PyObject * +MD5_copy(MD5object *self, PyObject *unused) +{ + MD5object *newobj; + + if (Py_Type(self) == &MD5type) { + if ( (newobj = newMD5object())==NULL) + return NULL; + } else { + if ( (newobj = newMD5object())==NULL) + return NULL; + } + + newobj->hash_state = self->hash_state; + return (PyObject *)newobj; +} + +PyDoc_STRVAR(MD5_digest__doc__, +"Return the digest value as a string of binary data."); + +static PyObject * +MD5_digest(MD5object *self, PyObject *unused) +{ + unsigned char digest[MD5_DIGESTSIZE]; + struct md5_state temp; + + temp = self->hash_state; + md5_done(&temp, digest); + return PyBytes_FromStringAndSize((const char *)digest, MD5_DIGESTSIZE); +} + +PyDoc_STRVAR(MD5_hexdigest__doc__, +"Return the digest value as a string of hexadecimal digits."); + +static PyObject * +MD5_hexdigest(MD5object *self, PyObject *unused) +{ + unsigned char digest[MD5_DIGESTSIZE]; + struct md5_state temp; + PyObject *retval; + Py_UNICODE *hex_digest; + int i, j; + + /* Get the raw (binary) digest value */ + temp = self->hash_state; + md5_done(&temp, digest); + + /* Create a new string */ + retval = PyUnicode_FromStringAndSize(NULL, MD5_DIGESTSIZE * 2); + if (!retval) + return NULL; + hex_digest = PyUnicode_AS_UNICODE(retval); + if (!hex_digest) { + Py_DECREF(retval); + return NULL; + } + + /* Make hex version of the digest */ + for(i=j=0; i> 4) & 0xf; + c = (c>9) ? c+'a'-10 : c + '0'; + hex_digest[j++] = c; + c = (digest[i] & 0xf); + c = (c>9) ? c+'a'-10 : c + '0'; + hex_digest[j++] = c; + } + return retval; +} + +PyDoc_STRVAR(MD5_update__doc__, +"Update this hash object's state with the provided string."); + +static PyObject * +MD5_update(MD5object *self, PyObject *args) +{ + unsigned char *cp; + int len; + + if (!PyArg_ParseTuple(args, "s#:update", &cp, &len)) + return NULL; + + md5_process(&self->hash_state, cp, len); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyMethodDef MD5_methods[] = { + {"copy", (PyCFunction)MD5_copy, METH_NOARGS, MD5_copy__doc__}, + {"digest", (PyCFunction)MD5_digest, METH_NOARGS, MD5_digest__doc__}, + {"hexdigest", (PyCFunction)MD5_hexdigest, METH_NOARGS, MD5_hexdigest__doc__}, + {"update", (PyCFunction)MD5_update, METH_VARARGS, MD5_update__doc__}, + {NULL, NULL} /* sentinel */ +}; + +static PyObject * +MD5_get_block_size(PyObject *self, void *closure) +{ + return PyInt_FromLong(MD5_BLOCKSIZE); +} + +static PyObject * +MD5_get_name(PyObject *self, void *closure) +{ + return PyUnicode_FromStringAndSize("MD5", 3); +} + +static PyObject * +md5_get_digest_size(PyObject *self, void *closure) +{ + return PyInt_FromLong(MD5_DIGESTSIZE); +} + + +static PyGetSetDef MD5_getseters[] = { + {"block_size", + (getter)MD5_get_block_size, NULL, + NULL, + NULL}, + {"name", + (getter)MD5_get_name, NULL, + NULL, + NULL}, + {"digest_size", + (getter)md5_get_digest_size, NULL, + NULL, + NULL}, + {NULL} /* Sentinel */ +}; + +static PyTypeObject MD5type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_md5.md5", /*tp_name*/ + sizeof(MD5object), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + MD5_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + MD5_methods, /* tp_methods */ + NULL, /* tp_members */ + MD5_getseters, /* tp_getset */ +}; + + +/* The single module-level function: new() */ + +PyDoc_STRVAR(MD5_new__doc__, +"Return a new MD5 hash object; optionally initialized with a string."); + +static PyObject * +MD5_new(PyObject *self, PyObject *args, PyObject *kwdict) +{ + static char *kwlist[] = {"string", NULL}; + MD5object *new; + unsigned char *cp = NULL; + int len; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|s#:new", kwlist, + &cp, &len)) { + return NULL; + } + + if ((new = newMD5object()) == NULL) + return NULL; + + md5_init(&new->hash_state); + + if (PyErr_Occurred()) { + Py_DECREF(new); + return NULL; + } + if (cp) + md5_process(&new->hash_state, cp, len); + + return (PyObject *)new; +} + + +/* List of functions exported by this module */ + +static struct PyMethodDef MD5_functions[] = { + {"md5", (PyCFunction)MD5_new, METH_VARARGS|METH_KEYWORDS, MD5_new__doc__}, + {NULL, NULL} /* Sentinel */ +}; + + +/* Initialize this module. */ + +#define insint(n,v) { PyModule_AddIntConstant(m,n,v); } + +PyMODINIT_FUNC +init_md5(void) +{ + PyObject *m; + + Py_Type(&MD5type) = &PyType_Type; + if (PyType_Ready(&MD5type) < 0) + return; + m = Py_InitModule("_md5", MD5_functions); + if (m == NULL) + return; +} Added: python/branches/py3k/Modules/sha1module.c ============================================================================== --- (empty file) +++ python/branches/py3k/Modules/sha1module.c Sun Sep 9 08:44:34 2007 @@ -0,0 +1,537 @@ +/* SHA1 module */ + +/* This module provides an interface to the SHA1 algorithm */ + +/* See below for information about the original code this module was + based upon. Additional work performed by: + + Andrew Kuchling (amk at amk.ca) + Greg Stein (gstein at lyra.org) + Trevor Perrin (trevp at trevp.net) + + Copyright (C) 2005-2007 Gregory P. Smith (greg at krypto.org) + Licensed to PSF under a Contributor Agreement. + +*/ + +/* SHA1 objects */ + +#include "Python.h" + + +/* Some useful types */ + +#if SIZEOF_INT == 4 +typedef unsigned int SHA1_INT32; /* 32-bit integer */ +typedef PY_LONG_LONG SHA1_INT64; /* 64-bit integer */ +#else +/* not defined. compilation will die. */ +#endif + +/* The SHA1 block size and message digest sizes, in bytes */ + +#define SHA1_BLOCKSIZE 64 +#define SHA1_DIGESTSIZE 20 + +/* The structure for storing SHA1 info */ + +struct sha1_state { + SHA1_INT64 length; + SHA1_INT32 state[5], curlen; + unsigned char buf[SHA1_BLOCKSIZE]; +}; + +typedef struct { + PyObject_HEAD + + struct sha1_state hash_state; +} SHA1object; + + +/* ------------------------------------------------------------------------ + * + * This code for the SHA1 algorithm was noted as public domain. The + * original headers are pasted below. + * + * Several changes have been made to make it more compatible with the + * Python environment and desired interface. + * + */ + +/* LibTomCrypt, modular cryptographic library -- Tom St Denis + * + * LibTomCrypt is a library that provides various cryptographic + * algorithms in a highly modular and flexible manner. + * + * The library is free for all purposes without any express + * guarantee it works. + * + * Tom St Denis, tomstdenis at gmail.com, http://libtom.org + */ + +/* rotate the hard way (platform optimizations could be done) */ +#define ROL(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL) +#define ROLc(x, y) ( (((unsigned long)(x)<<(unsigned long)((y)&31)) | (((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL) + +/* Endian Neutral macros that work on all platforms */ + +#define STORE32H(x, y) \ + { (y)[0] = (unsigned char)(((x)>>24)&255); (y)[1] = (unsigned char)(((x)>>16)&255); \ + (y)[2] = (unsigned char)(((x)>>8)&255); (y)[3] = (unsigned char)((x)&255); } + +#define LOAD32H(x, y) \ + { x = ((unsigned long)((y)[0] & 255)<<24) | \ + ((unsigned long)((y)[1] & 255)<<16) | \ + ((unsigned long)((y)[2] & 255)<<8) | \ + ((unsigned long)((y)[3] & 255)); } + +#define STORE64H(x, y) \ + { (y)[0] = (unsigned char)(((x)>>56)&255); (y)[1] = (unsigned char)(((x)>>48)&255); \ + (y)[2] = (unsigned char)(((x)>>40)&255); (y)[3] = (unsigned char)(((x)>>32)&255); \ + (y)[4] = (unsigned char)(((x)>>24)&255); (y)[5] = (unsigned char)(((x)>>16)&255); \ + (y)[6] = (unsigned char)(((x)>>8)&255); (y)[7] = (unsigned char)((x)&255); } + +#ifndef MIN + #define MIN(x, y) ( ((x)<(y))?(x):(y) ) +#endif + + +/* SHA1 macros */ + +#define F0(x,y,z) (z ^ (x & (y ^ z))) +#define F1(x,y,z) (x ^ y ^ z) +#define F2(x,y,z) ((x & y) | (z & (x | y))) +#define F3(x,y,z) (x ^ y ^ z) + +static void sha1_compress(struct sha1_state *sha1, unsigned char *buf) +{ + SHA1_INT32 a,b,c,d,e,W[80],i; + + /* copy the state into 512-bits into W[0..15] */ + for (i = 0; i < 16; i++) { + LOAD32H(W[i], buf + (4*i)); + } + + /* copy state */ + a = sha1->state[0]; + b = sha1->state[1]; + c = sha1->state[2]; + d = sha1->state[3]; + e = sha1->state[4]; + + /* expand it */ + for (i = 16; i < 80; i++) { + W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1); + } + + /* compress */ + /* round one */ + #define FF0(a,b,c,d,e,i) e = (ROLc(a, 5) + F0(b,c,d) + e + W[i] + 0x5a827999UL); b = ROLc(b, 30); + #define FF1(a,b,c,d,e,i) e = (ROLc(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROLc(b, 30); + #define FF2(a,b,c,d,e,i) e = (ROLc(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROLc(b, 30); + #define FF3(a,b,c,d,e,i) e = (ROLc(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROLc(b, 30); + + for (i = 0; i < 20; ) { + FF0(a,b,c,d,e,i++); + FF0(e,a,b,c,d,i++); + FF0(d,e,a,b,c,i++); + FF0(c,d,e,a,b,i++); + FF0(b,c,d,e,a,i++); + } + + /* round two */ + for (; i < 40; ) { + FF1(a,b,c,d,e,i++); + FF1(e,a,b,c,d,i++); + FF1(d,e,a,b,c,i++); + FF1(c,d,e,a,b,i++); + FF1(b,c,d,e,a,i++); + } + + /* round three */ + for (; i < 60; ) { + FF2(a,b,c,d,e,i++); + FF2(e,a,b,c,d,i++); + FF2(d,e,a,b,c,i++); + FF2(c,d,e,a,b,i++); + FF2(b,c,d,e,a,i++); + } + + /* round four */ + for (; i < 80; ) { + FF3(a,b,c,d,e,i++); + FF3(e,a,b,c,d,i++); + FF3(d,e,a,b,c,i++); + FF3(c,d,e,a,b,i++); + FF3(b,c,d,e,a,i++); + } + + #undef FF0 + #undef FF1 + #undef FF2 + #undef FF3 + + /* store */ + sha1->state[0] = sha1->state[0] + a; + sha1->state[1] = sha1->state[1] + b; + sha1->state[2] = sha1->state[2] + c; + sha1->state[3] = sha1->state[3] + d; + sha1->state[4] = sha1->state[4] + e; +} + +/** + Initialize the hash state + @param sha1 The hash state you wish to initialize +*/ +void sha1_init(struct sha1_state *sha1) +{ + assert(sha1 != NULL); + sha1->state[0] = 0x67452301UL; + sha1->state[1] = 0xefcdab89UL; + sha1->state[2] = 0x98badcfeUL; + sha1->state[3] = 0x10325476UL; + sha1->state[4] = 0xc3d2e1f0UL; + sha1->curlen = 0; + sha1->length = 0; +} + +/** + Process a block of memory though the hash + @param sha1 The hash state + @param in The data to hash + @param inlen The length of the data (octets) +*/ +void sha1_process(struct sha1_state *sha1, + const unsigned char *in, unsigned long inlen) +{ + unsigned long n; + + assert(sha1 != NULL); + assert(in != NULL); + assert(sha1->curlen <= sizeof(sha1->buf)); + + while (inlen > 0) { + if (sha1->curlen == 0 && inlen >= SHA1_BLOCKSIZE) { + sha1_compress(sha1, (unsigned char *)in); + sha1->length += SHA1_BLOCKSIZE * 8; + in += SHA1_BLOCKSIZE; + inlen -= SHA1_BLOCKSIZE; + } else { + n = MIN(inlen, (SHA1_BLOCKSIZE - sha1->curlen)); + memcpy(sha1->buf + sha1->curlen, in, (size_t)n); + sha1->curlen += n; + in += n; + inlen -= n; + if (sha1->curlen == SHA1_BLOCKSIZE) { + sha1_compress(sha1, sha1->buf); + sha1->length += 8*SHA1_BLOCKSIZE; + sha1->curlen = 0; + } + } + } +} + +/** + Terminate the hash to get the digest + @param sha1 The hash state + @param out [out] The destination of the hash (20 bytes) +*/ +void sha1_done(struct sha1_state *sha1, unsigned char *out) +{ + int i; + + assert(sha1 != NULL); + assert(out != NULL); + assert(sha1->curlen < sizeof(sha1->buf)); + + /* increase the length of the message */ + sha1->length += sha1->curlen * 8; + + /* append the '1' bit */ + sha1->buf[sha1->curlen++] = (unsigned char)0x80; + + /* if the length is currently above 56 bytes we append zeros + * then compress. Then we can fall back to padding zeros and length + * encoding like normal. + */ + if (sha1->curlen > 56) { + while (sha1->curlen < 64) { + sha1->buf[sha1->curlen++] = (unsigned char)0; + } + sha1_compress(sha1, sha1->buf); + sha1->curlen = 0; + } + + /* pad upto 56 bytes of zeroes */ + while (sha1->curlen < 56) { + sha1->buf[sha1->curlen++] = (unsigned char)0; + } + + /* store length */ + STORE64H(sha1->length, sha1->buf+56); + sha1_compress(sha1, sha1->buf); + + /* copy output */ + for (i = 0; i < 5; i++) { + STORE32H(sha1->state[i], out+(4*i)); + } +} + + +/* .Source: /cvs/libtom/libtomcrypt/src/hashes/sha1.c,v $ */ +/* .Revision: 1.10 $ */ +/* .Date: 2007/05/12 14:25:28 $ */ + +/* + * End of copied SHA1 code. + * + * ------------------------------------------------------------------------ + */ + +static PyTypeObject SHA1type; + + +static SHA1object * +newSHA1object(void) +{ + return (SHA1object *)PyObject_New(SHA1object, &SHA1type); +} + + +/* Internal methods for a hash object */ + +static void +SHA1_dealloc(PyObject *ptr) +{ + PyObject_Del(ptr); +} + + +/* External methods for a hash object */ + +PyDoc_STRVAR(SHA1_copy__doc__, "Return a copy of the hash object."); + +static PyObject * +SHA1_copy(SHA1object *self, PyObject *unused) +{ + SHA1object *newobj; + + if (Py_Type(self) == &SHA1type) { + if ( (newobj = newSHA1object())==NULL) + return NULL; + } else { + if ( (newobj = newSHA1object())==NULL) + return NULL; + } + + newobj->hash_state = self->hash_state; + return (PyObject *)newobj; +} + +PyDoc_STRVAR(SHA1_digest__doc__, +"Return the digest value as a string of binary data."); + +static PyObject * +SHA1_digest(SHA1object *self, PyObject *unused) +{ + unsigned char digest[SHA1_DIGESTSIZE]; + struct sha1_state temp; + + temp = self->hash_state; + sha1_done(&temp, digest); + return PyBytes_FromStringAndSize((const char *)digest, SHA1_DIGESTSIZE); +} + +PyDoc_STRVAR(SHA1_hexdigest__doc__, +"Return the digest value as a string of hexadecimal digits."); + +static PyObject * +SHA1_hexdigest(SHA1object *self, PyObject *unused) +{ + unsigned char digest[SHA1_DIGESTSIZE]; + struct sha1_state temp; + PyObject *retval; + Py_UNICODE *hex_digest; + int i, j; + + /* Get the raw (binary) digest value */ + temp = self->hash_state; + sha1_done(&temp, digest); + + /* Create a new string */ + retval = PyUnicode_FromStringAndSize(NULL, SHA1_DIGESTSIZE * 2); + if (!retval) + return NULL; + hex_digest = PyUnicode_AS_UNICODE(retval); + if (!hex_digest) { + Py_DECREF(retval); + return NULL; + } + + /* Make hex version of the digest */ + for(i=j=0; i> 4) & 0xf; + c = (c>9) ? c+'a'-10 : c + '0'; + hex_digest[j++] = c; + c = (digest[i] & 0xf); + c = (c>9) ? c+'a'-10 : c + '0'; + hex_digest[j++] = c; + } + return retval; +} + +PyDoc_STRVAR(SHA1_update__doc__, +"Update this hash object's state with the provided string."); + +static PyObject * +SHA1_update(SHA1object *self, PyObject *args) +{ + unsigned char *cp; + int len; + + if (!PyArg_ParseTuple(args, "s#:update", &cp, &len)) + return NULL; + + sha1_process(&self->hash_state, cp, len); + + Py_INCREF(Py_None); + return Py_None; +} + +static PyMethodDef SHA1_methods[] = { + {"copy", (PyCFunction)SHA1_copy, METH_NOARGS, SHA1_copy__doc__}, + {"digest", (PyCFunction)SHA1_digest, METH_NOARGS, SHA1_digest__doc__}, + {"hexdigest", (PyCFunction)SHA1_hexdigest, METH_NOARGS, SHA1_hexdigest__doc__}, + {"update", (PyCFunction)SHA1_update, METH_VARARGS, SHA1_update__doc__}, + {NULL, NULL} /* sentinel */ +}; + +static PyObject * +SHA1_get_block_size(PyObject *self, void *closure) +{ + return PyInt_FromLong(SHA1_BLOCKSIZE); +} + +static PyObject * +SHA1_get_name(PyObject *self, void *closure) +{ + return PyUnicode_FromStringAndSize("SHA1", 3); +} + +static PyObject * +sha1_get_digest_size(PyObject *self, void *closure) +{ + return PyInt_FromLong(SHA1_DIGESTSIZE); +} + + +static PyGetSetDef SHA1_getseters[] = { + {"block_size", + (getter)SHA1_get_block_size, NULL, + NULL, + NULL}, + {"name", + (getter)SHA1_get_name, NULL, + NULL, + NULL}, + {"digest_size", + (getter)sha1_get_digest_size, NULL, + NULL, + NULL}, + {NULL} /* Sentinel */ +}; + +static PyTypeObject SHA1type = { + PyVarObject_HEAD_INIT(NULL, 0) + "_sha1.sha1", /*tp_name*/ + sizeof(SHA1object), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + SHA1_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + 0, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + 0, /*tp_as_number*/ + 0, /*tp_as_sequence*/ + 0, /*tp_as_mapping*/ + 0, /*tp_hash*/ + 0, /*tp_call*/ + 0, /*tp_str*/ + 0, /*tp_getattro*/ + 0, /*tp_setattro*/ + 0, /*tp_as_buffer*/ + Py_TPFLAGS_DEFAULT, /*tp_flags*/ + 0, /*tp_doc*/ + 0, /*tp_traverse*/ + 0, /*tp_clear*/ + 0, /*tp_richcompare*/ + 0, /*tp_weaklistoffset*/ + 0, /*tp_iter*/ + 0, /*tp_iternext*/ + SHA1_methods, /* tp_methods */ + NULL, /* tp_members */ + SHA1_getseters, /* tp_getset */ +}; + + +/* The single module-level function: new() */ + +PyDoc_STRVAR(SHA1_new__doc__, +"Return a new SHA1 hash object; optionally initialized with a string."); + +static PyObject * +SHA1_new(PyObject *self, PyObject *args, PyObject *kwdict) +{ + static char *kwlist[] = {"string", NULL}; + SHA1object *new; + unsigned char *cp = NULL; + int len; + + if (!PyArg_ParseTupleAndKeywords(args, kwdict, "|s#:new", kwlist, + &cp, &len)) { + return NULL; + } + + if ((new = newSHA1object()) == NULL) + return NULL; + + sha1_init(&new->hash_state); + + if (PyErr_Occurred()) { + Py_DECREF(new); + return NULL; + } + if (cp) + sha1_process(&new->hash_state, cp, len); + + return (PyObject *)new; +} + + +/* List of functions exported by this module */ + +static struct PyMethodDef SHA1_functions[] = { + {"sha1",(PyCFunction)SHA1_new, METH_VARARGS|METH_KEYWORDS,SHA1_new__doc__}, + {NULL, NULL} /* Sentinel */ +}; + + +/* Initialize this module. */ + +#define insint(n,v) { PyModule_AddIntConstant(m,n,v); } + +PyMODINIT_FUNC +init_sha1(void) +{ + PyObject *m; + + Py_Type(&SHA1type) = &PyType_Type; + if (PyType_Ready(&SHA1type) < 0) + return; + m = Py_InitModule("_sha1", SHA1_functions); + if (m == NULL) + return; +} Modified: python/branches/py3k/Modules/sha256module.c ============================================================================== --- python/branches/py3k/Modules/sha256module.c (original) +++ python/branches/py3k/Modules/sha256module.c Sun Sep 9 08:44:34 2007 @@ -9,7 +9,7 @@ Greg Stein (gstein at lyra.org) Trevor Perrin (trevp at trevp.net) - Copyright (C) 2005 Gregory P. Smith (greg at electricrain.com) + Copyright (C) 2005-2007 Gregory P. Smith (greg at krypto.org) Licensed to PSF under a Contributor Agreement. */ @@ -103,7 +103,7 @@ * The library is free for all purposes without any express * gurantee it works. * - * Tom St Denis, tomstdenis at iahu.ca, http://libtomcrypt.org + * Tom St Denis, tomstdenis at iahu.ca, http://libtom.org */ Modified: python/branches/py3k/Modules/sha512module.c ============================================================================== --- python/branches/py3k/Modules/sha512module.c (original) +++ python/branches/py3k/Modules/sha512module.c Sun Sep 9 08:44:34 2007 @@ -9,7 +9,7 @@ Greg Stein (gstein at lyra.org) Trevor Perrin (trevp at trevp.net) - Copyright (C) 2005 Gregory P. Smith (greg at electricrain.com) + Copyright (C) 2005-2007 Gregory P. Smith (greg at krypto.org) Licensed to PSF under a Contributor Agreement. */ @@ -113,7 +113,7 @@ * The library is free for all purposes without any express * gurantee it works. * - * Tom St Denis, tomstdenis at iahu.ca, http://libtomcrypt.org + * Tom St Denis, tomstdenis at iahu.ca, http://libtom.org */ Modified: python/branches/py3k/setup.py ============================================================================== --- python/branches/py3k/setup.py (original) +++ python/branches/py3k/setup.py Sun Sep 9 08:44:34 2007 @@ -618,6 +618,11 @@ exts.append( Extension('_sha256', ['sha256module.c']) ) exts.append( Extension('_sha512', ['sha512module.c']) ) + if not openssl_ver: + # no openssl at all, use our own md5 and sha1 + exts.append( Extension('_md5', ['md5module.c']) ) + exts.append( Extension('_sha1', ['sha1module.c']) ) + # Modules that provide persistent dictionary-like semantics. You will # probably want to arrange for at least one of them to be available on # your machine, though none are defined by default because of library From python-3000-checkins at python.org Sun Sep 9 20:01:42 2007 From: python-3000-checkins at python.org (gregory.p.smith) Date: Sun, 9 Sep 2007 20:01:42 +0200 (CEST) Subject: [Python-3000-checkins] r58062 - python/branches/py3k/setup.py Message-ID: <20070909180143.002831E400F@bag.python.org> Author: gregory.p.smith Date: Sun Sep 9 20:01:42 2007 New Revision: 58062 Modified: python/branches/py3k/setup.py Log: openssl 0.9.6 is too old to use, use our own modules Modified: python/branches/py3k/setup.py ============================================================================== --- python/branches/py3k/setup.py (original) +++ python/branches/py3k/setup.py Sun Sep 9 20:01:42 2007 @@ -613,12 +613,12 @@ else: missing.append('_hashlib') - if (openssl_ver < 0x00908000): + if openssl_ver < 0x00908000: # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash exts.append( Extension('_sha256', ['sha256module.c']) ) exts.append( Extension('_sha512', ['sha512module.c']) ) - if not openssl_ver: + if openssl_ver < 0x00907000: # no openssl at all, use our own md5 and sha1 exts.append( Extension('_md5', ['md5module.c']) ) exts.append( Extension('_sha1', ['sha1module.c']) ) From python-3000-checkins at python.org Sun Sep 9 22:17:22 2007 From: python-3000-checkins at python.org (gregory.p.smith) Date: Sun, 9 Sep 2007 22:17:22 +0200 (CEST) Subject: [Python-3000-checkins] r58063 - in python/branches/py3k: Lib/test/test_hashlib.py Modules/_bsddb.c Message-ID: <20070909201722.B3ED71E400F@bag.python.org> Author: gregory.p.smith Date: Sun Sep 9 22:17:22 2007 New Revision: 58063 Modified: python/branches/py3k/Lib/test/test_hashlib.py python/branches/py3k/Modules/_bsddb.c Log: email address update Modified: python/branches/py3k/Lib/test/test_hashlib.py ============================================================================== --- python/branches/py3k/Lib/test/test_hashlib.py (original) +++ python/branches/py3k/Lib/test/test_hashlib.py Sun Sep 9 22:17:22 2007 @@ -2,7 +2,7 @@ # # $Id$ # -# Copyright (C) 2005 Gregory P. Smith (greg at electricrain.com) +# Copyright (C) 2005 Gregory P. Smith (greg at krypto.org) # Licensed to PSF under a Contributor Agreement. # Modified: python/branches/py3k/Modules/_bsddb.c ============================================================================== --- python/branches/py3k/Modules/_bsddb.c (original) +++ python/branches/py3k/Modules/_bsddb.c Sun Sep 9 22:17:22 2007 @@ -39,16 +39,16 @@ * to compile with BerkeleyDB versions 3.2 through 4.2. * * This module was started by Andrew Kuchling to remove the dependency - * on SWIG in a package by Gregory P. Smith who - * based his work on a similar package by Robin Dunn - * which wrapped Berkeley DB 2.7.x. + * on SWIG in a package by Gregory P. Smith who based his work on a + * similar package by Robin Dunn which wrapped + * Berkeley DB 2.7.x. * * Development of this module then returned full circle back to Robin Dunn * who worked on behalf of Digital Creations to complete the wrapping of * the DB 3.x API and to build a solid unit test suite. Robin has * since gone onto other projects (wxPython). * - * Gregory P. Smith is once again the maintainer. + * Gregory P. Smith is once again the maintainer. * * Use the pybsddb-users at lists.sf.net mailing list for all questions. * Things can change faster than the header of this file is updated. This From python-3000-checkins at python.org Mon Sep 10 01:55:56 2007 From: python-3000-checkins at python.org (gregory.p.smith) Date: Mon, 10 Sep 2007 01:55:56 +0200 (CEST) Subject: [Python-3000-checkins] r58068 - in python/branches/py3k: Doc/library/exceptions.rst Doc/library/socket.rst Doc/whatsnew/2.6.rst Lib/test/test_urllib2net.py Lib/urllib2.py Modules/socketmodule.c Message-ID: <20070909235556.04BA71E400F@bag.python.org> Author: gregory.p.smith Date: Mon Sep 10 01:55:55 2007 New Revision: 58068 Modified: python/branches/py3k/Doc/library/exceptions.rst python/branches/py3k/Doc/library/socket.rst python/branches/py3k/Doc/whatsnew/2.6.rst python/branches/py3k/Lib/test/test_urllib2net.py python/branches/py3k/Lib/urllib2.py python/branches/py3k/Modules/socketmodule.c Log: merge this from trunk: r58067 | gregory.p.smith | 2007-09-09 16:36:46 -0700 (Sun, 09 Sep 2007) | 22 lin es Change socket.error to inherit from IOError rather than being a stand alone class. This addresses the primary concern in http://bugs.python.org/issue1706815 python-dev discussion here: http://mail.python.org/pipermail/python-dev/2007-July/073749.html I chose IOError rather than EnvironmentError as the base class since socket objects are often used as transparent duck typed file objects in code already prepared to deal with IOError exceptions. also a minor fix: urllib2 - fix a couple places where IOError was raised rather than URLError. for better or worse, URLError already inherits from IOError so this won't break any existing code. test_urllib2net - replace bad ftp urls. Modified: python/branches/py3k/Doc/library/exceptions.rst ============================================================================== --- python/branches/py3k/Doc/library/exceptions.rst (original) +++ python/branches/py3k/Doc/library/exceptions.rst Mon Sep 10 01:55:55 2007 @@ -147,6 +147,9 @@ This class is derived from :exc:`EnvironmentError`. See the discussion above for more information on exception instance attributes. + .. versionchanged:: 2.6 + Changed :exc:`socket.error` to use this as a base class. + .. exception:: ImportError Modified: python/branches/py3k/Doc/library/socket.rst ============================================================================== --- python/branches/py3k/Doc/library/socket.rst (original) +++ python/branches/py3k/Doc/library/socket.rst Mon Sep 10 01:55:55 2007 @@ -85,6 +85,9 @@ accompanying :exc:`os.error`. See the module :mod:`errno`, which contains names for the error codes defined by the underlying operating system. + .. versionchanged:: 2.6 + :exc:`socket.error` is now a child class of :exc:`IOError`. + .. exception:: herror Modified: python/branches/py3k/Doc/whatsnew/2.6.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/2.6.rst (original) +++ python/branches/py3k/Doc/whatsnew/2.6.rst Mon Sep 10 01:55:55 2007 @@ -282,7 +282,8 @@ This section lists previously described changes that may require changes to your code: -* Everything is all in the details! +* The :mod:`socket` module exception :exc:`socket.error` now inherits from + :exc:`IOError`. .. % ====================================================================== Modified: python/branches/py3k/Lib/test/test_urllib2net.py ============================================================================== --- python/branches/py3k/Lib/test/test_urllib2net.py (original) +++ python/branches/py3k/Lib/test/test_urllib2net.py Mon Sep 10 01:55:55 2007 @@ -164,8 +164,9 @@ def test_ftp(self): urls = [ - 'ftp://www.python.org/pub/python/misc/sousa.au', - 'ftp://www.python.org/pub/tmp/blat', + 'ftp://ftp.kernel.org/pub/linux/kernel/README', + 'ftp://ftp.kernel.org/pub/linux/kernel/non-existant-file', + #'ftp://ftp.kernel.org/pub/leenox/kernel/test', 'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC' '/research-reports/00README-Legal-Rules-Regs', ] @@ -179,10 +180,7 @@ f.close() urls = [ 'file:'+sanepathname2url(os.path.abspath(TESTFN)), - - # XXX bug, should raise URLError - #('file://nonsensename/etc/passwd', None, urllib2.URLError) - ('file://nonsensename/etc/passwd', None, (EnvironmentError, socket.error)) + ('file:///nonsensename/etc/passwd', None, urllib2.URLError), ] self._test_urls(urls, self._extra_handlers()) finally: @@ -242,11 +240,11 @@ debug(url) try: f = urllib2.urlopen(url, req) - except (IOError, socket.error, OSError) as err: + except EnvironmentError as err: debug(err) if expected_err: - msg = ("Didn't get expected error(s) %s for %s %s, got %s" % - (expected_err, url, req, err)) + msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" % + (expected_err, url, req, type(err), err)) self.assert_(isinstance(err, expected_err), msg) else: with test_support.transient_internet(): Modified: python/branches/py3k/Lib/urllib2.py ============================================================================== --- python/branches/py3k/Lib/urllib2.py (original) +++ python/branches/py3k/Lib/urllib2.py Mon Sep 10 01:55:55 2007 @@ -1240,7 +1240,7 @@ import mimetypes host = req.get_host() if not host: - raise IOError('ftp error', 'no host given') + raise URLError('ftp error', 'no host given') host, port = splitport(host) if port is None: port = ftplib.FTP_PORT @@ -1286,7 +1286,7 @@ headers = mimetools.Message(sf) return addinfourl(fp, headers, req.get_full_url()) except ftplib.all_errors as msg: - raise IOError('ftp error', msg).with_traceback(sys.exc_info()[2]) + raise URLError('ftp error', msg).with_traceback(sys.exc_info()[2]) def connect_ftp(self, user, passwd, host, port, dirs, timeout): fw = ftpwrapper(user, passwd, host, port, dirs, timeout) Modified: python/branches/py3k/Modules/socketmodule.c ============================================================================== --- python/branches/py3k/Modules/socketmodule.c (original) +++ python/branches/py3k/Modules/socketmodule.c Mon Sep 10 01:55:55 2007 @@ -4035,7 +4035,8 @@ if (m == NULL) return; - socket_error = PyErr_NewException("socket.error", NULL, NULL); + socket_error = PyErr_NewException("socket.error", + PyExc_IOError, NULL); if (socket_error == NULL) return; PySocketModuleAPI.error = socket_error; From python-3000-checkins at python.org Mon Sep 10 02:03:42 2007 From: python-3000-checkins at python.org (collin.winter) Date: Mon, 10 Sep 2007 02:03:42 +0200 (CEST) Subject: [Python-3000-checkins] r58069 - python/branches/py3k/Doc/library/wsgiref.rst python/branches/py3k/Doc/library/xml.sax.reader.rst Message-ID: <20070910000342.2874B1E400F@bag.python.org> Author: collin.winter Date: Mon Sep 10 02:03:41 2007 New Revision: 58069 Modified: python/branches/py3k/Doc/library/wsgiref.rst python/branches/py3k/Doc/library/xml.sax.reader.rst Log: Remove two lingering references to now-gone has_key() methods from the library docs. Modified: python/branches/py3k/Doc/library/wsgiref.rst ============================================================================== --- python/branches/py3k/Doc/library/wsgiref.rst (original) +++ python/branches/py3k/Doc/library/wsgiref.rst Mon Sep 10 02:03:41 2007 @@ -156,7 +156,7 @@ :class:`Headers` objects support typical mapping operations including :meth:`__getitem__`, :meth:`get`, :meth:`__setitem__`, :meth:`setdefault`, - :meth:`__delitem__`, :meth:`__contains__` and :meth:`has_key`. For each of + :meth:`__delitem__` and :meth:`__contains__`. For each of these methods, the key is the header name (treated case-insensitively), and the value is the first value associated with that header name. Setting a header deletes any existing values for that header, then adds a new value at the end of Modified: python/branches/py3k/Doc/library/xml.sax.reader.rst ============================================================================== --- python/branches/py3k/Doc/library/xml.sax.reader.rst (original) +++ python/branches/py3k/Doc/library/xml.sax.reader.rst Mon Sep 10 02:03:41 2007 @@ -324,8 +324,9 @@ --------------------------------- :class:`Attributes` objects implement a portion of the mapping protocol, -including the methods :meth:`copy`, :meth:`get`, :meth:`has_key`, :meth:`items`, -:meth:`keys`, and :meth:`values`. The following methods are also provided: +including the methods :meth:`copy`, :meth:`get`, :meth:`__contains__`, +:meth:`items`, :meth:`keys`, and :meth:`values`. The following methods +are also provided: .. method:: Attributes.getLength() From python-3000-checkins at python.org Mon Sep 10 02:20:05 2007 From: python-3000-checkins at python.org (collin.winter) Date: Mon, 10 Sep 2007 02:20:05 +0200 (CEST) Subject: [Python-3000-checkins] r58070 - python/branches/py3k/Doc/library/pickle.rst Message-ID: <20070910002006.00CF21E427F@bag.python.org> Author: collin.winter Date: Mon Sep 10 02:20:05 2007 New Revision: 58070 Modified: python/branches/py3k/Doc/library/pickle.rst Log: Fix a legacy raise statement in pickle's docs. Modified: python/branches/py3k/Doc/library/pickle.rst ============================================================================== --- python/branches/py3k/Doc/library/pickle.rst (original) +++ python/branches/py3k/Doc/library/pickle.rst Mon Sep 10 02:20:05 2007 @@ -592,7 +592,7 @@ value = int(persid.split()[2]) return FancyInteger(value) else: - raise pickle.UnpicklingError, 'Invalid persistent id' + raise pickle.UnpicklingError('Invalid persistent id') up.persistent_load = persistent_load From python-3000-checkins at python.org Mon Sep 10 02:20:47 2007 From: python-3000-checkins at python.org (collin.winter) Date: Mon, 10 Sep 2007 02:20:47 +0200 (CEST) Subject: [Python-3000-checkins] r58071 - in python/branches/py3k/Doc: c-api/abstract.rst reference/datamodel.rst tutorial/datastructures.rst Message-ID: <20070910002047.16C431E4063@bag.python.org> Author: collin.winter Date: Mon Sep 10 02:20:46 2007 New Revision: 58071 Modified: python/branches/py3k/Doc/c-api/abstract.rst python/branches/py3k/Doc/reference/datamodel.rst python/branches/py3k/Doc/tutorial/datastructures.rst Log: Remove yet more references to has_key() methods. Modified: python/branches/py3k/Doc/c-api/abstract.rst ============================================================================== --- python/branches/py3k/Doc/c-api/abstract.rst (original) +++ python/branches/py3k/Doc/c-api/abstract.rst Mon Sep 10 02:20:46 2007 @@ -824,14 +824,14 @@ .. cfunction:: int PyMapping_HasKeyString(PyObject *o, char *key) On success, return ``1`` if the mapping object has the key *key* and ``0`` - otherwise. This is equivalent to the Python expression ``o.has_key(key)``. + otherwise. This is equivalent to the Python expression ``key in o``. This function always succeeds. .. cfunction:: int PyMapping_HasKey(PyObject *o, PyObject *key) Return ``1`` if the mapping object has the key *key* and ``0`` otherwise. This - is equivalent to the Python expression ``o.has_key(key)``. This function always + is equivalent to the Python expression ``key in o``. This function always succeeds. Modified: python/branches/py3k/Doc/reference/datamodel.rst ============================================================================== --- python/branches/py3k/Doc/reference/datamodel.rst (original) +++ python/branches/py3k/Doc/reference/datamodel.rst Mon Sep 10 02:20:46 2007 @@ -1602,7 +1602,7 @@ a sequence, the allowable keys should be the integers *k* for which ``0 <= k < N`` where *N* is the length of the sequence, or slice objects, which define a range of items. It is also recommended that mappings provide the methods -:meth:`keys`, :meth:`values`, :meth:`items`, :meth:`has_key`, :meth:`get`, +:meth:`keys`, :meth:`values`, :meth:`items`, :meth:`get`, :meth:`clear`, :meth:`setdefault`, :meth:`pop`, :meth:`popitem`, :meth:`copy`, and :meth:`update` behaving similar to those for Python's standard dictionary @@ -1618,8 +1618,8 @@ described below; they should not define other numerical operators. It is recommended that both mappings and sequences implement the :meth:`__contains__` method to allow efficient use of the ``in`` operator; for mappings, ``in`` -should be equivalent of :meth:`has_key`; for sequences, it should search through -the values. It is further recommended that both mappings and sequences +should search the mapping's keys; for sequences, it should search +through the values. It is further recommended that both mappings and sequences implement the :meth:`__iter__` method to allow efficient iteration through the container; for mappings, :meth:`__iter__` should be the same as :meth:`keys`; for sequences, it should iterate through the values. Modified: python/branches/py3k/Doc/tutorial/datastructures.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/datastructures.rst (original) +++ python/branches/py3k/Doc/tutorial/datastructures.rst Mon Sep 10 02:20:46 2007 @@ -385,8 +385,7 @@ The :meth:`keys` method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the :meth:`sort` method to the list of keys). To check whether a single key is -in the dictionary, either use the dictionary's :meth:`has_key` method or the -:keyword:`in` keyword. +in the dictionary, use the :keyword:`in` keyword. Here is a small example using a dictionary:: From python-3000-checkins at python.org Mon Sep 10 02:27:13 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 10 Sep 2007 02:27:13 +0200 (CEST) Subject: [Python-3000-checkins] r58072 - python/branches/py3k/Lib/poplib.py Message-ID: <20070910002713.5346E1E4004@bag.python.org> Author: guido.van.rossum Date: Mon Sep 10 02:27:13 2007 New Revision: 58072 Modified: python/branches/py3k/Lib/poplib.py Log: Patch # 1094 by Serge Julien. Fix some bytes/str comparisons. (Bah, the poplib test didn't catch this.) Modified: python/branches/py3k/Lib/poplib.py ============================================================================== --- python/branches/py3k/Lib/poplib.py (original) +++ python/branches/py3k/Lib/poplib.py Mon Sep 10 02:27:13 2007 @@ -134,8 +134,8 @@ resp = self._getresp() list = []; octets = 0 line, o = self._getline() - while line != '.': - if line[:2] == '..': + while line != b'.': + if line[:2] == b'..': o = o-1 line = line[1:] octets = octets + o From python-3000-checkins at python.org Mon Sep 10 02:27:23 2007 From: python-3000-checkins at python.org (collin.winter) Date: Mon, 10 Sep 2007 02:27:23 +0200 (CEST) Subject: [Python-3000-checkins] r58073 - python/branches/py3k/Doc/tutorial/classes.rst Message-ID: <20070910002723.D41691E4004@bag.python.org> Author: collin.winter Date: Mon Sep 10 02:27:23 2007 New Revision: 58073 Modified: python/branches/py3k/Doc/tutorial/classes.rst Log: Update tutorial/classes.rst to remove references to the old two-argument form of the raise statement. Modified: python/branches/py3k/Doc/tutorial/classes.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/classes.rst (original) +++ python/branches/py3k/Doc/tutorial/classes.rst Mon Sep 10 02:27:23 2007 @@ -586,16 +586,16 @@ User-defined exceptions are identified by classes as well. Using this mechanism it is possible to create extensible hierarchies of exceptions. -There are two new valid (semantic) forms for the raise statement:: +There are two valid (semantic) forms for the raise statement:: - raise Class, instance + raise Class - raise instance + raise Instance -In the first form, ``instance`` must be an instance of :class:`Class` or of a -class derived from it. The second form is a shorthand for:: +In the first form, ``Class`` must be an instance of :class:`type` or of a +class derived from it. The first form is a shorthand for:: - raise instance.__class__, instance + raise Class() A class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way around --- an except clause From python-3000-checkins at python.org Mon Sep 10 02:31:50 2007 From: python-3000-checkins at python.org (collin.winter) Date: Mon, 10 Sep 2007 02:31:50 +0200 (CEST) Subject: [Python-3000-checkins] r58074 - python/branches/py3k/Doc/tutorial/errors.rst Message-ID: <20070910003150.D05DB1E401F@bag.python.org> Author: collin.winter Date: Mon Sep 10 02:31:50 2007 New Revision: 58074 Modified: python/branches/py3k/Doc/tutorial/errors.rst Log: Fix more two-arg raise statements. Modified: python/branches/py3k/Doc/tutorial/errors.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/errors.rst (original) +++ python/branches/py3k/Doc/tutorial/errors.rst Mon Sep 10 02:31:50 2007 @@ -216,7 +216,7 @@ The :keyword:`raise` statement allows the programmer to force a specified exception to occur. For example:: - >>> raise NameError, 'HiThere' + >>> raise NameError('HiThere') Traceback (most recent call last): File "", line 1, in ? NameError: HiThere @@ -231,7 +231,7 @@ re-raise the exception:: >>> try: - ... raise NameError, 'HiThere' + ... raise NameError('HiThere') ... except NameError: ... print('An exception flew by!') ... raise From python-3000-checkins at python.org Mon Sep 10 02:32:45 2007 From: python-3000-checkins at python.org (collin.winter) Date: Mon, 10 Sep 2007 02:32:45 +0200 (CEST) Subject: [Python-3000-checkins] r58075 - python/branches/py3k/Doc/tutorial/errors.rst Message-ID: <20070910003245.B3FD61E4004@bag.python.org> Author: collin.winter Date: Mon Sep 10 02:32:45 2007 New Revision: 58075 Modified: python/branches/py3k/Doc/tutorial/errors.rst Log: Fix docs that imply that tuples in except clauses must be parenthesized. Modified: python/branches/py3k/Doc/tutorial/errors.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/errors.rst (original) +++ python/branches/py3k/Doc/tutorial/errors.rst Mon Sep 10 02:32:45 2007 @@ -115,9 +115,9 @@ handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same :keyword:`try` statement. An except clause may -name multiple exceptions as a parenthesized tuple, for example:: +name multiple exceptions as a tuple, for example:: - ... except (RuntimeError, TypeError, NameError): + ... except RuntimeError, TypeError, NameError: ... pass The last except clause may omit the exception name(s), to serve as a wildcard. From python-3000-checkins at python.org Mon Sep 10 02:36:58 2007 From: python-3000-checkins at python.org (collin.winter) Date: Mon, 10 Sep 2007 02:36:58 +0200 (CEST) Subject: [Python-3000-checkins] r58076 - python/branches/py3k/Doc/tutorial/errors.rst Message-ID: <20070910003658.3196B1E4004@bag.python.org> Author: collin.winter Date: Mon Sep 10 02:36:57 2007 New Revision: 58076 Modified: python/branches/py3k/Doc/tutorial/errors.rst Log: More two-argument raise cleanup in the tutorial. Modified: python/branches/py3k/Doc/tutorial/errors.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/errors.rst (original) +++ python/branches/py3k/Doc/tutorial/errors.rst Mon Sep 10 02:36:57 2007 @@ -221,10 +221,9 @@ File "", line 1, in ? NameError: HiThere -The first argument to :keyword:`raise` names the exception to be raised. The -optional second argument specifies the exception's argument. Alternatively, the -above could be written as ``raise NameError('HiThere')``. Either form works -fine, but there seems to be a growing stylistic preference for the latter. +The sole argument to :keyword:`raise` indicates the exception to be raised. +This must be either an exception instance or an exception class (a class that +derives from :class:`Exception`). If you need to determine whether an exception was raised but don't intend to handle it, a simpler form of the :keyword:`raise` statement allows you to From python-3000-checkins at python.org Mon Sep 10 02:39:53 2007 From: python-3000-checkins at python.org (collin.winter) Date: Mon, 10 Sep 2007 02:39:53 +0200 (CEST) Subject: [Python-3000-checkins] r58077 - python/branches/py3k/Doc/tutorial/controlflow.rst python/branches/py3k/Doc/tutorial/errors.rst Message-ID: <20070910003953.28B7D1E4004@bag.python.org> Author: collin.winter Date: Mon Sep 10 02:39:52 2007 New Revision: 58077 Modified: python/branches/py3k/Doc/tutorial/controlflow.rst python/branches/py3k/Doc/tutorial/errors.rst Log: Fix more raise statments in the docs. Modified: python/branches/py3k/Doc/tutorial/controlflow.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/controlflow.rst (original) +++ python/branches/py3k/Doc/tutorial/controlflow.rst Mon Sep 10 02:39:52 2007 @@ -329,7 +329,8 @@ if ok in ('y', 'ye', 'yes'): return True if ok in ('n', 'no', 'nop', 'nope'): return False retries = retries - 1 - if retries < 0: raise IOError, 'refusenik user' + if retries < 0: + raise IOError('refusenik user') print(complaint) This function can be called either like this: ``ask_ok('Do you really want to Modified: python/branches/py3k/Doc/tutorial/errors.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/errors.rst (original) +++ python/branches/py3k/Doc/tutorial/errors.rst Mon Sep 10 02:39:52 2007 @@ -262,7 +262,7 @@ ... print('My exception occurred, value:', e.value) ... My exception occurred, value: 4 - >>> raise MyError, 'oops!' + >>> raise MyError('oops!') Traceback (most recent call last): File "", line 1, in ? __main__.MyError: 'oops!' From guido at python.org Mon Sep 10 02:42:57 2007 From: guido at python.org (Guido van Rossum) Date: Sun, 9 Sep 2007 17:42:57 -0700 Subject: [Python-3000-checkins] r58075 - python/branches/py3k/Doc/tutorial/errors.rst In-Reply-To: <20070910003245.B3FD61E4004@bag.python.org> References: <20070910003245.B3FD61E4004@bag.python.org> Message-ID: Um, that's incorrect. They must still be parenthesized. (This is so that old code doesn't accidentally change its meaning when it isn't explicitly converted.) On 9/9/07, collin.winter wrote: > Author: collin.winter > Date: Mon Sep 10 02:32:45 2007 > New Revision: 58075 > > Modified: > python/branches/py3k/Doc/tutorial/errors.rst > Log: > Fix docs that imply that tuples in except clauses must be parenthesized. > > Modified: python/branches/py3k/Doc/tutorial/errors.rst > ============================================================================== > --- python/branches/py3k/Doc/tutorial/errors.rst (original) > +++ python/branches/py3k/Doc/tutorial/errors.rst Mon Sep 10 02:32:45 2007 > @@ -115,9 +115,9 @@ > handlers for different exceptions. At most one handler will be executed. > Handlers only handle exceptions that occur in the corresponding try clause, not > in other handlers of the same :keyword:`try` statement. An except clause may > -name multiple exceptions as a parenthesized tuple, for example:: > +name multiple exceptions as a tuple, for example:: > > - ... except (RuntimeError, TypeError, NameError): > + ... except RuntimeError, TypeError, NameError: > ... pass > > The last except clause may omit the exception name(s), to serve as a wildcard. > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > -- --Guido van Rossum (home page: http://www.python.org/~guido/) From python-3000-checkins at python.org Mon Sep 10 02:47:21 2007 From: python-3000-checkins at python.org (collin.winter) Date: Mon, 10 Sep 2007 02:47:21 +0200 (CEST) Subject: [Python-3000-checkins] r58078 - python/branches/py3k/Doc/howto/sockets.rst Message-ID: <20070910004721.3B5CA1E4004@bag.python.org> Author: collin.winter Date: Mon Sep 10 02:47:20 2007 New Revision: 58078 Modified: python/branches/py3k/Doc/howto/sockets.rst Log: General clean-up in socket howto. Modified: python/branches/py3k/Doc/howto/sockets.rst ============================================================================== --- python/branches/py3k/Doc/howto/sockets.rst (original) +++ python/branches/py3k/Doc/howto/sockets.rst Mon Sep 10 02:47:20 2007 @@ -61,8 +61,7 @@ your browser did something like the following:: #create an INET, STREAMing socket - s = socket.socket( - socket.AF_INET, socket.SOCK_STREAM) + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #now connect to the web server on port 80 # - the normal http port s.connect(("www.mcmillan-inc.com", 80)) @@ -100,7 +99,7 @@ OK, now we have a "server" socket, listening on port 80. Now we enter the mainloop of the web server:: - while 1: + while True: #accept connections from outside (clientsocket, address) = serversocket.accept() #now do something with the clientsocket @@ -185,38 +184,36 @@ length message:: class mysocket: - '''demonstration class only + """demonstration class only - coded for clarity, not efficiency - ''' + """ def __init__(self, sock=None): - if sock is None: - self.sock = socket.socket( - socket.AF_INET, socket.SOCK_STREAM) - else: - self.sock = sock + if sock is None: + self.sock = socket.socket( + socket.AF_INET, socket.SOCK_STREAM) + else: + self.sock = sock def connect(self, host, port): - self.sock.connect((host, port)) + self.sock.connect((host, port)) def mysend(self, msg): - totalsent = 0 - while totalsent < MSGLEN: - sent = self.sock.send(msg[totalsent:]) - if sent == 0: - raise RuntimeError, \ - "socket connection broken" - totalsent = totalsent + sent + totalsent = 0 + while totalsent < MSGLEN: + sent = self.sock.send(msg[totalsent:]) + if sent == 0: + raise RuntimeError("socket connection broken") + totalsent = totalsent + sent def myreceive(self): - msg = '' - while len(msg) < MSGLEN: - chunk = self.sock.recv(MSGLEN-len(msg)) - if chunk == '': - raise RuntimeError, \ - "socket connection broken" - msg = msg + chunk - return msg + msg = '' + while len(msg) < MSGLEN: + chunk = self.sock.recv(MSGLEN-len(msg)) + if chunk == '': + raise RuntimeError("socket connection broken") + msg = msg + chunk + return msg The sending code here is usable for almost any messaging scheme - in Python you send strings, and you can use ``len()`` to determine its length (even if it has From python-3000-checkins at python.org Mon Sep 10 02:49:58 2007 From: python-3000-checkins at python.org (collin.winter) Date: Mon, 10 Sep 2007 02:49:58 +0200 (CEST) Subject: [Python-3000-checkins] r58079 - in python/branches/py3k/Doc: howto/curses.rst library/cgi.rst library/logging.rst library/smtplib.rst library/socket.rst Message-ID: <20070910004958.4B8161E4004@bag.python.org> Author: collin.winter Date: Mon Sep 10 02:49:57 2007 New Revision: 58079 Modified: python/branches/py3k/Doc/howto/curses.rst python/branches/py3k/Doc/library/cgi.rst python/branches/py3k/Doc/library/logging.rst python/branches/py3k/Doc/library/smtplib.rst python/branches/py3k/Doc/library/socket.rst Log: Change instances of 'while 1:' in the docs into 'while True:'. Modified: python/branches/py3k/Doc/howto/curses.rst ============================================================================== --- python/branches/py3k/Doc/howto/curses.rst (original) +++ python/branches/py3k/Doc/howto/curses.rst Mon Sep 10 02:49:57 2007 @@ -377,7 +377,7 @@ :const:`curses.KEY_HOME`, or :const:`curses.KEY_LEFT`. Usually the main loop of your program will look something like this:: - while 1: + while True: c = stdscr.getch() if c == ord('p'): PrintDocument() elif c == ord('q'): break # Exit the while() Modified: python/branches/py3k/Doc/library/cgi.rst ============================================================================== --- python/branches/py3k/Doc/library/cgi.rst (original) +++ python/branches/py3k/Doc/library/cgi.rst Mon Sep 10 02:49:57 2007 @@ -142,7 +142,7 @@ if fileitem.file: # It's an uploaded file; count lines linecount = 0 - while 1: + while True: line = fileitem.file.readline() if not line: break linecount = linecount + 1 Modified: python/branches/py3k/Doc/library/logging.rst ============================================================================== --- python/branches/py3k/Doc/library/logging.rst (original) +++ python/branches/py3k/Doc/library/logging.rst Mon Sep 10 02:49:57 2007 @@ -783,7 +783,7 @@ followed by the LogRecord in pickle format. Logs the record according to whatever policy is configured locally. """ - while 1: + while True: chunk = self.connection.recv(4) if len(chunk) < 4: break Modified: python/branches/py3k/Doc/library/smtplib.rst ============================================================================== --- python/branches/py3k/Doc/library/smtplib.rst (original) +++ python/branches/py3k/Doc/library/smtplib.rst Mon Sep 10 02:49:57 2007 @@ -322,7 +322,7 @@ # Add the From: and To: headers at the start! msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs))) - while 1: + while True: try: line = raw_input() except EOFError: Modified: python/branches/py3k/Doc/library/socket.rst ============================================================================== --- python/branches/py3k/Doc/library/socket.rst (original) +++ python/branches/py3k/Doc/library/socket.rst Mon Sep 10 02:49:57 2007 @@ -734,7 +734,7 @@ s.listen(1) conn, addr = s.accept() print('Connected by', addr) - while 1: + while True: data = conn.recv(1024) if not data: break conn.send(data) @@ -788,7 +788,7 @@ sys.exit(1) conn, addr = s.accept() print('Connected by', addr) - while 1: + while True: data = conn.recv(1024) if not data: break conn.send(data) From python-3000-checkins at python.org Mon Sep 10 09:59:54 2007 From: python-3000-checkins at python.org (martin.v.loewis) Date: Mon, 10 Sep 2007 09:59:54 +0200 (CEST) Subject: [Python-3000-checkins] r58085 - python/branches/py3k/Objects/longobject.c Message-ID: <20070910075954.A41FE1E401E@bag.python.org> Author: martin.v.loewis Date: Mon Sep 10 09:59:54 2007 New Revision: 58085 Modified: python/branches/py3k/Objects/longobject.c Log: Drop convert_binop. Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Mon Sep 10 09:59:54 2007 @@ -1279,29 +1279,8 @@ #endif /* HAVE_LONG_LONG */ - -static int -convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) { - if (PyLong_Check(v)) { - *a = (PyLongObject *) v; - Py_INCREF(v); - } - else { - return 0; - } - if (PyLong_Check(w)) { - *b = (PyLongObject *) w; - Py_INCREF(w); - } - else { - Py_DECREF(*a); - return 0; - } - return 1; -} - -#define CONVERT_BINOP(v, w, a, b) \ - if (!convert_binop(v, w, a, b)) { \ +#define CHECK_BINOP(v,w) \ + if (!PyLong_Check(v) || !PyLong_Check(w)) { \ Py_INCREF(Py_NotImplemented); \ return Py_NotImplemented; \ } @@ -2188,12 +2167,10 @@ static PyObject * long_richcompare(PyObject *self, PyObject *other, int op) { - PyLongObject *a, *b; PyObject *result; - CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b); - result = Py_CmpToRich(op, long_compare(a, b)); - Py_DECREF(a); - Py_DECREF(b); + CHECK_BINOP(self, other); + result = Py_CmpToRich(op, long_compare((PyLongObject*)self, + (PyLongObject*)other)); return result; } @@ -2323,17 +2300,15 @@ } static PyObject * -long_add(PyLongObject *v, PyLongObject *w) +long_add(PyLongObject *a, PyLongObject *b) { - PyLongObject *a, *b, *z; + PyLongObject *z; - CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b); + CHECK_BINOP(a, b); if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) { PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) + MEDIUM_VALUE(b)); - Py_DECREF(a); - Py_DECREF(b); return result; } if (Py_Size(a) < 0) { @@ -2351,23 +2326,19 @@ else z = x_add(a, b); } - Py_DECREF(a); - Py_DECREF(b); return (PyObject *)z; } static PyObject * -long_sub(PyLongObject *v, PyLongObject *w) +long_sub(PyLongObject *a, PyLongObject *b) { - PyLongObject *a, *b, *z; + PyLongObject *z; - CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b); + CHECK_BINOP(a, b); if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) { PyObject* r; r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b)); - Py_DECREF(a); - Py_DECREF(b); return r; } if (Py_Size(a) < 0) { @@ -2384,8 +2355,6 @@ else z = x_sub(a, b); } - Py_DECREF(a); - Py_DECREF(b); return (PyObject *)z; } @@ -2790,20 +2759,15 @@ } static PyObject * -long_mul(PyLongObject *v, PyLongObject *w) +long_mul(PyLongObject *a, PyLongObject *b) { - PyLongObject *a, *b, *z; + PyLongObject *z; - if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } + CHECK_BINOP(a, b); - if (ABS(Py_Size(v)) <= 1 && ABS(Py_Size(w)) <= 1) { + if (ABS(Py_Size(a)) <= 1 && ABS(Py_Size(b)) <= 1) { PyObject *r; - r = PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w)); - Py_DECREF(a); - Py_DECREF(b); + r = PyLong_FromLong(MEDIUM_VALUE(a)*MEDIUM_VALUE(b)); return r; } @@ -2811,8 +2775,6 @@ /* Negate if exactly one of the inputs is negative. */ if (((Py_Size(a) ^ Py_Size(b)) < 0) && z) NEGATE(z); - Py_DECREF(a); - Py_DECREF(b); return (PyObject *)z; } @@ -2882,31 +2844,26 @@ } static PyObject * -long_div(PyObject *v, PyObject *w) +long_div(PyObject *a, PyObject *b) { - PyLongObject *a, *b, *div; + PyLongObject *div; - CONVERT_BINOP(v, w, &a, &b); - if (l_divmod(a, b, &div, NULL) < 0) + CHECK_BINOP(a, b); + if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, NULL) < 0) div = NULL; - Py_DECREF(a); - Py_DECREF(b); return (PyObject *)div; } static PyObject * -long_true_divide(PyObject *v, PyObject *w) +long_true_divide(PyObject *a, PyObject *b) { - PyLongObject *a, *b; double ad, bd; int failed, aexp = -1, bexp = -1; - CONVERT_BINOP(v, w, &a, &b); + CHECK_BINOP(a, b); ad = _PyLong_AsScaledDouble((PyObject *)a, &aexp); bd = _PyLong_AsScaledDouble((PyObject *)b, &bexp); failed = (ad == -1.0 || bd == -1.0) && PyErr_Occurred(); - Py_DECREF(a); - Py_DECREF(b); if (failed) return NULL; /* 'aexp' and 'bexp' were initialized to -1 to silence gcc-4.0.x, @@ -2941,30 +2898,26 @@ } static PyObject * -long_mod(PyObject *v, PyObject *w) +long_mod(PyObject *a, PyObject *b) { - PyLongObject *a, *b, *mod; - - CONVERT_BINOP(v, w, &a, &b); + PyLongObject *mod; + + CHECK_BINOP(a, b); - if (l_divmod(a, b, NULL, &mod) < 0) + if (l_divmod((PyLongObject*)a, (PyLongObject*)b, NULL, &mod) < 0) mod = NULL; - Py_DECREF(a); - Py_DECREF(b); return (PyObject *)mod; } static PyObject * -long_divmod(PyObject *v, PyObject *w) +long_divmod(PyObject *a, PyObject *b) { - PyLongObject *a, *b, *div, *mod; + PyLongObject *div, *mod; PyObject *z; - CONVERT_BINOP(v, w, &a, &b); + CHECK_BINOP(a, b); - if (l_divmod(a, b, &div, &mod) < 0) { - Py_DECREF(a); - Py_DECREF(b); + if (l_divmod((PyLongObject*)a, (PyLongObject*)b, &div, &mod) < 0) { return NULL; } z = PyTuple_New(2); @@ -2976,8 +2929,6 @@ Py_DECREF(div); Py_DECREF(mod); } - Py_DECREF(a); - Py_DECREF(b); return z; } @@ -2999,7 +2950,9 @@ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; /* a, b, c = v, w, x */ - CONVERT_BINOP(v, w, &a, &b); + CHECK_BINOP(v, w); + a = (PyLongObject*)v; Py_INCREF(a); + b = (PyLongObject*)w; Py_INCREF(b); if (PyLong_Check(x)) { c = (PyLongObject *)x; Py_INCREF(x); @@ -3211,15 +3164,14 @@ } static PyObject * -long_rshift(PyLongObject *v, PyLongObject *w) +long_rshift(PyLongObject *a, PyLongObject *b) { - PyLongObject *a, *b; PyLongObject *z = NULL; long shiftby; Py_ssize_t newsize, wordshift, loshift, hishift, i, j; digit lomask, himask; - CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b); + CHECK_BINOP(a, b); if (Py_Size(a) < 0) { /* Right shifting negative numbers is harder */ @@ -3248,8 +3200,6 @@ newsize = ABS(Py_Size(a)) - wordshift; if (newsize <= 0) { z = _PyLong_New(0); - Py_DECREF(a); - Py_DECREF(b); return (PyObject *)z; } loshift = shiftby % PyLong_SHIFT; @@ -3270,8 +3220,6 @@ z = long_normalize(z); } rshift_error: - Py_DECREF(a); - Py_DECREF(b); return (PyObject *) z; } @@ -3280,13 +3228,14 @@ long_lshift(PyObject *v, PyObject *w) { /* This version due to Tim Peters */ - PyLongObject *a, *b; + PyLongObject *a = (PyLongObject*)v; + PyLongObject *b = (PyLongObject*)w; PyLongObject *z = NULL; long shiftby; Py_ssize_t oldsize, newsize, wordshift, remshift, i, j; twodigits accum; - CONVERT_BINOP(v, w, &a, &b); + CHECK_BINOP(a, b); shiftby = PyLong_AsLong((PyObject *)b); if (shiftby == -1L && PyErr_Occurred()) @@ -3327,8 +3276,6 @@ assert(!accum); z = long_normalize(z); lshift_error: - Py_DECREF(a); - Py_DECREF(b); return (PyObject *) z; } @@ -3442,38 +3389,29 @@ } static PyObject * -long_and(PyObject *v, PyObject *w) +long_and(PyObject *a, PyObject *b) { - PyLongObject *a, *b; PyObject *c; - CONVERT_BINOP(v, w, &a, &b); - c = long_bitwise(a, '&', b); - Py_DECREF(a); - Py_DECREF(b); + CHECK_BINOP(a, b); + c = long_bitwise((PyLongObject*)a, '&', (PyLongObject*)b); return c; } static PyObject * -long_xor(PyObject *v, PyObject *w) +long_xor(PyObject *a, PyObject *b) { - PyLongObject *a, *b; PyObject *c; - CONVERT_BINOP(v, w, &a, &b); - c = long_bitwise(a, '^', b); - Py_DECREF(a); - Py_DECREF(b); + CHECK_BINOP(a, b); + c = long_bitwise((PyLongObject*)a, '^', (PyLongObject*)b); return c; } static PyObject * -long_or(PyObject *v, PyObject *w) +long_or(PyObject *a, PyObject *b) { - PyLongObject *a, *b; PyObject *c; - CONVERT_BINOP(v, w, &a, &b); - c = long_bitwise(a, '|', b); - Py_DECREF(a); - Py_DECREF(b); + CHECK_BINOP(a, b); + c = long_bitwise((PyLongObject*)a, '|', (PyLongObject*)b); return c; } From thomas at python.org Mon Sep 10 17:33:57 2007 From: thomas at python.org (Thomas Wouters) Date: Mon, 10 Sep 2007 17:33:57 +0200 Subject: [Python-3000-checkins] r58068 - in python/branches/py3k: Doc/library/exceptions.rst Doc/library/socket.rst Doc/whatsnew/2.6.rst Lib/test/test_urllib2net.py Lib/urllib2.py Modules/socketmodule.c In-Reply-To: <20070909235556.04BA71E400F@bag.python.org> References: <20070909235556.04BA71E400F@bag.python.org> Message-ID: <9e804ac0709100833t10461267l346a4ebfeabcaedf@mail.gmail.com> On 9/10/07, gregory.p.smith wrote: > > Author: gregory.p.smith > Date: Mon Sep 10 01:55:55 2007 > New Revision: 58068 > > Modified: > python/branches/py3k/Doc/library/exceptions.rst > python/branches/py3k/Doc/library/socket.rst > python/branches/py3k/Doc/whatsnew/2.6.rst > python/branches/py3k/Lib/test/test_urllib2net.py > python/branches/py3k/Lib/urllib2.py > python/branches/py3k/Modules/socketmodule.c > Log: > merge this from trunk: Please do these merges with snvmerge. Otherwise, the bookkeeping of what was merged or not gets all messed up, and the next person to use svnmerge will be in a world of hurt. (I know, I've been there.) py3k% svnmerge merge -r58067 [ resolve conflicts, configure, make, make test ] py3k% svn commit -F svnmerge-commit-message.txt svnmerge should come with svn, nowadays, or you can download it separately (as svnmerge.py, probably; it's just a Python script.) Alternatively, if you know what you're doing, you can edit the svnmerge-integrated property on the branch directly -- but don't mess it up :) -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-3000-checkins/attachments/20070910/94ad3eb0/attachment.htm From python-3000-checkins at python.org Mon Sep 10 18:38:12 2007 From: python-3000-checkins at python.org (gregory.p.smith) Date: Mon, 10 Sep 2007 18:38:12 +0200 (CEST) Subject: [Python-3000-checkins] r58092 - python/branches/py3k/setup.py Message-ID: <20070910163812.559C61E4002@bag.python.org> Author: gregory.p.smith Date: Mon Sep 10 18:38:12 2007 New Revision: 58092 Modified: python/branches/py3k/setup.py Log: merge of r58091 from trunk: Don't allow BerkeleyDB 4.6.x as the current 4.6.19 release is prone to lockups. We'll reenable it once a good 4.6.x release exists. Modified: python/branches/py3k/setup.py ============================================================================== --- python/branches/py3k/setup.py (original) +++ python/branches/py3k/setup.py Mon Sep 10 18:38:12 2007 @@ -637,7 +637,9 @@ # a release. Most open source OSes come with one or more # versions of BerkeleyDB already installed. - max_db_ver = (4, 6) + # XXX(gps) - Do not allow BerkeleyDB 4.6.x until Oracle fixes + # the DB_HASH lockup bug that is present in 4.6.19. + max_db_ver = (4, 5) min_db_ver = (3, 3) db_setup_debug = False # verbose debug prints from this script? @@ -655,7 +657,7 @@ '/sw/include/db3', ] # 4.x minor number specific paths - for x in (0,1,2,3,4,5,6): + for x in range(max_db_ver[1]+1): db_inc_paths.append('/usr/include/db4%d' % x) db_inc_paths.append('/usr/include/db4.%d' % x) db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x) From janssen at parc.com Mon Sep 10 18:11:04 2007 From: janssen at parc.com (Bill Janssen) Date: Mon, 10 Sep 2007 09:11:04 PDT Subject: [Python-3000-checkins] [Python-3000] r58068 - in python/branches/py3k: Doc/library/exceptions.rst Doc/library/socket.rst Doc/whatsnew/2.6.rst Lib/test/test_urllib2net.py Lib/urllib2.py Modules/socketmodule.c In-Reply-To: <9e804ac0709100833t10461267l346a4ebfeabcaedf@mail.gmail.com> References: <20070909235556.04BA71E400F@bag.python.org> <9e804ac0709100833t10461267l346a4ebfeabcaedf@mail.gmail.com> Message-ID: <07Sep10.091110pdt."57996"@synergy1.parc.xerox.com> > svnmerge should come with svn, nowadays, or you can download it separately > (as svnmerge.py, probably; it's just a Python script.) It comes with version 3 of svn. Or http://svn.collab.net/repos/svn/trunk/contrib/client-side/svnmerge/svnmerge.py. Bill From greg at krypto.org Mon Sep 10 18:41:30 2007 From: greg at krypto.org (Gregory P. Smith) Date: Mon, 10 Sep 2007 09:41:30 -0700 Subject: [Python-3000-checkins] r58068 - in python/branches/py3k: Doc/library/exceptions.rst Doc/library/socket.rst Doc/whatsnew/2.6.rst Lib/test/test_urllib2net.py Lib/urllib2.py Modules/socketmodule.c In-Reply-To: <9e804ac0709100833t10461267l346a4ebfeabcaedf@mail.gmail.com> References: <20070909235556.04BA71E400F@bag.python.org> <9e804ac0709100833t10461267l346a4ebfeabcaedf@mail.gmail.com> Message-ID: <52dc1c820709100941m66d2a5b2v156ac9d0a471a87b@mail.gmail.com> On 9/10/07, Thomas Wouters wrote: > > > On 9/10/07, gregory.p.smith wrote: > > > > Author: gregory.p.smith > > Date: Mon Sep 10 01:55:55 2007 > > New Revision: 58068 > > > > Modified: > > python/branches/py3k/Doc/library/exceptions.rst > > python/branches/py3k/Doc/library/socket.rst > > python/branches/py3k/Doc/whatsnew/2.6.rst > > python/branches/py3k/Lib/test/test_urllib2net.py > > python/branches/py3k/Lib/urllib2.py > > python/branches/py3k/Modules/socketmodule.c > > Log: > > merge this from trunk: > > > Please do these merges with snvmerge. Otherwise, the bookkeeping of what > was merged or not gets all messed up, and the next person to use svnmerge > will be in a world of hurt. (I know, I've been there.) > > py3k% svnmerge merge -r58067 > [ resolve conflicts, configure, make, make test ] > py3k% svn commit -F svnmerge-commit-message.txt > > svnmerge should come with svn, nowadays, or you can download it separately > (as svnmerge.py, probably; it's just a Python script.) > > Alternatively, if you know what you're doing, you can edit the > svnmerge-integrated property on the branch directly -- but don't mess it up > :) Sorry about that & thanks for the pointers, I'll use svnmerge (instead of "svn merge" or "svn diff | patch" which i had been using) in the future. -gps -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-3000-checkins/attachments/20070910/a3a5ccdc/attachment.htm From python-3000-checkins at python.org Mon Sep 10 18:53:45 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 10 Sep 2007 18:53:45 +0200 (CEST) Subject: [Python-3000-checkins] r58093 - in python/branches/py3k: Lib/test/test_bytes.py Objects/bytesobject.c Message-ID: <20070910165345.A9F181E4002@bag.python.org> Author: guido.van.rossum Date: Mon Sep 10 18:53:45 2007 New Revision: 58093 Modified: python/branches/py3k/Lib/test/test_bytes.py python/branches/py3k/Objects/bytesobject.c Log: Bug # 1125 (my code). Support bytes.split() and bytes.strip() -- these split/strip using ASCII whitespace (tab, space, CR, LF, FF, VT) like their str counterparts. Also for rsplit(), lstrip() and rstrip(). And change all these functions to accept arbitrary buffer-API-supporting arguments. With unit tests. Modified: python/branches/py3k/Lib/test/test_bytes.py ============================================================================== --- python/branches/py3k/Lib/test/test_bytes.py (original) +++ python/branches/py3k/Lib/test/test_bytes.py Mon Sep 10 18:53:45 2007 @@ -617,16 +617,46 @@ self.assertEqual(b.split(b'i'), [b'm', b'ss', b'ss', b'pp', b'']) self.assertEqual(b.split(b'ss'), [b'mi', b'i', b'ippi']) self.assertEqual(b.split(b'w'), [b]) - # require an arg (no magic whitespace split) - self.assertRaises(TypeError, b.split) + + def test_split_whitespace(self): + for b in (b' arf barf ', b'arf\tbarf', b'arf\nbarf', b'arf\rbarf', + b'arf\fbarf', b'arf\vbarf'): + self.assertEqual(b.split(), [b'arf', b'barf']) + self.assertEqual(b.split(None), [b'arf', b'barf']) + self.assertEqual(b.split(None, 2), [b'arf', b'barf']) + self.assertEqual(b' a bb c '.split(None, 0), [b'a bb c ']) + self.assertEqual(b' a bb c '.split(None, 1), [b'a', b'bb c ']) + self.assertEqual(b' a bb c '.split(None, 2), [b'a', b'bb', b'c ']) + self.assertEqual(b' a bb c '.split(None, 3), [b'a', b'bb', b'c']) + + def test_split_buffer(self): + self.assertEqual(b'a b'.split(buffer(b' ')), [b'a', b'b']) + + def test_split_string_error(self): + self.assertRaises(TypeError, b'a b'.split, ' ') def test_rsplit(self): b = b'mississippi' self.assertEqual(b.rsplit(b'i'), [b'm', b'ss', b'ss', b'pp', b'']) self.assertEqual(b.rsplit(b'ss'), [b'mi', b'i', b'ippi']) self.assertEqual(b.rsplit(b'w'), [b]) - # require an arg (no magic whitespace split) - self.assertRaises(TypeError, b.rsplit) + + def test_rsplit_whitespace(self): + for b in (b' arf barf ', b'arf\tbarf', b'arf\nbarf', b'arf\rbarf', + b'arf\fbarf', b'arf\vbarf'): + self.assertEqual(b.rsplit(), [b'arf', b'barf']) + self.assertEqual(b.rsplit(None), [b'arf', b'barf']) + self.assertEqual(b.rsplit(None, 2), [b'arf', b'barf']) + self.assertEqual(b' a bb c '.rsplit(None, 0), [b' a bb c']) + self.assertEqual(b' a bb c '.rsplit(None, 1), [b' a bb', b'c']) + self.assertEqual(b' a bb c '.rsplit(None,2), [b' a', b'bb', b'c']) + self.assertEqual(b' a bb c '.rsplit(None, 3), [b'a', b'bb', b'c']) + + def test_rplit_buffer(self): + self.assertEqual(b'a b'.rsplit(buffer(b' ')), [b'a', b'b']) + + def test_rplit_string_error(self): + self.assertRaises(TypeError, b'a b'.rsplit, ' ') def test_partition(self): b = b'mississippi' @@ -670,6 +700,22 @@ self.assertEqual(b.rstrip(b'im'), b'mississipp') self.assertEqual(b.rstrip(b'pim'), b'mississ') + def test_strip_whitespace(self): + b = b' \t\n\r\f\vabc \t\n\r\f\v' + self.assertEqual(b.strip(), b'abc') + self.assertEqual(b.lstrip(), b'abc \t\n\r\f\v') + self.assertEqual(b.rstrip(), b' \t\n\r\f\vabc') + + def test_strip_buffer(self): + self.assertEqual(b'abc'.strip(buffer(b'ac')), b'b') + self.assertEqual(b'abc'.lstrip(buffer(b'ac')), b'bc') + self.assertEqual(b'abc'.rstrip(buffer(b'ac')), b'ab') + + def test_strip_string_error(self): + self.assertRaises(TypeError, b'abc'.strip, 'b') + self.assertRaises(TypeError, b'abc'.lstrip, 'b') + self.assertRaises(TypeError, b'abc'.rstrip, 'b') + def test_ord(self): b = b'\0A\x7f\x80\xff' self.assertEqual([ord(b[i:i+1]) for i in range(len(b))], Modified: python/branches/py3k/Objects/bytesobject.c ============================================================================== --- python/branches/py3k/Objects/bytesobject.c (original) +++ python/branches/py3k/Objects/bytesobject.c Mon Sep 10 18:53:45 2007 @@ -2104,7 +2104,7 @@ Py_LOCAL_INLINE(PyObject *) split_char(const char *s, Py_ssize_t len, char ch, Py_ssize_t maxcount) { - register Py_ssize_t i, j, count=0; + register Py_ssize_t i, j, count = 0; PyObject *str; PyObject *list = PyList_New(PREALLOC_SIZE(maxcount)); @@ -2113,7 +2113,7 @@ i = j = 0; while ((j < len) && (maxcount-- > 0)) { - for(; j list of bytes\n\ +"B.split([sep [, maxsplit]]) -> list of bytes\n\ \n\ -Return a list of the bytes in the string B, using sep as the\n\ -delimiter. If maxsplit is given, at most maxsplit\n\ -splits are done."); +Return a list of the bytes in the string B, using sep as the delimiter.\n\ +If sep is not given, B is split on ASCII whitespace charcters\n\ +(space, tab, return, newline, formfeed, vertical tab).\n\ +If maxsplit is given, at most maxsplit splits are done."); static PyObject * bytes_split(PyBytesObject *self, PyObject *args) { Py_ssize_t len = PyBytes_GET_SIZE(self), n, i, j; - Py_ssize_t maxsplit = -1, count=0; + Py_ssize_t maxsplit = -1, count = 0; const char *s = PyBytes_AS_STRING(self), *sub; - PyObject *list, *str, *subobj; + PyObject *list, *str, *subobj = Py_None; + PyBuffer vsub; #ifdef USE_FAST Py_ssize_t pos; #endif - if (!PyArg_ParseTuple(args, "O|n:split", &subobj, &maxsplit)) + if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit)) return NULL; if (maxsplit < 0) maxsplit = PY_SSIZE_T_MAX; - if (PyBytes_Check(subobj)) { - sub = PyBytes_AS_STRING(subobj); - n = PyBytes_GET_SIZE(subobj); - } - /* XXX -> use the modern buffer interface */ - else if (PyObject_AsCharBuffer(subobj, &sub, &n)) + + if (subobj == Py_None) + return split_whitespace(s, len, maxsplit); + + if (_getbuffer(subobj, &vsub) < 0) return NULL; + sub = vsub.buf; + n = vsub.len; if (n == 0) { PyErr_SetString(PyExc_ValueError, "empty separator"); + PyObject_ReleaseBuffer(subobj, &vsub); return NULL; } - else if (n == 1) + if (n == 1) return split_char(s, len, sub[0], maxsplit); list = PyList_New(PREALLOC_SIZE(maxsplit)); - if (list == NULL) + if (list == NULL) { + PyObject_ReleaseBuffer(subobj, &vsub); return NULL; + } #ifdef USE_FAST i = j = 0; @@ -2198,10 +2243,12 @@ #endif SPLIT_ADD(s, i, len); FIX_PREALLOC_SIZE(list); + PyObject_ReleaseBuffer(subobj, &vsub); return list; onError: Py_DECREF(list); + PyObject_ReleaseBuffer(subobj, &vsub); return NULL; } @@ -2293,44 +2340,90 @@ return NULL; } +Py_LOCAL_INLINE(PyObject *) +rsplit_whitespace(const char *s, Py_ssize_t len, Py_ssize_t maxcount) +{ + register Py_ssize_t i, j, count = 0; + PyObject *str; + PyObject *list = PyList_New(PREALLOC_SIZE(maxcount)); + + if (list == NULL) + return NULL; + + for (i = j = len - 1; i >= 0; ) { + /* find a token */ + while (i >= 0 && Py_UNICODE_ISSPACE(s[i])) + i--; + j = i; + while (i >= 0 && !Py_UNICODE_ISSPACE(s[i])) + i--; + if (j > i) { + if (maxcount-- <= 0) + break; + SPLIT_ADD(s, i + 1, j + 1); + while (i >= 0 && Py_UNICODE_ISSPACE(s[i])) + i--; + j = i; + } + } + if (j >= 0) { + SPLIT_ADD(s, 0, j + 1); + } + FIX_PREALLOC_SIZE(list); + if (PyList_Reverse(list) < 0) + goto onError; + + return list; + + onError: + Py_DECREF(list); + return NULL; +} + PyDoc_STRVAR(rsplit__doc__, "B.rsplit(sep [,maxsplit]) -> list of bytes\n\ \n\ -Return a list of the sections in the byte B, using sep as the\n\ -delimiter, starting at the end of the bytes and working\n\ -to the front. If maxsplit is given, at most maxsplit splits are\n\ -done."); +Return a list of the sections in the byte B, using sep as the delimiter,\n\ +starting at the end of the bytes and working to the front.\n\ +If sep is not given, B is split on ASCII whitespace characters\n\ +(space, tab, return, newline, formfeed, vertical tab).\n\ +If maxsplit is given, at most maxsplit splits are done."); static PyObject * bytes_rsplit(PyBytesObject *self, PyObject *args) { Py_ssize_t len = PyBytes_GET_SIZE(self), n, i, j; - Py_ssize_t maxsplit = -1, count=0; + Py_ssize_t maxsplit = -1, count = 0; const char *s = PyBytes_AS_STRING(self), *sub; - PyObject *list, *str, *subobj; + PyObject *list, *str, *subobj = Py_None; + PyBuffer vsub; - if (!PyArg_ParseTuple(args, "O|n:rsplit", &subobj, &maxsplit)) + if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit)) return NULL; if (maxsplit < 0) maxsplit = PY_SSIZE_T_MAX; - if (PyBytes_Check(subobj)) { - sub = PyBytes_AS_STRING(subobj); - n = PyBytes_GET_SIZE(subobj); - } - /* XXX -> Use the modern buffer interface */ - else if (PyObject_AsCharBuffer(subobj, &sub, &n)) + + if (subobj == Py_None) + return rsplit_whitespace(s, len, maxsplit); + + if (_getbuffer(subobj, &vsub) < 0) return NULL; + sub = vsub.buf; + n = vsub.len; if (n == 0) { PyErr_SetString(PyExc_ValueError, "empty separator"); + PyObject_ReleaseBuffer(subobj, &vsub); return NULL; } else if (n == 1) return rsplit_char(s, len, sub[0], maxsplit); list = PyList_New(PREALLOC_SIZE(maxsplit)); - if (list == NULL) + if (list == NULL) { + PyObject_ReleaseBuffer(subobj, &vsub); return NULL; + } j = len; i = j - n; @@ -2349,10 +2442,12 @@ FIX_PREALLOC_SIZE(list); if (PyList_Reverse(list) < 0) goto onError; + PyObject_ReleaseBuffer(subobj, &vsub); return list; onError: Py_DECREF(list); + PyObject_ReleaseBuffer(subobj, &vsub); return NULL; } @@ -2542,71 +2637,104 @@ } PyDoc_STRVAR(strip__doc__, -"B.strip(bytes) -> bytes\n\ +"B.strip([bytes]) -> bytes\n\ \n\ -Strip leading and trailing bytes contained in the argument."); +Strip leading and trailing bytes contained in the argument.\n\ +If the argument is omitted, strip ASCII whitespace."); static PyObject * -bytes_strip(PyBytesObject *self, PyObject *arg) +bytes_strip(PyBytesObject *self, PyObject *args) { Py_ssize_t left, right, mysize, argsize; void *myptr, *argptr; - if (arg == NULL || !PyBytes_Check(arg)) { - PyErr_SetString(PyExc_TypeError, "strip() requires a bytes argument"); - return NULL; + PyObject *arg = Py_None; + PyBuffer varg; + if (!PyArg_ParseTuple(args, "|O:strip", &arg)) + return NULL; + if (arg == Py_None) { + argptr = "\t\n\r\f\v "; + argsize = 6; + } + else { + if (_getbuffer(arg, &varg) < 0) + return NULL; + argptr = varg.buf; + argsize = varg.len; } myptr = self->ob_bytes; mysize = Py_Size(self); - argptr = ((PyBytesObject *)arg)->ob_bytes; - argsize = Py_Size(arg); left = lstrip_helper(myptr, mysize, argptr, argsize); if (left == mysize) right = left; else right = rstrip_helper(myptr, mysize, argptr, argsize); + if (arg != Py_None) + PyObject_ReleaseBuffer(arg, &varg); return PyBytes_FromStringAndSize(self->ob_bytes + left, right - left); } PyDoc_STRVAR(lstrip__doc__, -"B.lstrip(bytes) -> bytes\n\ +"B.lstrip([bytes]) -> bytes\n\ \n\ -Strip leading bytes contained in the argument."); +Strip leading bytes contained in the argument.\n\ +If the argument is omitted, strip leading ASCII whitespace."); static PyObject * -bytes_lstrip(PyBytesObject *self, PyObject *arg) +bytes_lstrip(PyBytesObject *self, PyObject *args) { Py_ssize_t left, right, mysize, argsize; void *myptr, *argptr; - if (arg == NULL || !PyBytes_Check(arg)) { - PyErr_SetString(PyExc_TypeError, "strip() requires a bytes argument"); - return NULL; + PyObject *arg = Py_None; + PyBuffer varg; + if (!PyArg_ParseTuple(args, "|O:lstrip", &arg)) + return NULL; + if (arg == Py_None) { + argptr = "\t\n\r\f\v "; + argsize = 6; + } + else { + if (_getbuffer(arg, &varg) < 0) + return NULL; + argptr = varg.buf; + argsize = varg.len; } myptr = self->ob_bytes; mysize = Py_Size(self); - argptr = ((PyBytesObject *)arg)->ob_bytes; - argsize = Py_Size(arg); left = lstrip_helper(myptr, mysize, argptr, argsize); right = mysize; + if (arg != Py_None) + PyObject_ReleaseBuffer(arg, &varg); return PyBytes_FromStringAndSize(self->ob_bytes + left, right - left); } PyDoc_STRVAR(rstrip__doc__, -"B.rstrip(bytes) -> bytes\n\ +"B.rstrip([bytes]) -> bytes\n\ \n\ -Strip trailing bytes contained in the argument."); +Strip trailing bytes contained in the argument.\n\ +If the argument is omitted, strip trailing ASCII whitespace."); static PyObject * -bytes_rstrip(PyBytesObject *self, PyObject *arg) +bytes_rstrip(PyBytesObject *self, PyObject *args) { Py_ssize_t left, right, mysize, argsize; void *myptr, *argptr; - if (arg == NULL || !PyBytes_Check(arg)) { - PyErr_SetString(PyExc_TypeError, "strip() requires a bytes argument"); - return NULL; + PyObject *arg = Py_None; + PyBuffer varg; + if (!PyArg_ParseTuple(args, "|O:rstrip", &arg)) + return NULL; + if (arg == Py_None) { + argptr = "\t\n\r\f\v "; + argsize = 6; + } + else { + if (_getbuffer(arg, &varg) < 0) + return NULL; + argptr = varg.buf; + argsize = varg.len; } myptr = self->ob_bytes; mysize = Py_Size(self); - argptr = ((PyBytesObject *)arg)->ob_bytes; - argsize = Py_Size(arg); left = 0; right = rstrip_helper(myptr, mysize, argptr, argsize); + if (arg != Py_None) + PyObject_ReleaseBuffer(arg, &varg); return PyBytes_FromStringAndSize(self->ob_bytes + left, right - left); } @@ -2839,9 +2967,9 @@ {"reverse", (PyCFunction)bytes_reverse, METH_NOARGS, reverse__doc__}, {"pop", (PyCFunction)bytes_pop, METH_VARARGS, pop__doc__}, {"remove", (PyCFunction)bytes_remove, METH_O, remove__doc__}, - {"strip", (PyCFunction)bytes_strip, METH_O, strip__doc__}, - {"lstrip", (PyCFunction)bytes_lstrip, METH_O, lstrip__doc__}, - {"rstrip", (PyCFunction)bytes_rstrip, METH_O, rstrip__doc__}, + {"strip", (PyCFunction)bytes_strip, METH_VARARGS, strip__doc__}, + {"lstrip", (PyCFunction)bytes_lstrip, METH_VARARGS, lstrip__doc__}, + {"rstrip", (PyCFunction)bytes_rstrip, METH_VARARGS, rstrip__doc__}, {"decode", (PyCFunction)bytes_decode, METH_VARARGS, decode_doc}, {"__alloc__", (PyCFunction)bytes_alloc, METH_NOARGS, alloc_doc}, {"fromhex", (PyCFunction)bytes_fromhex, METH_VARARGS|METH_CLASS, From mike.klaas at gmail.com Mon Sep 10 18:58:49 2007 From: mike.klaas at gmail.com (Mike Klaas) Date: Mon, 10 Sep 2007 09:58:49 -0700 Subject: [Python-3000-checkins] [Python-3000] r58068 - in python/branches/py3k: Doc/library/exceptions.rst Doc/library/socket.rst Doc/whatsnew/2.6.rst Lib/test/test_urllib2net.py Lib/urllib2.py Modules/socketmodule.c In-Reply-To: <9e804ac0709100833t10461267l346a4ebfeabcaedf@mail.gmail.com> References: <20070909235556.04BA71E400F@bag.python.org> <9e804ac0709100833t10461267l346a4ebfeabcaedf@mail.gmail.com> Message-ID: <1DF55068-6E1E-45E7-8CC6-4C10EF097A62@gmail.com> On 10-Sep-07, at 8:33 AM, Thomas Wouters wrote: > Alternatively, if you know what you're doing, you can edit the > svnmerge-integrated property on the branch directly -- but don't > mess it up :) > svnmerge also has a handy -M flag that marks a (set of) revisions as merged, but doesn't actually do any merging. -Mike From python-3000-checkins at python.org Mon Sep 10 21:32:14 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Mon, 10 Sep 2007 21:32:14 +0200 (CEST) Subject: [Python-3000-checkins] r58094 - in python/branches/py3k: Doc/Makefile Lib/test/test_pipes.py Makefile.pre.in Tools/buildbot/buildmsi.bat Tools/msi/msi.py Message-ID: <20070910193214.B67AE1E400C@bag.python.org> Author: thomas.wouters Date: Mon Sep 10 21:32:14 2007 New Revision: 58094 Added: python/branches/py3k/Tools/buildbot/buildmsi.bat - copied unchanged from r58090, python/trunk/Tools/buildbot/buildmsi.bat Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/Makefile python/branches/py3k/Lib/test/test_pipes.py python/branches/py3k/Makefile.pre.in python/branches/py3k/Tools/msi/msi.py Log: Merged revisions 58053-58090 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r58061 | ronald.oussoren | 2007-09-09 13:13:42 +0200 (Sun, 09 Sep 2007) | 12 lines Newer autoconf versions (from 2.60) want a 'datarootdir' definition in (Make-)files that use mandir (and other data directory macros). This patch solves a warning during configure, specifically: ... config.status: creating Makefile.pre config.status: WARNING: ../Makefile.pre.in seems to ignore the --datarootdir setting ... See also: ........ r58064 | gregory.p.smith | 2007-09-09 22:25:00 +0200 (Sun, 09 Sep 2007) | 2 lines email address update ........ r58067 | gregory.p.smith | 2007-09-10 01:36:46 +0200 (Mon, 10 Sep 2007) | 22 lines Change socket.error to inherit from IOError rather than being a stand alone class. This addresses the primary concern in http://bugs.python.org/issue1706815 python-dev discussion here: http://mail.python.org/pipermail/python-dev/2007-July/073749.html I chose IOError rather than EnvironmentError as the base class since socket objects are often used as transparent duck typed file objects in code already prepared to deal with IOError exceptions. also a minor fix: urllib2 - fix a couple places where IOError was raised rather than URLError. for better or worse, URLError already inherits from IOError so this won't break any existing code. test_urllib2net - replace bad ftp urls. ........ r58084 | martin.v.loewis | 2007-09-10 08:18:32 +0200 (Mon, 10 Sep 2007) | 3 lines tr a-z A-Z does not work on Solaris (would require /usr/xpg4/bin/tr); make the character ranges explicit. ........ r58086 | martin.v.loewis | 2007-09-10 12:21:22 +0200 (Mon, 10 Sep 2007) | 1 line Take chm file from build/htmlhelp/pydoc.chm. ........ r58087 | martin.v.loewis | 2007-09-10 12:22:05 +0200 (Mon, 10 Sep 2007) | 1 line Beginnings of a "build MSI" step. ........ r58088 | martin.v.loewis | 2007-09-10 15:19:10 +0200 (Mon, 10 Sep 2007) | 1 line Allow making update with no prior checkout. ........ r58089 | martin.v.loewis | 2007-09-10 15:20:03 +0200 (Mon, 10 Sep 2007) | 1 line Update before making htmlhelp. ........ r58090 | martin.v.loewis | 2007-09-10 15:30:38 +0200 (Mon, 10 Sep 2007) | 1 line Require that bash.exe is on the path, along with the rest of Cygwin. ........ Modified: python/branches/py3k/Doc/Makefile ============================================================================== --- python/branches/py3k/Doc/Makefile (original) +++ python/branches/py3k/Doc/Makefile Mon Sep 10 21:32:14 2007 @@ -32,7 +32,7 @@ svn checkout $(SVNROOT)/external/Pygments-0.8.1/pygments tools/pygments; \ fi -update: +update: checkout svn update tools/sphinx svn update tools/docutils svn update tools/pygments Modified: python/branches/py3k/Lib/test/test_pipes.py ============================================================================== --- python/branches/py3k/Lib/test/test_pipes.py (original) +++ python/branches/py3k/Lib/test/test_pipes.py Mon Sep 10 21:32:14 2007 @@ -9,6 +9,9 @@ TESTFN2 = TESTFN + "2" +# tr a-z A-Z is not portable, so make the ranges explicit +s_command = 'tr %s %s' % (string.ascii_lowercase, string.ascii_uppercase) + class SimplePipeTests(unittest.TestCase): def tearDown(self): for f in (TESTFN, TESTFN2): @@ -16,7 +19,7 @@ def testSimplePipe1(self): t = pipes.Template() - t.append('tr a-z A-Z', pipes.STDIN_STDOUT) + t.append(s_command, pipes.STDIN_STDOUT) f = t.open(TESTFN, 'w') f.write('hello world #1') f.close() @@ -25,14 +28,14 @@ def testSimplePipe2(self): open(TESTFN, 'w').write('hello world #2') t = pipes.Template() - t.append('tr a-z A-Z < $IN > $OUT', pipes.FILEIN_FILEOUT) + t.append(s_command + ' < $IN > $OUT', pipes.FILEIN_FILEOUT) t.copy(TESTFN, TESTFN2) self.assertEqual(open(TESTFN2).read(), 'HELLO WORLD #2') def testSimplePipe3(self): open(TESTFN, 'w').write('hello world #2') t = pipes.Template() - t.append('tr a-z A-Z < $IN', pipes.FILEIN_STDOUT) + t.append(s_command + ' < $IN', pipes.FILEIN_STDOUT) self.assertEqual(t.open(TESTFN, 'r').read(), 'HELLO WORLD #2') def testEmptyPipeline1(self): Modified: python/branches/py3k/Makefile.pre.in ============================================================================== --- python/branches/py3k/Makefile.pre.in (original) +++ python/branches/py3k/Makefile.pre.in Mon Sep 10 21:32:14 2007 @@ -82,6 +82,9 @@ # Install prefix for architecture-dependent files exec_prefix= @exec_prefix@ +# Install prefix for data files +datarootdir= @datarootdir@ + # Expanded directories BINDIR= $(exec_prefix)/bin LIBDIR= $(exec_prefix)/lib Modified: python/branches/py3k/Tools/msi/msi.py ============================================================================== --- python/branches/py3k/Tools/msi/msi.py (original) +++ python/branches/py3k/Tools/msi/msi.py Mon Sep 10 21:32:14 2007 @@ -1049,7 +1049,7 @@ htmlfiles.set_current() lib = PyDirectory(db, cab, root, "Doc", "Doc", "DOC|Doc") lib.start_component("documentation", keyfile="Python%s%s.chm" % (major,minor)) - lib.add_file("Python%s%s.chm" % (major, minor)) + lib.add_file("Python%s%s.chm" % (major, minor), src="build/htmlhelp/pydoc.chm") cab.commit(db) From python-3000-checkins at python.org Mon Sep 10 21:33:14 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Mon, 10 Sep 2007 21:33:14 +0200 (CEST) Subject: [Python-3000-checkins] r58095 - python/branches/py3k Message-ID: <20070910193314.F128C1E4002@bag.python.org> Author: thomas.wouters Date: Mon Sep 10 21:33:14 2007 New Revision: 58095 Modified: python/branches/py3k/ (props changed) Log: Merged revisions 58091-58094 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r58091 | gregory.p.smith | 2007-09-10 18:36:32 +0200 (Mon, 10 Sep 2007) | 3 lines Don't allow BerkeleyDB 4.6.x as the current 4.6.19 release is prone to lockups. We'll reenable it once a good 4.6.x release exists. ........ From python-3000-checkins at python.org Tue Sep 11 20:06:02 2007 From: python-3000-checkins at python.org (eric.smith) Date: Tue, 11 Sep 2007 20:06:02 +0200 (CEST) Subject: [Python-3000-checkins] r58105 - in python/branches/py3k: Lib/test/test_datetime.py Modules/datetimemodule.c Message-ID: <20070911180602.AD7531E4004@bag.python.org> Author: eric.smith Date: Tue Sep 11 20:06:02 2007 New Revision: 58105 Modified: python/branches/py3k/Lib/test/test_datetime.py python/branches/py3k/Modules/datetimemodule.c Log: Added __format__ method to datetime.datetime, datetime.date, and datetime.time. If format_spec is empty, __format__ calls str(self), else it calls self.strftime(format_spec). Modified: python/branches/py3k/Lib/test/test_datetime.py ============================================================================== --- python/branches/py3k/Lib/test/test_datetime.py (original) +++ python/branches/py3k/Lib/test/test_datetime.py Tue Sep 11 20:06:02 2007 @@ -849,6 +849,32 @@ # A naive object replaces %z and %Z w/ empty strings. self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''") + def test_format(self): + dt = self.theclass(2007, 9, 10) + self.assertEqual(format(dt, ''), str(dt)) + + # check that a derived class's __str__() gets called + class A(self.theclass): + def __str__(self): + return 'A' + a = A(2007, 9, 10) + self.assertEqual(format(a, ''), 'A') + + # check that a derived class's strftime gets called + class B(self.theclass): + def strftime(self, format_spec): + return 'B' + b = B(2007, 9, 10) + self.assertEqual(format(b, ''), str(dt)) + + for fmt in ["m:%m d:%d y:%y", + "m:%m d:%d y:%y H:%H M:%M S:%S", + "%z %Z", + ]: + self.assertEqual(format(dt, fmt), dt.strftime(fmt)) + self.assertEqual(format(a, fmt), dt.strftime(fmt)) + self.assertEqual(format(b, fmt), 'B') + def test_resolution_info(self): self.assert_(isinstance(self.theclass.min, self.theclass)) self.assert_(isinstance(self.theclass.max, self.theclass)) @@ -1150,6 +1176,34 @@ # str is ISO format with the separator forced to a blank. self.assertEqual(str(t), "0002-03-02 00:00:00") + def test_format(self): + dt = self.theclass(2007, 9, 10, 4, 5, 1, 123) + self.assertEqual(format(dt, ''), str(dt)) + + # check that a derived class's __str__() gets called + class A(self.theclass): + def __str__(self): + return 'A' + a = A(2007, 9, 10, 4, 5, 1, 123) + self.assertEqual(format(a, ''), 'A') + + # check that a derived class's strftime gets called + class B(self.theclass): + def strftime(self, format_spec): + return 'B' + b = B(2007, 9, 10, 4, 5, 1, 123) + self.assertEqual(format(b, ''), str(dt)) + + for fmt in ["m:%m d:%d y:%y", + "m:%m d:%d y:%y H:%H M:%M S:%S", + "%z %Z", + ]: + self.assertEqual(format(dt, fmt), dt.strftime(fmt)) + self.assertEqual(format(a, fmt), dt.strftime(fmt)) + self.assertEqual(format(b, fmt), 'B') + + + def test_more_ctime(self): # Test fields that TestDate doesn't touch. import time @@ -1781,6 +1835,30 @@ # A naive object replaces %z and %Z with empty strings. self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''") + def test_format(self): + t = self.theclass(1, 2, 3, 4) + self.assertEqual(format(t, ''), str(t)) + + # check that a derived class's __str__() gets called + class A(self.theclass): + def __str__(self): + return 'A' + a = A(1, 2, 3, 4) + self.assertEqual(format(a, ''), 'A') + + # check that a derived class's strftime gets called + class B(self.theclass): + def strftime(self, format_spec): + return 'B' + b = B(1, 2, 3, 4) + self.assertEqual(format(b, ''), str(t)) + + for fmt in ['%H %M %S', + ]: + self.assertEqual(format(t, fmt), t.strftime(fmt)) + self.assertEqual(format(a, fmt), t.strftime(fmt)) + self.assertEqual(format(b, fmt), 'B') + def test_str(self): self.assertEqual(str(self.theclass(1, 2, 3, 4)), "01:02:03.000004") self.assertEqual(str(self.theclass(10, 2, 3, 4000)), "10:02:03.004000") Modified: python/branches/py3k/Modules/datetimemodule.c ============================================================================== --- python/branches/py3k/Modules/datetimemodule.c (original) +++ python/branches/py3k/Modules/datetimemodule.c Tue Sep 11 20:06:02 2007 @@ -2440,6 +2440,21 @@ return result; } +static PyObject * +date_format(PyDateTime_Date *self, PyObject *args) +{ + PyObject *format; + + if (!PyArg_ParseTuple(args, "U:__format__", &format)) + return NULL; + + /* if the format is zero length, return str(self) */ + if (PyUnicode_GetSize(format) == 0) + return PyObject_Unicode((PyObject *)self); + + return PyObject_CallMethod((PyObject *)self, "strftime", "O", format); +} + /* ISO methods. */ static PyObject * @@ -2610,6 +2625,9 @@ {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS, PyDoc_STR("format -> strftime() style string.")}, + {"__format__", (PyCFunction)date_format, METH_VARARGS, + PyDoc_STR("Formats self with strftime.")}, + {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, PyDoc_STR("Return time tuple, compatible with time.localtime().")}, @@ -3198,6 +3216,21 @@ return result; } +static PyObject * +time_format(PyDateTime_Time *self, PyObject *args) +{ + PyObject *format; + + if (!PyArg_ParseTuple(args, "U:__format__", &format)) + return NULL; + + /* if the format is zero length, return str(self) */ + if (PyUnicode_GetSize(format) == 0) + return PyObject_Unicode((PyObject *)self); + + return PyObject_CallMethod((PyObject *)self, "strftime", "O", format); +} + /* * Miscellaneous methods. */ @@ -3385,6 +3418,9 @@ {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS, PyDoc_STR("format -> strftime() style string.")}, + {"__format__", (PyCFunction)time_format, METH_VARARGS, + PyDoc_STR("Formats self with strftime.")}, + {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS, PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, From python-3000-checkins at python.org Tue Sep 11 22:42:31 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 11 Sep 2007 22:42:31 +0200 (CEST) Subject: [Python-3000-checkins] r58107 - in python/branches/py3k/Lib: abc.py test/test_abc.py Message-ID: <20070911204231.0FFEF1E401D@bag.python.org> Author: guido.van.rossum Date: Tue Sep 11 22:42:30 2007 New Revision: 58107 Modified: python/branches/py3k/Lib/abc.py python/branches/py3k/Lib/test/test_abc.py Log: Thomas Wouters pointed out that _Abstract.__new__ should use super().__new__() instead of going straight to object.__new__(). Modified: python/branches/py3k/Lib/abc.py ============================================================================== --- python/branches/py3k/Lib/abc.py (original) +++ python/branches/py3k/Lib/abc.py Tue Sep 11 22:42:30 2007 @@ -56,8 +56,6 @@ """Helper class inserted into the bases by ABCMeta (using _fix_bases()). You should never need to explicitly subclass this class. - - There should never be a base class between _Abstract and object. """ def __new__(cls, *args, **kwds): @@ -69,7 +67,7 @@ if (args or kwds) and cls.__init__ is object.__init__: raise TypeError("Can't pass arguments to __new__ " "without overriding __init__") - return object.__new__(cls) + return super().__new__(cls) @classmethod def __subclasshook__(cls, subclass): Modified: python/branches/py3k/Lib/test/test_abc.py ============================================================================== --- python/branches/py3k/Lib/test/test_abc.py (original) +++ python/branches/py3k/Lib/test/test_abc.py Tue Sep 11 22:42:30 2007 @@ -130,6 +130,20 @@ self.failUnless(issubclass(MyInt, A)) self.failUnless(isinstance(42, A)) + def test_all_new_methods_are_called(self): + class A(metaclass=abc.ABCMeta): + pass + class B: + counter = 0 + def __new__(cls): + B.counter += 1 + return super().__new__(cls) + class C(A, B): + pass + self.assertEqual(B.counter, 0) + C() + self.assertEqual(B.counter, 1) + def test_main(): test_support.run_unittest(TestABC) From python-3000-checkins at python.org Wed Sep 12 20:04:37 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 12 Sep 2007 20:04:37 +0200 (CEST) Subject: [Python-3000-checkins] r58113 - python/branches/py3k/Doc/library/bdb.rst python/branches/py3k/Doc/library/debug.rst python/branches/py3k/Doc/library/index.rst python/branches/py3k/Doc/library/pdb.rst Message-ID: <20070912180437.EC42B1E4005@bag.python.org> Author: georg.brandl Date: Wed Sep 12 20:04:37 2007 New Revision: 58113 Added: python/branches/py3k/Doc/library/bdb.rst python/branches/py3k/Doc/library/debug.rst Modified: python/branches/py3k/Doc/library/index.rst python/branches/py3k/Doc/library/pdb.rst Log: New documentation for the bdb module. Forward-port from rev. 58112, with a few 3k-specific changes. Added: python/branches/py3k/Doc/library/bdb.rst ============================================================================== --- (empty file) +++ python/branches/py3k/Doc/library/bdb.rst Wed Sep 12 20:04:37 2007 @@ -0,0 +1,337 @@ +:mod:`bdb` --- Debugger framework +================================= + +.. module:: bdb + :synopsis: Debugger framework. + +The :mod:`bdb` module handles basic debugger functions, like setting breakpoints +or managing execution via the debugger. + +The following exception is defined: + +.. exception:: BdbQuit + + Exception raised by the :class:`Bdb` class for quitting the debugger. + + +The :mod:`bdb` module also defines two classes: + +.. class:: Breakpoint(self, file, line[, temporary=0[, cond=None [, funcname=None]]]) + + This class implements temporary breakpoints, ignore counts, disabling and + (re-)enabling, and conditionals. + + Breakpoints are indexed by number through a list called :attr:`bpbynumber` + and by ``(file, line)`` pairs through :attr:`bplist`. The former points to a + single instance of class :class:`Breakpoint`. The latter points to a list of + such instances since there may be more than one breakpoint per line. + + When creating a breakpoint, its associated filename should be in canonical + form. If a *funcname* is defined, a breakpoint hit will be counted when the + first line of that function is executed. A conditional breakpoint always + counts a hit. + +:class:`Breakpoint` instances have the following methods: + +.. method:: Breakpoint.deleteMe() + + Delete the breakpoint from the list associated to a file/line. If it is the + last breakpoint in that position, it also deletes the entry for the + file/line. + +.. method:: Breakpoint.enable() + + Mark the breakpoint as enabled. + +.. method:: Breakpoint.disable() + + Mark the breakpoint as disabled. + +.. method:: Breakpoint.bpprint([out]) + + Print all the information about the breakpoint: + + * The breakpoint number. + * If it is temporary or not. + * Its file,line position. + * The condition that causes a break. + * If it must be ignored the next N times. + * The breakpoint hit count. + + +.. class:: Bdb() + + The :class:`Bdb` acts as a generic Python debugger base class. + + This class takes care of the details of the trace facility; a derived class + should implement user interaction. The standard debugger class + (:class:`pdb.Pdb`) is an example. + + +The following methods of :class:`Bdb` normally don't need to be overridden. + +.. method:: Bdb.canonic(filename) + + Auxiliary method for getting a filename in a canonical form, that is, as a + case-normalized (on case-insensitive filesystems) absolute path, stripped + of surrounding angle brackets. + +.. method:: Bdb.reset() + + Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and + :attr:`quitting` attributes with values ready to start debugging. + + +.. method:: Bdb.trace_dispatch(frame, event, arg) + + This function is installed as the trace function of debugged frames. Its + return value is the new trace function (in most cases, that is, itself). + + The default implementation decides how to dispatch a frame, depending on the + type of event (passed as a string) that is about to be executed. *event* can + be one of the following: + + * ``"line"``: A new line of code is going to be executed. + * ``"call"``: A function is about to be called, or another code block + entered. + * ``"return"``: A function or other code block is about to return. + * ``"exception"``: An exception has occurred. + * ``"c_call"``: A C function is about to be called. + * ``"c_return"``: A C function has returned. + * ``"c_exception"``: A C function has thrown an exception. + + For the Python events, specialized functions (see below) are called. For the + C events, no action is taken. + + The *arg* parameter depends on the previous event. + + For more information on trace functions, see :ref:`debugger-hooks`. For more + information on code and frame objects, refer to :ref:`types`. + +.. method:: Bdb.dispatch_line(frame) + + If the debugger should stop on the current line, invoke the :meth:`user_line` + method (which should be overridden in subclasses). Raise a :exc:`BdbQuit` + exception if the :attr:`Bdb.quitting` flag is set (which can be set from + :meth:`user_line`). Return a reference to the :meth:`trace_dispatch` method + for further tracing in that scope. + +.. method:: Bdb.dispatch_call(frame, arg) + + If the debugger should stop on this function call, invoke the + :meth:`user_call` method (which should be overridden in subclasses). Raise a + :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set (which can + be set from :meth:`user_call`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. + +.. method:: Bdb.dispatch_return(frame, arg) + + If the debugger should stop on this function return, invoke the + :meth:`user_return` method (which should be overridden in subclasses). Raise + a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set (which can + be set from :meth:`user_return`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. + +.. method:: Bdb.dispatch_exception(frame, arg) + + If the debugger should stop at this exception, invokes the + :meth:`user_exception` method (which should be overridden in subclasses). + Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set + (which can be set from :meth:`user_exception`). Return a reference to the + :meth:`trace_dispatch` method for further tracing in that scope. + +Normally derived classes don't override the following methods, but they may if +they want to redefine the definition of stopping and breakpoints. + +.. method:: Bdb.stop_here(frame) + + This method checks if the *frame* is somewhere below :attr:`botframe` in the + call stack. :attr:`botframe` is the frame in which debugging started. + +.. method:: Bdb.break_here(frame) + + This method checks if there is a breakpoint in the filename and line + belonging to *frame* or, at least, in the current function. If the + breakpoint is a temporary one, this method deletes it. + +.. method:: Bdb.break_anywhere(frame) + + This method checks if there is a breakpoint in the filename of the current + frame. + +Derived classes should override these methods to gain control over debugger +operation. + +.. method:: Bdb.user_call(frame, argument_list) + + This method is called from :meth:`dispatch_call` when there is the + possibility that a break might be necessary anywhere inside the called + function. + +.. method:: Bdb.user_line(frame) + + This method is called from :meth:`dispatch_line` when either + :meth:`stop_here` or :meth:`break_here` yields True. + +.. method:: Bdb.user_return(frame, return_value) + + This method is called from :meth:`dispatch_return` when :meth:`stop_here` + yields True. + +.. method:: Bdb.user_exception(frame, exc_info) + + This method is called from :meth:`dispatch_exception` when :meth:`stop_here` + yields True. + +.. method:: Bdb.do_clear(arg) + + Handle how a breakpoint must be removed when it is a temporary one. + + This method must be implemented by derived classes. + + +Derived classes and clients can call the following methods to affect the +stepping state. + +.. method:: Bdb.set_step() + + Stop after one line of code. + +.. method:: Bdb.set_next(frame) + + Stop on the next line in or below the given frame. + +.. method:: Bdb.set_return(frame) + + Stop when returning from the given frame. + +.. method:: Bdb.set_trace([frame]) + + Start debugging from *frame*. If *frame* is not specified, debugging starts + from caller's frame. + +.. method:: Bdb.set_continue() + + Stop only at breakpoints or when finished. If there are no breakpoints, set + the system trace function to None. + +.. method:: Bdb.set_quit() + + Set the :attr:`quitting` attribute to True. This raises :exc:`BdbQuit` in + the next call to one of the :meth:`dispatch_\*` methods. + + +Derived classes and clients can call the following methods to manipulate +breakpoints. These methods return a string containing an error message if +something went wrong, or ``None`` if all is well. + +.. method:: Bdb.set_break(filename, lineno[, temporary=0[, cond[, funcname]]]) + + Set a new breakpoint. If the *lineno* line doesn't exist for the *filename* + passed as argument, return an error message. The *filename* should be in + canonical form, as described in the :meth:`canonic` method. + +.. method:: Bdb.clear_break(filename, lineno) + + Delete the breakpoints in *filename* and *lineno*. If none were set, an + error message is returned. + +.. method:: Bdb.clear_bpbynumber(arg) + + Delete the breakpoint which has the index *arg* in the + :attr:`Breakpoint.bpbynumber`. If `arg` is not numeric or out of range, + return an error message. + +.. method:: Bdb.clear_all_file_breaks(filename) + + Delete all breakpoints in *filename*. If none were set, an error message is + returned. + +.. method:: Bdb.clear_all_breaks() + + Delete all existing breakpoints. + +.. method:: Bdb.get_break(filename, lineno) + + Check if there is a breakpoint for *lineno* of *filename*. + +.. method:: Bdb.get_breaks(filename, lineno) + + Return all breakpoints for *lineno* in *filename*, or an empty list if none + are set. + +.. method:: Bdb.get_file_breaks(filename) + + Return all breakpoints in *filename*, or an empty list if none are set. + +.. method:: Bdb.get_all_breaks() + + Return all breakpoints that are set. + + +Derived classes and clients can call the following methods to get a data +structure representing a stack trace. + +.. method:: Bdb.get_stack(f, t) + + Get a list of records for a frame and all higher (calling) and lower frames, + and the size of the higher part. + +.. method:: Bdb.format_stack_entry(frame_lineno, [lprefix=': ']) + + Return a string with information about a stack entry, identified by a + ``(frame, lineno)`` tuple: + + * The canonical form of the filename which contains the frame. + * The function name, or ``""``. + * The input arguments. + * The return value. + * The line of code (if it exists). + + +The following two methods can be called by clients to use a debugger to debug a +statement, given as a string. + +.. method:: Bdb.run(cmd, [globals, [locals]]) + + Debug a statement executed via the :func:`exec` function. *globals* + defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*. + +.. method:: Bdb.runeval(expr, [globals, [locals]]) + + Debug an expression executed via the :func:`eval` function. *globals* and + *locals* have the same meaning as in :meth:`run`. + +.. method:: Bdb.runctx(cmd, globals, locals) + + For backwards compatibility. Calls the :meth:`run` method. + +.. method:: Bdb.runcall(func, *args, **kwds) + + Debug a single function call, and return its result. + + +Finally, the module defines the following functions: + +.. function:: checkfuncname(b, frame) + + Check whether we should break here, depending on the way the breakpoint *b* + was set. + + If it was set via line number, it checks if ``b.line`` is the same as the one + in the frame also passed as argument. If the breakpoint was set via function + name, we have to check we are in the right frame (the right function) and if + we are in its first executable line. + +.. function:: effective(file, line, frame) + + Determine if there is an effective (active) breakpoint at this line of code. + Return breakpoint number or 0 if none. + + Called only if we know there is a breakpoint at this location. Returns the + breakpoint that was triggered and a flag that indicates if it is ok to delete + a temporary breakpoint. + +.. function:: set_trace() + + Starts debugging with a :class:`Bdb` instance from caller's frame. Added: python/branches/py3k/Doc/library/debug.rst ============================================================================== --- (empty file) +++ python/branches/py3k/Doc/library/debug.rst Wed Sep 12 20:04:37 2007 @@ -0,0 +1,17 @@ +*********************** +Debugging and Profiling +*********************** + +These libraries help you with Python development: the debugger enables you to +step through code, analyze stack frames and set breakpoints etc., and the +profilers run code and give you a detailed breakdown of execution times, +allowing you to identify bottlenecks in your programs. + +.. toctree:: + + bdb.rst + pdb.rst + profile.rst + hotshot.rst + timeit.rst + trace.rst \ No newline at end of file Modified: python/branches/py3k/Doc/library/index.rst ============================================================================== --- python/branches/py3k/Doc/library/index.rst (original) +++ python/branches/py3k/Doc/library/index.rst Wed Sep 12 20:04:37 2007 @@ -64,11 +64,7 @@ frameworks.rst tk.rst development.rst - pdb.rst - profile.rst - hotshot.rst - timeit.rst - trace.rst + debug.rst python.rst custominterp.rst modules.rst Modified: python/branches/py3k/Doc/library/pdb.rst ============================================================================== --- python/branches/py3k/Doc/library/pdb.rst (original) +++ python/branches/py3k/Doc/library/pdb.rst Wed Sep 12 20:04:37 2007 @@ -1,9 +1,8 @@ .. _debugger: -******************* -The Python Debugger -******************* +:mod:`pdb` --- The Python Debugger +================================== .. module:: pdb :synopsis: The Python debugger for interactive interpreters. From python-3000-checkins at python.org Wed Sep 12 21:04:22 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 12 Sep 2007 21:04:22 +0200 (CEST) Subject: [Python-3000-checkins] r58124 - python/branches/py3k/Doc/library/inspect.rst Message-ID: <20070912190422.31F6F1E4005@bag.python.org> Author: georg.brandl Date: Wed Sep 12 21:04:21 2007 New Revision: 58124 Modified: python/branches/py3k/Doc/library/inspect.rst Log: Document inspect.getfullargspec(). Fixes #1121. Modified: python/branches/py3k/Doc/library/inspect.rst ============================================================================== --- python/branches/py3k/Doc/library/inspect.rst (original) +++ python/branches/py3k/Doc/library/inspect.rst Wed Sep 12 21:04:21 2007 @@ -376,10 +376,31 @@ Get the names and default values of a function's arguments. A tuple of four things is returned: ``(args, varargs, varkw, defaults)``. *args* is a list of - the argument names (it may contain nested lists). *varargs* and *varkw* are the - names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a tuple of - default argument values or None if there are no default arguments; if this tuple - has *n* elements, they correspond to the last *n* elements listed in *args*. + the argument names. *varargs* and *varkw* are the names of the ``*`` and + ``**`` arguments or ``None``. *defaults* is a tuple of default argument + values or None if there are no default arguments; if this tuple has *n* + elements, they correspond to the last *n* elements listed in *args*. + + .. deprecated:: 3.0 + Use :func:`getfullargspec` instead, which provides information about + keyword-only arguments. + + +.. function:: getfullargspec(func) + + Get the names and default values of a function's arguments. A tuple of seven + things is returned: + + ``(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations)`` + + *args* is a list of the argument names. *varargs* and *varkw* are the names + of the ``*`` and ``**`` arguments or ``None``. *defaults* is an n-tuple of + the default values of the last n arguments. *kwonlyargs* is a list of + keyword-only argument names. *kwonlydefaults* is a dictionary mapping names + from kwonlyargs to defaults. *annotations* is a dictionary mapping argument + names to annotations. + + The first four items in the tuple correspond to :func:`getargspec`. .. function:: getargvalues(frame) From python-3000-checkins at python.org Wed Sep 12 21:43:09 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 12 Sep 2007 21:43:09 +0200 (CEST) Subject: [Python-3000-checkins] r58126 - in python/branches/py3k/Lib: httplib.py test/test_httplib.py Message-ID: <20070912194310.01ED21E4005@bag.python.org> Author: guido.van.rossum Date: Wed Sep 12 21:43:09 2007 New Revision: 58126 Modified: python/branches/py3k/Lib/httplib.py python/branches/py3k/Lib/test/test_httplib.py Log: Fix for bug 1148: str/bytes issue in httplib's _safe_read(). Modified: python/branches/py3k/Lib/httplib.py ============================================================================== --- python/branches/py3k/Lib/httplib.py (original) +++ python/branches/py3k/Lib/httplib.py Wed Sep 12 21:43:09 2007 @@ -624,7 +624,7 @@ raise IncompleteRead(s) s.append(chunk) amt -= len(chunk) - return "".join(s) + return b"".join(s) def getheader(self, name, default=None): if self.msg is None: Modified: python/branches/py3k/Lib/test/test_httplib.py ============================================================================== --- python/branches/py3k/Lib/test/test_httplib.py (original) +++ python/branches/py3k/Lib/test/test_httplib.py Wed Sep 12 21:43:09 2007 @@ -133,7 +133,7 @@ NoEOFStringIO) resp = httplib.HTTPResponse(sock, method="HEAD") resp.begin() - if resp.read() != "": + if resp.read(): self.fail("Did not expect response from HEAD request") resp.close() From python-3000-checkins at python.org Wed Sep 12 21:44:18 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 12 Sep 2007 21:44:18 +0200 (CEST) Subject: [Python-3000-checkins] r58127 - python/branches/py3k/Lib/pdb.py Message-ID: <20070912194418.F1BB61E4005@bag.python.org> Author: georg.brandl Date: Wed Sep 12 21:44:18 2007 New Revision: 58127 Modified: python/branches/py3k/Lib/pdb.py Log: Repair a bad translation of the exec statement. Fixes #1038: pdb command line invocation fails. Modified: python/branches/py3k/Lib/pdb.py ============================================================================== --- python/branches/py3k/Lib/pdb.py (original) +++ python/branches/py3k/Lib/pdb.py Wed Sep 12 21:44:18 2007 @@ -1166,12 +1166,8 @@ self._wait_for_mainpyfile = 1 self.mainpyfile = self.canonic(filename) self._user_requested_quit = 0 - fp = open(filename) - try: - script = fp.read() - finally: - fp.close() - statement = 'exec("%s")' % script + with open(filename) as fp: + statement = fp.read() self.run(statement) # Simplified interface From python-3000-checkins at python.org Wed Sep 12 23:29:27 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 12 Sep 2007 23:29:27 +0200 (CEST) Subject: [Python-3000-checkins] r58131 - python/branches/py3k/Doc/library/functions.rst Message-ID: <20070912212927.D2A001E400A@bag.python.org> Author: georg.brandl Date: Wed Sep 12 23:29:27 2007 New Revision: 58131 Modified: python/branches/py3k/Doc/library/functions.rst Log: Document input() function. Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Wed Sep 12 23:29:27 2007 @@ -524,6 +524,22 @@ (Implementation note: this is the address of the object.) +.. function:: input([prompt]) + + If the *prompt* argument is present, it is written to standard output without + a trailing newline. The function then reads a line from input, converts it + to a string (stripping a trailing newline), and returns that. When EOF is + read, :exc:`EOFError` is raised. Example:: + + >>> s = raw_input('--> ') + --> Monty Python's Flying Circus + >>> s + "Monty Python's Flying Circus" + + If the :mod:`readline` module was loaded, then :func:`raw_input` will use it + to provide elaborate line editing and history features. + + .. function:: int([x[, radix]]) Convert a string or number to an integer. If the argument is a string, it From python-3000-checkins at python.org Wed Sep 12 23:32:27 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Wed, 12 Sep 2007 23:32:27 +0200 (CEST) Subject: [Python-3000-checkins] r58132 - python/branches/py3k/Doc/library/functions.rst Message-ID: <20070912213227.647A51E4008@bag.python.org> Author: georg.brandl Date: Wed Sep 12 23:32:27 2007 New Revision: 58132 Modified: python/branches/py3k/Doc/library/functions.rst Log: Oops. Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Wed Sep 12 23:32:27 2007 @@ -531,12 +531,12 @@ to a string (stripping a trailing newline), and returns that. When EOF is read, :exc:`EOFError` is raised. Example:: - >>> s = raw_input('--> ') + >>> s = input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus" - If the :mod:`readline` module was loaded, then :func:`raw_input` will use it + If the :mod:`readline` module was loaded, then :func:`input` will use it to provide elaborate line editing and history features. From python-3000-checkins at python.org Thu Sep 13 15:33:46 2007 From: python-3000-checkins at python.org (martin.v.loewis) Date: Thu, 13 Sep 2007 15:33:46 +0200 (CEST) Subject: [Python-3000-checkins] r58136 - in python/branches/py3k: Tools/buildbot/buildmsi.bat Message-ID: <20070913133346.873121E400A@bag.python.org> Author: martin.v.loewis Date: Thu Sep 13 15:33:46 2007 New Revision: 58136 Modified: python/branches/py3k/ (props changed) python/branches/py3k/Tools/buildbot/buildmsi.bat Log: Merged revisions 58133-58135 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r58133 | martin.v.loewis | 2007-09-13 11:59:00 +0200 (Do, 13 Sep 2007) | 2 lines Add more automated actions. ........ r58134 | martin.v.loewis | 2007-09-13 12:38:42 +0200 (Do, 13 Sep 2007) | 2 lines Fix path. ........ r58135 | martin.v.loewis | 2007-09-13 15:27:27 +0200 (Do, 13 Sep 2007) | 2 lines More path fixes. ........ Modified: python/branches/py3k/Tools/buildbot/buildmsi.bat ============================================================================== --- python/branches/py3k/Tools/buildbot/buildmsi.bat (original) +++ python/branches/py3k/Tools/buildbot/buildmsi.bat Thu Sep 13 15:33:46 2007 @@ -1,10 +1,24 @@ @rem Used by the buildbot "buildmsi" step. + cmd /c Tools\buildbot\external.bat + at rem build release versions of things call "%VS71COMNTOOLS%vsvars32.bat" +if not exist ..\db-4.4.20\build_win32\release\libdb44s.lib ( + devenv ..\db-4.4.20\build_win32\Berkeley_DB.sln /build Release /project db_static +) + + at rem build Python cmd /q/c Tools\buildbot\kill_python.bat devenv.com /useenv /build Release PCbuild\pcbuild.sln + + at rem build the documentation bash.exe -c 'cd Doc;make PYTHON=python2.5 update htmlhelp' -"%ProgramFiles%\HTML Help Workshop\hhc.exe Doc\build\htmlhelp\pydoc.hhp -cd Tools\msi +"%ProgramFiles%\HTML Help Workshop\hhc.exe" Doc\build\htmlhelp\pydoc.hhp + + at rem buold the MSI file +cd PC +nmake /f icons.mak +cd ..\Tools\msi del *.msi +nmake /f msisupport.mak %HOST_PYTHON% msi.py From python-3000-checkins at python.org Fri Sep 14 09:03:21 2007 From: python-3000-checkins at python.org (martin.v.loewis) Date: Fri, 14 Sep 2007 09:03:21 +0200 (CEST) Subject: [Python-3000-checkins] r58153 - in python/branches/py3k: PCbuild/_msi.vcproj Tools/buildbot/clean.bat Message-ID: <20070914070321.C996E1E4007@bag.python.org> Author: martin.v.loewis Date: Fri Sep 14 09:03:21 2007 New Revision: 58153 Modified: python/branches/py3k/ (props changed) python/branches/py3k/PCbuild/_msi.vcproj python/branches/py3k/Tools/buildbot/clean.bat Log: Merged revisions 58149-58150 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r58149 | martin.v.loewis | 2007-09-14 08:49:43 +0200 (Fr, 14 Sep 2007) | 3 lines Clean both Release and Debug projects, to support the MSI builder. ........ r58150 | martin.v.loewis | 2007-09-14 08:50:21 +0200 (Fr, 14 Sep 2007) | 2 lines Rename import library for debug build to _msi_d.lib. ........ Modified: python/branches/py3k/PCbuild/_msi.vcproj ============================================================================== --- python/branches/py3k/PCbuild/_msi.vcproj (original) +++ python/branches/py3k/PCbuild/_msi.vcproj Fri Sep 14 09:03:21 2007 @@ -42,7 +42,7 @@ GenerateDebugInformation="TRUE" ProgramDatabaseFile=".\./_msi_d.pdb" BaseAddress="0x1D160000" - ImportLibrary=".\./_msi.lib" + ImportLibrary=".\./_msi_d.lib" TargetMachine="1"/> Modified: python/branches/py3k/Tools/buildbot/clean.bat ============================================================================== --- python/branches/py3k/Tools/buildbot/clean.bat (original) +++ python/branches/py3k/Tools/buildbot/clean.bat Fri Sep 14 09:03:21 2007 @@ -3,4 +3,5 @@ cd PCbuild @echo Deleting .pyc/.pyo files ... python_d.exe rmpyc.py +devenv.com /clean Release pcbuild.sln devenv.com /clean Debug pcbuild.sln From python-3000-checkins at python.org Mon Sep 17 19:55:37 2007 From: python-3000-checkins at python.org (sean.reifschneider) Date: Mon, 17 Sep 2007 19:55:37 +0200 (CEST) Subject: [Python-3000-checkins] r58182 - in python/branches/py3k: Doc/c-api/abstract.rst Doc/c-api/concrete.rst Include/abstract.h Include/memoryobject.h Include/object.h Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py Lib/plat-mac/macresource.py Misc/HISTORY Misc/setuid-prog.c Modules/mmapmodule.c Modules/socketmodule.c Objects/abstract.c Objects/memoryobject.c Message-ID: <20070917175538.083EF1E4003@bag.python.org> Author: sean.reifschneider Date: Mon Sep 17 19:55:36 2007 New Revision: 58182 Modified: python/branches/py3k/Doc/c-api/abstract.rst python/branches/py3k/Doc/c-api/concrete.rst python/branches/py3k/Include/abstract.h python/branches/py3k/Include/memoryobject.h python/branches/py3k/Include/object.h python/branches/py3k/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py python/branches/py3k/Lib/plat-mac/macresource.py python/branches/py3k/Misc/HISTORY python/branches/py3k/Misc/setuid-prog.c python/branches/py3k/Modules/mmapmodule.c python/branches/py3k/Modules/socketmodule.c python/branches/py3k/Objects/abstract.c python/branches/py3k/Objects/memoryobject.c Log: Fixing the spelling of "writeable" to "writable", particularly PyBUF_WRITEABLE. Modified: python/branches/py3k/Doc/c-api/abstract.rst ============================================================================== --- python/branches/py3k/Doc/c-api/abstract.rst (original) +++ python/branches/py3k/Doc/c-api/abstract.rst Mon Sep 17 19:55:36 2007 @@ -944,7 +944,7 @@ .. cfunction:: int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len) - Returns a pointer to a writeable memory location. The *obj* argument must + Returns a pointer to a writable memory location. The *obj* argument must support the single-segment, character buffer interface. On success, returns ``0``, sets *buffer* to the memory location and *buffer_len* to the buffer length. Returns ``-1`` and sets a :exc:`TypeError` on error. Modified: python/branches/py3k/Doc/c-api/concrete.rst ============================================================================== --- python/branches/py3k/Doc/c-api/concrete.rst (original) +++ python/branches/py3k/Doc/c-api/concrete.rst Mon Sep 17 19:55:36 2007 @@ -1882,7 +1882,7 @@ Return a new writable buffer object. Parameters and exceptions are similar to those for :cfunc:`PyBuffer_FromObject`. If the *base* object does not export - the writeable buffer protocol, then :exc:`TypeError` is raised. + the writable buffer protocol, then :exc:`TypeError` is raised. .. cfunction:: PyObject* PyBuffer_FromMemory(void *ptr, Py_ssize_t size) Modified: python/branches/py3k/Include/abstract.h ============================================================================== --- python/branches/py3k/Include/abstract.h (original) +++ python/branches/py3k/Include/abstract.h Mon Sep 17 19:55:36 2007 @@ -524,9 +524,9 @@ Py_ssize_t *buffer_len); /* - Takes an arbitrary object which must support the (writeable, + Takes an arbitrary object which must support the (writable, single segment) buffer interface and returns a pointer to a - writeable memory location in buffer of size buffer_len. + writable memory location in buffer of size buffer_len. 0 is returned on success. buffer and buffer_len are only set in case no error occurrs. Otherwise, -1 is returned and Modified: python/branches/py3k/Include/memoryobject.h ============================================================================== --- python/branches/py3k/Include/memoryobject.h (original) +++ python/branches/py3k/Include/memoryobject.h Mon Sep 17 19:55:36 2007 @@ -33,15 +33,15 @@ The buffertype argument can be PyBUF_READ, PyBUF_WRITE, PyBUF_UPDATEIFCOPY to determine whether the returned buffer - should be READONLY, WRITEABLE, or set to update the + should be READONLY, WRITABLE, or set to update the original buffer if a copy must be made. If buffertype is PyBUF_WRITE and the buffer is not contiguous an error will be raised. In this circumstance, the user can use - PyBUF_UPDATEIFCOPY to ensure that a a writeable temporary + PyBUF_UPDATEIFCOPY to ensure that a a writable temporary contiguous buffer is returned. The contents of this contiguous buffer will be copied back into the original object after the memoryview object is deleted as long as - the original object is writeable and allows setting its + the original object is writable and allows setting its memory to "readonly". If this is not allowed by the original object, then a BufferError is raised. Modified: python/branches/py3k/Include/object.h ============================================================================== --- python/branches/py3k/Include/object.h (original) +++ python/branches/py3k/Include/object.h Mon Sep 17 19:55:36 2007 @@ -162,7 +162,9 @@ /* Flags for getting buffers */ #define PyBUF_SIMPLE 0 #define PyBUF_CHARACTER 1 -#define PyBUF_WRITEABLE 0x0002 +#define PyBUF_WRITABLE 0x0002 +/* we used to include an E, backwards compatible alias */ +#define PyBUF_WRITEABLE PyBUF_WRITABLE #define PyBUF_LOCKDATA 0x0004 #define PyBUF_FORMAT 0x0008 #define PyBUF_ND 0x0010 @@ -172,19 +174,19 @@ #define PyBUF_ANY_CONTIGUOUS (0x0100 | PyBUF_STRIDES) #define PyBUF_INDIRECT (0x0200 | PyBUF_STRIDES) -#define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITEABLE) +#define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITABLE) #define PyBUF_CONTIG_RO (PyBUF_ND) #define PyBUF_CONTIG_LCK (PyBUF_ND | PyBUF_LOCKDATA) -#define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITEABLE) +#define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITABLE) #define PyBUF_STRIDED_RO (PyBUF_STRIDES) #define PyBUF_STRIDED_LCK (PyBUF_STRIDES | PyBUF_LOCKDATA) -#define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITEABLE | PyBUF_FORMAT) +#define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT) #define PyBUF_RECORDS_RO (PyBUF_STRIDES | PyBUF_FORMAT) #define PyBUF_RECORDS_LCK (PyBUF_STRIDES | PyBUF_LOCKDATA | PyBUF_FORMAT) -#define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITEABLE | PyBUF_FORMAT) +#define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT) #define PyBUF_FULL_RO (PyBUF_INDIRECT | PyBUF_FORMAT) #define PyBUF_FULL_LCK (PyBUF_INDIRECT | PyBUF_LOCKDATA | PyBUF_FORMAT) Modified: python/branches/py3k/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py ============================================================================== --- python/branches/py3k/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py (original) +++ python/branches/py3k/Lib/plat-mac/lib-scriptpackages/CodeWarrior/Metrowerks_Shell_Suite.py Mon Sep 17 19:55:36 2007 @@ -1346,7 +1346,7 @@ which = 'Frmt' want = 'PthF' class _Prop_framework(aetools.NProperty): - """framework - Is the path a Mac OS X framework style path? (This flag is readable but not writeable from AppleScript.) """ + """framework - Is the path a Mac OS X framework style path? (This flag is readable but not writable from AppleScript.) """ which = 'Frmw' want = 'bool' class _Prop_host_flags(aetools.NProperty): Modified: python/branches/py3k/Lib/plat-mac/macresource.py ============================================================================== --- python/branches/py3k/Lib/plat-mac/macresource.py (original) +++ python/branches/py3k/Lib/plat-mac/macresource.py Mon Sep 17 19:55:36 2007 @@ -135,7 +135,7 @@ return newpathname if hasattr(os, 'access') and not \ os.access(os.path.dirname(pathname), os.W_OK|os.X_OK): - # The destination directory isn't writeable. Create the file in + # The destination directory isn't writable. Create the file in # a temporary directory import tempfile fd, newpathname = tempfile.mkstemp(".rsrc") Modified: python/branches/py3k/Misc/HISTORY ============================================================================== --- python/branches/py3k/Misc/HISTORY (original) +++ python/branches/py3k/Misc/HISTORY Mon Sep 17 19:55:36 2007 @@ -403,7 +403,7 @@ - os.urandom has been added for systems that support sources of random data. -- Patch 1012740: truncate() on a writeable cStringIO now resets the +- Patch 1012740: truncate() on a writable cStringIO now resets the position to the end of the stream. This is consistent with the original StringIO module and avoids inadvertently resurrecting data that was supposed to have been truncated away. Modified: python/branches/py3k/Misc/setuid-prog.c ============================================================================== --- python/branches/py3k/Misc/setuid-prog.c (original) +++ python/branches/py3k/Misc/setuid-prog.c Mon Sep 17 19:55:36 2007 @@ -155,7 +155,7 @@ fprintf(stderr, "%s: %s has the wrong owner\n", argv[0], FULL_PATH); fprintf(stderr, "The script should be owned by root,\n"); - fprintf(stderr, "and shouldn't be writeable by anyone.\n"); + fprintf(stderr, "and shouldn't be writable by anyone.\n"); exit(1); } Modified: python/branches/py3k/Modules/mmapmodule.c ============================================================================== --- python/branches/py3k/Modules/mmapmodule.c (original) +++ python/branches/py3k/Modules/mmapmodule.c Mon Sep 17 19:55:36 2007 @@ -272,7 +272,7 @@ } static int -is_writeable(mmap_object *self) +is_writable(mmap_object *self) { if (self->access != ACCESS_READ) return 1; @@ -307,7 +307,7 @@ if (!PyArg_ParseTuple(args, "s#:write", &data, &length)) return(NULL); - if (!is_writeable(self)) + if (!is_writable(self)) return NULL; if ((self->pos + length) > self->size) { @@ -330,7 +330,7 @@ if (!PyArg_ParseTuple(args, "c:write_byte", &value)) return(NULL); - if (!is_writeable(self)) + if (!is_writable(self)) return NULL; *(self->data+self->pos) = value; self->pos += 1; @@ -562,7 +562,7 @@ unsigned long dest, src, count; CHECK_VALID(NULL); if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &count) || - !is_writeable(self)) { + !is_writable(self)) { return NULL; } else { /* bounds check the values */ @@ -733,7 +733,7 @@ "mmap assignment must be length-1 bytes()"); return -1; } - if (!is_writeable(self)) + if (!is_writable(self)) return -1; buf = PyBytes_AsString(v); self->data[i] = buf[0]; @@ -768,7 +768,7 @@ "mmap assignment must be length-1 bytes()"); return -1; } - if (!is_writeable(self)) + if (!is_writable(self)) return -1; buf = PyBytes_AsString(value); self->data[i] = buf[0]; @@ -797,7 +797,7 @@ "mmap slice assignment is wrong size"); return -1; } - if (!is_writeable(self)) + if (!is_writable(self)) return -1; if (slicelen == 0) Modified: python/branches/py3k/Modules/socketmodule.c ============================================================================== --- python/branches/py3k/Modules/socketmodule.c (original) +++ python/branches/py3k/Modules/socketmodule.c Mon Sep 17 19:55:36 2007 @@ -1831,7 +1831,7 @@ timeout = 1; } else if (res > 0) { if (FD_ISSET(s->sock_fd, &fds)) - /* The socket is in the writeable set - this + /* The socket is in the writable set - this means connected */ res = 0; else { Modified: python/branches/py3k/Objects/abstract.c ============================================================================== --- python/branches/py3k/Objects/abstract.c (original) +++ python/branches/py3k/Objects/abstract.c Mon Sep 17 19:55:36 2007 @@ -304,9 +304,9 @@ pb = obj->ob_type->tp_as_buffer; if (pb == NULL || pb->bf_getbuffer == NULL || - ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITEABLE) != 0)) { + ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) { PyErr_SetString(PyExc_TypeError, - "expected an object with a writeable buffer interface"); + "expected an object with a writable buffer interface"); return -1; } @@ -659,10 +659,10 @@ "Cannot make this object read-only."); return -1; } - if (((flags & PyBUF_WRITEABLE) == PyBUF_WRITEABLE) && + if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) && readonly == 1) { PyErr_SetString(PyExc_BufferError, - "Object is not writeable."); + "Object is not writable."); return -1; } Modified: python/branches/py3k/Objects/memoryobject.c ============================================================================== --- python/branches/py3k/Objects/memoryobject.c (original) +++ python/branches/py3k/Objects/memoryobject.c Mon Sep 17 19:55:36 2007 @@ -183,8 +183,8 @@ buffertype PyBUF_READ buffer only needs to be read-only - PyBUF_WRITE buffer needs to be writeable (give error if not contiguous) - PyBUF_SHADOW buffer needs to be writeable so shadow it with + PyBUF_WRITE buffer needs to be writable (give error if not contiguous) + PyBUF_SHADOW buffer needs to be writable so shadow it with a contiguous buffer if it is not. The view will point to the shadow buffer which can be written to and then will be copied back into the other buffer when the memory @@ -235,7 +235,7 @@ if (buffertype == PyBUF_WRITE) { PyObject_DEL(mem); PyErr_SetString(PyExc_BufferError, - "writeable contiguous buffer requested for a non-contiguous" \ + "writable contiguous buffer requested for a non-contiguous" \ "object."); return NULL; } From python-3000-checkins at python.org Tue Sep 18 06:30:43 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 18 Sep 2007 06:30:43 +0200 (CEST) Subject: [Python-3000-checkins] r58187 - python/branches/py3k/Objects/dictobject.c python/branches/py3k/Objects/unicodeobject.c Message-ID: <20070918043043.848691E4002@bag.python.org> Author: guido.van.rossum Date: Tue Sep 18 06:30:42 2007 New Revision: 58187 Modified: python/branches/py3k/Objects/dictobject.c python/branches/py3k/Objects/unicodeobject.c Log: Micro optimizations after staring at gprof output for a while. Modified: python/branches/py3k/Objects/dictobject.c ============================================================================== --- python/branches/py3k/Objects/dictobject.c (original) +++ python/branches/py3k/Objects/dictobject.c Tue Sep 18 06:30:42 2007 @@ -566,8 +566,8 @@ PyThreadState *tstate; if (!PyDict_Check(op)) return NULL; - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) { @@ -650,12 +650,9 @@ assert(key); assert(value); mp = (dictobject *)op; - if (PyString_CheckExact(key)) { - hash = ((PyStringObject *)key)->ob_shash; - if (hash == -1) - hash = PyObject_Hash(key); - } - else { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) + { hash = PyObject_Hash(key); if (hash == -1) return -1; Modified: python/branches/py3k/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k/Objects/unicodeobject.c (original) +++ python/branches/py3k/Objects/unicodeobject.c Tue Sep 18 06:30:42 2007 @@ -6597,9 +6597,10 @@ /* Since Unicode objects compare equal to their UTF-8 string counterparts, we hash the UTF-8 string. */ PyObject *v = _PyUnicode_AsDefaultEncodedString((PyObject*)self, NULL); - long x = PyObject_Hash(v); - self->hash = x; - return x; + if (v == NULL) + return -1; + assert(PyString_CheckExact(v)); + return self->hash = v->ob_type->tp_hash(v); } } From python-3000-checkins at python.org Tue Sep 18 07:06:47 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Tue, 18 Sep 2007 07:06:47 +0200 (CEST) Subject: [Python-3000-checkins] r58188 - python/branches/py3k-importlib Message-ID: <20070918050647.CA3431E4002@bag.python.org> Author: brett.cannon Date: Tue Sep 18 07:06:47 2007 New Revision: 58188 Added: python/branches/py3k-importlib/ - copied from r58187, python/branches/py3k/ Log: Branch to be used for trying to move Py3K over to using importlib as the import implementation. From python-3000-checkins at python.org Tue Sep 18 07:21:51 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Tue, 18 Sep 2007 07:21:51 +0200 (CEST) Subject: [Python-3000-checkins] r58189 - python/branches/py3k-importlib Message-ID: <20070918052151.122391E4002@bag.python.org> Author: brett.cannon Date: Tue Sep 18 07:21:50 2007 New Revision: 58189 Modified: python/branches/py3k-importlib/ (props changed) Log: svnmerge init. From python-3000-checkins at python.org Tue Sep 18 08:45:22 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Tue, 18 Sep 2007 08:45:22 +0200 (CEST) Subject: [Python-3000-checkins] r58190 - python/branches/py3k-importlib Message-ID: <20070918064522.6A0901E4003@bag.python.org> Author: brett.cannon Date: Tue Sep 18 08:45:22 2007 New Revision: 58190 Modified: python/branches/py3k-importlib/ (props changed) Log: Pull in Py3K version of importlib. From python-3000-checkins at python.org Tue Sep 18 08:46:39 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Tue, 18 Sep 2007 08:46:39 +0200 (CEST) Subject: [Python-3000-checkins] r58191 - python/branches/py3k-importlib/Lib/_importlib.py python/branches/py3k-importlib/Lib/importlib.py Message-ID: <20070918064639.D27F01E4003@bag.python.org> Author: brett.cannon Date: Tue Sep 18 08:46:39 2007 New Revision: 58191 Added: python/branches/py3k-importlib/Lib/_importlib.py (contents, props changed) python/branches/py3k-importlib/Lib/importlib.py (contents, props changed) Log: Add _importlib and importlib to the stdlib through a symlink. Added: python/branches/py3k-importlib/Lib/_importlib.py ============================================================================== --- (empty file) +++ python/branches/py3k-importlib/Lib/_importlib.py Tue Sep 18 08:46:39 2007 @@ -0,0 +1 @@ +link ../importlib/_importlib.py \ No newline at end of file Added: python/branches/py3k-importlib/Lib/importlib.py ============================================================================== --- (empty file) +++ python/branches/py3k-importlib/Lib/importlib.py Tue Sep 18 08:46:39 2007 @@ -0,0 +1 @@ +link ../importlib/importlib.py \ No newline at end of file From python-3000-checkins at python.org Tue Sep 18 19:26:56 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 18 Sep 2007 19:26:56 +0200 (CEST) Subject: [Python-3000-checkins] r58194 - python/branches/py3k/Objects/dictobject.c Message-ID: <20070918172656.D50F71E400F@bag.python.org> Author: guido.van.rossum Date: Tue Sep 18 19:26:56 2007 New Revision: 58194 Modified: python/branches/py3k/Objects/dictobject.c Log: Switch dict lookup around to optimizing for unicode. For now, unicode_eq() is static inside dictobject.c; eventually we may have to move it into unicodeobject.c, so as to support the same hacks from setobject.c. None of this seems to affect performance much, but it's still the right thing to do. Modified: python/branches/py3k/Objects/dictobject.c ============================================================================== --- python/branches/py3k/Objects/dictobject.c (original) +++ python/branches/py3k/Objects/dictobject.c Tue Sep 18 19:26:56 2007 @@ -149,7 +149,7 @@ /* forward declarations */ static dictentry * -lookdict_string(dictobject *mp, PyObject *key, long hash); +lookdict_unicode(dictobject *mp, PyObject *key, long hash); #ifdef SHOW_CONVERSION_COUNTS static long created = 0L; @@ -218,7 +218,7 @@ return NULL; EMPTY_TO_MINSIZE(mp); } - mp->ma_lookup = lookdict_string; + mp->ma_lookup = lookdict_unicode; #ifdef SHOW_CONVERSION_COUNTS ++created; #endif @@ -243,7 +243,7 @@ lookdict() is general-purpose, and may return NULL if (and only if) a comparison raises an exception (this was new in Python 2.5). -lookdict_string() below is specialized to string keys, comparison of which can +lookdict_unicode() below is specialized to string keys, comparison of which can never raise an exception; that function can never return NULL. For both, when the key isn't found a dictentry* is returned for which the me_value field is NULL; this is the slot in the dict at which the key would have been found, and @@ -325,17 +325,37 @@ return 0; } +/* Return 1 if two unicode objects are equal, 0 if not. */ +static int +unicode_eq(PyObject *aa, PyObject *bb) +{ + PyUnicodeObject *a = (PyUnicodeObject *)aa; + PyUnicodeObject *b = (PyUnicodeObject *)bb; + + if (a->length != b->length) + return 0; + if (a->length == 0) + return 1; + if (a->str[0] != b->str[0]) + return 0; + if (a->length == 1) + return 1; + return PyUnicode_Compare(aa, bb) == 0; +} + + /* - * Hacked up version of lookdict which can assume keys are always strings; - * this assumption allows testing for errors during PyObject_RichCompareBool() - * to be dropped; string-string comparisons never raise exceptions. This also - * means we don't need to go through PyObject_RichCompareBool(); we can always - * use _PyString_Eq() directly. + * Hacked up version of lookdict which can assume keys are always + * unicodes; this assumption allows testing for errors during + * PyObject_RichCompareBool() to be dropped; unicode-unicode + * comparisons never raise exceptions. This also means we don't need + * to go through PyObject_RichCompareBool(); we can always use + * unicode_eq() directly. * - * This is valuable because dicts with only string keys are very common. + * This is valuable because dicts with only unicode keys are very common. */ static dictentry * -lookdict_string(dictobject *mp, PyObject *key, register long hash) +lookdict_unicode(dictobject *mp, PyObject *key, register long hash) { register size_t i; register size_t perturb; @@ -344,11 +364,11 @@ dictentry *ep0 = mp->ma_table; register dictentry *ep; - /* Make sure this function doesn't have to handle non-string keys, + /* Make sure this function doesn't have to handle non-unicode keys, including subclasses of str; e.g., one reason to subclass - strings is to override __eq__, and for speed we don't cater to + unicodes is to override __eq__, and for speed we don't cater to that here. */ - if (!PyString_CheckExact(key)) { + if (!PyUnicode_CheckExact(key)) { #ifdef SHOW_CONVERSION_COUNTS ++converted; #endif @@ -362,7 +382,7 @@ if (ep->me_key == dummy) freeslot = ep; else { - if (ep->me_hash == hash && _PyString_Eq(ep->me_key, key)) + if (ep->me_hash == hash && unicode_eq(ep->me_key, key)) return ep; freeslot = NULL; } @@ -377,7 +397,7 @@ if (ep->me_key == key || (ep->me_hash == hash && ep->me_key != dummy - && _PyString_Eq(ep->me_key, key))) + && unicode_eq(ep->me_key, key))) return ep; if (ep->me_key == dummy && freeslot == NULL) freeslot = ep; @@ -615,8 +635,8 @@ PyErr_BadInternalCall(); return NULL; } - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) { @@ -695,8 +715,8 @@ return -1; } assert(key); - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return -1; @@ -975,8 +995,8 @@ long hash; dictentry *ep; assert(mp->ma_table != NULL); - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; @@ -1547,8 +1567,8 @@ long hash; dictentry *ep; - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; @@ -1571,8 +1591,8 @@ if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj)) return NULL; - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; @@ -1600,8 +1620,8 @@ if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj)) return NULL; - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; @@ -1646,8 +1666,8 @@ "pop(): dictionary is empty"); return NULL; } - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; @@ -1842,8 +1862,8 @@ dictobject *mp = (dictobject *)op; dictentry *ep; - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return -1; @@ -1889,7 +1909,7 @@ /* It's guaranteed that tp->alloc zeroed out the struct. */ assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0); INIT_NONZERO_DICT_SLOTS(d); - d->ma_lookup = lookdict_string; + d->ma_lookup = lookdict_unicode; #ifdef SHOW_CONVERSION_COUNTS ++created; #endif From python-3000-checkins at python.org Tue Sep 18 20:39:51 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 18 Sep 2007 20:39:51 +0200 (CEST) Subject: [Python-3000-checkins] r58195 - python/branches/py3k/Objects/dictobject.c Message-ID: <20070918183951.2EED61E4004@bag.python.org> Author: guido.van.rossum Date: Tue Sep 18 20:39:50 2007 New Revision: 58195 Modified: python/branches/py3k/Objects/dictobject.c Log: Thomas Wouters suggested an obvious improvement to unicode_eq(): use memcmp(). Modified: python/branches/py3k/Objects/dictobject.c ============================================================================== --- python/branches/py3k/Objects/dictobject.c (original) +++ python/branches/py3k/Objects/dictobject.c Tue Sep 18 20:39:50 2007 @@ -340,7 +340,7 @@ return 0; if (a->length == 1) return 1; - return PyUnicode_Compare(aa, bb) == 0; + return memcmp(a->str, b->str, a->length * sizeof(Py_UNICODE)) == 0; } From python-3000-checkins at python.org Tue Sep 18 21:42:40 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 18 Sep 2007 21:42:40 +0200 (CEST) Subject: [Python-3000-checkins] r58196 - python/branches/py3k/Objects/unicodeobject.c Message-ID: <20070918194240.A237B1E4010@bag.python.org> Author: guido.van.rossum Date: Tue Sep 18 21:42:40 2007 New Revision: 58196 Modified: python/branches/py3k/Objects/unicodeobject.c Log: Optimize unicode_hash() by not calling _PyUnicode_AsDefaultEncodedString() at all -- this saves two object allocations (three block allocations!) and lots of redundant work. By using the same hash algorithm as string_hash(), we maintain the invariant that the hash of an ASCII string is the same whether represented as a PyString or a PyUnicode. Modified: python/branches/py3k/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k/Objects/unicodeobject.c (original) +++ python/branches/py3k/Objects/unicodeobject.c Tue Sep 18 21:42:40 2007 @@ -6587,21 +6587,27 @@ return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1); } +/* Believe it or not, this produces the same value for ASCII strings + as string_hash(). */ static long unicode_hash(PyUnicodeObject *self) { - if (self->hash != -1) { - return self->hash; - } - else { - /* Since Unicode objects compare equal to their UTF-8 string - counterparts, we hash the UTF-8 string. */ - PyObject *v = _PyUnicode_AsDefaultEncodedString((PyObject*)self, NULL); - if (v == NULL) - return -1; - assert(PyString_CheckExact(v)); - return self->hash = v->ob_type->tp_hash(v); - } + Py_ssize_t len; + Py_UNICODE *p; + long x; + + if (self->hash != -1) + return self->hash; + len = Py_Size(self); + p = self->str; + x = *p << 7; + while (--len >= 0) + x = (1000003*x) ^ *p++; + x ^= Py_Size(self); + if (x == -1) + x = -2; + self->hash = x; + return x; } PyDoc_STRVAR(index__doc__, From python-3000-checkins at python.org Wed Sep 19 01:39:36 2007 From: python-3000-checkins at python.org (sean.reifschneider) Date: Wed, 19 Sep 2007 01:39:36 +0200 (CEST) Subject: [Python-3000-checkins] r58201 - python/branches/py3k/Doc/library/cgi.rst Message-ID: <20070918233936.3B0E51E4005@bag.python.org> Author: sean.reifschneider Date: Wed Sep 19 01:39:35 2007 New Revision: 58201 Modified: python/branches/py3k/Doc/library/cgi.rst Log: issue1172: Documentation of "done" attribute in cgi module. Modified: python/branches/py3k/Doc/library/cgi.rst ============================================================================== --- python/branches/py3k/Doc/library/cgi.rst (original) +++ python/branches/py3k/Doc/library/cgi.rst Wed Sep 19 01:39:35 2007 @@ -147,6 +147,11 @@ if not line: break linecount = linecount + 1 +If an error is encountered when obtaining the contents of an uploaded file +(for example, when the user interrupts the form submission by clicking on +a Back or Cancel button) the :attr:`done` attribute of the object for the +field will be set to the value -1. + The file upload draft standard entertains the possibility of uploading multiple files from one field (using a recursive :mimetype:`multipart/\*` encoding). When this occurs, the item will be a dictionary-like :class:`FieldStorage` item. From python-3000-checkins at python.org Wed Sep 19 05:06:37 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Wed, 19 Sep 2007 05:06:37 +0200 (CEST) Subject: [Python-3000-checkins] r58202 - in python/branches/py3k: Doc/c-api/concrete.rst Doc/library/collections.rst Doc/library/decimal.rst Doc/library/fileinput.rst Doc/library/functions.rst Doc/library/hashlib.rst Doc/library/operator.rst Doc/library/os.rst Doc/library/simplexmlrpcserver.rst Doc/library/ssl.rst Doc/library/undoc.rst Doc/reference/index.rst Doc/reference/simple_stmts.rst Doc/whatsnew/2.5.rst Doc/whatsnew/2.6.rst Lib/collections.py Lib/ctypes/test/test_cfuncs.py Lib/ctypes/test/test_functions.py Lib/ctypes/util.py Lib/decimal.py Lib/distutils/command/build_scripts.py Lib/httplib.py Lib/imaplib.py Lib/platform.py Lib/poplib.py Lib/repr.py Lib/smtplib.py Lib/socket.py Lib/ssl.py Lib/test/badcert.pem Lib/test/badkey.pem Lib/test/decimaltestdata/abs.decTest Lib/test/decimaltestdata/add.decTest Lib/test/decimaltestdata/and.decTest Lib/test/decimaltestdata/base.decTest Lib/test/decimaltestdata/clamp.decTest Lib/test/decimaltestdata/class.decTest Lib/test/decimaltestdata/compare.decTest Lib/test/decimaltestdata/comparetotal.decTest Lib/test/decimaltestdata/comparetotmag.decTest Lib/test/decimaltestdata/copy.decTest Lib/test/decimaltestdata/copyabs.decTest Lib/test/decimaltestdata/copynegate.decTest Lib/test/decimaltestdata/copysign.decTest Lib/test/decimaltestdata/ddAbs.decTest Lib/test/decimaltestdata/ddAdd.decTest Lib/test/decimaltestdata/ddAnd.decTest Lib/test/decimaltestdata/ddBase.decTest Lib/test/decimaltestdata/ddCanonical.decTest Lib/test/decimaltestdata/ddClass.decTest Lib/test/decimaltestdata/ddCompare.decTest Lib/test/decimaltestdata/ddCompareSig.decTest Lib/test/decimaltestdata/ddCompareTotal.decTest Lib/test/decimaltestdata/ddCompareTotalMag.decTest Lib/test/decimaltestdata/ddCopy.decTest Lib/test/decimaltestdata/ddCopyAbs.decTest Lib/test/decimaltestdata/ddCopyNegate.decTest Lib/test/decimaltestdata/ddCopySign.decTest Lib/test/decimaltestdata/ddDivide.decTest Lib/test/decimaltestdata/ddDivideInt.decTest Lib/test/decimaltestdata/ddEncode.decTest Lib/test/decimaltestdata/ddFMA.decTest Lib/test/decimaltestdata/ddInvert.decTest Lib/test/decimaltestdata/ddLogB.decTest Lib/test/decimaltestdata/ddMax.decTest Lib/test/decimaltestdata/ddMaxMag.decTest Lib/test/decimaltestdata/ddMin.decTest Lib/test/decimaltestdata/ddMinMag.decTest Lib/test/decimaltestdata/ddMinus.decTest Lib/test/decimaltestdata/ddMultiply.decTest Lib/test/decimaltestdata/ddNextMinus.decTest Lib/test/decimaltestdata/ddNextPlus.decTest Lib/test/decimaltestdata/ddNextToward.decTest Lib/test/decimaltestdata/ddOr.decTest Lib/test/decimaltestdata/ddPlus.decTest Lib/test/decimaltestdata/ddQuantize.decTest Lib/test/decimaltestdata/ddReduce.decTest Lib/test/decimaltestdata/ddRemainder.decTest Lib/test/decimaltestdata/ddRemainderNear.decTest Lib/test/decimaltestdata/ddRotate.decTest Lib/test/decimaltestdata/ddSameQuantum.decTest Lib/test/decimaltestdata/ddScaleB.decTest Lib/test/decimaltestdata/ddShift.decTest Lib/test/decimaltestdata/ddSubtract.decTest Lib/test/decimaltestdata/ddToIntegral.decTest Lib/test/decimaltestdata/ddXor.decTest Lib/test/decimaltestdata/decDouble.decTest Lib/test/decimaltestdata/decQuad.decTest Lib/test/decimaltestdata/decSingle.decTest Lib/test/decimaltestdata/decimal128.decTest Lib/test/decimaltestdata/decimal32.decTest Lib/test/decimaltestdata/decimal64.decTest Lib/test/decimaltestdata/divide.decTest Lib/test/decimaltestdata/divideint.decTest Lib/test/decimaltestdata/dqAbs.decTest Lib/test/decimaltestdata/dqAdd.decTest Lib/test/decimaltestdata/dqAnd.decTest Lib/test/decimaltestdata/dqBase.decTest Lib/test/decimaltestdata/dqCanonical.decTest Lib/test/decimaltestdata/dqClass.decTest Lib/test/decimaltestdata/dqCompare.decTest Lib/test/decimaltestdata/dqCompareSig.decTest Lib/test/decimaltestdata/dqCompareTotal.decTest Lib/test/decimaltestdata/dqCompareTotalMag.decTest Lib/test/decimaltestdata/dqCopy.decTest Lib/test/decimaltestdata/dqCopyAbs.decTest Lib/test/decimaltestdata/dqCopyNegate.decTest Lib/test/decimaltestdata/dqCopySign.decTest Lib/test/decimaltestdata/dqDivide.decTest Lib/test/decimaltestdata/dqDivideInt.decTest Lib/test/decimaltestdata/dqEncode.decTest Lib/test/decimaltestdata/dqFMA.decTest Lib/test/decimaltestdata/dqInvert.decTest Lib/test/decimaltestdata/dqLogB.decTest Lib/test/decimaltestdata/dqMax.decTest Lib/test/decimaltestdata/dqMaxMag.decTest Lib/test/decimaltestdata/dqMin.decTest Lib/test/decimaltestdata/dqMinMag.decTest Lib/test/decimaltestdata/dqMinus.decTest Lib/test/decimaltestdata/dqMultiply.decTest Lib/test/decimaltestdata/dqNextMinus.decTest Lib/test/decimaltestdata/dqNextPlus.decTest Lib/test/decimaltestdata/dqNextToward.decTest Lib/test/decimaltestdata/dqOr.decTest Lib/test/decimaltestdata/dqPlus.decTest Lib/test/decimaltestdata/dqQuantize.decTest Lib/test/decimaltestdata/dqReduce.decTest Lib/test/decimaltestdata/dqRemainder.decTest Lib/test/decimaltestdata/dqRemainderNear.decTest Lib/test/decimaltestdata/dqRotate.decTest Lib/test/decimaltestdata/dqSameQuantum.decTest Lib/test/decimaltestdata/dqScaleB.decTest Lib/test/decimaltestdata/dqShift.decTest Lib/test/decimaltestdata/dqSubtract.decTest Lib/test/decimaltestdata/dqToIntegral.decTest Lib/test/decimaltestdata/dqXor.decTest Lib/test/decimaltestdata/dsBase.decTest Lib/test/decimaltestdata/dsEncode.decTest Lib/test/decimaltestdata/exp.decTest Lib/test/decimaltestdata/extra.decTest Lib/test/decimaltestdata/fma.decTest Lib/test/decimaltestdata/inexact.decTest Lib/test/decimaltestdata/invert.decTest Lib/test/decimaltestdata/ln.decTest Lib/test/decimaltestdata/log10.decTest Lib/test/decimaltestdata/logb.decTest Lib/test/decimaltestdata/max.decTest Lib/test/decimaltestdata/maxmag.decTest Lib/test/decimaltestdata/min.decTest Lib/test/decimaltestdata/minmag.decTest Lib/test/decimaltestdata/minus.decTest Lib/test/decimaltestdata/multiply.decTest Lib/test/decimaltestdata/nextminus.decTest Lib/test/decimaltestdata/nextplus.decTest Lib/test/decimaltestdata/nexttoward.decTest Lib/test/decimaltestdata/normalize.decTest Lib/test/decimaltestdata/or.decTest Lib/test/decimaltestdata/plus.decTest Lib/test/decimaltestdata/power.decTest Lib/test/decimaltestdata/powersqrt.decTest Lib/test/decimaltestdata/quantize.decTest Lib/test/decimaltestdata/randomBound32.decTest Lib/test/decimaltestdata/randoms.decTest Lib/test/decimaltestdata/reduce.decTest Lib/test/decimaltestdata/remainder.decTest Lib/test/decimaltestdata/remainderNear.decTest Lib/test/decimaltestdata/rescale.decTest Lib/test/decimaltestdata/rotate.decTest Lib/test/decimaltestdata/rounding.decTest Lib/test/decimaltestdata/samequantum.decTest Lib/test/decimaltestdata/scaleb.decTest Lib/test/decimaltestdata/shift.decTest Lib/test/decimaltestdata/squareroot.decTest Lib/test/decimaltestdata/subtract.decTest Lib/test/decimaltestdata/testall.decTest Lib/test/decimaltestdata/tointegral.decTest Lib/test/decimaltestdata/tointegralx.decTest Lib/test/decimaltestdata/xor.decTest Lib/test/https_svn_python_org_root.pem Lib/test/list_tests.py Lib/test/nullcert.pem Lib/test/regrtest.py Lib/test/test_cmd_line.py Lib/test/test_collections.py Lib/test/test_decimal.py Lib/test/test_re.py Lib/test/test_repr.py Lib/test/test_socket_ssl.py Lib/test/test_ssl.py Mac/Modules/cf/_CFmodule.c Mac/Modules/cf/cfsupport.py Mac/Modules/cf/pycfbridge.c Modules/_sre.c Modules/_ssl.c Modules/bz2module.c Objects/genobject.c Objects/listobject.c Objects/object.c Message-ID: <20070919030637.1EBBF1E4005@bag.python.org> Author: thomas.wouters Date: Wed Sep 19 05:06:30 2007 New Revision: 58202 Added: python/branches/py3k/Lib/test/badcert.pem - copied unchanged from r58125, python/trunk/Lib/test/badcert.pem python/branches/py3k/Lib/test/badkey.pem - copied unchanged from r58125, python/trunk/Lib/test/badkey.pem python/branches/py3k/Lib/test/decimaltestdata/and.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/and.decTest python/branches/py3k/Lib/test/decimaltestdata/class.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/class.decTest python/branches/py3k/Lib/test/decimaltestdata/comparetotal.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/comparetotal.decTest python/branches/py3k/Lib/test/decimaltestdata/comparetotmag.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/comparetotmag.decTest python/branches/py3k/Lib/test/decimaltestdata/copy.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/copy.decTest python/branches/py3k/Lib/test/decimaltestdata/copyabs.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/copyabs.decTest python/branches/py3k/Lib/test/decimaltestdata/copynegate.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/copynegate.decTest python/branches/py3k/Lib/test/decimaltestdata/copysign.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/copysign.decTest python/branches/py3k/Lib/test/decimaltestdata/ddAbs.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddAbs.decTest python/branches/py3k/Lib/test/decimaltestdata/ddAdd.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddAdd.decTest python/branches/py3k/Lib/test/decimaltestdata/ddAnd.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddAnd.decTest python/branches/py3k/Lib/test/decimaltestdata/ddBase.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddBase.decTest python/branches/py3k/Lib/test/decimaltestdata/ddCanonical.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddCanonical.decTest python/branches/py3k/Lib/test/decimaltestdata/ddClass.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddClass.decTest python/branches/py3k/Lib/test/decimaltestdata/ddCompare.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddCompare.decTest python/branches/py3k/Lib/test/decimaltestdata/ddCompareSig.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddCompareSig.decTest python/branches/py3k/Lib/test/decimaltestdata/ddCompareTotal.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddCompareTotal.decTest python/branches/py3k/Lib/test/decimaltestdata/ddCompareTotalMag.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddCompareTotalMag.decTest python/branches/py3k/Lib/test/decimaltestdata/ddCopy.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddCopy.decTest python/branches/py3k/Lib/test/decimaltestdata/ddCopyAbs.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddCopyAbs.decTest python/branches/py3k/Lib/test/decimaltestdata/ddCopyNegate.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddCopyNegate.decTest python/branches/py3k/Lib/test/decimaltestdata/ddCopySign.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddCopySign.decTest python/branches/py3k/Lib/test/decimaltestdata/ddDivide.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddDivide.decTest python/branches/py3k/Lib/test/decimaltestdata/ddDivideInt.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddDivideInt.decTest python/branches/py3k/Lib/test/decimaltestdata/ddEncode.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddEncode.decTest python/branches/py3k/Lib/test/decimaltestdata/ddFMA.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddFMA.decTest python/branches/py3k/Lib/test/decimaltestdata/ddInvert.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddInvert.decTest python/branches/py3k/Lib/test/decimaltestdata/ddLogB.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddLogB.decTest python/branches/py3k/Lib/test/decimaltestdata/ddMax.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddMax.decTest python/branches/py3k/Lib/test/decimaltestdata/ddMaxMag.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddMaxMag.decTest python/branches/py3k/Lib/test/decimaltestdata/ddMin.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddMin.decTest python/branches/py3k/Lib/test/decimaltestdata/ddMinMag.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddMinMag.decTest python/branches/py3k/Lib/test/decimaltestdata/ddMinus.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddMinus.decTest python/branches/py3k/Lib/test/decimaltestdata/ddMultiply.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddMultiply.decTest python/branches/py3k/Lib/test/decimaltestdata/ddNextMinus.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddNextMinus.decTest python/branches/py3k/Lib/test/decimaltestdata/ddNextPlus.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddNextPlus.decTest python/branches/py3k/Lib/test/decimaltestdata/ddNextToward.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddNextToward.decTest python/branches/py3k/Lib/test/decimaltestdata/ddOr.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddOr.decTest python/branches/py3k/Lib/test/decimaltestdata/ddPlus.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddPlus.decTest python/branches/py3k/Lib/test/decimaltestdata/ddQuantize.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddQuantize.decTest python/branches/py3k/Lib/test/decimaltestdata/ddReduce.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddReduce.decTest python/branches/py3k/Lib/test/decimaltestdata/ddRemainder.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddRemainder.decTest python/branches/py3k/Lib/test/decimaltestdata/ddRemainderNear.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddRemainderNear.decTest python/branches/py3k/Lib/test/decimaltestdata/ddRotate.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddRotate.decTest python/branches/py3k/Lib/test/decimaltestdata/ddSameQuantum.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddSameQuantum.decTest python/branches/py3k/Lib/test/decimaltestdata/ddScaleB.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddScaleB.decTest python/branches/py3k/Lib/test/decimaltestdata/ddShift.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddShift.decTest python/branches/py3k/Lib/test/decimaltestdata/ddSubtract.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddSubtract.decTest python/branches/py3k/Lib/test/decimaltestdata/ddToIntegral.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddToIntegral.decTest python/branches/py3k/Lib/test/decimaltestdata/ddXor.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ddXor.decTest python/branches/py3k/Lib/test/decimaltestdata/decDouble.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/decDouble.decTest python/branches/py3k/Lib/test/decimaltestdata/decQuad.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/decQuad.decTest python/branches/py3k/Lib/test/decimaltestdata/decSingle.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/decSingle.decTest python/branches/py3k/Lib/test/decimaltestdata/dqAbs.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqAbs.decTest python/branches/py3k/Lib/test/decimaltestdata/dqAdd.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqAdd.decTest python/branches/py3k/Lib/test/decimaltestdata/dqAnd.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqAnd.decTest python/branches/py3k/Lib/test/decimaltestdata/dqBase.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqBase.decTest python/branches/py3k/Lib/test/decimaltestdata/dqCanonical.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqCanonical.decTest python/branches/py3k/Lib/test/decimaltestdata/dqClass.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqClass.decTest python/branches/py3k/Lib/test/decimaltestdata/dqCompare.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqCompare.decTest python/branches/py3k/Lib/test/decimaltestdata/dqCompareSig.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqCompareSig.decTest python/branches/py3k/Lib/test/decimaltestdata/dqCompareTotal.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqCompareTotal.decTest python/branches/py3k/Lib/test/decimaltestdata/dqCompareTotalMag.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqCompareTotalMag.decTest python/branches/py3k/Lib/test/decimaltestdata/dqCopy.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqCopy.decTest python/branches/py3k/Lib/test/decimaltestdata/dqCopyAbs.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqCopyAbs.decTest python/branches/py3k/Lib/test/decimaltestdata/dqCopyNegate.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqCopyNegate.decTest python/branches/py3k/Lib/test/decimaltestdata/dqCopySign.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqCopySign.decTest python/branches/py3k/Lib/test/decimaltestdata/dqDivide.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqDivide.decTest python/branches/py3k/Lib/test/decimaltestdata/dqDivideInt.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqDivideInt.decTest python/branches/py3k/Lib/test/decimaltestdata/dqEncode.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqEncode.decTest python/branches/py3k/Lib/test/decimaltestdata/dqFMA.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqFMA.decTest python/branches/py3k/Lib/test/decimaltestdata/dqInvert.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqInvert.decTest python/branches/py3k/Lib/test/decimaltestdata/dqLogB.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqLogB.decTest python/branches/py3k/Lib/test/decimaltestdata/dqMax.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqMax.decTest python/branches/py3k/Lib/test/decimaltestdata/dqMaxMag.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqMaxMag.decTest python/branches/py3k/Lib/test/decimaltestdata/dqMin.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqMin.decTest python/branches/py3k/Lib/test/decimaltestdata/dqMinMag.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqMinMag.decTest python/branches/py3k/Lib/test/decimaltestdata/dqMinus.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqMinus.decTest python/branches/py3k/Lib/test/decimaltestdata/dqMultiply.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqMultiply.decTest python/branches/py3k/Lib/test/decimaltestdata/dqNextMinus.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqNextMinus.decTest python/branches/py3k/Lib/test/decimaltestdata/dqNextPlus.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqNextPlus.decTest python/branches/py3k/Lib/test/decimaltestdata/dqNextToward.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqNextToward.decTest python/branches/py3k/Lib/test/decimaltestdata/dqOr.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqOr.decTest python/branches/py3k/Lib/test/decimaltestdata/dqPlus.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqPlus.decTest python/branches/py3k/Lib/test/decimaltestdata/dqQuantize.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqQuantize.decTest python/branches/py3k/Lib/test/decimaltestdata/dqReduce.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqReduce.decTest python/branches/py3k/Lib/test/decimaltestdata/dqRemainder.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqRemainder.decTest python/branches/py3k/Lib/test/decimaltestdata/dqRemainderNear.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqRemainderNear.decTest python/branches/py3k/Lib/test/decimaltestdata/dqRotate.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqRotate.decTest python/branches/py3k/Lib/test/decimaltestdata/dqSameQuantum.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqSameQuantum.decTest python/branches/py3k/Lib/test/decimaltestdata/dqScaleB.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqScaleB.decTest python/branches/py3k/Lib/test/decimaltestdata/dqShift.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqShift.decTest python/branches/py3k/Lib/test/decimaltestdata/dqSubtract.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqSubtract.decTest python/branches/py3k/Lib/test/decimaltestdata/dqToIntegral.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqToIntegral.decTest python/branches/py3k/Lib/test/decimaltestdata/dqXor.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dqXor.decTest python/branches/py3k/Lib/test/decimaltestdata/dsBase.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dsBase.decTest python/branches/py3k/Lib/test/decimaltestdata/dsEncode.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/dsEncode.decTest python/branches/py3k/Lib/test/decimaltestdata/exp.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/exp.decTest python/branches/py3k/Lib/test/decimaltestdata/extra.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/extra.decTest python/branches/py3k/Lib/test/decimaltestdata/fma.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/fma.decTest python/branches/py3k/Lib/test/decimaltestdata/invert.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/invert.decTest python/branches/py3k/Lib/test/decimaltestdata/ln.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/ln.decTest python/branches/py3k/Lib/test/decimaltestdata/log10.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/log10.decTest python/branches/py3k/Lib/test/decimaltestdata/logb.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/logb.decTest python/branches/py3k/Lib/test/decimaltestdata/maxmag.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/maxmag.decTest python/branches/py3k/Lib/test/decimaltestdata/minmag.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/minmag.decTest python/branches/py3k/Lib/test/decimaltestdata/nextminus.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/nextminus.decTest python/branches/py3k/Lib/test/decimaltestdata/nextplus.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/nextplus.decTest python/branches/py3k/Lib/test/decimaltestdata/nexttoward.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/nexttoward.decTest python/branches/py3k/Lib/test/decimaltestdata/or.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/or.decTest python/branches/py3k/Lib/test/decimaltestdata/powersqrt.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/powersqrt.decTest python/branches/py3k/Lib/test/decimaltestdata/reduce.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/reduce.decTest python/branches/py3k/Lib/test/decimaltestdata/rotate.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/rotate.decTest python/branches/py3k/Lib/test/decimaltestdata/scaleb.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/scaleb.decTest python/branches/py3k/Lib/test/decimaltestdata/shift.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/shift.decTest python/branches/py3k/Lib/test/decimaltestdata/tointegralx.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/tointegralx.decTest python/branches/py3k/Lib/test/decimaltestdata/xor.decTest - copied unchanged from r58148, python/trunk/Lib/test/decimaltestdata/xor.decTest python/branches/py3k/Lib/test/https_svn_python_org_root.pem - copied unchanged from r58125, python/trunk/Lib/test/https_svn_python_org_root.pem python/branches/py3k/Lib/test/nullcert.pem - copied unchanged from r58125, python/trunk/Lib/test/nullcert.pem Removed: python/branches/py3k/Lib/test/decimaltestdata/decimal128.decTest python/branches/py3k/Lib/test/decimaltestdata/decimal32.decTest python/branches/py3k/Lib/test/decimaltestdata/decimal64.decTest python/branches/py3k/Lib/test/decimaltestdata/normalize.decTest Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/c-api/concrete.rst python/branches/py3k/Doc/library/collections.rst python/branches/py3k/Doc/library/decimal.rst python/branches/py3k/Doc/library/fileinput.rst python/branches/py3k/Doc/library/functions.rst python/branches/py3k/Doc/library/hashlib.rst python/branches/py3k/Doc/library/operator.rst python/branches/py3k/Doc/library/os.rst python/branches/py3k/Doc/library/simplexmlrpcserver.rst python/branches/py3k/Doc/library/ssl.rst python/branches/py3k/Doc/library/undoc.rst python/branches/py3k/Doc/reference/index.rst python/branches/py3k/Doc/reference/simple_stmts.rst python/branches/py3k/Doc/whatsnew/2.5.rst python/branches/py3k/Doc/whatsnew/2.6.rst python/branches/py3k/Lib/collections.py python/branches/py3k/Lib/ctypes/test/test_cfuncs.py python/branches/py3k/Lib/ctypes/test/test_functions.py python/branches/py3k/Lib/ctypes/util.py python/branches/py3k/Lib/decimal.py python/branches/py3k/Lib/distutils/command/build_scripts.py python/branches/py3k/Lib/httplib.py python/branches/py3k/Lib/imaplib.py python/branches/py3k/Lib/platform.py python/branches/py3k/Lib/poplib.py python/branches/py3k/Lib/repr.py python/branches/py3k/Lib/smtplib.py python/branches/py3k/Lib/socket.py python/branches/py3k/Lib/ssl.py python/branches/py3k/Lib/test/decimaltestdata/abs.decTest python/branches/py3k/Lib/test/decimaltestdata/add.decTest python/branches/py3k/Lib/test/decimaltestdata/base.decTest python/branches/py3k/Lib/test/decimaltestdata/clamp.decTest python/branches/py3k/Lib/test/decimaltestdata/compare.decTest python/branches/py3k/Lib/test/decimaltestdata/divide.decTest python/branches/py3k/Lib/test/decimaltestdata/divideint.decTest python/branches/py3k/Lib/test/decimaltestdata/inexact.decTest python/branches/py3k/Lib/test/decimaltestdata/max.decTest python/branches/py3k/Lib/test/decimaltestdata/min.decTest python/branches/py3k/Lib/test/decimaltestdata/minus.decTest python/branches/py3k/Lib/test/decimaltestdata/multiply.decTest python/branches/py3k/Lib/test/decimaltestdata/plus.decTest python/branches/py3k/Lib/test/decimaltestdata/power.decTest python/branches/py3k/Lib/test/decimaltestdata/quantize.decTest python/branches/py3k/Lib/test/decimaltestdata/randomBound32.decTest python/branches/py3k/Lib/test/decimaltestdata/randoms.decTest python/branches/py3k/Lib/test/decimaltestdata/remainder.decTest python/branches/py3k/Lib/test/decimaltestdata/remainderNear.decTest python/branches/py3k/Lib/test/decimaltestdata/rescale.decTest python/branches/py3k/Lib/test/decimaltestdata/rounding.decTest python/branches/py3k/Lib/test/decimaltestdata/samequantum.decTest python/branches/py3k/Lib/test/decimaltestdata/squareroot.decTest python/branches/py3k/Lib/test/decimaltestdata/subtract.decTest python/branches/py3k/Lib/test/decimaltestdata/testall.decTest python/branches/py3k/Lib/test/decimaltestdata/tointegral.decTest python/branches/py3k/Lib/test/list_tests.py python/branches/py3k/Lib/test/regrtest.py python/branches/py3k/Lib/test/test_cmd_line.py python/branches/py3k/Lib/test/test_collections.py python/branches/py3k/Lib/test/test_decimal.py python/branches/py3k/Lib/test/test_re.py python/branches/py3k/Lib/test/test_repr.py python/branches/py3k/Lib/test/test_socket_ssl.py python/branches/py3k/Lib/test/test_ssl.py python/branches/py3k/Mac/Modules/cf/_CFmodule.c python/branches/py3k/Mac/Modules/cf/cfsupport.py python/branches/py3k/Mac/Modules/cf/pycfbridge.c python/branches/py3k/Modules/_sre.c python/branches/py3k/Modules/_ssl.c python/branches/py3k/Modules/bz2module.c python/branches/py3k/Objects/genobject.c python/branches/py3k/Objects/listobject.c python/branches/py3k/Objects/object.c Log: Merged revisions 58095-58132,58136-58148,58151-58197 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r58096 | brett.cannon | 2007-09-10 23:38:27 +0200 (Mon, 10 Sep 2007) | 4 lines Fix a possible segfault from recursing too deep to get the repr of a list. Closes issue #1096. ........ r58097 | bill.janssen | 2007-09-10 23:51:02 +0200 (Mon, 10 Sep 2007) | 33 lines More work on SSL support. * Much expanded test suite: All protocols tested against all other protocols. All protocols tested with all certificate options. Tests for bad key and bad cert. Test of STARTTLS functionality. Test of RAND_* functions. * Fixes for threading/malloc bug. * Issue 1065 fixed: sslsocket class renamed to SSLSocket. sslerror class renamed to SSLError. Function "wrap_socket" now used to wrap an existing socket. * Issue 1583946 finally fixed: Support for subjectAltName added. Subject name now returned as proper DN list of RDNs. * SSLError exported from socket as "sslerror". * RAND_* functions properly exported from ssl.py. * Documentation improved: Example of how to create a self-signed certificate. Better indexing. ........ r58098 | guido.van.rossum | 2007-09-11 00:02:25 +0200 (Tue, 11 Sep 2007) | 9 lines Patch # 1140 (my code, approved by Effbot). Make sure the type of the return value of re.sub(x, y, z) is the type of y+x (i.e. unicode if either is unicode, str if they are both str) even if there are no substitutions or if x==z (which triggered various special cases in join_list()). Could be backported to 2.5; no need to port to 3.0. ........ r58099 | guido.van.rossum | 2007-09-11 00:36:02 +0200 (Tue, 11 Sep 2007) | 8 lines Patch # 1026 by Benjamin Aranguren (with Alex Martelli): Backport abc.py and isinstance/issubclass overloading to 2.6. I had to backport test_typechecks.py myself, and make one small change to abc.py to avoid duplicate work when x.__class__ and type(x) are the same. ........ r58100 | bill.janssen | 2007-09-11 01:41:24 +0200 (Tue, 11 Sep 2007) | 3 lines A better way of finding an open port to test with. ........ r58101 | bill.janssen | 2007-09-11 03:09:19 +0200 (Tue, 11 Sep 2007) | 4 lines Make sure test_ssl doesn't reference the ssl module in a context where it can't be imported. ........ r58102 | bill.janssen | 2007-09-11 04:42:07 +0200 (Tue, 11 Sep 2007) | 3 lines Fix some documentation bugs. ........ r58103 | nick.coghlan | 2007-09-11 16:01:18 +0200 (Tue, 11 Sep 2007) | 1 line Always use the -E flag when spawning subprocesses in test_cmd_line (Issue 1056) ........ r58106 | thomas.heller | 2007-09-11 21:17:48 +0200 (Tue, 11 Sep 2007) | 3 lines Disable some tests that fail on the 'ppc Debian unstable' buildbot to find out if they cause the segfault on the 'alpha Debian' machine. ........ r58108 | brett.cannon | 2007-09-11 23:02:28 +0200 (Tue, 11 Sep 2007) | 6 lines Generators had their throw() method allowing string exceptions. That's a no-no. Fixes issue #1147. Need to fix 2.5 to raise a proper warning if a string exception is passed in. ........ r58112 | georg.brandl | 2007-09-12 20:03:51 +0200 (Wed, 12 Sep 2007) | 3 lines New documentation page for the bdb module. (This doesn't need to be merged to Py3k.) ........ r58114 | georg.brandl | 2007-09-12 20:05:57 +0200 (Wed, 12 Sep 2007) | 2 lines Bug #1152: use non-deprecated name in example. ........ r58115 | georg.brandl | 2007-09-12 20:08:33 +0200 (Wed, 12 Sep 2007) | 2 lines Fix #1122: wrong return type documented for various _Size() functions. ........ r58117 | georg.brandl | 2007-09-12 20:10:56 +0200 (Wed, 12 Sep 2007) | 2 lines Fix #1139: PyFile_Encoding really is PyFile_SetEncoding. ........ r58119 | georg.brandl | 2007-09-12 20:29:18 +0200 (Wed, 12 Sep 2007) | 2 lines bug #1154: release memory allocated by "es" PyArg_ParseTuple format specifier. ........ r58121 | bill.janssen | 2007-09-12 20:52:05 +0200 (Wed, 12 Sep 2007) | 1 line root certificate for https://svn.python.org/, used in test_ssl ........ r58122 | georg.brandl | 2007-09-12 21:00:07 +0200 (Wed, 12 Sep 2007) | 3 lines Bug #1153: repr.repr() now doesn't require set and dictionary items to be orderable to properly represent them. ........ r58125 | georg.brandl | 2007-09-12 21:29:28 +0200 (Wed, 12 Sep 2007) | 4 lines #1120: put explicit version in the shebang lines of pydoc, idle and smtpd.py scripts that are installed by setup.py. That way, they work when only "make altinstall" is used. ........ r58139 | mark.summerfield | 2007-09-13 16:54:30 +0200 (Thu, 13 Sep 2007) | 9 lines Replaced variable o with obj in operator.rst because o is easy to confuse. Added a note about Python 3's collections.Mapping etc., above section that describes isMappingType() etc. Added xrefs between os, os.path, fileinput, and open(). ........ r58143 | facundo.batista | 2007-09-13 20:13:15 +0200 (Thu, 13 Sep 2007) | 7 lines Merged the decimal-branch (revisions 54886 to 58140). Decimal is now fully updated to the latests Decimal Specification (v1.66) and the latests test cases (v2.56). Thanks to Mark Dickinson for all his help during this process. ........ r58145 | facundo.batista | 2007-09-13 20:42:09 +0200 (Thu, 13 Sep 2007) | 7 lines Put the parameter watchexp back in (changed watchexp from an int to a bool). Also second argument to watchexp is now converted to Decimal, just as with all the other two-argument operations. Thanks Mark Dickinson. ........ r58147 | andrew.kuchling | 2007-09-14 00:49:34 +0200 (Fri, 14 Sep 2007) | 1 line Add various items ........ r58148 | andrew.kuchling | 2007-09-14 00:50:10 +0200 (Fri, 14 Sep 2007) | 1 line Make target unique ........ r58154 | facundo.batista | 2007-09-14 20:58:34 +0200 (Fri, 14 Sep 2007) | 3 lines Included the new functions, and new descriptions. ........ r58155 | thomas.heller | 2007-09-14 21:40:35 +0200 (Fri, 14 Sep 2007) | 2 lines ctypes.util.find_library uses dump(1) instead of objdump(1) on Solaris. Fixes issue #1777530; will backport to release25-maint. ........ r58159 | facundo.batista | 2007-09-14 23:29:52 +0200 (Fri, 14 Sep 2007) | 3 lines Some additions (examples and a bit on the tutorial). ........ r58160 | georg.brandl | 2007-09-15 18:53:36 +0200 (Sat, 15 Sep 2007) | 2 lines Remove bdb from the "undocumented modules" list. ........ r58164 | bill.janssen | 2007-09-17 00:06:00 +0200 (Mon, 17 Sep 2007) | 15 lines Add support for asyncore server-side SSL support. This requires adding the 'makefile' method to ssl.SSLSocket, and importing the requisite fakefile class from socket.py, and making the appropriate changes to it to make it use the SSL connection. Added sample HTTPS server to test_ssl.py, and test that uses it. Change SSL tests to use https://svn.python.org/, instead of www.sf.net and pop.gmail.com. Added utility function to ssl module, get_server_certificate, to wrap up the several things to be done to pull a certificate from a remote server. ........ r58173 | bill.janssen | 2007-09-17 01:16:46 +0200 (Mon, 17 Sep 2007) | 1 line use binary mode when reading files for testAsyncore to make Windows happy ........ r58175 | raymond.hettinger | 2007-09-17 02:55:00 +0200 (Mon, 17 Sep 2007) | 7 lines Sync-up named tuples with the latest version of the ASPN recipe. Allows optional commas in the field-name spec (help when named tuples are used in conjuction with sql queries). Adds the __fields__ attribute for introspection and to support conversion to dictionary form. Adds a __replace__() method similar to str.replace() but using a named field as a target. Clean-up spelling and presentation in doc-strings. ........ r58176 | brett.cannon | 2007-09-17 05:28:34 +0200 (Mon, 17 Sep 2007) | 5 lines Add a bunch of GIL release/acquire points in tp_print implementations and for PyObject_Print(). Closes issue #1164. ........ r58177 | sean.reifschneider | 2007-09-17 07:45:04 +0200 (Mon, 17 Sep 2007) | 2 lines issue1597011: Fix for bz2 module corner-case error due to error checking bug. ........ r58180 | facundo.batista | 2007-09-17 18:26:50 +0200 (Mon, 17 Sep 2007) | 3 lines Decimal is updated, :) ........ r58181 | facundo.batista | 2007-09-17 19:30:13 +0200 (Mon, 17 Sep 2007) | 5 lines The methods always return Decimal classes, even if they're executed through a subclass (thanks Mark Dickinson). Added a bit of testing for this. ........ r58183 | sean.reifschneider | 2007-09-17 22:53:21 +0200 (Mon, 17 Sep 2007) | 2 lines issue1082: Fixing platform and system for Vista. ........ r58185 | andrew.kuchling | 2007-09-18 03:36:16 +0200 (Tue, 18 Sep 2007) | 1 line Add item; sort properly ........ r58186 | raymond.hettinger | 2007-09-18 05:33:19 +0200 (Tue, 18 Sep 2007) | 1 line Handle corner cased on 0-tuples and 1-tuples. Add verbose option so people can see how it works. ........ r58192 | georg.brandl | 2007-09-18 09:24:40 +0200 (Tue, 18 Sep 2007) | 2 lines A bit of reordering, also show more subheadings in the lang ref index. ........ r58193 | facundo.batista | 2007-09-18 18:53:18 +0200 (Tue, 18 Sep 2007) | 4 lines Speed up of the various division operations (remainder, divide, divideint and divmod). Thanks Mark Dickinson. ........ r58197 | raymond.hettinger | 2007-09-19 00:18:02 +0200 (Wed, 19 Sep 2007) | 1 line Cleanup docs for NamedTuple. ........ Modified: python/branches/py3k/Doc/c-api/concrete.rst ============================================================================== --- python/branches/py3k/Doc/c-api/concrete.rst (original) +++ python/branches/py3k/Doc/c-api/concrete.rst Wed Sep 19 05:06:30 2007 @@ -1953,12 +1953,12 @@ ``PyTuple_Pack(2, a, b)`` is equivalent to ``Py_BuildValue("(OO)", a, b)``. -.. cfunction:: int PyTuple_Size(PyObject *p) +.. cfunction:: Py_ssize_t PyTuple_Size(PyObject *p) Take a pointer to a tuple object, and return the size of that tuple. -.. cfunction:: int PyTuple_GET_SIZE(PyObject *p) +.. cfunction:: Py_ssize_t PyTuple_GET_SIZE(PyObject *p) Return the size of the tuple *p*, which must be non-*NULL* and point to a tuple; no error checking is performed. @@ -2458,7 +2458,7 @@ immediately after file object creation. -.. cfunction:: int PyFile_Encoding(PyFileObject *p, char *enc) +.. cfunction:: int PyFile_SetEncoding(PyFileObject *p, const char *enc) Set the file's encoding for Unicode output to *enc*. Return 1 on success and 0 on failure. @@ -3371,7 +3371,7 @@ or :class:`frozenset` or instances of their subtypes. -.. cfunction:: int PySet_Size(PyObject *anyset) +.. cfunction:: Py_ssize_t PySet_Size(PyObject *anyset) .. index:: builtin: len @@ -3380,7 +3380,7 @@ :class:`set`, :class:`frozenset`, or an instance of a subtype. -.. cfunction:: int PySet_GET_SIZE(PyObject *anyset) +.. cfunction:: Py_ssize_t PySet_GET_SIZE(PyObject *anyset) Macro form of :cfunc:`PySet_Size` without error checking. Modified: python/branches/py3k/Doc/library/collections.rst ============================================================================== --- python/branches/py3k/Doc/library/collections.rst (original) +++ python/branches/py3k/Doc/library/collections.rst Wed Sep 19 05:06:30 2007 @@ -395,11 +395,14 @@ .. _named-tuple-factory: -:func:`NamedTuple` datatype factory function --------------------------------------------- +:func:`NamedTuple` factory function +----------------------------------- +Named tuples assign meaning to each position in a tuple and allow for more readable, +self-documenting code. They can be used wherever regular tuples are used, and +they add the ability to access fields by name instead of position index. -.. function:: NamedTuple(typename, fieldnames) +.. function:: NamedTuple(typename, fieldnames, [verbose]) Returns a new tuple subclass named *typename*. The new subclass is used to create tuple-like objects that have fields accessable by attribute lookup as @@ -407,43 +410,88 @@ helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__` method which lists the tuple contents in a ``name=value`` format. - The *fieldnames* are specified in a single string and are separated by spaces. - Any valid Python identifier may be used for a field name. + The *fieldnames* are specified in a single string with each fieldname separated by + a space and/or comma. Any valid Python identifier may be used for a field name. - Example:: + If *verbose* is true, the *NamedTuple* call will print the class definition. - >>> Point = NamedTuple('Point', 'x y') - >>> Point.__doc__ # docstring for the new datatype - 'Point(x, y)' - >>> p = Point(11, y=22) # instantiate with positional or keyword arguments - >>> p[0] + p[1] # works just like the tuple (11, 22) - 33 - >>> x, y = p # unpacks just like a tuple - >>> x, y - (11, 22) - >>> p.x + p.y # fields also accessable by name - 33 - >>> p # readable __repr__ with name=value style - Point(x=11, y=22) - - The use cases are the same as those for tuples. The named factories assign - meaning to each tuple position and allow for more readable, self-documenting - code. Named tuples can also be used to assign field names to tuples returned - by the :mod:`csv` or :mod:`sqlite3` modules. For example:: - - from itertools import starmap - import csv - EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade') - for record in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))): - print(record) - - To cast an individual record stored as :class:`list`, :class:`tuple`, or some - other iterable type, use the star-operator [#]_ to unpack the values:: - - >>> Color = NamedTuple('Color', 'name code') - >>> m = dict(red=1, green=2, blue=3) - >>> print(Color(*m.popitem())) - Color(name='blue', code=3) + *NamedTuple* instances do not have per-instance dictionaries, so they are + lightweight, requiring no more memory than regular tuples. + +Example:: + + >>> Point = NamedTuple('Point', 'x y', True) + class Point(tuple): + 'Point(x, y)' + __slots__ = () + __fields__ = ('x', 'y') + def __new__(cls, x, y): + return tuple.__new__(cls, (x, y)) + def __repr__(self): + return 'Point(x=%r, y=%r)' % self + def __replace__(self, field, value): + 'Return a new Point object replacing one field with a new value' + return Point(**dict(zip(('x', 'y'), self) + [(field, value)])) + x = property(itemgetter(0)) + y = property(itemgetter(1)) + + >>> p = Point(11, y=22) # instantiate with positional or keyword arguments + >>> p[0] + p[1] # indexable like the regular tuple (11, 22) + 33 + >>> x, y = p # unpack like a regular tuple + >>> x, y + (11, 22) + >>> p.x + p.y # fields also accessable by name + 33 + >>> p # readable __repr__ with a name=value style + Point(x=11, y=22) + +Named tuples are especially useful for assigning field names to result tuples returned +by the :mod:`csv` or :mod:`sqlite3` modules:: + + from itertools import starmap + import csv + EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade') + for record in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))): + print(emp.name, emp.title) + +When casting a single record to a *NamedTuple*, use the star-operator [#]_ to unpack +the values:: + + >>> t = [11, 22] + >>> Point(*t) # the star-operator unpacks any iterable object + Point(x=11, y=22) + +In addition to the methods inherited from tuples, named tuples support +an additonal method and an informational read-only attribute. + +.. method:: somenamedtuple.replace(field, value) + + Return a new instance of the named tuple replacing the named *field* with a new *value*:: + + >>> p = Point(x=11, y=22) + >>> p.__replace__('x', 33) + Point(x=33, y=22) + + >>> for recordnum, record in inventory: + ... inventory[recordnum] = record.replace('total', record.price * record.quantity) + +.. attribute:: somenamedtuple.__fields__ + + Return a tuple of strings listing the field names. This is useful for introspection, + for converting a named tuple instance to a dictionary, and for combining named tuple + types to create new named tuple types:: + + >>> p.__fields__ # view the field names + ('x', 'y') + >>> dict(zip(p.__fields__, p)) # convert to a dictionary + {'y': 22, 'x': 11} + + >>> Color = NamedTuple('Color', 'red green blue') + >>> pixel_fields = ' '.join(Point.__fields__ + Color.__fields__) # combine fields + >>> Pixel = NamedTuple('Pixel', pixel_fields) + >>> Pixel(11, 22, 128, 255, 0) + Pixel(x=11, y=22, red=128, green=255, blue=0)' .. rubric:: Footnotes Modified: python/branches/py3k/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k/Doc/library/decimal.rst (original) +++ python/branches/py3k/Doc/library/decimal.rst Wed Sep 19 05:06:30 2007 @@ -14,7 +14,7 @@ The :mod:`decimal` module provides support for decimal floating point -arithmetic. It offers several advantages over the :class:`float()` datatype: +arithmetic. It offers several advantages over the :class:`float` datatype: * Decimal numbers can be represented exactly. In contrast, numbers like :const:`1.1` do not have an exact representation in binary floating point. End @@ -22,7 +22,7 @@ :const:`1.1000000000000001` as it does with binary floating point. * The exactness carries over into arithmetic. In decimal floating point, ``0.1 - + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, result + + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result is :const:`5.5511151231257827e-017`. While near to zero, the differences prevent reliable equality testing and differences can accumulate. For this reason, decimal would be preferred in accounting applications which have strict @@ -36,7 +36,7 @@ 1.20`` gives :const:`1.5600`. * Unlike hardware based binary floating point, the decimal module has a user - settable precision (defaulting to 28 places) which can be as large as needed for + alterable precision (defaulting to 28 places) which can be as large as needed for a given problem:: >>> getcontext().prec = 6 @@ -56,7 +56,7 @@ A decimal number is immutable. It has a sign, coefficient digits, and an exponent. To preserve significance, the coefficient digits do not truncate -trailing zeroes. Decimals also include special values such as +trailing zeros. Decimals also include special values such as :const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also differentiates :const:`-0` from :const:`+0`. @@ -65,7 +65,7 @@ enablers which determine whether signals are treated as exceptions. Rounding options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`, :const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`, -:const:`ROUND_HALF_UP`, and :const:`ROUND_UP`. +:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`. Signals are groups of exceptional conditions arising during the course of computation. Depending on the needs of the application, signals may be ignored, @@ -82,11 +82,11 @@ .. seealso:: - IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic - Specification `_. + * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic + Specification `_. - IEEE standard 854-1987, `Unofficial IEEE 854 Text - `_. + * IEEE standard 854-1987, `Unofficial IEEE 854 Text + `_. .. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -123,6 +123,8 @@ Decimal("3.14") >>> Decimal(str(2.0 ** 0.5)) Decimal("1.41421356237") + >>> Decimal(2) ** Decimal("0.5") + Decimal("1.414213562373095048801688724") >>> Decimal("NaN") Decimal("NaN") >>> Decimal("-Infinity") @@ -172,6 +174,17 @@ >>> c % a Decimal("0.77") +And some mathematic functions are also available to Decimal:: + + >>> Decimal(2).sqrt() + Decimal("1.414213562373095048801688724") + >>> Decimal(1).exp() + Decimal("2.718281828459045235360287471") + >>> Decimal("10").ln() + Decimal("2.302585092994045684017991455") + >>> Decimal("10").log10() + Decimal("1") + The :meth:`quantize` method rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of places:: @@ -285,7 +298,7 @@ The *context* precision does not affect how many digits are stored. That is determined exclusively by the number of digits in *value*. For example, - ``Decimal("3.00000")`` records all five zeroes even if the context precision is + ``Decimal("3.00000")`` records all five zeros even if the context precision is only three. The purpose of the *context* argument is determining what to do if *value* is a @@ -295,7 +308,7 @@ Once constructed, :class:`Decimal` objects are immutable. -Decimal floating point objects share many properties with the other builtin +Decimal floating point objects share many properties with the other built-in numeric types such as :class:`float` and :class:`int`. All of the usual math operations and special methods apply. Likewise, decimal objects can be copied, pickled, printed, used as dictionary keys, used as set elements, compared, @@ -315,50 +328,363 @@ .. method:: Decimal.as_tuple() - Returns a tuple representation of the number: ``(sign, digittuple, exponent)``. + Return a tuple representation of the number: ``(sign, digit_tuple, exponent)``. + +.. method:: Decimal.canonical() + + Return the canonical encoding of the argument. Currently, the + encoding of a :class:`Decimal` instance is always canonical, so + this operation returns its argument unchanged. + + .. versionadded:: 2.6 .. method:: Decimal.compare(other[, context]) - Compares like :meth:`__cmp__` but returns a decimal instance:: + Compare the values of two Decimal instances. This operation + behaves in the same way as the usual comparison method + :meth:`__cmp__`, except that :meth:`compare` returns a Decimal + instance rather than an integer, and if either operand is a NaN + then the result is a NaN:: a or b is a NaN ==> Decimal("NaN") a < b ==> Decimal("-1") a == b ==> Decimal("0") a > b ==> Decimal("1") +.. method:: Decimal.compare_signal(other[, context]) + + This operation is identical to the :meth:`compare` method, except + that all NaNs signal. That is, if neither operand is a signaling + NaN then any quiet NaN operand is treated as though it were a + signaling NaN. + + .. versionadded:: 2.6 + +.. method:: Decimal.compare_total(other) + + Compare two operands using their abstract representation rather + than their numerical value. Similar to the :meth:`compare` method, + but the result gives a total ordering on :class:`Decimal` + instances. Two :class:`Decimal` instances with the same numeric + value but different representations compare unequal in this + ordering:: + + >>> Decimal("12.0").compare_total(Decimal("12")) + Decimal("-1") + + Quiet and signaling NaNs are also included in the total ordering. + The result of this function is ``Decimal("0")`` if both operands + have the same representation, ``Decimal("-1")`` if the first + operand is lower in the total order than the second, and + ``Decimal("1")`` if the first operand is higher in the total order + than the second operand. See the specification for details of the + total order. + + .. versionadded:: 2.6 + +.. method:: Decimal.compare_total_mag(other) + + Compare two operands using their abstract representation rather + than their value as in :meth:`compare_total`, but ignoring the sign + of each operand. ``x.compare_total_mag(y)`` is equivalent to + ``x.copy_abs().compare_total(y.copy_abs())``. + + .. versionadded:: 2.6 + +.. method:: Decimal.copy_abs() + + Return the absolute value of the argument. This operation is + unaffected by the context and is quiet: no flags are changed and no + rounding is performed. + + .. versionadded:: 2.6 + +.. method:: Decimal.copy_negate() + + Return the negation of the argument. This operation is unaffected + by the context and is quiet: no flags are changed and no rounding + is performed. + + .. versionadded:: 2.6 + +.. method:: Decimal.copy_sign(other) + + Return a copy of the first operand with the sign set to be the + same as the sign of the second operand. For example:: + + >>> Decimal("2.3").copy_sign(Decimal("-1.5")) + Decimal("-2.3") + + This operation is unaffected by the context and is quiet: no flags + are changed and no rounding is performed. + + .. versionadded:: 2.6 + +.. method:: Decimal.exp([context]) + + Return the value of the (natural) exponential function ``e**x`` at the + given number. The result is correctly rounded using the + :const:`ROUND_HALF_EVEN` rounding mode. + + >>> Decimal(1).exp() + Decimal("2.718281828459045235360287471") + >>> Decimal(321).exp() + Decimal("2.561702493119680037517373933E+139") + + .. versionadded:: 2.6 + +.. method:: Decimal.fma(other, third[, context]) + + Fused multiply-add. Return self*other+third with no rounding of + the intermediate product self*other. + + >>> Decimal(2).fma(3, 5) + Decimal("11") + + .. versionadded:: 2.6 + +.. method:: Decimal.is_canonical() + + Return :const:`True` if the argument is canonical and + :const:`False` otherwise. Currently, a :class:`Decimal` instance + is always canonical, so this operation always returns + :const:`True`. + + .. versionadded:: 2.6 + +.. method:: is_finite() + + Return :const:`True` if the argument is a finite number, and + :const:`False` if the argument is an infinity or a NaN. + + .. versionadded:: 2.6 + +.. method:: is_infinite() + + Return :const:`True` if the argument is either positive or + negative infinity and :const:`False` otherwise. + + .. versionadded:: 2.6 + +.. method:: is_nan() + + Return :const:`True` if the argument is a (quiet or signaling) + NaN and :const:`False` otherwise. + + .. versionadded:: 2.6 + +.. method:: is_normal() + + Return :const:`True` if the argument is a *normal* finite number. + Return :const:`False` if the argument is zero, subnormal, infinite + or a NaN. + + .. versionadded:: 2.6 + +.. method:: is_qnan() + + Return :const:`True` if the argument is a quiet NaN, and + :const:`False` otherwise. + + .. versionadded:: 2.6 + +.. method:: is_signed() + + Return :const:`True` if the argument has a negative sign and + :const:`False` otherwise. Note that zeros and NaNs can both carry + signs. + + .. versionadded:: 2.6 + +.. method:: is_snan() + + Return :const:`True` if the argument is a signaling NaN and + :const:`False` otherwise. + + .. versionadded:: 2.6 + +.. method:: is_subnormal() + + Return :const:`True` if the argument is subnormal, and + :const:`False` otherwise. + + .. versionadded:: 2.6 + +.. method:: is_zero() + + Return :const:`True` if the argument is a (positive or negative) + zero and :const:`False` otherwise. + + .. versionadded:: 2.6 + +.. method:: Decimal.ln([context]) + + Return the natural (base e) logarithm of the operand. The result + is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding + mode. + + .. versionadded:: 2.6 + +.. method:: Decimal.log10([context]) + + Return the base ten logarithm of the operand. The result is + correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. + + .. versionadded:: 2.6 + +.. method: Decimal.logb([context]) + + For a nonzero number, return the adjusted exponent of its operand + as a :class:`Decimal` instance. If the operand is a zero then + ``Decimal("-Infinity")`` is returned and the + :const:`DivisionByZero` flag is raised. If the operand is an + infinity then ``Decimal("Infinity")`` is returned. + + .. versionadded:: 2.6 + +.. method:: Decimal.logical_and(other[, context]) + + :meth:`logical_and` is a logical operation which takes two + *logical operands* (see :ref:`logical_operands_label`). The result + is the digit-wise ``and`` of the two operands. + + .. versionadded:: 2.6 + +.. method:: Decimal.logical_invert(other[, context]) + + :meth:`logical_invert` is a logical operation. The argument must + be a *logical operand* (see :ref:`logical_operands_label`). The + result is the digit-wise inversion of the operand. + + .. versionadded:: 2.6 + +.. method:: Decimal.logical_or(other[, context]) + + :meth:`logical_or` is a logical operation which takes two *logical + operands* (see :ref:`logical_operands_label`). The result is the + digit-wise ``or`` of the two operands. + + .. versionadded:: 2.6 + +.. method:: Decimal.logical_xor(other[, context]) + + :meth:`logical_xor` is a logical operation which takes two + *logical operands* (see :ref:`logical_operands_label`). The result + is the digit-wise exclusive or of the two operands. + + .. versionadded:: 2.6 .. method:: Decimal.max(other[, context]) Like ``max(self, other)`` except that the context rounding rule is applied - before returning and that :const:`NaN` values are either signalled or ignored + before returning and that :const:`NaN` values are either signaled or ignored (depending on the context and whether they are signaling or quiet). +.. method:: Decimal.max_mag(other[, context]) + + Similar to the :meth:`max` method, but the comparison is done using + the absolute values of the operands. + + .. versionadded:: 2.6 .. method:: Decimal.min(other[, context]) Like ``min(self, other)`` except that the context rounding rule is applied - before returning and that :const:`NaN` values are either signalled or ignored + before returning and that :const:`NaN` values are either signaled or ignored (depending on the context and whether they are signaling or quiet). +.. method:: Decimal.min_mag(other[, context]) + + Similar to the :meth:`min` method, but the comparison is done using + the absolute values of the operands. + + .. versionadded:: 2.6 + +.. method:: Decimal.next_minus([context]) + + Return the largest number representable in the given context (or + in the current thread's context if no context is given) that is smaller + than the given operand. + + .. versionadded:: 2.6 + +.. method:: Decimal.next_plus([context]) + + Return the smallest number representable in the given context (or + in the current thread's context if no context is given) that is + larger than the given operand. + + .. versionadded:: 2.6 + +.. method:: Decimal.next_toward(other[, context]) + + If the two operands are unequal, return the number closest to the + first operand in the direction of the second operand. If both + operands are numerically equal, return a copy of the first operand + with the sign set to be the same as the sign of the second operand. + + .. versionadded:: 2.6 .. method:: Decimal.normalize([context]) - Normalize the number by stripping the rightmost trailing zeroes and converting + Normalize the number by stripping the rightmost trailing zeros and converting any result equal to :const:`Decimal("0")` to :const:`Decimal("0e0")`. Used for producing canonical values for members of an equivalence class. For example, ``Decimal("32.100")`` and ``Decimal("0.321000e+2")`` both normalize to the equivalent value ``Decimal("32.1")``. +.. method:: Decimal.number_class([context]) + + Return a string describing the *class* of the operand. The + returned value is one of the following ten strings. + + * ``"-Infinity"``, indicating that the operand is negative infinity. + * ``"-Normal"``, indicating that the operand is a negative normal number. + * ``"-Subnormal"``, indicating that the operand is negative and subnormal. + * ``"-Zero"``, indicating that the operand is a negative zero. + * ``"+Zero"``, indicating that the operand is a positive zero. + * ``"+Subnormal"``, indicating that the operand is positive and subnormal. + * ``"+Normal"``, indicating that the operand is a positive normal number. + * ``"+Infinity"``, indicating that the operand is positive infinity. + * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). + * ``"sNaN"``, indicating that the operand is a signaling NaN. -.. method:: Decimal.quantize(exp [, rounding[, context[, watchexp]]]) + .. versionadded:: 2.6 - Quantize makes the exponent the same as *exp*. Searches for a rounding method - in *rounding*, then in *context*, and then in the current context. +.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]]) - If *watchexp* is set (default), then an error is returned whenever the resulting - exponent is greater than :attr:`Emax` or less than :attr:`Etiny`. + Returns a value equal to the first operand after rounding and + having the exponent of the second operand. + >>> Decimal("1.41421356").quantize(Decimal("1.000")) + Decimal("1.414") + + Unlike other operations, if the length of the coefficient after the + quantize operation would be greater than precision, then an + :const:`InvalidOperation` is signaled. This guarantees that, unless + there is an error condition, the quantized exponent is always equal + to that of the right-hand operand. + + Also unlike other operations, quantize never signals Underflow, + even if the result is subnormal and inexact. + + If the exponent of the second operand is larger than that of the + first then rounding may be necessary. In this case, the rounding + mode is determined by the ``rounding`` argument if given, else by + the given ``context`` argument; if neither argument is given the + rounding mode of the current thread's context is used. + + If watchexp is set (default), then an error is returned whenever + the resulting exponent is greater than Emax or less than Etiny. + +.. method:: Decimal.radix() + + Return ``Decimal(10)``, the radix (base) in which the + :class:`Decimal` class does all its arithmetic. Included for + compatibility with the specification. + + .. versionadded:: 2.6 .. method:: Decimal.remainder_near(other[, context]) @@ -368,16 +694,49 @@ If both are equally close, the one chosen will have the same sign as *self*. +.. method:: Decimal.rotate(other[, context]) + + Return the result of rotating the digits of the first operand by + an amount specified by the second operand. The second operand + must be an integer in the range -precision through precision. The + absolute value of the second operand gives the number of places to + rotate. If the second operand is positive then rotation is to the + left; otherwise rotation is to the right. The coefficient of the + first operand is padded on the left with zeros to length precision + if necessary. The sign and exponent of the first operand are + unchanged. + + .. versionadded:: 2.6 .. method:: Decimal.same_quantum(other[, context]) Test whether self and other have the same exponent or whether both are :const:`NaN`. +.. method:: Decimal.scaleb(other[, context]) + + Return the first operand with exponent adjusted by the second. + Equivalently, return the first operand multiplied by ``10**other``. + The second operand must be an integer. + + .. versionadded:: 2.6 + +.. method:: Decimal.shift(other[, context]) + + Return the result of shifting the digits of the first operand by + an amount specified by the second operand. The second operand must + be an integer in the range -precision through precision. The + absolute value of the second operand gives the number of places to + shift. If the second operand is positive then the shift is to the + left; otherwise the shift is to the right. Digits shifted into the + coefficient are zeros. The sign and exponent of the first operand + are unchanged. + + .. versionadded:: 2.6 .. method:: Decimal.sqrt([context]) - Return the square root to full precision. + Return the square root of the argument to full precision. .. method:: Decimal.to_eng_string([context]) @@ -388,13 +747,53 @@ to 3 digits left of the decimal place. For example, converts ``Decimal('123E+1')`` to ``Decimal("1.23E+3")`` - .. method:: Decimal.to_integral([rounding[, context]]) + Identical to the :meth:`to_integral_value` method. The ``to_integral`` + name has been kept for compatibility with older versions. + +.. method:: Decimal.to_integral_exact([rounding[, context]]) + + Round the argument to the nearest integer, signaling + :const:`Inexact` or :const:`Rounded` as appropriate if rounding + occurs. The rounding mode is determined by the ``rounding`` + parameter if given, else by the given ``context``. If neither + parameter is given then the rounding mode of the current context is + used. + + .. versionadded:: 2.6 + +.. method:: Decimal.to_integral_value([rounding[, context]]) + Rounds to the nearest integer without signaling :const:`Inexact` or :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding method in either the supplied *context* or the current context. + .. versionchanged:: 2.6 + renamed from ``to_integral`` to ``to_integral_value``. The old name + remains valid for compatibility. + +.. method:: Decimal.trim() + + Returns its argument with *insignificant* trailing zeros removed. + Here, a trailing zero is considered insignificant either if it + follows the decimal point, or if the exponent of the argument (that + is, the last element of the :meth:`as_tuple` representation) is + positive. + + .. versionadded:: 2.6 + +.. _logical_operands_label: + +Logical operands +^^^^^^^^^^^^^^^^ + +The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`, +and :meth:`logical_xor` methods expect their arguments to be *logical +operands*. A *logical operand* is a :class:`Decimal` instance whose +exponent and sign are both zero, and whose digits are all either +:const:`0` or :const:`1`. + .. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -509,6 +908,8 @@ * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer), * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or * :const:`ROUND_UP` (away from zero). + * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero + would have been 0 or 5; otherwise towards zero) The *traps* and *flags* fields list any signals to be set. Generally, new contexts should only set traps and leave the flags clear. @@ -520,9 +921,16 @@ :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`. -The :class:`Context` class defines several general purpose methods as well as a -large number of methods for doing arithmetic directly in a given context. + .. versionchanged:: 2.6 + The :const:`ROUND_05UP` rounding mode was added. +The :class:`Context` class defines several general purpose methods as +well as a large number of methods for doing arithmetic directly in a +given context. In addition, for each of the :class:`Decimal` methods +described above (with the exception of the :meth:`adjusted` and +:meth:`as_tuple` methods) there is a corresponding :class:`Context` +method. For example, ``C.exp(x)`` is equivalent to +``x.exp(context=C)``. .. method:: Context.clear_flags() @@ -533,6 +941,9 @@ Return a duplicate of the context. +.. method:: Context.copy_decimal(num) + + Return a copy of the Decimal instance num. .. method:: Context.create_decimal(num) @@ -581,42 +992,19 @@ Return the sum of *x* and *y*. -.. method:: Context.compare(x, y) - - Compares values numerically. - - Like :meth:`__cmp__` but returns a decimal instance:: - - a or b is a NaN ==> Decimal("NaN") - a < b ==> Decimal("-1") - a == b ==> Decimal("0") - a > b ==> Decimal("1") - - .. method:: Context.divide(x, y) Return *x* divided by *y*. -.. method:: Context.divmod(x, y) - - Divides two numbers and returns the integer part of the result. - - -.. method:: Context.max(x, y) - - Compare two values numerically and return the maximum. - - If they are numerically equal then the left-hand operand is chosen as the - result. +.. method:: Context.divide_int(x, y) + Return *x* divided by *y*, truncated to an integer. -.. method:: Context.min(x, y) - Compare two values numerically and return the minimum. +.. method:: Context.divmod(x, y) - If they are numerically equal then the left-hand operand is chosen as the - result. + Divides two numbers and returns the integer part of the result. .. method:: Context.minus(x) @@ -629,14 +1017,6 @@ Return the product of *x* and *y*. -.. method:: Context.normalize(x) - - Normalize reduces an operand to its simplest form. - - Essentially a :meth:`plus` operation with all trailing zeros removed from the - result. - - .. method:: Context.plus(x) Plus corresponds to the unary prefix plus operator in Python. This operation @@ -646,33 +1026,31 @@ .. method:: Context.power(x, y[, modulo]) - Return ``x ** y`` to the *modulo* if given. - - The right-hand operand must be a whole number whose integer part (after any - exponent has been applied) has no more than 9 digits and whose fractional part - (if any) is all zeros before any rounding. The operand may be positive, - negative, or zero; if negative, the absolute value of the power is used, and the - left-hand operand is inverted (divided into 1) before use. - - If the increased precision needed for the intermediate calculations exceeds the - capabilities of the implementation then an :const:`InvalidOperation` condition - is signaled. + Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if + given. - If, when raising to a negative power, an underflow occurs during the division - into 1, the operation is not halted at that point but continues. - - -.. method:: Context.quantize(x, y) - - Returns a value equal to *x* after rounding and having the exponent of *y*. - - Unlike other operations, if the length of the coefficient after the quantize - operation would be greater than precision, then an :const:`InvalidOperation` is - signaled. This guarantees that, unless there is an error condition, the - quantized exponent is always equal to that of the right-hand operand. - - Also unlike other operations, quantize never signals Underflow, even if the - result is subnormal and inexact. + With two arguments, compute ``x**y``. If ``x`` is negative then + ``y`` must be integral. The result will be inexact unless ``y`` is + integral and the result is finite and can be expressed exactly in + 'precision' digits. The result should always be correctly rounded, + using the rounding mode of the current thread's context. + + With three arguments, compute ``(x**y) % modulo``. For the three + argument form, the following restrictions on the arguments hold: + + - all three arguments must be integral + - ``y`` must be nonnegative + - at least one of ``x`` or ``y`` must be nonzero + - ``modulo`` must be nonzero and have at most 'precision' digits + + The result of ``Context.power(x, y, modulo)`` is identical to + the result that would be obtained by computing ``(x**y) % + modulo`` with unbounded precision, but is computed more + efficiently. It is always exact. + + .. versionchanged:: 2.6 + ``y`` may now be nonintegral in ``x**y``. + Stricter requirements for the three-argument version. .. method:: Context.remainder(x, y) @@ -682,47 +1060,10 @@ The sign of the result, if non-zero, is the same as that of the original dividend. - -.. method:: Context.remainder_near(x, y) - - Computed the modulo as either a positive or negative value depending on which is - closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns - ``Decimal("-2")`` which is closer to zero than ``Decimal("4")``. - - If both are equally close, the one chosen will have the same sign as *self*. - - -.. method:: Context.same_quantum(x, y) - - Test whether *x* and *y* have the same exponent or whether both are - :const:`NaN`. - - -.. method:: Context.sqrt(x) - - Return the square root of *x* to full precision. - - .. method:: Context.subtract(x, y) Return the difference between *x* and *y*. - -.. method:: Context.to_eng_string() - - Convert to engineering-type string. - - Engineering notation has an exponent which is a multiple of 3, so there are up - to 3 digits left of the decimal place. For example, converts - ``Decimal('123E+1')`` to ``Decimal("1.23E+3")`` - - -.. method:: Context.to_integral(x) - - Rounds to the nearest integer without signaling :const:`Inexact` or - :const:`Rounded`. - - .. method:: Context.to_sci_string(x) Converts a number to a string using scientific notation. @@ -755,7 +1096,7 @@ Typically, clamping occurs when an exponent falls outside the context's :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to - fit by adding zeroes to the coefficient. + fit by adding zeros to the coefficient. .. class:: DecimalException @@ -908,7 +1249,7 @@ The number system for the :mod:`decimal` module provides special values including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`, -and two zeroes, :const:`+0` and :const:`-0`. +and two zeros, :const:`+0` and :const:`-0`. Infinities can be constructed directly with: ``Decimal('Infinity')``. Also, they can arise from dividing by zero when the :exc:`DivisionByZero` signal is Modified: python/branches/py3k/Doc/library/fileinput.rst ============================================================================== --- python/branches/py3k/Doc/library/fileinput.rst (original) +++ python/branches/py3k/Doc/library/fileinput.rst Wed Sep 19 05:06:30 2007 @@ -7,8 +7,9 @@ .. sectionauthor:: Fred L. Drake, Jr. -This module implements a helper class and functions to quickly write a loop over -standard input or a list of files. +This module implements a helper class and functions to quickly write a +loop over standard input or a list of files. If you just want to read or +write one file see :func:`open`. The typical use is:: Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Wed Sep 19 05:06:30 2007 @@ -746,7 +746,8 @@ Python enforces that the mode, after stripping ``'U'``, begins with ``'r'``, ``'w'`` or ``'a'``. - See also the :mod:`fileinput` module. + See also the :mod:`fileinput` module, the :mod:`os` module, and the + :mod:`os.path` module. .. function:: ord(c) Modified: python/branches/py3k/Doc/library/hashlib.rst ============================================================================== --- python/branches/py3k/Doc/library/hashlib.rst (original) +++ python/branches/py3k/Doc/library/hashlib.rst Wed Sep 19 05:06:30 2007 @@ -36,7 +36,7 @@ Feeding string objects is to :meth:`update` is not supported, as hashes work on bytes, not on characters. -.. index:: single: OpenSSL +.. index:: single: OpenSSL; (use in module hashlib) Constructors for hash algorithms that are always present in this module are :func:`md5`, :func:`sha1`, :func:`sha224`, :func:`sha256`, :func:`sha384`, and Modified: python/branches/py3k/Doc/library/operator.rst ============================================================================== --- python/branches/py3k/Doc/library/operator.rst (original) +++ python/branches/py3k/Doc/library/operator.rst Wed Sep 19 05:06:30 2007 @@ -47,18 +47,18 @@ truth tests, identity tests, and boolean operations: -.. function:: not_(o) - __not__(o) +.. function:: not_(obj) + __not__(obj) - Return the outcome of :keyword:`not` *o*. (Note that there is no + Return the outcome of :keyword:`not` *obj*. (Note that there is no :meth:`__not__` method for object instances; only the interpreter core defines this operation. The result is affected by the :meth:`__bool__` and :meth:`__len__` methods.) -.. function:: truth(o) +.. function:: truth(obj) - Return :const:`True` if *o* is true, and :const:`False` otherwise. This is + Return :const:`True` if *obj* is true, and :const:`False` otherwise. This is equivalent to using the :class:`bool` constructor. @@ -75,10 +75,10 @@ The mathematical and bitwise operations are the most numerous: -.. function:: abs(o) - __abs__(o) +.. function:: abs(obj) + __abs__(obj) - Return the absolute value of *o*. + Return the absolute value of *obj*. .. function:: add(a, b) @@ -106,12 +106,12 @@ Return ``a // b``. -.. function:: inv(o) - invert(o) - __inv__(o) - __invert__(o) +.. function:: inv(obj) + invert(obj) + __inv__(obj) + __invert__(obj) - Return the bitwise inverse of the number *o*. This is equivalent to ``~o``. + Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``. .. function:: lshift(a, b) @@ -132,10 +132,10 @@ Return ``a * b``, for *a* and *b* numbers. -.. function:: neg(o) - __neg__(o) +.. function:: neg(obj) + __neg__(obj) - Return *o* negated. + Return *obj* negated. .. function:: or_(a, b) @@ -144,10 +144,10 @@ Return the bitwise or of *a* and *b*. -.. function:: pos(o) - __pos__(o) +.. function:: pos(obj) + __pos__(obj) - Return *o* positive. + Return *obj* positive. .. function:: pow(a, b) @@ -373,24 +373,30 @@ ... pass ... >>> import operator - >>> o = C() - >>> operator.isMappingType(o) + >>> obj = C() + >>> operator.isMappingType(obj) True +.. note:: + + Python 3 is expected to introduce abstract base classes for + collection types, so it should be possible to write, for example, + ``isinstance(obj, collections.Mapping)`` and ``isinstance(obj, + collections.Sequence)``. -.. function:: isCallable(o) +.. function:: isCallable(obj) .. deprecated:: 2.0 Use the :func:`callable` built-in function instead. - Returns true if the object *o* can be called like a function, otherwise it + Returns true if the object *obj* can be called like a function, otherwise it returns false. True is returned for functions, bound and unbound methods, class objects, and instance objects which support the :meth:`__call__` method. -.. function:: isMappingType(o) +.. function:: isMappingType(obj) - Returns true if the object *o* supports the mapping interface. This is true for + Returns true if the object *obj* supports the mapping interface. This is true for dictionaries and all instance objects defining :meth:`__getitem__`. .. warning:: @@ -400,9 +406,9 @@ useful than it otherwise might be. -.. function:: isNumberType(o) +.. function:: isNumberType(obj) - Returns true if the object *o* represents a number. This is true for all + Returns true if the object *obj* represents a number. This is true for all numeric types implemented in C. .. warning:: @@ -412,9 +418,9 @@ useful than it otherwise might be. -.. function:: isSequenceType(o) +.. function:: isSequenceType(obj) - Returns true if the object *o* supports the sequence protocol. This returns true + Returns true if the object *obj* supports the sequence protocol. This returns true for all objects which define sequence methods in C, and for all instance objects defining :meth:`__getitem__`. @@ -484,7 +490,7 @@ +-----------------------+-------------------------+---------------------------------+ | Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` | +-----------------------+-------------------------+---------------------------------+ -| Containment Test | ``o in seq`` | ``contains(seq, o)`` | +| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` | +-----------------------+-------------------------+---------------------------------+ | Division | ``a / b`` | ``div(a, b)`` (without | | | | ``__future__.division``) | @@ -508,11 +514,11 @@ +-----------------------+-------------------------+---------------------------------+ | Identity | ``a is not b`` | ``is_not(a, b)`` | +-----------------------+-------------------------+---------------------------------+ -| Indexed Assignment | ``o[k] = v`` | ``setitem(o, k, v)`` | +| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` | +-----------------------+-------------------------+---------------------------------+ -| Indexed Deletion | ``del o[k]`` | ``delitem(o, k)`` | +| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` | +-----------------------+-------------------------+---------------------------------+ -| Indexing | ``o[k]`` | ``getitem(o, k)`` | +| Indexing | ``obj[k]`` | ``getitem(obj, k)`` | +-----------------------+-------------------------+---------------------------------+ | Left Shift | ``a << b`` | ``lshift(a, b)`` | +-----------------------+-------------------------+---------------------------------+ @@ -534,11 +540,11 @@ +-----------------------+-------------------------+---------------------------------+ | Slicing | ``seq[i:j]`` | ``getslice(seq, i, j)`` | +-----------------------+-------------------------+---------------------------------+ -| String Formatting | ``s % o`` | ``mod(s, o)`` | +| String Formatting | ``s % obj`` | ``mod(s, obj)`` | +-----------------------+-------------------------+---------------------------------+ | Subtraction | ``a - b`` | ``sub(a, b)`` | +-----------------------+-------------------------+---------------------------------+ -| Truth Test | ``o`` | ``truth(o)`` | +| Truth Test | ``obj`` | ``truth(obj)`` | +-----------------------+-------------------------+---------------------------------+ | Ordering | ``a < b`` | ``lt(a, b)`` | +-----------------------+-------------------------+---------------------------------+ Modified: python/branches/py3k/Doc/library/os.rst ============================================================================== --- python/branches/py3k/Doc/library/os.rst (original) +++ python/branches/py3k/Doc/library/os.rst Wed Sep 19 05:06:30 2007 @@ -8,9 +8,10 @@ This module provides a more portable way of using operating system dependent functionality than importing a operating system dependent built-in module like -:mod:`posix` or :mod:`nt`. (If you just want to read or write a file see -:func:`open`, and if you want to manipulate paths, see the :mod:`os.path` -module.) +:mod:`posix` or :mod:`nt`. If you just want to read or write a file see +:func:`open`, if you want to manipulate paths, see the :mod:`os.path` +module, and if you want to read all the lines in all the files on the +command line see the :mod:`fileinput` module. This module searches for an operating system dependent built-in module like :mod:`mac` or :mod:`posix` and exports the same functions and data as found Modified: python/branches/py3k/Doc/library/simplexmlrpcserver.rst ============================================================================== --- python/branches/py3k/Doc/library/simplexmlrpcserver.rst (original) +++ python/branches/py3k/Doc/library/simplexmlrpcserver.rst Wed Sep 19 05:06:30 2007 @@ -142,7 +142,7 @@ import xmlrpclib - s = xmlrpclib.Server('http://localhost:8000') + s = xmlrpclib.ServerProxy('http://localhost:8000') print(s.pow(2,3)) # Returns 2**3 = 8 print(s.add(2,3)) # Returns 5 print(s.div(5,2)) # Returns 5//2 = 2 Modified: python/branches/py3k/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k/Doc/library/ssl.rst (original) +++ python/branches/py3k/Doc/library/ssl.rst Wed Sep 19 05:06:30 2007 @@ -9,6 +9,10 @@ .. sectionauthor:: Bill Janssen +.. index:: single: OpenSSL; (use in module ssl) + +.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer + This module provides access to Transport Layer Security (often known as "Secure Sockets Layer") encryption and peer authentication facilities for network sockets, both client-side and server-side. @@ -19,18 +23,125 @@ .. note:: Some behavior may be platform dependent, since calls are made to the operating - system socket APIs. + system socket APIs. The installed version of OpenSSL may also cause + variations in behavior. This section documents the objects and functions in the ``ssl`` module; for more general information about TLS, SSL, and certificates, the -reader is referred to the documents in the :ref:`ssl-references` section. +reader is referred to the documents in the "See Also" section at +the bottom. -This module defines a class, :class:`ssl.sslsocket`, which is -derived from the :class:`socket.socket` type, and supports additional +This module provides a class, :class:`ssl.SSLSocket`, which is +derived from the :class:`socket.socket` type, and provides +a socket-like wrapper that also encrypts and decrypts the data +going over the socket with SSL. It supports additional :meth:`read` and :meth:`write` methods, along with a method, :meth:`getpeercert`, -to retrieve the certificate of the other side of the connection. +to retrieve the certificate of the other side of the connection, and +a method, :meth:`cipher`, to retrieve the cipher being used for the +secure connection. + +Functions, Constants, and Exceptions +------------------------------------ + +.. exception:: SSLError + + Raised to signal an error from the underlying SSL implementation. This + signifies some problem in the higher-level + encryption and authentication layer that's superimposed on the underlying + network connection. This error is a subtype of :exc:`socket.error`, which + in turn is a subtype of :exc:`IOError`. + +.. function:: wrap_socket (sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None) + + Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance of :class:`ssl.SSLSocket`, a subtype + of :class:`socket.socket`, which wraps the underlying socket in an SSL context. + For client-side sockets, the context construction is lazy; if the underlying socket isn't + connected yet, the context construction will be performed after :meth:`connect` is called + on the socket. For server-side sockets, if the socket has no remote peer, it is assumed + to be a listening socket, and the server-side SSL wrapping is automatically performed + on client connections accepted via the :meth:`accept` method. :func:`wrap_socket` may + raise :exc:`SSLError`. + + The ``keyfile`` and ``certfile`` parameters specify optional files which contain a certificate + to be used to identify the local side of the connection. See the discussion of :ref:`ssl-certificates` + for more information on how the certificate is stored in the ``certfile``. + + Often the private key is stored + in the same file as the certificate; in this case, only the ``certfile`` parameter need be + passed. If the private key is stored in a separate file, both parameters must be used. + If the private key is stored in the ``certfile``, it should come before the first certificate + in the certificate chain:: + + -----BEGIN RSA PRIVATE KEY----- + ... (private key in base64 encoding) ... + -----END RSA PRIVATE KEY----- + -----BEGIN CERTIFICATE----- + ... (certificate in base64 PEM encoding) ... + -----END CERTIFICATE----- + + The parameter ``server_side`` is a boolean which identifies whether server-side or client-side + behavior is desired from this socket. -This module defines the following functions, exceptions, and constants: + The parameter ``cert_reqs`` specifies whether a certificate is + required from the other side of the connection, and whether it will + be validated if provided. It must be one of the three values + :const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required, + but validated if provided), or :const:`CERT_REQUIRED` (required and + validated). If the value of this parameter is not :const:`CERT_NONE`, then + the ``ca_certs`` parameter must point to a file of CA certificates. + + The ``ca_certs`` file contains a set of concatenated "certification authority" certificates, + which are used to validate certificates passed from the other end of the connection. + See the discussion of :ref:`ssl-certificates` for more information about how to arrange + the certificates in this file. + + The parameter ``ssl_version`` specifies which version of the SSL protocol to use. + Typically, the server chooses a particular protocol version, and the client + must adapt to the server's choice. Most of the versions are not interoperable + with the other versions. If not specified, for client-side operation, the + default SSL version is SSLv3; for server-side operation, SSLv23. These + version selections provide the most compatibility with other versions. + + Here's a table showing which versions in a client (down the side) + can connect to which versions in a server (along the top): + + .. table:: + + ======================== ========= ========= ========== ========= + *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1** + *SSLv2* yes no yes* no + *SSLv3* yes yes yes no + *SSLv23* yes no yes no + *TLSv1* no no yes yes + ======================== ========= ========= ========== ========= + + `*` In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4), + an SSLv2 client could not connect to an SSLv23 server. + +.. function:: RAND_status() + + Returns True if the SSL pseudo-random number generator has been + seeded with 'enough' randomness, and False otherwise. You can use + :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness + of the pseudo-random number generator. + +.. function:: RAND_egd(path) + + If you are running an entropy-gathering daemon (EGD) somewhere, and ``path`` + is the pathname of a socket connection open to it, this will read + 256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generator + to increase the security of generated secret keys. This is typically only + necessary on systems without better sources of randomness. + + See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for + sources of entropy-gathering daemons. + +.. function:: RAND_add(bytes, entropy) + + Mixes the given ``bytes`` into the SSL pseudo-random number generator. + The parameter ``entropy`` (a float) is a lower bound on the entropy + contained in string (so you can always use :const:`0.0`). + See :rfc:`1750` for more information on sources of entropy. .. function:: cert_time_to_seconds(timestring) @@ -48,12 +159,27 @@ 'Wed May 9 00:00:00 2007' >>> -.. exception:: sslerror +.. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None) - Raised to signal an error from the underlying SSL implementation. This - signifies some problem in the higher-level - encryption and authentication layer that's superimposed on the underlying - network connection. + Given the address ``addr`` of an SSL-protected server, as a + (*hostname*, *port-number*) pair, fetches the server's certificate, + and returns it as a PEM-encoded string. If ``ssl_version`` is + specified, uses that version of the SSL protocol to attempt to + connect to the server. If ``ca_certs`` is specified, it should be + a file containing a list of root certificates, the same format as + used for the same parameter in :func:`wrap_socket`. The call will + attempt to validate the server certificate against that set of root + certificates, and will fail if the validation attempt fails. + +.. function:: DER_cert_to_PEM_cert (DER_cert_bytes) + + Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded + string version of the same certificate. + +.. function:: PEM_cert_to_DER_cert (PEM_cert_string) + + Given a certificate as an ASCII PEM string, returns a DER-encoded + sequence of bytes for that same certificate. .. data:: CERT_NONE @@ -84,13 +210,16 @@ .. data:: PROTOCOL_SSLv23 - Selects SSL version 2 or 3 as the channel encryption protocol. This is a setting to use for maximum compatibility - with the other end of an SSL connection, but it may cause the specific ciphers chosen for the encryption to be - of fairly low quality. + Selects SSL version 2 or 3 as the channel encryption protocol. + This is a setting to use with servers for maximum compatibility + with the other end of an SSL connection, but it may cause the + specific ciphers chosen for the encryption to be of fairly low + quality. .. data:: PROTOCOL_SSLv3 Selects SSL version 3 as the channel encryption protocol. + For clients, this is the maximally compatible SSL variant. .. data:: PROTOCOL_TLSv1 @@ -99,6 +228,69 @@ protection, if both sides can speak it. +SSLSocket Objects +----------------- + +.. method:: SSLSocket.read([nbytes=1024]) + + Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them. + +.. method:: SSLSocket.write(data) + + Writes the ``data`` to the other side of the connection, using the + SSL channel to encrypt. Returns the number of bytes written. + +.. method:: SSLSocket.getpeercert(binary_form=False) + + If there is no certificate for the peer on the other end of the + connection, returns ``None``. + + If the the parameter ``binary_form`` is :const:`False`, and a + certificate was received from the peer, this method returns a + :class:`dict` instance. If the certificate was not validated, the + dict is empty. If the certificate was validated, it returns a dict + with the keys ``subject`` (the principal for which the certificate + was issued), and ``notAfter`` (the time after which the certificate + should not be trusted). The certificate was already validated, so + the ``notBefore`` and ``issuer`` fields are not returned. If a + certificate contains an instance of the *Subject Alternative Name* + extension (see :rfc:`3280`), there will also be a + ``subjectAltName`` key in the dictionary. + + The "subject" field is a tuple containing the sequence of relative + distinguished names (RDNs) given in the certificate's data + structure for the principal, and each RDN is a sequence of + name-value pairs:: + + {'notAfter': 'Feb 16 16:54:50 2013 GMT', + 'subject': ((('countryName', u'US'),), + (('stateOrProvinceName', u'Delaware'),), + (('localityName', u'Wilmington'),), + (('organizationName', u'Python Software Foundation'),), + (('organizationalUnitName', u'SSL'),), + (('commonName', u'somemachine.python.org'),))} + + If the ``binary_form`` parameter is :const:`True`, and a + certificate was provided, this method returns the DER-encoded form + of the entire certificate as a sequence of bytes, or :const:`None` if the + peer did not provide a certificate. This return + value is independent of validation; if validation was required + (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have + been validated, but if :const:`CERT_NONE` was used to establish the + connection, the certificate, if present, will not have been validated. + +.. method:: SSLSocket.cipher() + + Returns a three-value tuple containing the name of the cipher being + used, the version of the SSL protocol that defines its use, and the + number of secret bits being used. If no connection has been + established, returns ``None``. + + +.. index:: single: certificates + +.. index:: single: X509 certificate + .. _ssl-certificates: Certificates @@ -127,8 +319,12 @@ side of a network connection can also be required to produce a certificate, and that certificate can be validated to the satisfaction of the client or server that requires such validation. -The connection can be set to fail automatically if such -validation is not achieved. +The connection attempt can be set to raise an exception if +the validation fails. Validation is done +automatically, by the underlying OpenSSL framework; the +application need not concern itself with its mechanics. +But the application does usually need to provide +sets of certificates to allow this process to take place. Python uses files to contain certificates. They should be formatted as "PEM" (see :rfc:`1422`), which is a base-64 encoded form wrapped @@ -167,108 +363,55 @@ chains for each issuer you are willing to trust. Again, this file just contains these chains concatenated together. For validation, Python will use the first chain it finds in the file which matches. -Some "standard" root certificates are available at -http://www.thawte.com/roots/ (for Thawte roots) and -http://www.verisign.com/support/roots.html (for Verisign roots). -See also :rfc:`4158` for more discussion of the way in which +Some "standard" root certificates are available from various certification +authorities: +`CACert.org `_, +`Thawte `_, +`Verisign `_, +`Positive SSL `_ (used by python.org), +`Equifax and GeoTrust `_. + +In general, if you are using +SSL3 or TLS1, you don't need to put the full chain in your "CA certs" file; +you only need the root certificates, and the remote peer is supposed to +furnish the other certificates necessary to chain from its certificate to +a root certificate. +See :rfc:`4158` for more discussion of the way in which certification chains can be built. - -sslsocket Objects ------------------ - -.. class:: sslsocket(sock [, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_SSLv23, ca_certs=None]) - - Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance of a subtype - of :class:`socket.socket` which wraps the underlying socket in an SSL context. - For client-side sockets, the context construction is lazy; if the underlying socket isn't - connected yet, the context construction will be performed after :meth:`connect` is called - on the socket. - - The ``keyfile`` and ``certfile`` parameters specify optional files which contain a certificate - to be used to identify the local side of the connection. See the above discussion of :ref:`ssl-certificates` - for more information on how the certificate is stored in the ``certfile``. - - Often the private key is stored - in the same file as the certificate; in this case, only the ``certfile`` parameter need be - passed. If the private key is stored in a separate file, both parameters must be used. - If the private key is stored in the ``certfile``, it should come before the first certificate - in the certificate chain:: - - -----BEGIN RSA PRIVATE KEY----- - ... (private key in base64 encoding) ... - -----END RSA PRIVATE KEY----- - -----BEGIN CERTIFICATE----- - ... (certificate in base64 PEM encoding) ... - -----END CERTIFICATE----- - - The parameter ``server_side`` is a boolean which identifies whether server-side or client-side - behavior is desired from this socket. - - The parameter ``cert_reqs`` specifies whether a certificate is - required from the other side of the connection, and whether it will - be validated if provided. It must be one of the three values - :const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required, - but validated if provided), or :const:`CERT_REQUIRED` (required and - validated). If the value of this parameter is not :const:`CERT_NONE`, then - the ``ca_certs`` parameter must point to a file of CA certificates. - - The parameter ``ssl_version`` specifies which version of the SSL protocol to use. Typically, - the server specifies this, and a client connecting to it must use the same protocol. An - SSL server using :const:`PROTOCOL_SSLv23` can understand a client connecting via SSL2, SSL3, or TLS1, - but a client using :const:`PROTOCOL_SSLv23` can only connect to an SSL2 server. - - The ``ca_certs`` file contains a set of concatenated "certification authority" certificates, - which are used to validate certificates passed from the other end of the connection. - See the above discussion of :ref:`ssl-certificates` for more information about how to arrange - the certificates in this file. - -.. method:: sslsocket.read([nbytes]) - - Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them. - -.. method:: sslsocket.write(data) - - Writes the ``data`` to the other side of the connection, using the SSL channel to encrypt. Returns the number - of bytes written. - -.. method:: sslsocket.getpeercert() - - If there is no certificate for the peer on the other end of the connection, returns ``None``. - If a certificate was received from the peer, but not validated, returns an empty ``dict`` instance. - If a certificate was received and validated, returns a ``dict`` instance with the fields - ``subject`` (the principal for which the certificate was issued), ``issuer`` (the signer of - the certificate), ``notBefore`` (the time before which the certificate should not be trusted), - and ``notAfter`` (the time after which the certificate should not be trusted) filled in. - - The "subject" and "issuer" fields are tuples containing the name-value fields - given in the certificate's data structure for each principal:: - - {'issuer': (('countryName', u'US'), - ('stateOrProvinceName', u'Delaware'), - ('localityName', u'Wilmington'), - ('organizationName', u'Python Software Foundation'), - ('organizationalUnitName', u'SSL'), - ('commonName', u'somemachine.python.org')), - 'notAfter': 'Feb 16 16:54:50 2013 GMT', - 'notBefore': 'Aug 27 16:54:50 2007 GMT', - 'subject': (('countryName', u'US'), - ('stateOrProvinceName', u'Delaware'), - ('localityName', u'Wilmington'), - ('organizationName', u'Python Software Foundation'), - ('organizationalUnitName', u'SSL'), - ('commonName', u'somemachine.python.org')), - 'version': 2} - - This certificate is said to be *self-signed*, because the subject - and issuer are the same entity. The *version* field refers to the X509 version - that's used for the certificate. - -.. method:: sslsocket.ssl_shutdown() - - Closes the SSL context (if any) over the socket, but leaves the socket connection - open for further use, if both sides are willing. This is different from :meth:`socket.socket.shutdown`, - which will close the connection, but leave the local socket available for further use. +If you are going to create a server that provides SSL-encrypted +connection services, you will need to acquire a certificate for that +service. There are many ways of acquiring appropriate certificates, +such as buying one from a certification authority. Another common +practice is to generate a self-signed certificate. The simplest +way to do this is with the OpenSSL package, using something like +the following:: + + % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem + Generating a 1024 bit RSA private key + .......++++++ + .............................++++++ + writing new private key to 'cert.pem' + ----- + You are about to be asked to enter information that will be incorporated + into your certificate request. + What you are about to enter is what is called a Distinguished Name or a DN. + There are quite a few fields but you can leave some blank + For some fields there will be a default value, + If you enter '.', the field will be left blank. + ----- + Country Name (2 letter code) [AU]:US + State or Province Name (full name) [Some-State]:MyState + Locality Name (eg, city) []:Some City + Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc. + Organizational Unit Name (eg, section) []:My Group + Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com + Email Address []:ops at myserver.mygroup.myorganization.com + % + +The disadvantage of a self-signed certificate is that it is its +own root certificate, and no one else will have it in their cache +of known (and trusted) root certificates. Examples @@ -295,12 +438,17 @@ import socket, ssl, pprint s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - ssl_sock = ssl.sslsocket(s, ca_certs="/etc/ca_certs_file", cert_reqs=ssl.CERT_REQUIRED) + + # require a certificate from the server + ssl_sock = ssl.wrap_socket(s, + ca_certs="/etc/ca_certs_file", + cert_reqs=ssl.CERT_REQUIRED) ssl_sock.connect(('www.verisign.com', 443)) print(repr(ssl_sock.getpeername())) pprint.pprint(ssl_sock.getpeercert()) + print(pprint.pformat(ssl_sock.getpeercert())) # Set a simple HTTP request -- use httplib in actual code. ssl_sock.write("""GET / HTTP/1.0\r @@ -310,35 +458,29 @@ # read all the data returned by the server. data = ssl_sock.read() - # note that closing the sslsocket will also close the underlying socket + # note that closing the SSLSocket will also close the underlying socket ssl_sock.close() -As of September 4, 2007, the certificate printed by this program +As of September 6, 2007, the certificate printed by this program looked like this:: - {'issuer': (('countryName', u'US'), - ('organizationName', u'VeriSign, Inc.'), - ('organizationalUnitName', u'VeriSign Trust Network'), - ('organizationalUnitName', - u'Terms of use at https://www.verisign.com/rpa (c)06'), - ('commonName', - u'VeriSign Class 3 Extended Validation SSL SGC CA')), - 'notAfter': 'May 8 23:59:59 2009 GMT', - 'notBefore': 'May 9 00:00:00 2007 GMT', - 'subject': (('serialNumber', u'2497886'), - ('1.3.6.1.4.1.311.60.2.1.3', u'US'), - ('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'), - ('countryName', u'US'), - ('postalCode', u'94043'), - ('stateOrProvinceName', u'California'), - ('localityName', u'Mountain View'), - ('streetAddress', u'487 East Middlefield Road'), - ('organizationName', u'VeriSign, Inc.'), - ('organizationalUnitName', u'Production Security Services'), - ('organizationalUnitName', - u'Terms of use at www.verisign.com/rpa (c)06'), - ('commonName', u'www.verisign.com')), - 'version': 2} + {'notAfter': 'May 8 23:59:59 2009 GMT', + 'subject': ((('serialNumber', u'2497886'),), + (('1.3.6.1.4.1.311.60.2.1.3', u'US'),), + (('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),), + (('countryName', u'US'),), + (('postalCode', u'94043'),), + (('stateOrProvinceName', u'California'),), + (('localityName', u'Mountain View'),), + (('streetAddress', u'487 East Middlefield Road'),), + (('organizationName', u'VeriSign, Inc.'),), + (('organizationalUnitName', + u'Production Security Services'),), + (('organizationalUnitName', + u'Terms of use at www.verisign.com/rpa (c)06'),), + (('commonName', u'www.verisign.com'),))} + +which is a fairly poorly-formed ``subject`` field. Server-side operation ^^^^^^^^^^^^^^^^^^^^^ @@ -354,12 +496,15 @@ bindsocket.listen(5) When one did, you'd call :meth:`accept` on the socket to get the new socket from the other -end, and use :func:`sslsocket` to create a server-side SSL context for it:: +end, and use :func:`wrap_socket` to create a server-side SSL context for it:: while True: newsocket, fromaddr = bindsocket.accept() - connstream = ssl.sslsocket(newsocket, server_side=True, certfile="mycertfile", - keyfile="mykeyfile", ssl_protocol=ssl.PROTOCOL_TLSv1) + connstream = ssl.wrap_socket(newsocket, + server_side=True, + certfile="mycertfile", + keyfile="mykeyfile", + ssl_protocol=ssl.PROTOCOL_TLSv1) deal_with_client(connstream) Then you'd read data from the ``connstream`` and do something with it till you are finished with the client (or the client is finished with you):: @@ -370,7 +515,8 @@ # null data means the client is finished with us while data: if not do_something(connstream, data): - # we'll assume do_something returns False when we're finished with client + # we'll assume do_something returns False + # when we're finished with client break data = connstream.read() # finished with client @@ -379,16 +525,19 @@ And go back to listening for new client connections. -.. _ssl-references: +.. seealso:: -References ----------- + Class :class:`socket.socket` + Documentation of underlying :mod:`socket` class -Class :class:`socket.socket` - Documentation of underlying :mod:`socket` class + `Introducing SSL and Certificates using OpenSSL `_ + Frederick J. Hirsch -`Introducing SSL and Certificates using OpenSSL `_, by Frederick J. Hirsch + `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management `_ + Steve Kent -`Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management`, :rfc:`1422`, by Steve Kent + `RFC 1750: Randomness Recommendations for Security `_ + D. Eastlake et. al. -`Internet X.509 Public Key Infrastructure Certificate and CRL Profile`, :rfc:`3280`, Housley et. al. + `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile `_ + Housley et. al. Modified: python/branches/py3k/Doc/library/undoc.rst ============================================================================== --- python/branches/py3k/Doc/library/undoc.rst (original) +++ python/branches/py3k/Doc/library/undoc.rst Wed Sep 19 05:06:30 2007 @@ -19,9 +19,6 @@ Some of these are very old and/or not very robust; marked with "hmm." -:mod:`bdb` - --- A generic Python debugger base class (used by pdb). - :mod:`ihooks` --- Import hook support (for :mod:`rexec`; may become obsolete). Modified: python/branches/py3k/Doc/reference/index.rst ============================================================================== --- python/branches/py3k/Doc/reference/index.rst (original) +++ python/branches/py3k/Doc/reference/index.rst Wed Sep 19 05:06:30 2007 @@ -17,7 +17,7 @@ interfaces available to C/C++ programmers in detail. .. toctree:: - :maxdepth: 2 + :maxdepth: 3 introduction.rst lexical_analysis.rst Modified: python/branches/py3k/Doc/reference/simple_stmts.rst ============================================================================== --- python/branches/py3k/Doc/reference/simple_stmts.rst (original) +++ python/branches/py3k/Doc/reference/simple_stmts.rst Wed Sep 19 05:06:30 2007 @@ -62,47 +62,6 @@ standard output on a line by itself (except if the result is ``None``, so that procedure calls do not cause any output.) - -.. _assert: - -Assert statements -================= - -.. index:: - statement: assert - pair: debugging; assertions - single: __debug__ - exception: AssertionError - -Assert statements are a convenient way to insert debugging assertions into a -program: - -.. productionlist:: - assert_stmt: "assert" `expression` ["," `expression`] - -The simple form, ``assert expression``, is equivalent to :: - - if __debug__: - if not expression: raise AssertionError - -The extended form, ``assert expression1, expression2``, is equivalent to :: - - if __debug__: - if not expression1: raise AssertionError(expression2) - -These equivalences assume that :data:`__debug__` and :exc:`AssertionError` refer -to the built-in variables with those names. In the current implementation, the -built-in variable :data:`__debug__` is ``True`` under normal circumstances, -``False`` when optimization is requested (command line option ``-O``). The -current code generator emits no code for an assert statement when optimization -is requested at compile time. Note that it is unnecessary to include the source -code for the expression that failed in the error message; it will be displayed -as part of the stack trace. - -Assignments to :data:`__debug__` are illegal. The value for the built-in -variable is determined when the interpreter starts. - - .. _assignment: Assignment statements @@ -308,6 +267,48 @@ a.x += 1 # writes a.x as 4 leaving A.x as 3 +.. _assert: + +The :keyword:`assert` statement +=============================== + +.. index:: + statement: assert + pair: debugging; assertions + +Assert statements are a convenient way to insert debugging assertions into a +program: + +.. productionlist:: + assert_stmt: "assert" `expression` ["," `expression`] + +The simple form, ``assert expression``, is equivalent to :: + + if __debug__: + if not expression: raise AssertionError + +The extended form, ``assert expression1, expression2``, is equivalent to :: + + if __debug__: + if not expression1: raise AssertionError, expression2 + +.. index:: + single: __debug__ + exception: AssertionError + +These equivalences assume that ``__debug__`` and :exc:`AssertionError` refer to +the built-in variables with those names. In the current implementation, the +built-in variable ``__debug__`` is ``True`` under normal circumstances, +``False`` when optimization is requested (command line option -O). The current +code generator emits no code for an assert statement when optimization is +requested at compile time. Note that it is unnecessary to include the source +code for the expression that failed in the error message; it will be displayed +as part of the stack trace. + +Assignments to ``__debug__`` are illegal. The value for the built-in variable +is determined when the interpreter starts. + + .. _pass: The :keyword:`pass` statement Modified: python/branches/py3k/Doc/whatsnew/2.5.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/2.5.rst (original) +++ python/branches/py3k/Doc/whatsnew/2.5.rst Wed Sep 19 05:06:30 2007 @@ -637,7 +637,7 @@ print v.sqrt() -.. _context-managers: +.. _new-25-context-managers: Writing Context Managers ------------------------ Modified: python/branches/py3k/Doc/whatsnew/2.6.rst ============================================================================== --- python/branches/py3k/Doc/whatsnew/2.6.rst (original) +++ python/branches/py3k/Doc/whatsnew/2.6.rst Wed Sep 19 05:06:30 2007 @@ -2,6 +2,9 @@ What's New in Python 2.6 **************************** +.. % XXX mention switch to reST for documentation +.. % XXX mention switch to Roundup for bug tracking + :Author: A.M. Kuchling :Release: |release| :Date: |today| @@ -67,12 +70,367 @@ .. % sets module deprecated .. % ====================================================================== +Python 3.0 +================ + +.. % XXX add general comment about Python 3.0 features in 2.6 + +.. % XXX mention -3 switch + +A new command-line switch, :option:`-3`, enables warnings +about features that will be removed in Python 3.0. You can run code +with this switch to see how much work will be necessary to port +code to 3.0. + +.. seealso:: + + The 3xxx series of PEPs, which describes the development process for + Python 3.0 and various features that have been accepted, rejected, + or are still under consideration. + +PEP 343: The 'with' statement +============================= + +The previous version, Python 2.5, added the ':keyword:`with`' +statement an optional feature, to be enabled by a ``from __future__ +import generators`` directive. In 2.6 the statement no longer need to +be specially enabled; this means that :keyword:`with` is now always a +keyword. The rest of this section is a copy of the corresponding +section from "What's New in Python 2.5" document; if you read +it back when Python 2.5 came out, you can skip the rest of this +section. + +The ':keyword:`with`' statement clarifies code that previously would use +``try...finally`` blocks to ensure that clean-up code is executed. In this +section, I'll discuss the statement as it will commonly be used. In the next +section, I'll examine the implementation details and show how to write objects +for use with this statement. + +The ':keyword:`with`' statement is a new control-flow structure whose basic +structure is:: + + with expression [as variable]: + with-block + +The expression is evaluated, and it should result in an object that supports the +context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__` +methods. + +The object's :meth:`__enter__` is called before *with-block* is executed and +therefore can run set-up code. It also may return a value that is bound to the +name *variable*, if given. (Note carefully that *variable* is *not* assigned +the result of *expression*.) + +After execution of the *with-block* is finished, the object's :meth:`__exit__` +method is called, even if the block raised an exception, and can therefore run +clean-up code. + +Some standard Python objects now support the context management protocol and can +be used with the ':keyword:`with`' statement. File objects are one example:: + + with open('/etc/passwd', 'r') as f: + for line in f: + print line + ... more processing code ... + +After this statement has executed, the file object in *f* will have been +automatically closed, even if the :keyword:`for` loop raised an exception part- +way through the block. + +.. note:: + + In this case, *f* is the same object created by :func:`open`, because + :meth:`file.__enter__` returns *self*. + +The :mod:`threading` module's locks and condition variables also support the +':keyword:`with`' statement:: + + lock = threading.Lock() + with lock: + # Critical section of code + ... + +The lock is acquired before the block is executed and always released once the +block is complete. + +The new :func:`localcontext` function in the :mod:`decimal` module makes it easy +to save and restore the current decimal context, which encapsulates the desired +precision and rounding characteristics for computations:: + + from decimal import Decimal, Context, localcontext + + # Displays with default precision of 28 digits + v = Decimal('578') + print v.sqrt() + + with localcontext(Context(prec=16)): + # All code in this block uses a precision of 16 digits. + # The original context is restored on exiting the block. + print v.sqrt() + + +.. _new-26-context-managers: + +Writing Context Managers +------------------------ + +Under the hood, the ':keyword:`with`' statement is fairly complicated. Most +people will only use ':keyword:`with`' in company with existing objects and +don't need to know these details, so you can skip the rest of this section if +you like. Authors of new objects will need to understand the details of the +underlying implementation and should keep reading. + +A high-level explanation of the context management protocol is: + +* The expression is evaluated and should result in an object called a "context + manager". The context manager must have :meth:`__enter__` and :meth:`__exit__` + methods. + +* The context manager's :meth:`__enter__` method is called. The value returned + is assigned to *VAR*. If no ``'as VAR'`` clause is present, the value is simply + discarded. + +* The code in *BLOCK* is executed. + +* If *BLOCK* raises an exception, the :meth:`__exit__(type, value, traceback)` + is called with the exception details, the same values returned by + :func:`sys.exc_info`. The method's return value controls whether the exception + is re-raised: any false value re-raises the exception, and ``True`` will result + in suppressing it. You'll only rarely want to suppress the exception, because + if you do the author of the code containing the ':keyword:`with`' statement will + never realize anything went wrong. + +* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still + called, but *type*, *value*, and *traceback* are all ``None``. + +Let's think through an example. I won't present detailed code but will only +sketch the methods necessary for a database that supports transactions. + +(For people unfamiliar with database terminology: a set of changes to the +database are grouped into a transaction. Transactions can be either committed, +meaning that all the changes are written into the database, or rolled back, +meaning that the changes are all discarded and the database is unchanged. See +any database textbook for more information.) + +Let's assume there's an object representing a database connection. Our goal will +be to let the user write code like this:: + + db_connection = DatabaseConnection() + with db_connection as cursor: + cursor.execute('insert into ...') + cursor.execute('delete from ...') + # ... more operations ... + +The transaction should be committed if the code in the block runs flawlessly or +rolled back if there's an exception. Here's the basic interface for +:class:`DatabaseConnection` that I'll assume:: + + class DatabaseConnection: + # Database interface + def cursor (self): + "Returns a cursor object and starts a new transaction" + def commit (self): + "Commits current transaction" + def rollback (self): + "Rolls back current transaction" + +The :meth:`__enter__` method is pretty easy, having only to start a new +transaction. For this application the resulting cursor object would be a useful +result, so the method will return it. The user can then add ``as cursor`` to +their ':keyword:`with`' statement to bind the cursor to a variable name. :: + + class DatabaseConnection: + ... + def __enter__ (self): + # Code to start a new transaction + cursor = self.cursor() + return cursor + +The :meth:`__exit__` method is the most complicated because it's where most of +the work has to be done. The method has to check if an exception occurred. If +there was no exception, the transaction is committed. The transaction is rolled +back if there was an exception. + +In the code below, execution will just fall off the end of the function, +returning the default value of ``None``. ``None`` is false, so the exception +will be re-raised automatically. If you wished, you could be more explicit and +add a :keyword:`return` statement at the marked location. :: + + class DatabaseConnection: + ... + def __exit__ (self, type, value, tb): + if tb is None: + # No exception, so commit + self.commit() + else: + # Exception occurred, so rollback. + self.rollback() + # return False + + +.. _module-contextlib: + +The contextlib module +--------------------- + +The new :mod:`contextlib` module provides some functions and a decorator that +are useful for writing objects for use with the ':keyword:`with`' statement. + +The decorator is called :func:`contextmanager`, and lets you write a single +generator function instead of defining a new class. The generator should yield +exactly one value. The code up to the :keyword:`yield` will be executed as the +:meth:`__enter__` method, and the value yielded will be the method's return +value that will get bound to the variable in the ':keyword:`with`' statement's +:keyword:`as` clause, if any. The code after the :keyword:`yield` will be +executed in the :meth:`__exit__` method. Any exception raised in the block will +be raised by the :keyword:`yield` statement. + +Our database example from the previous section could be written using this +decorator as:: + + from contextlib import contextmanager + + @contextmanager + def db_transaction (connection): + cursor = connection.cursor() + try: + yield cursor + except: + connection.rollback() + raise + else: + connection.commit() + + db = DatabaseConnection() + with db_transaction(db) as cursor: + ... + +The :mod:`contextlib` module also has a :func:`nested(mgr1, mgr2, ...)` function +that combines a number of context managers so you don't need to write nested +':keyword:`with`' statements. In this example, the single ':keyword:`with`' +statement both starts a database transaction and acquires a thread lock:: + + lock = threading.Lock() + with nested (db_transaction(db), lock) as (cursor, locked): + ... + +Finally, the :func:`closing(object)` function returns *object* so that it can be +bound to a variable, and calls ``object.close`` at the end of the block. :: + + import urllib, sys + from contextlib import closing + + with closing(urllib.urlopen('http://www.yahoo.com')) as f: + for line in f: + sys.stdout.write(line) + + +.. seealso:: + + :pep:`343` - The "with" statement + PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland, + Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a + ':keyword:`with`' statement, which can be helpful in learning how the statement + works. + + The documentation for the :mod:`contextlib` module. + +.. % ====================================================================== + +.. _pep-3110: + +PEP 3110: Exception-Handling Changes +===================================================== + +One error that Python programmers occasionally make +is the following:: + + try: + ... + except TypeError, ValueError: + ... + +The author is probably trying to catch both +:exc:`TypeError` and :exc:`ValueError` exceptions, but this code +actually does something different: it will catch +:exc:`TypeError` and bind the resulting exception object +to the local name ``"ValueError"``. The correct code +would have specified a tuple:: + + try: + ... + except (TypeError, ValueError): + ... + +This error is possible because the use of the comma here is ambiguous: +does it indicate two different nodes in the parse tree, or a single +node that's a tuple. + +Python 3.0 changes the syntax to make this unambiguous by replacing +the comma with the word "as". To catch an exception and store the +exception object in the variable ``exc``, you must write:: + + try: + ... + except TypeError as exc: + ... + +Python 3.0 will only support the use of "as", and therefore interprets +the first example as catching two different exceptions. Python 2.6 +supports both the comma and "as", so existing code will continue to +work. + +.. seealso:: + + :pep:`3110` - Catching Exceptions in Python 3000 + PEP written and implemented by Collin Winter. + +.. % ====================================================================== + +.. _pep-3119: + +PEP 3119: Abstract Base Classes +===================================================== + +XXX + +.. seealso:: + + :pep:`3119` - Introducing Abstract Base Classes + PEP written by Guido van Rossum and Talin. + Implemented by XXX. + Backported to 2.6 by Benjamin Aranguren (with Alex Martelli). Other Language Changes ====================== Here are all of the changes that Python 2.6 makes to the core Python language. +* Changes to the :class:`Exception` interface + as dictated by :pep:`352` continue to be made. For 2.6, + the :attr:`message` attribute is being deprecated in favor of the + :attr:`args` attribute. + +* When calling a function using the ``**`` syntax to provide keyword + arguments, you are no longer required to use a Python dictionary; + any mapping will now work:: + + >>> def f(**kw): + ... print sorted(kw) + ... + >>> ud=UserDict.UserDict() + >>> ud['a'] = 1 + >>> ud['b'] = 'string' + >>> f(**ud) + ['a', 'b'] + + .. % Patch 1686487 + +* The :func:`compile` built-in function now accepts keyword arguments + as well as positional parameters. (Contributed by XXX.) + + .. % Patch 1444529 + * The :func:`complex` constructor now accepts strings containing parenthesized complex numbers, letting ``complex(repr(cmplx))`` will now round-trip values. For example, ``complex('(3+4j)')`` @@ -87,6 +445,15 @@ .. % Patch 1193128 +* The built-in :func:`dir` function now checks for a :meth:`__dir__` + method on the objects it receives. This method must return a list + of strings containing the names of valid attributes for the object, + and lets the object control the value that :func:`dir` produces. + Objects that have :meth:`__getattr__` or :meth:`__getattribute__` + methods. + + .. % Patch 1591665 + * An obscure change: when you use the the :func:`locals` function inside a :keyword:`class` statement, the resulting dictionary no longer returns free variables. (Free variables, in this case, are variables referred to in the @@ -160,6 +527,11 @@ (Contributed by Raymond Hettinger.) +* An optional ``timeout`` parameter was added to the + :class:`httplib.HTTPConnection` and :class:`HTTPSConnection` + class constructors, specifying a timeout measured in seconds. + (Added by Facundo Batista.) + * A new function in the :mod:`itertools` module: ``izip_longest(iter1, iter2, ...[, fillvalue])`` makes tuples from each of the elements; if some of the iterables are shorter than others, the missing values are set to *fillvalue*. @@ -176,6 +548,15 @@ .. % Patch #1490190 +* The :func:`os.walk` function now has a "followlinks" parameter. If + set to True, it will follow symlinks pointing to directories and + visit the directory's contents. For backward compatibility, the + parameter's default value is false. Note that the function can fall + into an infinite recursion if there's a symlink that points to a + parent directory. + + .. % Patch 1273829 + * In the :mod:`os.path` module, the :func:`splitext` function has been changed to not split on leading period characters. This produces better results when operating on Unix's dot-files. @@ -191,6 +572,12 @@ .. % Patch 1339796 + On Windows, :func:`os.path.expandvars` will now expand environment variables + in the form "%var%", and "~user" will be expanded into the + user's home directory path. (Contributed by XXX.) + + .. % Patch 957650 + * New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags` are wrappers for the corresponding system calls (where they're available). Constants for the flag values are defined in the :mod:`stat` module; some @@ -217,13 +604,78 @@ .. % Patch #957003 +* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and + POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar + format that was already supported. The default format + is GNU tar; specify the ``format`` parameter to open a file + using a different format:: + + tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT) + + The new ``errors`` parameter lets you specify an error handling + scheme for character conversions: the three standard ways Python can + handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the + special value ``'utf-8'``, which replaces bad characters with their + UTF-8 representation. Character conversions occur because the PAX + format supports Unicode filenames, defaulting to UTF-8 encoding. + + The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's + a function that can be used to exclude certain filenames from + an archive. + The function must take a filename and return true if the file + should be excluded or false if it should be archived. + The function is applied to both the name initially passed to :meth:`add` + and to the names of files in recursively-added directories. + + (All changes contributed by Lars Gust?bel). + * An optional ``timeout`` parameter was added to the :class:`telnetlib.Telnet` class constructor, specifying a timeout measured in seconds. (Added by Facundo Batista.) -* The :mod:`test.test_support` module now contains a :func:`EnvironmentVarGuard` +* The :class:`tempfile.NamedTemporaryFile` class usually deletes + the temporary file it created when the file is closed. This + behaviour can now be changed by passing ``delete=False`` to the + constructor. (Contributed by Damien Miller.) + + .. % Patch #1537850 + +* The :mod:`test.test_support` module now contains a + :func:`EnvironmentVarGuard` context manager that supports temporarily changing environment variables and - automatically restores them to their old values. (Contributed by Brett Cannon.) + automatically restores them to their old values. + + Another context manager, :class:`TransientResource`, can surround calls + to resources that may or may not be available; it will catch and + ignore a specified list of exceptions. For example, + a network test may ignore certain failures when connecting to an + external web site:: + + with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT): + f = urllib.urlopen('https://sf.net') + ... + + (Contributed by Brett Cannon.) + +* The :mod:`textwrap` module can now preserve existing whitespace + at the beginnings and ends of the newly-created lines + by specifying ``drop_whitespace=False`` + as an argument:: + + >>> S = """This sentence has a bunch of extra whitespace.""" + >>> print textwrap.fill(S, width=15) + This sentence + has a bunch + of extra + whitespace. + >>> print textwrap.fill(S, drop_whitespace=False, width=15) + This sentence + has a bunch + of extra + whitespace. + >>> + + .. % Patch #1581073 * The :mod:`timeit` module now accepts callables as well as strings for the statement being timed and for the setup code. @@ -235,6 +687,20 @@ .. % Patch #1533909 +* An optional ``timeout`` parameter was added to the + :func:`urllib.urlopen` function and the + :class:`urllib.ftpwrapper` class constructor, as well as the + :func:`urllib2.urlopen` function. The parameter specifies a timeout + measured in seconds. For example:: + + >>> u = urllib2.urlopen("http://slow.example.com", timeout=3) + Traceback (most recent call last): + ... + urllib2.URLError: + >>> + + (Added by Facundo Batista.) + .. % ====================================================================== .. % whole new modules get described in \subsections here Modified: python/branches/py3k/Lib/collections.py ============================================================================== --- python/branches/py3k/Lib/collections.py (original) +++ python/branches/py3k/Lib/collections.py Wed Sep 19 05:06:30 2007 @@ -11,40 +11,50 @@ __all__ += _abcoll.__all__ -def NamedTuple(typename, s): +def NamedTuple(typename, s, verbose=False): """Returns a new subclass of tuple with named fields. >>> Point = NamedTuple('Point', 'x y') - >>> Point.__doc__ # docstring for the new class + >>> Point.__doc__ # docstring for the new class 'Point(x, y)' - >>> p = Point(11, y=22) # instantiate with positional args or keywords - >>> p[0] + p[1] # works just like the tuple (11, 22) + >>> p = Point(11, y=22) # instantiate with positional args or keywords + >>> p[0] + p[1] # works just like the tuple (11, 22) 33 - >>> x, y = p # unpacks just like a tuple + >>> x, y = p # unpacks just like a tuple >>> x, y (11, 22) - >>> p.x + p.y # fields also accessable by name + >>> p.x + p.y # fields also accessable by name 33 - >>> p # readable __repr__ with name=value style + >>> p # readable __repr__ with name=value style Point(x=11, y=22) + >>> p.__replace__('x', 100) # __replace__() is like str.replace() but targets a named field + Point(x=100, y=22) + >>> d = dict(zip(p.__fields__, p)) # use __fields__ to make a dictionary + >>> d['x'] + 11 """ - field_names = s.split() - if not ''.join([typename] + field_names).replace('_', '').isalnum(): + field_names = tuple(s.replace(',', ' ').split()) # names separated by spaces and/or commas + if not ''.join((typename,) + field_names).replace('_', '').isalnum(): raise ValueError('Type names and field names can only contain alphanumeric characters and underscores') - argtxt = ', '.join(field_names) + argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes reprtxt = ', '.join('%s=%%r' % name for name in field_names) template = '''class %(typename)s(tuple): '%(typename)s(%(argtxt)s)' __slots__ = () + __fields__ = %(field_names)r def __new__(cls, %(argtxt)s): - return tuple.__new__(cls, (%(argtxt)s,)) + return tuple.__new__(cls, (%(argtxt)s)) def __repr__(self): return '%(typename)s(%(reprtxt)s)' %% self - ''' % locals() + def __replace__(self, field, value): + 'Return a new %(typename)s object replacing one field with a new value' + return %(typename)s(**dict(list(zip(%(field_names)r, self)) + [(field, value)])) \n''' % locals() for i, name in enumerate(field_names): - template += '\n %s = property(itemgetter(%d))\n' % (name, i) + template += ' %s = property(itemgetter(%d))\n' % (name, i) + if verbose: + print(template) m = dict(itemgetter=_itemgetter) exec(template, m) result = m[typename] @@ -57,9 +67,9 @@ if __name__ == '__main__': - # verify that instances are pickable + # verify that instances can be pickled from pickle import loads, dumps - Point = NamedTuple('Point', 'x y') + Point = NamedTuple('Point', 'x, y', True) p = Point(x=10, y=20) assert p == loads(dumps(p)) Modified: python/branches/py3k/Lib/ctypes/test/test_cfuncs.py ============================================================================== --- python/branches/py3k/Lib/ctypes/test/test_cfuncs.py (original) +++ python/branches/py3k/Lib/ctypes/test/test_cfuncs.py Wed Sep 19 05:06:30 2007 @@ -158,17 +158,17 @@ self.failUnlessEqual(self._dll.tf_bd(0, 42.), 14.) self.failUnlessEqual(self.S(), 42) - def test_longdouble(self): - self._dll.tf_D.restype = c_longdouble - self._dll.tf_D.argtypes = (c_longdouble,) - self.failUnlessEqual(self._dll.tf_D(42.), 14.) - self.failUnlessEqual(self.S(), 42) - - def test_longdouble_plus(self): - self._dll.tf_bD.restype = c_longdouble - self._dll.tf_bD.argtypes = (c_byte, c_longdouble) - self.failUnlessEqual(self._dll.tf_bD(0, 42.), 14.) - self.failUnlessEqual(self.S(), 42) +## def test_longdouble(self): +## self._dll.tf_D.restype = c_longdouble +## self._dll.tf_D.argtypes = (c_longdouble,) +## self.failUnlessEqual(self._dll.tf_D(42.), 14.) +## self.failUnlessEqual(self.S(), 42) + +## def test_longdouble_plus(self): +## self._dll.tf_bD.restype = c_longdouble +## self._dll.tf_bD.argtypes = (c_byte, c_longdouble) +## self.failUnlessEqual(self._dll.tf_bD(0, 42.), 14.) +## self.failUnlessEqual(self.S(), 42) def test_callwithresult(self): def process_result(result): Modified: python/branches/py3k/Lib/ctypes/test/test_functions.py ============================================================================== --- python/branches/py3k/Lib/ctypes/test/test_functions.py (original) +++ python/branches/py3k/Lib/ctypes/test/test_functions.py Wed Sep 19 05:06:30 2007 @@ -143,17 +143,17 @@ self.failUnlessEqual(result, -21) self.failUnlessEqual(type(result), float) - def test_longdoubleresult(self): - f = dll._testfunc_D_bhilfD - f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_longdouble] - f.restype = c_longdouble - result = f(1, 2, 3, 4, 5.0, 6.0) - self.failUnlessEqual(result, 21) - self.failUnlessEqual(type(result), float) - - result = f(-1, -2, -3, -4, -5.0, -6.0) - self.failUnlessEqual(result, -21) - self.failUnlessEqual(type(result), float) +## def test_longdoubleresult(self): +## f = dll._testfunc_D_bhilfD +## f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_longdouble] +## f.restype = c_longdouble +## result = f(1, 2, 3, 4, 5.0, 6.0) +## self.failUnlessEqual(result, 21) +## self.failUnlessEqual(type(result), float) + +## result = f(-1, -2, -3, -4, -5.0, -6.0) +## self.failUnlessEqual(result, -21) +## self.failUnlessEqual(type(result), float) def test_longlongresult(self): try: Modified: python/branches/py3k/Lib/ctypes/util.py ============================================================================== --- python/branches/py3k/Lib/ctypes/util.py (original) +++ python/branches/py3k/Lib/ctypes/util.py Wed Sep 19 05:06:30 2007 @@ -63,15 +63,27 @@ return None return res.group(0) - def _get_soname(f): - # assuming GNU binutils / ELF - if not f: - return None - cmd = "objdump -p -j .dynamic 2>/dev/null " + f - res = re.search(r'\sSONAME\s+([^\s]+)', os.popen(cmd).read()) - if not res: - return None - return res.group(1) + + if sys.platform == "sunos5": + # use /usr/ccs/bin/dump on solaris + def _get_soname(f): + if not f: + return None + cmd = "/usr/ccs/bin/dump -Lpv 2>/dev/null " + f + res = re.search(r'\[.*\]\sSONAME\s+([^\s]+)', os.popen(cmd).read()) + if not res: + return None + return res.group(1) + else: + def _get_soname(f): + # assuming GNU binutils / ELF + if not f: + return None + cmd = "objdump -p -j .dynamic 2>/dev/null " + f + res = re.search(r'\sSONAME\s+([^\s]+)', os.popen(cmd).read()) + if not res: + return None + return res.group(1) if (sys.platform.startswith("freebsd") or sys.platform.startswith("openbsd") Modified: python/branches/py3k/Lib/decimal.py ============================================================================== --- python/branches/py3k/Lib/decimal.py (original) +++ python/branches/py3k/Lib/decimal.py Wed Sep 19 05:06:30 2007 @@ -128,7 +128,7 @@ # Constants for use in setting up contexts 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING', - 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', + 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP', # Functions for manipulating contexts 'setcontext', 'getcontext', 'localcontext' @@ -144,6 +144,7 @@ ROUND_FLOOR = 'ROUND_FLOOR' ROUND_UP = 'ROUND_UP' ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' +ROUND_05UP = 'ROUND_05UP' # Rounding decision (not part of the public API) NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY @@ -204,13 +205,22 @@ x ** (non-integer) x ** (+-)INF An operand is invalid + + The result of the operation after these is a quiet positive NaN, + except when the cause is a signaling NaN, in which case the result is + also a quiet NaN, but with the original sign, and an optional + diagnostic information. """ def handle(self, context, *args): if args: if args[0] == 1: # sNaN, must drop 's' but keep diagnostics - return Decimal( (args[1]._sign, args[1]._int, 'n') ) + ans = Decimal((args[1]._sign, args[1]._int, 'n')) + return ans._fix_nan(context) + elif args[0] == 2: + return Decimal( (args[1], args[2], 'n') ) return NaN + class ConversionSyntax(InvalidOperation): """Trying to convert badly formed string. @@ -218,9 +228,8 @@ converted to a number and it does not conform to the numeric string syntax. The result is [0,qNaN]. """ - def handle(self, context, *args): - return (0, (0,), 'n') # Passed to something which uses a tuple. + return NaN class DivisionByZero(DecimalException, ZeroDivisionError): """Division by 0. @@ -235,9 +244,7 @@ -0, for power. """ - def handle(self, context, sign, double = None, *args): - if double is not None: - return (Infsign[sign],)*2 + def handle(self, context, sign, *args): return Infsign[sign] class DivisionImpossible(InvalidOperation): @@ -249,7 +256,7 @@ """ def handle(self, context, *args): - return (NaN, NaN) + return NaN class DivisionUndefined(InvalidOperation, ZeroDivisionError): """Undefined result of division. @@ -259,9 +266,7 @@ the dividend is also zero. The result is [0,qNaN]. """ - def handle(self, context, tup=None, *args): - if tup is not None: - return (NaN, NaN) # for 0 %0, 0 // 0 + def handle(self, context, *args): return NaN class Inexact(DecimalException): @@ -340,7 +345,7 @@ def handle(self, context, sign, *args): if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, - ROUND_HALF_DOWN, ROUND_UP): + ROUND_HALF_DOWN, ROUND_UP): return Infsign[sign] if sign == 0: if context.rounding == ROUND_CEILING: @@ -520,7 +525,7 @@ Decimal("3.14") >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) Decimal("3.14") - >>> Decimal(314) # int or long + >>> Decimal(314) # int Decimal("314") >>> Decimal(Decimal(314)) # another decimal instance Decimal("314") @@ -545,7 +550,7 @@ return self # From an integer - if isinstance(value, (int,int)): + if isinstance(value, int): if value >= 0: self._sign = 0 else: @@ -561,8 +566,8 @@ if value[0] not in (0,1): raise ValueError('Invalid sign') for digit in value[1]: - if not isinstance(digit, (int,int)) or digit < 0: - raise ValueError("The second value in the tuple must be" + if not isinstance(digit, int) or digit < 0: + raise ValueError("The second value in the tuple must be " "composed of non negative integer elements.") self._sign = value[0] self._int = tuple(value[1]) @@ -596,10 +601,6 @@ if _isnan(value): sig, sign, diag = _isnan(value) self._is_special = True - if len(diag) > context.prec: # Diagnostic info too long - self._sign, self._int, self._exp = \ - context._raise_error(ConversionSyntax) - return self if sig == 1: self._exp = 'n' # qNaN else: # sig == 2 @@ -611,9 +612,8 @@ self._sign, self._int, self._exp = _string2exact(value) except ValueError: self._is_special = True - self._sign, self._int, self._exp = \ - context._raise_error(ConversionSyntax, - "Invalid literal for Decimal: %r" % value) + return context._raise_error(ConversionSyntax, + "Invalid literal for Decimal: %r" % value) return self raise TypeError("Cannot convert %r to Decimal" % value) @@ -622,7 +622,7 @@ """Returns whether the number is not actually one. 0 if a number - 1 if NaN + 1 if NaN (it could be a normal quiet NaN or a phantom one) 2 if sNaN """ if self._is_special: @@ -646,7 +646,7 @@ return 1 return 0 - def _check_nans(self, other = None, context=None): + def _check_nans(self, other=None, context=None): """Returns whether the number is not actually one. if self, other are sNaN, signal @@ -673,9 +673,9 @@ return context._raise_error(InvalidOperation, 'sNaN', 1, other) if self_is_nan: - return self + return self._fix_nan(context) - return other + return other._fix_nan(context) return 0 def __bool__(self): @@ -688,21 +688,28 @@ return True return sum(self._int) != 0 - def __cmp__(self, other, context=None): + def __cmp__(self, other): other = _convert_other(other) if other is NotImplemented: - return other + # Never return NotImplemented + return 1 if self._is_special or other._is_special: - ans = self._check_nans(other, context) - if ans: + # check for nans, without raising on a signaling nan + if self._isnan() or other._isnan(): return 1 # Comparison involving NaN's always reports self > other # INF = INF return cmp(self._isinfinity(), other._isinfinity()) - if not self and not other: - return 0 # If both 0, sign comparison isn't certain. + # check for zeros; note that cmp(0, -0) should return 0 + if not self: + if not other: + return 0 + else: + return -((-1)**other._sign) + if not other: + return (-1)**self._sign # If different signs, neg one is less if other._sign < self._sign: @@ -712,35 +719,15 @@ self_adjusted = self.adjusted() other_adjusted = other.adjusted() - if self_adjusted == other_adjusted and \ - self._int + (0,)*(self._exp - other._exp) == \ - other._int + (0,)*(other._exp - self._exp): - return 0 # equal, except in precision. ([0]*(-x) = []) - elif self_adjusted > other_adjusted and self._int[0] != 0: + if self_adjusted == other_adjusted: + self_padded = self._int + (0,)*(self._exp - other._exp) + other_padded = other._int + (0,)*(other._exp - self._exp) + return cmp(self_padded, other_padded) * (-1)**self._sign + elif self_adjusted > other_adjusted: return (-1)**self._sign - elif self_adjusted < other_adjusted and other._int[0] != 0: + else: # self_adjusted < other_adjusted return -((-1)**self._sign) - # Need to round, so make sure we have a valid context - if context is None: - context = getcontext() - - context = context._shallow_copy() - rounding = context._set_rounding(ROUND_UP) # round away from 0 - - flags = context._ignore_all_flags() - res = self.__sub__(other, context=context) - - context._regard_flags(*flags) - - context.rounding = rounding - - if not res: - return 0 - elif res._sign: - return -1 - return 1 - def __eq__(self, other): if not isinstance(other, (Decimal, int)): return NotImplemented @@ -780,9 +767,7 @@ NaN => one is NaN Like __cmp__, but returns Decimal instances. """ - other = _convert_other(other) - if other is NotImplemented: - return other + other = _convert_other(other, raiseit=True) # Compare(NaN, NaN) = NaN if (self._is_special or other and other._is_special): @@ -790,7 +775,7 @@ if ans: return ans - return Decimal(self.__cmp__(other, context)) + return Decimal(self.__cmp__(other)) def __hash__(self): """x.__hash__() <==> hash(x)""" @@ -819,7 +804,7 @@ # Invariant: eval(repr(d)) == d return 'Decimal("%s")' % str(self) - def __str__(self, eng = 0, context=None): + def __str__(self, eng=False, context=None): """Return string representation of the number in scientific notation. Captures all of the information in the underlying representation. @@ -909,7 +894,7 @@ Same rules for when in exponential and when as a value as in __str__. """ - return self.__str__(eng=1, context=context) + return self.__str__(eng=True, context=context) def __neg__(self, context=None): """Returns a copy with the sign switched. @@ -923,17 +908,15 @@ if not self: # -Decimal('0') is Decimal('0'), not Decimal('-0') - sign = 0 - elif self._sign: - sign = 0 + ans = self.copy_sign(Dec_0) else: - sign = 1 + ans = self.copy_negate() if context is None: context = getcontext() if context._rounding_decision == ALWAYS_ROUND: - return Decimal((sign, self._int, self._exp))._fix(context) - return Decimal( (sign, self._int, self._exp)) + return ans._fix(context) + return ans def __pos__(self, context=None): """Returns a copy, unless it is a sNaN. @@ -945,19 +928,16 @@ if ans: return ans - sign = self._sign if not self: # + (-0) = 0 - sign = 0 + ans = self.copy_sign(Dec_0) + else: + ans = Decimal(self) if context is None: context = getcontext() - if context._rounding_decision == ALWAYS_ROUND: - ans = self._fix(context) - else: - ans = Decimal(self) - ans._sign = sign + return ans._fix(context) return ans def __abs__(self, round=1, context=None): @@ -1020,16 +1000,19 @@ sign = min(self._sign, other._sign) if negativezero: sign = 1 - return Decimal( (sign, (0,), exp)) + ans = Decimal( (sign, (0,), exp)) + if shouldround: + ans = ans._fix(context) + return ans if not self: exp = max(exp, other._exp - context.prec-1) - ans = other._rescale(exp, watchexp=0, context=context) + ans = other._rescale(exp, context.rounding) if shouldround: ans = ans._fix(context) return ans if not other: exp = max(exp, self._exp - context.prec-1) - ans = self._rescale(exp, watchexp=0, context=context) + ans = self._rescale(exp, context.rounding) if shouldround: ans = ans._fix(context) return ans @@ -1042,10 +1025,10 @@ if op1.sign != op2.sign: # Equal and opposite if op1.int == op2.int: - if exp < context.Etiny(): - exp = context.Etiny() - context._raise_error(Clamped) - return Decimal((negativezero, (0,), exp)) + ans = Decimal((negativezero, (0,), exp)) + if shouldround: + ans = ans._fix(context) + return ans if op1.int < op2.int: op1, op2 = op2, op1 # OK, now abs(op1) > abs(op2) @@ -1076,7 +1059,7 @@ __radd__ = __add__ def __sub__(self, other, context=None): - """Return self + (-other)""" + """Return self - other""" other = _convert_other(other) if other is NotImplemented: return other @@ -1086,41 +1069,28 @@ if ans: return ans - # -Decimal(0) = Decimal(0), which we don't want since - # (-0 - 0 = -0 + (-0) = -0, but -0 + 0 = 0.) - # so we change the sign directly to a copy - tmp = Decimal(other) - tmp._sign = 1-tmp._sign - - return self.__add__(tmp, context=context) + # self - other is computed as self + other.copy_negate() + return self.__add__(other.copy_negate(), context=context) def __rsub__(self, other, context=None): - """Return other + (-self)""" + """Return other - self""" other = _convert_other(other) if other is NotImplemented: return other - tmp = Decimal(self) - tmp._sign = 1 - tmp._sign - return other.__add__(tmp, context=context) + return other.__sub__(self, context=context) - def _increment(self, round=1, context=None): + def _increment(self): """Special case of add, adding 1eExponent Since it is common, (rounding, for example) this adds (sign)*one E self._exp to the number more efficiently than add. + Assumes that self is nonspecial. + For example: Decimal('5.624e10')._increment() == Decimal('5.625e10') """ - if self._is_special: - ans = self._check_nans(context=context) - if ans: - return ans - - # Must be infinite, and incrementing makes no difference - return Decimal(self) - L = list(self._int) L[-1] += 1 spot = len(L)-1 @@ -1131,13 +1101,7 @@ break L[spot-1] += 1 spot -= 1 - ans = Decimal((self._sign, L, self._exp)) - - if context is None: - context = getcontext() - if round and context._rounding_decision == ALWAYS_ROUND: - ans = ans._fix(context) - return ans + return Decimal((self._sign, L, self._exp)) def __mul__(self, other, context=None): """Return self * other. @@ -1205,25 +1169,9 @@ def __truediv__(self, other, context=None): """Return self / other.""" - return self._divide(other, context=context) - - def _divide(self, other, divmod = 0, context=None): - """Return a / b, to context.prec precision. - - divmod: - 0 => true division - 1 => (a //b, a%b) - 2 => a //b - 3 => a%b - - Actually, if divmod is 2 or 3 a tuple is returned, but errors for - computing the other value are not raised. - """ other = _convert_other(other) if other is NotImplemented: - if divmod in (0, 1): - return NotImplemented - return (NotImplemented, NotImplemented) + return NotImplemented if context is None: context = getcontext() @@ -1233,144 +1181,84 @@ if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: - if divmod: - return (ans, ans) return ans if self._isinfinity() and other._isinfinity(): - if divmod: - return (context._raise_error(InvalidOperation, - '(+-)INF // (+-)INF'), - context._raise_error(InvalidOperation, - '(+-)INF % (+-)INF')) return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') if self._isinfinity(): - if divmod == 1: - return (Infsign[sign], - context._raise_error(InvalidOperation, 'INF % x')) - elif divmod == 2: - return (Infsign[sign], NaN) - elif divmod == 3: - return (Infsign[sign], - context._raise_error(InvalidOperation, 'INF % x')) return Infsign[sign] if other._isinfinity(): - if divmod: - return (Decimal((sign, (0,), 0)), Decimal(self)) context._raise_error(Clamped, 'Division by infinity') return Decimal((sign, (0,), context.Etiny())) # Special cases for zeroes - if not self and not other: - if divmod: - return context._raise_error(DivisionUndefined, '0 / 0', 1) - return context._raise_error(DivisionUndefined, '0 / 0') - - if not self: - if divmod: - otherside = Decimal(self) - otherside._exp = min(self._exp, other._exp) - return (Decimal((sign, (0,), 0)), otherside) - exp = self._exp - other._exp - if exp < context.Etiny(): - exp = context.Etiny() - context._raise_error(Clamped, '0e-x / y') - if exp > context.Emax: - exp = context.Emax - context._raise_error(Clamped, '0e+x / y') - return Decimal( (sign, (0,), exp) ) - if not other: - if divmod: - return context._raise_error(DivisionByZero, 'divmod(x,0)', - sign, 1) + if not self: + return context._raise_error(DivisionUndefined, '0 / 0') return context._raise_error(DivisionByZero, 'x / 0', sign) - # OK, so neither = 0, INF or NaN - shouldround = context._rounding_decision == ALWAYS_ROUND - - # If we're dividing into ints, and self < other, stop. - # self.__abs__(0) does not round. - if divmod and (self.__abs__(0, context) < other.__abs__(0, context)): - - if divmod == 1 or divmod == 3: - exp = min(self._exp, other._exp) - ans2 = self._rescale(exp, context=context, watchexp=0) - if shouldround: - ans2 = ans2._fix(context) - return (Decimal( (sign, (0,), 0) ), - ans2) - - elif divmod == 2: - # Don't round the mod part, if we don't need it. - return (Decimal( (sign, (0,), 0) ), Decimal(self)) - - op1 = _WorkRep(self) - op2 = _WorkRep(other) - op1, op2, adjust = _adjust_coefficients(op1, op2) - res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) ) - if divmod and res.exp > context.prec + 1: - return context._raise_error(DivisionImpossible) - - prec_limit = 10 ** context.prec - while 1: - while op2.int <= op1.int: - res.int += 1 - op1.int -= op2.int - if res.exp == 0 and divmod: - if res.int >= prec_limit and shouldround: - return context._raise_error(DivisionImpossible) - otherside = Decimal(op1) - frozen = context._ignore_all_flags() - - exp = min(self._exp, other._exp) - otherside = otherside._rescale(exp, context=context, watchexp=0) - context._regard_flags(*frozen) - if shouldround: - otherside = otherside._fix(context) - return (Decimal(res), otherside) - - if op1.int == 0 and adjust >= 0 and not divmod: - break - if res.int >= prec_limit and shouldround: - if divmod: - return context._raise_error(DivisionImpossible) - shouldround=1 - # Really, the answer is a bit higher, so adding a one to - # the end will make sure the rounding is right. - if op1.int != 0: - res.int *= 10 - res.int += 1 - res.exp -= 1 - - break - res.int *= 10 - res.exp -= 1 - adjust += 1 - op1.int *= 10 - op1.exp -= 1 - - if res.exp == 0 and divmod and op2.int > op1.int: - # Solves an error in precision. Same as a previous block. - - if res.int >= prec_limit and shouldround: - return context._raise_error(DivisionImpossible) - otherside = Decimal(op1) - frozen = context._ignore_all_flags() + if not self: + exp = self._exp - other._exp + coeff = 0 + else: + # OK, so neither = 0, INF or NaN + shift = len(other._int) - len(self._int) + context.prec + 1 + exp = self._exp - other._exp - shift + op1 = _WorkRep(self) + op2 = _WorkRep(other) + if shift >= 0: + coeff, remainder = divmod(op1.int * 10**shift, op2.int) + else: + coeff, remainder = divmod(op1.int, op2.int * 10**-shift) + if remainder: + # result is not exact; adjust to ensure correct rounding + if coeff % 5 == 0: + coeff += 1 + else: + # result is exact; get as close to ideal exponent as possible + ideal_exp = self._exp - other._exp + while exp < ideal_exp and coeff % 10 == 0: + coeff //= 10 + exp += 1 - exp = min(self._exp, other._exp) - otherside = otherside._rescale(exp, context=context) + ans = Decimal((sign, list(map(int, str(coeff))), exp)) + return ans._fix(context) - context._regard_flags(*frozen) + def _divide(self, other, context): + """Return (self // other, self % other), to context.prec precision. - return (Decimal(res), otherside) + Assumes that neither self nor other is a NaN, that self is not + infinite and that other is nonzero. + """ + sign = self._sign ^ other._sign + if other._isinfinity(): + ideal_exp = self._exp + else: + ideal_exp = min(self._exp, other._exp) - ans = Decimal(res) - if shouldround: - ans = ans._fix(context) - return ans + expdiff = self.adjusted() - other.adjusted() + if not self or other._isinfinity() or expdiff <= -2: + return (Decimal((sign, (0,), 0)), + self._rescale(ideal_exp, context.rounding)) + if expdiff <= context.prec: + op1 = _WorkRep(self) + op2 = _WorkRep(other) + if op1.exp >= op2.exp: + op1.int *= 10**(op1.exp - op2.exp) + else: + op2.int *= 10**(op2.exp - op1.exp) + q, r = divmod(op1.int, op2.int) + if q < 10**context.prec: + return (Decimal((sign, list(map(int, str(q))), 0)), + Decimal((self._sign, list(map(int, str(r))), + ideal_exp))) + + # Here the quotient is too large to be representable + ans = context._raise_error(DivisionImpossible, + 'quotient too large in //, % or divmod') + return ans, ans def __rtruediv__(self, other, context=None): """Swaps self/other and returns __truediv__.""" @@ -1381,9 +1269,40 @@ def __divmod__(self, other, context=None): """ - (self // other, self % other) + Return (self // other, self % other) """ - return self._divide(other, 1, context) + other = _convert_other(other) + if other is NotImplemented: + return other + + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return (ans, ans) + + sign = self._sign ^ other._sign + if self._isinfinity(): + if other._isinfinity(): + ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') + return ans, ans + else: + return (Infsign[sign], + context._raise_error(InvalidOperation, 'INF % x')) + + if not other: + if not self: + ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') + return ans, ans + else: + return (context._raise_error(DivisionByZero, 'x // 0', sign), + context._raise_error(InvalidOperation, 'x % 0')) + + quotient, remainder = self._divide(other, context) + if context._rounding_decision == ALWAYS_ROUND: + remainder = remainder._fix(context) + return quotient, remainder def __rdivmod__(self, other, context=None): """Swaps self/other and returns __divmod__.""" @@ -1400,15 +1319,25 @@ if other is NotImplemented: return other - if self._is_special or other._is_special: - ans = self._check_nans(other, context) - if ans: - return ans + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return ans - if self and not other: - return context._raise_error(InvalidOperation, 'x % 0') + if self._isinfinity(): + return context._raise_error(InvalidOperation, 'INF % x') + elif not other: + if self: + return context._raise_error(InvalidOperation, 'x % 0') + else: + return context._raise_error(DivisionUndefined, '0 % 0') - return self._divide(other, 3, context)[1] + remainder = self._divide(other, context)[1] + if context._rounding_decision == ALWAYS_ROUND: + remainder = remainder._fix(context) + return remainder def __rmod__(self, other, context=None): """Swaps self/other and returns __mod__.""" @@ -1421,85 +1350,104 @@ """ Remainder nearest to 0- abs(remainder-near) <= other/2 """ - other = _convert_other(other) - if other is NotImplemented: - return other - - if self._is_special or other._is_special: - ans = self._check_nans(other, context) - if ans: - return ans - if self and not other: - return context._raise_error(InvalidOperation, 'x % 0') - if context is None: context = getcontext() - # If DivisionImpossible causes an error, do not leave Rounded/Inexact - # ignored in the calling function. - context = context._shallow_copy() - flags = context._ignore_flags(Rounded, Inexact) - # Keep DivisionImpossible flags - (side, r) = self.__divmod__(other, context=context) - - if r._isnan(): - context._regard_flags(*flags) - return r - - context = context._shallow_copy() - rounding = context._set_rounding_decision(NEVER_ROUND) - if other._sign: - comparison = other.__truediv__(Decimal(-2), context=context) - else: - comparison = other.__truediv__(Decimal(2), context=context) + other = _convert_other(other, raiseit=True) - context._set_rounding_decision(rounding) - context._regard_flags(*flags) + ans = self._check_nans(other, context) + if ans: + return ans - s1, s2 = r._sign, comparison._sign - r._sign, comparison._sign = 0, 0 + # self == +/-infinity -> InvalidOperation + if self._isinfinity(): + return context._raise_error(InvalidOperation, + 'remainder_near(infinity, x)') - if r < comparison: - r._sign, comparison._sign = s1, s2 - # Get flags now - self.__divmod__(other, context=context) - return r._fix(context) - r._sign, comparison._sign = s1, s2 + # other == 0 -> either InvalidOperation or DivisionUndefined + if not other: + if self: + return context._raise_error(InvalidOperation, + 'remainder_near(x, 0)') + else: + return context._raise_error(DivisionUndefined, + 'remainder_near(0, 0)') - rounding = context._set_rounding_decision(NEVER_ROUND) + # other = +/-infinity -> remainder = self + if other._isinfinity(): + ans = Decimal(self) + return ans._fix(context) - (side, r) = self.__divmod__(other, context=context) - context._set_rounding_decision(rounding) - if r._isnan(): - return r + # self = 0 -> remainder = self, with ideal exponent + ideal_exponent = min(self._exp, other._exp) + if not self: + ans = Decimal((self._sign, (0,), ideal_exponent)) + return ans._fix(context) - decrease = not side._iseven() - rounding = context._set_rounding_decision(NEVER_ROUND) - side = side.__abs__(context=context) - context._set_rounding_decision(rounding) + # catch most cases of large or small quotient + expdiff = self.adjusted() - other.adjusted() + if expdiff >= context.prec + 1: + # expdiff >= prec+1 => abs(self/other) > 10**prec + return context._raise_error(DivisionImpossible) + if expdiff <= -2: + # expdiff <= -2 => abs(self/other) < 0.1 + ans = self._rescale(ideal_exponent, context.rounding) + return ans._fix(context) - s1, s2 = r._sign, comparison._sign - r._sign, comparison._sign = 0, 0 - if r > comparison or decrease and r == comparison: - r._sign, comparison._sign = s1, s2 - context.prec += 1 - numbsquant = len(side.__add__(Decimal(1), context=context)._int) - if numbsquant >= context.prec: - context.prec -= 1 - return context._raise_error(DivisionImpossible)[1] - context.prec -= 1 - if self._sign == other._sign: - r = r.__sub__(other, context=context) - else: - r = r.__add__(other, context=context) + # adjust both arguments to have the same exponent, then divide + op1 = _WorkRep(self) + op2 = _WorkRep(other) + if op1.exp >= op2.exp: + op1.int *= 10**(op1.exp - op2.exp) else: - r._sign, comparison._sign = s1, s2 + op2.int *= 10**(op2.exp - op1.exp) + q, r = divmod(op1.int, op2.int) + # remainder is r*10**ideal_exponent; other is +/-op2.int * + # 10**ideal_exponent. Apply correction to ensure that + # abs(remainder) <= abs(other)/2 + if 2*r + (q&1) > op2.int: + r -= op2.int + q += 1 + + if q >= 10**context.prec: + return context._raise_error(DivisionImpossible) + + # result has same sign as self unless r is negative + sign = self._sign + if r < 0: + sign = 1-sign + r = -r - return r._fix(context) + ans = Decimal((sign, list(map(int, str(r))), ideal_exponent)) + return ans._fix(context) def __floordiv__(self, other, context=None): """self // other""" - return self._divide(other, 2, context)[0] + other = _convert_other(other) + if other is NotImplemented: + return other + + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return ans + + if self._isinfinity(): + if other._isinfinity(): + return context._raise_error(InvalidOperation, 'INF // INF') + else: + return Infsign[self._sign ^ other._sign] + + if not other: + if self: + return context._raise_error(DivisionByZero, 'x // 0', + self._sign ^ other._sign) + else: + return context._raise_error(DivisionUndefined, '0 // 0') + + return self._divide(other, context)[0] def __rfloordiv__(self, other, context=None): """Swaps self/other and returns __floordiv__.""" @@ -1519,22 +1467,27 @@ context = getcontext() return context._raise_error(InvalidContext) elif self._isinfinity(): - raise OverflowError("Cannot convert infinity to long") + raise OverflowError("Cannot convert infinity to int") + s = (-1)**self._sign if self._exp >= 0: - s = ''.join(map(str, self._int)) + '0'*self._exp + return s*int(''.join(map(str, self._int)))*10**self._exp else: - s = ''.join(map(str, self._int))[:self._exp] - if s == '': - s = '0' - sign = '-'*self._sign - return int(sign + s) - - def __long__(self): - """Converts to a long. + return s*int(''.join(map(str, self._int))[:self._exp] or '0') - Equivalent to long(int(self)) - """ - return int(self.__int__()) + def _fix_nan(self, context): + """Decapitate the payload of a NaN to fit the context""" + payload = self._int + + # maximum length of payload is precision if _clamp=0, + # precision-1 if _clamp=1. + max_payload_len = context.prec - context._clamp + if len(payload) > max_payload_len: + pos = len(payload)-max_payload_len + while pos < len(payload) and payload[pos] == 0: + pos += 1 + payload = payload[pos:] + return Decimal((self._sign, payload, self._exp)) + return Decimal(self) def _fix(self, context): """Round if it is necessary to keep self within prec precision. @@ -1545,303 +1498,649 @@ self - Decimal instance context - context used. """ - if self._is_special: - return self + if context is None: context = getcontext() - prec = context.prec - ans = self._fixexponents(context) - if len(ans._int) > prec: - ans = ans._round(prec, context=context) - ans = ans._fixexponents(context) - return ans - def _fixexponents(self, context): - """Fix the exponents and return a copy with the exponent in bounds. - Only call if known to not be a special value. - """ - folddown = context._clamp - Emin = context.Emin - ans = self - ans_adjusted = ans.adjusted() - if ans_adjusted < Emin: - Etiny = context.Etiny() - if ans._exp < Etiny: - if not ans: - ans = Decimal(self) - ans._exp = Etiny - context._raise_error(Clamped) - return ans - ans = ans._rescale(Etiny, context=context) - # It isn't zero, and exp < Emin => subnormal - context._raise_error(Subnormal) - if context.flags[Inexact]: - context._raise_error(Underflow) + if self._is_special: + if self._isnan(): + # decapitate payload if necessary + return self._fix_nan(context) else: - if ans: - # Only raise subnormal if non-zero. - context._raise_error(Subnormal) - else: - Etop = context.Etop() - if folddown and ans._exp > Etop: + # self is +/-Infinity; return unaltered + return Decimal(self) + + # if self is zero then exponent should be between Etiny and + # Emax if _clamp==0, and between Etiny and Etop if _clamp==1. + Etiny = context.Etiny() + Etop = context.Etop() + if not self: + exp_max = [context.Emax, Etop][context._clamp] + new_exp = min(max(self._exp, Etiny), exp_max) + if new_exp != self._exp: context._raise_error(Clamped) - ans = ans._rescale(Etop, context=context) + return Decimal((self._sign, (0,), new_exp)) else: - Emax = context.Emax - if ans_adjusted > Emax: - if not ans: - ans = Decimal(self) - ans._exp = Emax - context._raise_error(Clamped) - return ans - context._raise_error(Inexact) - context._raise_error(Rounded) - c = context._raise_error(Overflow, 'above Emax', ans._sign) - return c - return ans - - def _round(self, prec=None, rounding=None, context=None): - """Returns a rounded version of self. - - You can specify the precision or rounding method. Otherwise, the - context determines it. - """ - - if self._is_special: - ans = self._check_nans(context=context) - if ans: - return ans - - if self._isinfinity(): return Decimal(self) - if context is None: - context = getcontext() - - if rounding is None: - rounding = context.rounding - if prec is None: - prec = context.prec - - if not self: - if prec <= 0: - dig = (0,) - exp = len(self._int) - prec + self._exp - else: - dig = (0,) * prec - exp = len(self._int) + self._exp - prec - ans = Decimal((self._sign, dig, exp)) + # exp_min is the smallest allowable exponent of the result, + # equal to max(self.adjusted()-context.prec+1, Etiny) + exp_min = len(self._int) + self._exp - context.prec + if exp_min > Etop: + # overflow: exp_min > Etop iff self.adjusted() > Emax + context._raise_error(Inexact) context._raise_error(Rounded) - return ans + return context._raise_error(Overflow, 'above Emax', self._sign) + self_is_subnormal = exp_min < Etiny + if self_is_subnormal: + context._raise_error(Subnormal) + exp_min = Etiny - if prec == 0: - temp = Decimal(self) - temp._int = (0,)+temp._int - prec = 1 - elif prec < 0: - exp = self._exp + len(self._int) - prec - 1 - temp = Decimal( (self._sign, (0, 1), exp)) - prec = 1 - else: - temp = Decimal(self) - - numdigits = len(temp._int) - if prec == numdigits: - return temp - - # See if we need to extend precision - expdiff = prec - numdigits - if expdiff > 0: - tmp = list(temp._int) - tmp.extend([0] * expdiff) - ans = Decimal( (temp._sign, tmp, temp._exp - expdiff)) - return ans - - # OK, but maybe all the lost digits are 0. - lostdigits = self._int[expdiff:] - if lostdigits == (0,) * len(lostdigits): - ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff)) - # Rounded, but not Inexact + # round if self has too many digits + if self._exp < exp_min: context._raise_error(Rounded) + ans = self._rescale(exp_min, context.rounding) + if ans != self: + context._raise_error(Inexact) + if self_is_subnormal: + context._raise_error(Underflow) + if not ans: + # raise Clamped on underflow to 0 + context._raise_error(Clamped) + elif len(ans._int) == context.prec+1: + # we get here only if rescaling rounds the + # cofficient up to exactly 10**context.prec + if ans._exp < Etop: + ans = Decimal((ans._sign, ans._int[:-1], ans._exp+1)) + else: + # Inexact and Rounded have already been raised + ans = context._raise_error(Overflow, 'above Emax', + self._sign) return ans - # Okay, let's round and lose data - - this_function = getattr(temp, self._pick_rounding_function[rounding]) - # Now we've got the rounding function + # fold down if _clamp == 1 and self has too few digits + if context._clamp == 1 and self._exp > Etop: + context._raise_error(Clamped) + self_padded = self._int + (0,)*(self._exp - Etop) + return Decimal((self._sign, self_padded, Etop)) - if prec != context.prec: - context = context._shallow_copy() - context.prec = prec - ans = this_function(prec, expdiff, context) - context._raise_error(Rounded) - context._raise_error(Inexact, 'Changed in rounding') - - return ans + # here self was representable to begin with; return unchanged + return Decimal(self) _pick_rounding_function = {} - def _round_down(self, prec, expdiff, context): - """Also known as round-towards-0, truncate.""" - return Decimal( (self._sign, self._int[:prec], self._exp - expdiff) ) + # for each of the rounding functions below: + # self is a finite, nonzero Decimal + # prec is an integer satisfying 0 <= prec < len(self._int) + # the rounded result will have exponent self._exp + len(self._int) - prec; - def _round_half_up(self, prec, expdiff, context, tmp = None): - """Rounds 5 up (away from 0)""" + def _round_down(self, prec): + """Also known as round-towards-0, truncate.""" + newexp = self._exp + len(self._int) - prec + return Decimal((self._sign, self._int[:prec] or (0,), newexp)) - if tmp is None: - tmp = Decimal( (self._sign,self._int[:prec], self._exp - expdiff)) - if self._int[prec] >= 5: - tmp = tmp._increment(round=0, context=context) - if len(tmp._int) > prec: - return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1)) + def _round_up(self, prec): + """Rounds away from 0.""" + newexp = self._exp + len(self._int) - prec + tmp = Decimal((self._sign, self._int[:prec] or (0,), newexp)) + for digit in self._int[prec:]: + if digit != 0: + return tmp._increment() return tmp - def _round_half_even(self, prec, expdiff, context): - """Round 5 to even, rest to nearest.""" - - tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff)) - half = (self._int[prec] == 5) - if half: - for digit in self._int[prec+1:]: - if digit != 0: - half = 0 - break - if half: - if self._int[prec-1] & 1 == 0: - return tmp - return self._round_half_up(prec, expdiff, context, tmp) + def _round_half_up(self, prec): + """Rounds 5 up (away from 0)""" + if self._int[prec] >= 5: + return self._round_up(prec) + else: + return self._round_down(prec) - def _round_half_down(self, prec, expdiff, context): + def _round_half_down(self, prec): """Round 5 down""" - - tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff)) - half = (self._int[prec] == 5) - if half: + if self._int[prec] == 5: for digit in self._int[prec+1:]: if digit != 0: - half = 0 break - if half: - return tmp - return self._round_half_up(prec, expdiff, context, tmp) + else: + return self._round_down(prec) + return self._round_half_up(prec) - def _round_up(self, prec, expdiff, context): - """Rounds away from 0.""" - tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff) ) - for digit in self._int[prec:]: - if digit != 0: - tmp = tmp._increment(round=1, context=context) - if len(tmp._int) > prec: - return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1)) - else: - return tmp - return tmp + def _round_half_even(self, prec): + """Round 5 to even, rest to nearest.""" + if prec and self._int[prec-1] & 1: + return self._round_half_up(prec) + else: + return self._round_half_down(prec) - def _round_ceiling(self, prec, expdiff, context): + def _round_ceiling(self, prec): """Rounds up (not away from 0 if negative.)""" if self._sign: - return self._round_down(prec, expdiff, context) + return self._round_down(prec) else: - return self._round_up(prec, expdiff, context) + return self._round_up(prec) - def _round_floor(self, prec, expdiff, context): + def _round_floor(self, prec): """Rounds down (not towards 0 if negative)""" if not self._sign: - return self._round_down(prec, expdiff, context) + return self._round_down(prec) else: - return self._round_up(prec, expdiff, context) + return self._round_up(prec) - def __pow__(self, n, modulo = None, context=None): - """Return self ** n (mod modulo) + def _round_05up(self, prec): + """Round down unless digit prec-1 is 0 or 5.""" + if prec == 0 or self._int[prec-1] in (0, 5): + return self._round_up(prec) + else: + return self._round_down(prec) + + def fma(self, other, third, context=None): + """Fused multiply-add. - If modulo is None (default), don't take it mod modulo. + Returns self*other+third with no rounding of the intermediate + product self*other. + + self and other are multiplied together, with no rounding of + the result. The third operand is then added to the result, + and a single final rounding is performed. """ - n = _convert_other(n) - if n is NotImplemented: - return n + + other = _convert_other(other, raiseit=True) + third = _convert_other(third, raiseit=True) if context is None: context = getcontext() - if self._is_special or n._is_special or n.adjusted() > 8: - # Because the spot << doesn't work with really big exponents - if n._isinfinity() or n.adjusted() > 8: - return context._raise_error(InvalidOperation, 'x ** INF') + # do self*other in fresh context with no traps and no rounding + mul_context = Context(traps=[], flags=[], + _rounding_decision=NEVER_ROUND) + product = self.__mul__(other, mul_context) + + if mul_context.flags[InvalidOperation]: + # reraise in current context + return context._raise_error(InvalidOperation, + 'invalid multiplication in fma', + 1, product) - ans = self._check_nans(n, context) - if ans: - return ans + ans = product.__add__(third, context) + return ans - if not n._isinteger(): - return context._raise_error(InvalidOperation, 'x ** (non-integer)') + def _power_modulo(self, other, modulo, context=None): + """Three argument version of __pow__""" - if not self and not n: - return context._raise_error(InvalidOperation, '0 ** 0') + # if can't convert other and modulo to Decimal, raise + # TypeError; there's no point returning NotImplemented (no + # equivalent of __rpow__ for three argument pow) + other = _convert_other(other, raiseit=True) + modulo = _convert_other(modulo, raiseit=True) - if not n: - return Decimal(1) + if context is None: + context = getcontext() - if self == Decimal(1): - return Decimal(1) + # deal with NaNs: if there are any sNaNs then first one wins, + # (i.e. behaviour for NaNs is identical to that of fma) + self_is_nan = self._isnan() + other_is_nan = other._isnan() + modulo_is_nan = modulo._isnan() + if self_is_nan or other_is_nan or modulo_is_nan: + if self_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + 1, self) + if other_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + 1, other) + if modulo_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + 1, modulo) + if self_is_nan: + return self._fix_nan(context) + if other_is_nan: + return other._fix_nan(context) + return modulo._fix_nan(context) + + # check inputs: we apply same restrictions as Python's pow() + if not (self._isinteger() and + other._isinteger() and + modulo._isinteger()): + return context._raise_error(InvalidOperation, + 'pow() 3rd argument not allowed ' + 'unless all arguments are integers') + if other < 0: + return context._raise_error(InvalidOperation, + 'pow() 2nd argument cannot be ' + 'negative when 3rd argument specified') + if not modulo: + return context._raise_error(InvalidOperation, + 'pow() 3rd argument cannot be 0') + + # additional restriction for decimal: the modulus must be less + # than 10**prec in absolute value + if modulo.adjusted() >= context.prec: + return context._raise_error(InvalidOperation, + 'insufficient precision: pow() 3rd ' + 'argument must not have more than ' + 'precision digits') + + # define 0**0 == NaN, for consistency with two-argument pow + # (even though it hurts!) + if not other and not self: + return context._raise_error(InvalidOperation, + 'at least one of pow() 1st argument ' + 'and 2nd argument must be nonzero ;' + '0**0 is not defined') + + # compute sign of result + if other._iseven(): + sign = 0 + else: + sign = self._sign - sign = self._sign and not n._iseven() - n = int(n) + # convert modulo to a Python integer, and self and other to + # Decimal integers (i.e. force their exponents to be >= 0) + modulo = abs(int(modulo)) + base = _WorkRep(self.to_integral_value()) + exponent = _WorkRep(other.to_integral_value()) + + # compute result using integer pow() + base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo + for i in range(exponent.exp): + base = pow(base, 10, modulo) + base = pow(base, exponent.int, modulo) + + return Decimal((sign, list(map(int, str(base))), 0)) + + def _power_exact(self, other, p): + """Attempt to compute self**other exactly. + + Given Decimals self and other and an integer p, attempt to + compute an exact result for the power self**other, with p + digits of precision. Return None if self**other is not + exactly representable in p digits. + + Assumes that elimination of special cases has already been + performed: self and other must both be nonspecial; self must + be positive and not numerically equal to 1; other must be + nonzero. For efficiency, other._exp should not be too large, + so that 10**abs(other._exp) is a feasible calculation.""" + + # In the comments below, we write x for the value of self and + # y for the value of other. Write x = xc*10**xe and y = + # yc*10**ye. + + # The main purpose of this method is to identify the *failure* + # of x**y to be exactly representable with as little effort as + # possible. So we look for cheap and easy tests that + # eliminate the possibility of x**y being exact. Only if all + # these tests are passed do we go on to actually compute x**y. + + # Here's the main idea. First normalize both x and y. We + # express y as a rational m/n, with m and n relatively prime + # and n>0. Then for x**y to be exactly representable (at + # *any* precision), xc must be the nth power of a positive + # integer and xe must be divisible by n. If m is negative + # then additionally xc must be a power of either 2 or 5, hence + # a power of 2**n or 5**n. + # + # There's a limit to how small |y| can be: if y=m/n as above + # then: + # + # (1) if xc != 1 then for the result to be representable we + # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So + # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <= + # 2**(1/|y|), hence xc**|y| < 2 and the result is not + # representable. + # + # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if + # |y| < 1/|xe| then the result is not representable. + # + # Note that since x is not equal to 1, at least one of (1) and + # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) < + # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye. + # + # There's also a limit to how large y can be, at least if it's + # positive: the normalized result will have coefficient xc**y, + # so if it's representable then xc**y < 10**p, and y < + # p/log10(xc). Hence if y*log10(xc) >= p then the result is + # not exactly representable. + + # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye, + # so |y| < 1/xe and the result is not representable. + # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y| + # < 1/nbits(xc). + + x = _WorkRep(self) + xc, xe = x.int, x.exp + while xc % 10 == 0: + xc //= 10 + xe += 1 + + y = _WorkRep(other) + yc, ye = y.int, y.exp + while yc % 10 == 0: + yc //= 10 + ye += 1 + + # case where xc == 1: result is 10**(xe*y), with xe*y + # required to be an integer + if xc == 1: + if ye >= 0: + exponent = xe*yc*10**ye + else: + exponent, remainder = divmod(xe*yc, 10**-ye) + if remainder: + return None + if y.sign == 1: + exponent = -exponent + # if other is a nonnegative integer, use ideal exponent + if other._isinteger() and other._sign == 0: + ideal_exponent = self._exp*int(other) + zeros = min(exponent-ideal_exponent, p-1) + else: + zeros = 0 + return Decimal((0, (1,) + (0,)*zeros, exponent-zeros)) + # case where y is negative: xc must be either a power + # of 2 or a power of 5. + if y.sign == 1: + last_digit = xc % 10 + if last_digit in (2,4,6,8): + # quick test for power of 2 + if xc & -xc != xc: + return None + # now xc is a power of 2; e is its exponent + e = _nbits(xc)-1 + # find e*y and xe*y; both must be integers + if ye >= 0: + y_as_int = yc*10**ye + e = e*y_as_int + xe = xe*y_as_int + else: + ten_pow = 10**-ye + e, remainder = divmod(e*yc, ten_pow) + if remainder: + return None + xe, remainder = divmod(xe*yc, ten_pow) + if remainder: + return None + + if e*65 >= p*93: # 93/65 > log(10)/log(5) + return None + xc = 5**e + + elif last_digit == 5: + # e >= log_5(xc) if xc is a power of 5; we have + # equality all the way up to xc=5**2658 + e = _nbits(xc)*28//65 + xc, remainder = divmod(5**e, xc) + if remainder: + return None + while xc % 5 == 0: + xc //= 5 + e -= 1 + if ye >= 0: + y_as_integer = yc*10**ye + e = e*y_as_integer + xe = xe*y_as_integer + else: + ten_pow = 10**-ye + e, remainder = divmod(e*yc, ten_pow) + if remainder: + return None + xe, remainder = divmod(xe*yc, ten_pow) + if remainder: + return None + if e*3 >= p*10: # 10/3 > log(10)/log(2) + return None + xc = 2**e + else: + return None + + if xc >= 10**p: + return None + xe = -e-xe + return Decimal((0, list(map(int, str(xc))), xe)) + + # now y is positive; find m and n such that y = m/n + if ye >= 0: + m, n = yc*10**ye, 1 + else: + if xe != 0 and len(str(abs(yc*xe))) <= -ye: + return None + xc_bits = _nbits(xc) + if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye: + return None + m, n = yc, 10**(-ye) + while m % 2 == n % 2 == 0: + m //= 2 + n //= 2 + while m % 5 == n % 5 == 0: + m //= 5 + n //= 5 + + # compute nth root of xc*10**xe + if n > 1: + # if 1 < xc < 2**n then xc isn't an nth power + if xc != 1 and xc_bits <= n: + return None + + xe, rem = divmod(xe, n) + if rem != 0: + return None + + # compute nth root of xc using Newton's method + a = 1 << -(-_nbits(xc)//n) # initial estimate + while True: + q, r = divmod(xc, a**(n-1)) + if a <= q: + break + else: + a = (a*(n-1) + q)//n + if not (a == q and r == 0): + return None + xc = a + + # now xc*10**xe is the nth root of the original xc*10**xe + # compute mth power of xc*10**xe + + # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m > + # 10**p and the result is not representable. + if xc > 1 and m > p*100//_log10_lb(xc): + return None + xc = xc**m + xe *= m + if xc > 10**p: + return None + + # by this point the result *is* exactly representable + # adjust the exponent to get as close as possible to the ideal + # exponent, if necessary + str_xc = str(xc) + if other._isinteger() and other._sign == 0: + ideal_exponent = self._exp*int(other) + zeros = min(xe-ideal_exponent, p-len(str_xc)) + else: + zeros = 0 + return Decimal((0, list(map(int, str_xc))+[0,]*zeros, xe-zeros)) + + def __pow__(self, other, modulo=None, context=None): + """Return self ** other [ % modulo]. + + With two arguments, compute self**other. + + With three arguments, compute (self**other) % modulo. For the + three argument form, the following restrictions on the + arguments hold: + + - all three arguments must be integral + - other must be nonnegative + - either self or other (or both) must be nonzero + - modulo must be nonzero and must have at most p digits, + where p is the context precision. + + If any of these restrictions is violated the InvalidOperation + flag is raised. + + The result of pow(self, other, modulo) is identical to the + result that would be obtained by computing (self**other) % + modulo with unbounded precision, but is computed more + efficiently. It is always exact. + """ + + if modulo is not None: + return self._power_modulo(other, modulo, context) + + other = _convert_other(other) + if other is NotImplemented: + return other + + if context is None: + context = getcontext() + + # either argument is a NaN => result is NaN + ans = self._check_nans(other, context) + if ans: + return ans + + # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) + if not other: + if not self: + return context._raise_error(InvalidOperation, '0 ** 0') + else: + return Dec_p1 + + # result has sign 1 iff self._sign is 1 and other is an odd integer + result_sign = 0 + if self._sign == 1: + if other._isinteger(): + if not other._iseven(): + result_sign = 1 + else: + # -ve**noninteger = NaN + # (-0)**noninteger = 0**noninteger + if self: + return context._raise_error(InvalidOperation, + 'x ** y with x negative and y not an integer') + # negate self, without doing any unwanted rounding + self = Decimal((0, self._int, self._exp)) + + # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity + if not self: + if other._sign == 0: + return Decimal((result_sign, (0,), 0)) + else: + return Infsign[result_sign] + + # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 if self._isinfinity(): - if modulo: - return context._raise_error(InvalidOperation, 'INF % x') - if n > 0: - return Infsign[sign] - return Decimal( (sign, (0,), 0) ) + if other._sign == 0: + return Infsign[result_sign] + else: + return Decimal((result_sign, (0,), 0)) + + # 1**other = 1, but the choice of exponent and the flags + # depend on the exponent of self, and on whether other is a + # positive integer, a negative integer, or neither + if self == Dec_p1: + if other._isinteger(): + # exp = max(self._exp*max(int(other), 0), + # 1-context.prec) but evaluating int(other) directly + # is dangerous until we know other is small (other + # could be 1e999999999) + if other._sign == 1: + multiplier = 0 + elif other > context.prec: + multiplier = context.prec + else: + multiplier = int(other) - # With ludicrously large exponent, just raise an overflow - # and return inf. - if not modulo and n > 0 and \ - (self._exp + len(self._int) - 1) * n > context.Emax and self: + exp = self._exp * multiplier + if exp < 1-context.prec: + exp = 1-context.prec + context._raise_error(Rounded) + else: + context._raise_error(Inexact) + context._raise_error(Rounded) + exp = 1-context.prec + + return Decimal((result_sign, (1,)+(0,)*-exp, exp)) + + # compute adjusted exponent of self + self_adj = self.adjusted() + + # self ** infinity is infinity if self > 1, 0 if self < 1 + # self ** -infinity is infinity if self < 1, 0 if self > 1 + if other._isinfinity(): + if (other._sign == 0) == (self_adj < 0): + return Decimal((result_sign, (0,), 0)) + else: + return Infsign[result_sign] - tmp = Decimal('inf') - tmp._sign = sign - context._raise_error(Rounded) - context._raise_error(Inexact) - context._raise_error(Overflow, 'Big power', sign) - return tmp + # from here on, the result always goes through the call + # to _fix at the end of this function. + ans = None + + # crude test to catch cases of extreme overflow/underflow. If + # log10(self)*other >= 10**bound and bound >= len(str(Emax)) + # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence + # self**other >= 10**(Emax+1), so overflow occurs. The test + # for underflow is similar. + bound = self._log10_exp_bound() + other.adjusted() + if (self_adj >= 0) == (other._sign == 0): + # self > 1 and other +ve, or self < 1 and other -ve + # possibility of overflow + if bound >= len(str(context.Emax)): + ans = Decimal((result_sign, (1,), context.Emax+1)) + else: + # self > 1 and other -ve, or self < 1 and other +ve + # possibility of underflow to 0 + Etiny = context.Etiny() + if bound >= len(str(-Etiny)): + ans = Decimal((result_sign, (1,), Etiny-1)) - elength = len(str(abs(n))) - firstprec = context.prec + # try for an exact result with precision +1 + if ans is None: + ans = self._power_exact(other, context.prec + 1) + if ans is not None and result_sign == 1: + ans = Decimal((1, ans._int, ans._exp)) + + # usual case: inexact result, x**y computed directly as exp(y*log(x)) + if ans is None: + p = context.prec + x = _WorkRep(self) + xc, xe = x.int, x.exp + y = _WorkRep(other) + yc, ye = y.int, y.exp + if y.sign == 1: + yc = -yc + + # compute correctly rounded result: start with precision +3, + # then increase precision until result is unambiguously roundable + extra = 3 + while True: + coeff, exp = _dpower(xc, xe, yc, ye, p+extra) + if coeff % (5*10**(len(str(coeff))-p-1)): + break + extra += 3 - if not modulo and firstprec + elength + 1 > DefaultContext.Emax: - return context._raise_error(Overflow, 'Too much precision.', sign) + ans = Decimal((result_sign, list(map(int, str(coeff))), exp)) - mul = Decimal(self) - val = Decimal(1) - context = context._shallow_copy() - context.prec = firstprec + elength + 1 - if n < 0: - # n is a long now, not Decimal instance - n = -n - mul = Decimal(1).__truediv__(mul, context=context) - - spot = 1 - while spot <= n: - spot <<= 1 - - spot >>= 1 - # spot is the highest power of 2 less than n - while spot: - val = val.__mul__(val, context=context) - if val._isinfinity(): - val = Infsign[sign] - break - if spot & n: - val = val.__mul__(mul, context=context) - if modulo is not None: - val = val.__mod__(modulo, context=context) - spot >>= 1 - context.prec = firstprec + # the specification says that for non-integer other we need to + # raise Inexact, even when the result is actually exact. In + # the same way, we need to raise Underflow here if the result + # is subnormal. (The call to _fix will take care of raising + # Rounded and Subnormal, as usual.) + if not other._isinteger(): + context._raise_error(Inexact) + # pad with zeros up to length context.prec+1 if necessary + if len(ans._int) <= context.prec: + expdiff = context.prec+1 - len(ans._int) + ans = Decimal((ans._sign, ans._int+(0,)*expdiff, ans._exp-expdiff)) + if ans.adjusted() < context.Emin: + context._raise_error(Underflow) - if context._rounding_decision == ALWAYS_ROUND: - return val._fix(context) - return val + # unlike exp, ln and log10, the power function respects the + # rounding mode; no need to use ROUND_HALF_EVEN here + ans = ans._fix(context) + return ans def __rpow__(self, other, context=None): """Swaps self/other and returns __pow__.""" @@ -1853,6 +2152,9 @@ def normalize(self, context=None): """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" + if context is None: + context = getcontext() + if self._is_special: ans = self._check_nans(context=context) if ans: @@ -1864,19 +2166,26 @@ if not dup: return Decimal( (dup._sign, (0,), 0) ) + exp_max = [context.Emax, context.Etop()][context._clamp] end = len(dup._int) exp = dup._exp - while dup._int[end-1] == 0: + while dup._int[end-1] == 0 and exp < exp_max: exp += 1 end -= 1 return Decimal( (dup._sign, dup._int[:end], exp) ) - - def quantize(self, exp, rounding=None, context=None, watchexp=1): + def quantize(self, exp, rounding=None, context=None, watchexp=True): """Quantize self so its exponent is the same as that of exp. Similar to self._rescale(exp._exp) but with error checking. """ + exp = _convert_other(exp, raiseit=True) + + if context is None: + context = getcontext() + if rounding is None: + rounding = context.rounding + if self._is_special or exp._is_special: ans = self._check_nans(exp, context) if ans: @@ -1884,12 +2193,56 @@ if exp._isinfinity() or self._isinfinity(): if exp._isinfinity() and self._isinfinity(): - return self # if both are inf, it is OK - if context is None: - context = getcontext() + return Decimal(self) # if both are inf, it is OK return context._raise_error(InvalidOperation, 'quantize with one INF') - return self._rescale(exp._exp, rounding, context, watchexp) + + # if we're not watching exponents, do a simple rescale + if not watchexp: + ans = self._rescale(exp._exp, rounding) + # raise Inexact and Rounded where appropriate + if ans._exp > self._exp: + context._raise_error(Rounded) + if ans != self: + context._raise_error(Inexact) + return ans + + # exp._exp should be between Etiny and Emax + if not (context.Etiny() <= exp._exp <= context.Emax): + return context._raise_error(InvalidOperation, + 'target exponent out of bounds in quantize') + + if not self: + ans = Decimal((self._sign, (0,), exp._exp)) + return ans._fix(context) + + self_adjusted = self.adjusted() + if self_adjusted > context.Emax: + return context._raise_error(InvalidOperation, + 'exponent of quantize result too large for current context') + if self_adjusted - exp._exp + 1 > context.prec: + return context._raise_error(InvalidOperation, + 'quantize result has too many digits for current context') + + ans = self._rescale(exp._exp, rounding) + if ans.adjusted() > context.Emax: + return context._raise_error(InvalidOperation, + 'exponent of quantize result too large for current context') + if len(ans._int) > context.prec: + return context._raise_error(InvalidOperation, + 'quantize result has too many digits for current context') + + # raise appropriate flags + if ans._exp > self._exp: + context._raise_error(Rounded) + if ans != self: + context._raise_error(Inexact) + if ans and ans.adjusted() < context.Emin: + context._raise_error(Subnormal) + + # call to fix takes care of any necessary folddown + ans = ans._fix(context) + return ans def same_quantum(self, other): """Test whether self and other have the same exponent. @@ -1903,83 +2256,85 @@ return self._isinfinity() and other._isinfinity() and True return self._exp == other._exp - def _rescale(self, exp, rounding=None, context=None, watchexp=1): - """Rescales so that the exponent is exp. + def _rescale(self, exp, rounding): + """Rescale self so that the exponent is exp, either by padding with zeros + or by truncating digits, using the given rounding mode. + + Specials are returned without change. This operation is + quiet: it raises no flags, and uses no information from the + context. exp = exp to scale to (an integer) - rounding = rounding version - watchexp: if set (default) an error is returned if exp is greater - than Emax or less than Etiny. + rounding = rounding mode """ - if context is None: - context = getcontext() - if self._is_special: - if self._isinfinity(): - return context._raise_error(InvalidOperation, 'rescale with an INF') - - ans = self._check_nans(context=context) - if ans: - return ans - - if watchexp and (context.Emax < exp or context.Etiny() > exp): - return context._raise_error(InvalidOperation, 'rescale(a, INF)') - + return Decimal(self) if not self: - ans = Decimal(self) - ans._int = (0,) - ans._exp = exp - return ans - - diff = self._exp - exp - digits = len(self._int) + diff - - if watchexp and digits > context.prec: - return context._raise_error(InvalidOperation, 'Rescale > prec') - - tmp = Decimal(self) - tmp._int = (0,) + tmp._int - digits += 1 + return Decimal((self._sign, (0,), exp)) + if self._exp >= exp: + # pad answer with zeros if necessary + return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp)) + + # too many digits; round and lose data. If self.adjusted() < + # exp-1, replace self by 10**(exp-1) before rounding + digits = len(self._int) + self._exp - exp if digits < 0: - tmp._exp = -digits + tmp._exp - tmp._int = (0,1) - digits = 1 - tmp = tmp._round(digits, rounding, context=context) - - if tmp._int[0] == 0 and len(tmp._int) > 1: - tmp._int = tmp._int[1:] - tmp._exp = exp + self = Decimal((self._sign, (1,), exp-1)) + digits = 0 + this_function = getattr(self, self._pick_rounding_function[rounding]) + return this_function(digits) + + def to_integral_exact(self, rounding=None, context=None): + """Rounds to a nearby integer. + + If no rounding mode is specified, take the rounding mode from + the context. This method raises the Rounded and Inexact flags + when appropriate. - tmp_adjusted = tmp.adjusted() - if tmp and tmp_adjusted < context.Emin: - context._raise_error(Subnormal) - elif tmp and tmp_adjusted > context.Emax: - return context._raise_error(InvalidOperation, 'rescale(a, INF)') - return tmp - - def to_integral(self, rounding=None, context=None): - """Rounds to the nearest integer, without raising inexact, rounded.""" + See also: to_integral_value, which does exactly the same as + this method except that it doesn't raise Inexact or Rounded. + """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans - return self + return Decimal(self) if self._exp >= 0: - return self + return Decimal(self) + if not self: + return Decimal((self._sign, (0,), 0)) if context is None: context = getcontext() - flags = context._ignore_flags(Rounded, Inexact) - ans = self._rescale(0, rounding, context=context) - context._regard_flags(flags) + if rounding is None: + rounding = context.rounding + context._raise_error(Rounded) + ans = self._rescale(0, rounding) + if ans != self: + context._raise_error(Inexact) return ans - def sqrt(self, context=None): - """Return the square root of self. + def to_integral_value(self, rounding=None, context=None): + """Rounds to the nearest integer, without raising inexact, rounded.""" + if context is None: + context = getcontext() + if rounding is None: + rounding = context.rounding + if self._is_special: + ans = self._check_nans(context=context) + if ans: + return ans + return Decimal(self) + if self._exp >= 0: + return Decimal(self) + else: + return self._rescale(0, rounding) - Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn)) - Should quadratically approach the right answer. - """ + # the method name changed, but we provide also the old one, for compatibility + to_integral = to_integral_value + + def sqrt(self, context=None): + """Return the square root of self.""" if self._is_special: ans = self._check_nans(context=context) if ans: @@ -1989,16 +2344,9 @@ return Decimal(self) if not self: - # exponent = self._exp / 2, using round_down. - # if self._exp < 0: - # exp = (self._exp+1) // 2 - # else: - exp = (self._exp) // 2 - if self._sign == 1: - # sqrt(-0) = -0 - return Decimal( (1, (0,), exp)) - else: - return Decimal( (0, (0,), exp)) + # exponent = self._exp // 2. sqrt(-0) = -0 + ans = Decimal((self._sign, (0,), self._exp // 2)) + return ans._fix(context) if context is None: context = getcontext() @@ -2006,104 +2354,94 @@ if self._sign == 1: return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') - tmp = Decimal(self) - - expadd = tmp._exp // 2 - if tmp._exp & 1: - tmp._int += (0,) - tmp._exp = 0 + # At this point self represents a positive number. Let p be + # the desired precision and express self in the form c*100**e + # with c a positive real number and e an integer, c and e + # being chosen so that 100**(p-1) <= c < 100**p. Then the + # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1) + # <= sqrt(c) < 10**p, so the closest representable Decimal at + # precision p is n*10**e where n = round_half_even(sqrt(c)), + # the closest integer to sqrt(c) with the even integer chosen + # in the case of a tie. + # + # To ensure correct rounding in all cases, we use the + # following trick: we compute the square root to an extra + # place (precision p+1 instead of precision p), rounding down. + # Then, if the result is inexact and its last digit is 0 or 5, + # we increase the last digit to 1 or 6 respectively; if it's + # exact we leave the last digit alone. Now the final round to + # p places (or fewer in the case of underflow) will round + # correctly and raise the appropriate flags. + + # use an extra digit of precision + prec = context.prec+1 + + # write argument in the form c*100**e where e = self._exp//2 + # is the 'ideal' exponent, to be used if the square root is + # exactly representable. l is the number of 'digits' of c in + # base 100, so that 100**(l-1) <= c < 100**l. + op = _WorkRep(self) + e = op.exp >> 1 + if op.exp & 1: + c = op.int * 10 + l = (len(self._int) >> 1) + 1 else: - tmp._exp = 0 - - context = context._shallow_copy() - flags = context._ignore_all_flags() - firstprec = context.prec - context.prec = 3 - if tmp.adjusted() & 1 == 0: - ans = Decimal( (0, (8,1,9), tmp.adjusted() - 2) ) - ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)), - context=context), context=context) - ans._exp -= 1 + tmp.adjusted() // 2 - else: - ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) ) - ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)), - context=context), context=context) - ans._exp -= 1 + tmp.adjusted() // 2 - - # ans is now a linear approximation. - Emax, Emin = context.Emax, context.Emin - context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin + c = op.int + l = len(self._int)+1 >> 1 - half = Decimal('0.5') - - maxp = firstprec + 2 - rounding = context._set_rounding(ROUND_HALF_EVEN) - while 1: - context.prec = min(2*context.prec - 2, maxp) - ans = half.__mul__(ans.__add__(tmp.__truediv__(ans, context=context), - context=context), context=context) - if context.prec == maxp: + # rescale so that c has exactly prec base 100 'digits' + shift = prec-l + if shift >= 0: + c *= 100**shift + exact = True + else: + c, remainder = divmod(c, 100**-shift) + exact = not remainder + e -= shift + + # find n = floor(sqrt(c)) using Newton's method + n = 10**prec + while True: + q = c//n + if n <= q: break + else: + n = n + q >> 1 + exact = exact and n*n == c - # Round to the answer's precision-- the only error can be 1 ulp. - context.prec = firstprec - prevexp = ans.adjusted() - ans = ans._round(context=context) - - # Now, check if the other last digits are better. - context.prec = firstprec + 1 - # In case we rounded up another digit and we should actually go lower. - if prevexp != ans.adjusted(): - ans._int += (0,) - ans._exp -= 1 - - - lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context) - context._set_rounding(ROUND_UP) - if lower.__mul__(lower, context=context) > (tmp): - ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context) - + if exact: + # result is exact; rescale to use ideal exponent e + if shift >= 0: + # assert n % 10**shift == 0 + n //= 10**shift + else: + n *= 10**-shift + e += shift else: - upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context) - context._set_rounding(ROUND_DOWN) - if upper.__mul__(upper, context=context) < tmp: - ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context) + # result is not exact; fix last digit as described above + if n % 5 == 0: + n += 1 - ans._exp += expadd + ans = Decimal((0, list(map(int, str(n))), e)) - context.prec = firstprec - context.rounding = rounding + # round, and fit to current context + context = context._shallow_copy() + rounding = context._set_rounding(ROUND_HALF_EVEN) ans = ans._fix(context) + context.rounding = rounding - rounding = context._set_rounding_decision(NEVER_ROUND) - if not ans.__mul__(ans, context=context) == self: - # Only rounded/inexact if here. - context._regard_flags(flags) - context._raise_error(Rounded) - context._raise_error(Inexact) - else: - # Exact answer, so let's set the exponent right. - # if self._exp < 0: - # exp = (self._exp +1)// 2 - # else: - exp = self._exp // 2 - context.prec += ans._exp - exp - ans = ans._rescale(exp, context=context) - context.prec = firstprec - context._regard_flags(flags) - context.Emax, context.Emin = Emax, Emin - - return ans._fix(context) + return ans def max(self, other, context=None): """Returns the larger value. - like max(self, other) except if one is not a number, returns + Like max(self, other) except if one is not a number, returns NaN (and signals if one is sNaN). Also rounds. """ - other = _convert_other(other) - if other is NotImplemented: - return other + other = _convert_other(other, raiseit=True) + + if context is None: + context = getcontext() if self._is_special or other._is_special: # If one operand is a quiet NaN and the other is number, then the @@ -2112,12 +2450,11 @@ on = other._isnan() if sn or on: if on == 1 and sn != 2: - return self + return self._fix_nan(context) if sn == 1 and on != 2: - return other + return other._fix_nan(context) return self._check_nans(other, context) - ans = self c = self.__cmp__(other) if c == 0: # If both operands are finite and equal in numerical value @@ -2127,19 +2464,14 @@ # positive sign and min returns the operand with the negative sign # # If the signs are the same then the exponent is used to select - # the result. - if self._sign != other._sign: - if self._sign: - ans = other - elif self._exp < other._exp and not self._sign: - ans = other - elif self._exp > other._exp and self._sign: - ans = other - elif c == -1: + # the result. This is exactly the ordering used in compare_total. + c = self.compare_total(other) + + if c == -1: ans = other + else: + ans = self - if context is None: - context = getcontext() if context._rounding_decision == ALWAYS_ROUND: return ans._fix(context) return ans @@ -2150,9 +2482,10 @@ Like min(self, other) except if one is not a number, returns NaN (and signals if one is sNaN). Also rounds. """ - other = _convert_other(other) - if other is NotImplemented: - return other + other = _convert_other(other, raiseit=True) + + if context is None: + context = getcontext() if self._is_special or other._is_special: # If one operand is a quiet NaN and the other is number, then the @@ -2161,49 +2494,37 @@ on = other._isnan() if sn or on: if on == 1 and sn != 2: - return self + return self._fix_nan(context) if sn == 1 and on != 2: - return other + return other._fix_nan(context) return self._check_nans(other, context) - ans = self c = self.__cmp__(other) if c == 0: - # If both operands are finite and equal in numerical value - # then an ordering is applied: - # - # If the signs differ then max returns the operand with the - # positive sign and min returns the operand with the negative sign - # - # If the signs are the same then the exponent is used to select - # the result. - if self._sign != other._sign: - if other._sign: - ans = other - elif self._exp > other._exp and not self._sign: - ans = other - elif self._exp < other._exp and self._sign: - ans = other - elif c == 1: + c = self.compare_total(other) + + if c == -1: + ans = self + else: ans = other - if context is None: - context = getcontext() if context._rounding_decision == ALWAYS_ROUND: return ans._fix(context) return ans def _isinteger(self): """Returns whether self is an integer""" + if self._is_special: + return False if self._exp >= 0: return True rest = self._int[self._exp:] return rest == (0,)*len(rest) def _iseven(self): - """Returns 1 if self is even. Assumes self is an integer.""" - if self._exp > 0: - return 1 + """Returns True if self is even. Assumes self is an integer.""" + if not self or self._exp > 0: + return True return self._int[-1+self._exp] & 1 == 0 def adjusted(self): @@ -2214,6 +2535,875 @@ except TypeError: return 0 + def canonical(self, context=None): + """Returns the same Decimal object. + + As we do not have different encodings for the same number, the + received object already is in its canonical form. + """ + return self + + def compare_signal(self, other, context=None): + """Compares self to the other operand numerically. + + It's pretty much like compare(), but all NaNs signal, with signaling + NaNs taking precedence over quiet NaNs. + """ + if context is None: + context = getcontext() + + self_is_nan = self._isnan() + other_is_nan = other._isnan() + if self_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + 1, self) + if other_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + 1, other) + if self_is_nan: + return context._raise_error(InvalidOperation, 'NaN in compare_signal', + 1, self) + if other_is_nan: + return context._raise_error(InvalidOperation, 'NaN in compare_signal', + 1, other) + return self.compare(other, context=context) + + def compare_total(self, other): + """Compares self to other using the abstract representations. + + This is not like the standard compare, which use their numerical + value. Note that a total ordering is defined for all possible abstract + representations. + """ + # if one is negative and the other is positive, it's easy + if self._sign and not other._sign: + return Dec_n1 + if not self._sign and other._sign: + return Dec_p1 + sign = self._sign + + # let's handle both NaN types + self_nan = self._isnan() + other_nan = other._isnan() + if self_nan or other_nan: + if self_nan == other_nan: + if self._int < other._int: + if sign: + return Dec_p1 + else: + return Dec_n1 + if self._int > other._int: + if sign: + return Dec_n1 + else: + return Dec_p1 + return Dec_0 + + if sign: + if self_nan == 1: + return Dec_n1 + if other_nan == 1: + return Dec_p1 + if self_nan == 2: + return Dec_n1 + if other_nan == 2: + return Dec_p1 + else: + if self_nan == 1: + return Dec_p1 + if other_nan == 1: + return Dec_n1 + if self_nan == 2: + return Dec_p1 + if other_nan == 2: + return Dec_n1 + + if self < other: + return Dec_n1 + if self > other: + return Dec_p1 + + if self._exp < other._exp: + if sign: + return Dec_p1 + else: + return Dec_n1 + if self._exp > other._exp: + if sign: + return Dec_n1 + else: + return Dec_p1 + return Dec_0 + + + def compare_total_mag(self, other): + """Compares self to other using abstract repr., ignoring sign. + + Like compare_total, but with operand's sign ignored and assumed to be 0. + """ + s = self.copy_abs() + o = other.copy_abs() + return s.compare_total(o) + + def copy_abs(self): + """Returns a copy with the sign set to 0. """ + return Decimal((0, self._int, self._exp)) + + def copy_negate(self): + """Returns a copy with the sign inverted.""" + if self._sign: + return Decimal((0, self._int, self._exp)) + else: + return Decimal((1, self._int, self._exp)) + + def copy_sign(self, other): + """Returns self with the sign of other.""" + return Decimal((other._sign, self._int, self._exp)) + + def exp(self, context=None): + """Returns e ** self.""" + + if context is None: + context = getcontext() + + # exp(NaN) = NaN + ans = self._check_nans(context=context) + if ans: + return ans + + # exp(-Infinity) = 0 + if self._isinfinity() == -1: + return Dec_0 + + # exp(0) = 1 + if not self: + return Dec_p1 + + # exp(Infinity) = Infinity + if self._isinfinity() == 1: + return Decimal(self) + + # the result is now guaranteed to be inexact (the true + # mathematical result is transcendental). There's no need to + # raise Rounded and Inexact here---they'll always be raised as + # a result of the call to _fix. + p = context.prec + adj = self.adjusted() + + # we only need to do any computation for quite a small range + # of adjusted exponents---for example, -29 <= adj <= 10 for + # the default context. For smaller exponent the result is + # indistinguishable from 1 at the given precision, while for + # larger exponent the result either overflows or underflows. + if self._sign == 0 and adj > len(str((context.Emax+1)*3)): + # overflow + ans = Decimal((0, (1,), context.Emax+1)) + elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)): + # underflow to 0 + ans = Decimal((0, (1,), context.Etiny()-1)) + elif self._sign == 0 and adj < -p: + # p+1 digits; final round will raise correct flags + ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p)) + elif self._sign == 1 and adj < -p-1: + # p+1 digits; final round will raise correct flags + ans = Decimal((0, (9,)*(p+1), -p-1)) + # general case + else: + op = _WorkRep(self) + c, e = op.int, op.exp + if op.sign == 1: + c = -c + + # compute correctly rounded result: increase precision by + # 3 digits at a time until we get an unambiguously + # roundable result + extra = 3 + while True: + coeff, exp = _dexp(c, e, p+extra) + if coeff % (5*10**(len(str(coeff))-p-1)): + break + extra += 3 + + ans = Decimal((0, list(map(int, str(coeff))), exp)) + + # at this stage, ans should round correctly with *any* + # rounding mode, not just with ROUND_HALF_EVEN + context = context._shallow_copy() + rounding = context._set_rounding(ROUND_HALF_EVEN) + ans = ans._fix(context) + context.rounding = rounding + + return ans + + def is_canonical(self): + """Returns 1 if self is canonical; otherwise returns 0.""" + return Dec_p1 + + def is_finite(self): + """Returns 1 if self is finite, otherwise returns 0. + + For it to be finite, it must be neither infinite nor a NaN. + """ + if self._is_special: + return Dec_0 + else: + return Dec_p1 + + def is_infinite(self): + """Returns 1 if self is an Infinite, otherwise returns 0.""" + if self._isinfinity(): + return Dec_p1 + else: + return Dec_0 + + def is_nan(self): + """Returns 1 if self is qNaN or sNaN, otherwise returns 0.""" + if self._isnan(): + return Dec_p1 + else: + return Dec_0 + + def is_normal(self, context=None): + """Returns 1 if self is a normal number, otherwise returns 0.""" + if self._is_special: + return Dec_0 + if not self: + return Dec_0 + if context is None: + context = getcontext() + if context.Emin <= self.adjusted() <= context.Emax: + return Dec_p1 + else: + return Dec_0 + + def is_qnan(self): + """Returns 1 if self is a quiet NaN, otherwise returns 0.""" + if self._isnan() == 1: + return Dec_p1 + else: + return Dec_0 + + def is_signed(self): + """Returns 1 if self is negative, otherwise returns 0.""" + return Decimal(self._sign) + + def is_snan(self): + """Returns 1 if self is a signaling NaN, otherwise returns 0.""" + if self._isnan() == 2: + return Dec_p1 + else: + return Dec_0 + + def is_subnormal(self, context=None): + """Returns 1 if self is subnormal, otherwise returns 0.""" + if self._is_special: + return Dec_0 + if not self: + return Dec_0 + if context is None: + context = getcontext() + + r = self._exp + len(self._int) + if r <= context.Emin: + return Dec_p1 + return Dec_0 + + def is_zero(self): + """Returns 1 if self is a zero, otherwise returns 0.""" + if self: + return Dec_0 + else: + return Dec_p1 + + def _ln_exp_bound(self): + """Compute a lower bound for the adjusted exponent of self.ln(). + In other words, compute r such that self.ln() >= 10**r. Assumes + that self is finite and positive and that self != 1. + """ + + # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1 + adj = self._exp + len(self._int) - 1 + if adj >= 1: + # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10) + return len(str(adj*23//10)) - 1 + if adj <= -2: + # argument <= 0.1 + return len(str((-1-adj)*23//10)) - 1 + op = _WorkRep(self) + c, e = op.int, op.exp + if adj == 0: + # 1 < self < 10 + num = str(c-10**-e) + den = str(c) + return len(num) - len(den) - (num < den) + # adj == -1, 0.1 <= self < 1 + return e + len(str(10**-e - c)) - 1 + + + def ln(self, context=None): + """Returns the natural (base e) logarithm of self.""" + + if context is None: + context = getcontext() + + # ln(NaN) = NaN + ans = self._check_nans(context=context) + if ans: + return ans + + # ln(0.0) == -Infinity + if not self: + return negInf + + # ln(Infinity) = Infinity + if self._isinfinity() == 1: + return Inf + + # ln(1.0) == 0.0 + if self == Dec_p1: + return Dec_0 + + # ln(negative) raises InvalidOperation + if self._sign == 1: + return context._raise_error(InvalidOperation, + 'ln of a negative value') + + # result is irrational, so necessarily inexact + op = _WorkRep(self) + c, e = op.int, op.exp + p = context.prec + + # correctly rounded result: repeatedly increase precision by 3 + # until we get an unambiguously roundable result + places = p - self._ln_exp_bound() + 2 # at least p+3 places + while True: + coeff = _dlog(c, e, places) + # assert len(str(abs(coeff)))-p >= 1 + if coeff % (5*10**(len(str(abs(coeff)))-p-1)): + break + places += 3 + ans = Decimal((int(coeff<0), list(map(int, str(abs(coeff)))), -places)) + + context = context._shallow_copy() + rounding = context._set_rounding(ROUND_HALF_EVEN) + ans = ans._fix(context) + context.rounding = rounding + return ans + + def _log10_exp_bound(self): + """Compute a lower bound for the adjusted exponent of self.log10(). + In other words, find r such that self.log10() >= 10**r. + Assumes that self is finite and positive and that self != 1. + """ + + # For x >= 10 or x < 0.1 we only need a bound on the integer + # part of log10(self), and this comes directly from the + # exponent of x. For 0.1 <= x <= 10 we use the inequalities + # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > + # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0 + + adj = self._exp + len(self._int) - 1 + if adj >= 1: + # self >= 10 + return len(str(adj))-1 + if adj <= -2: + # self < 0.1 + return len(str(-1-adj))-1 + op = _WorkRep(self) + c, e = op.int, op.exp + if adj == 0: + # 1 < self < 10 + num = str(c-10**-e) + den = str(231*c) + return len(num) - len(den) - (num < den) + 2 + # adj == -1, 0.1 <= self < 1 + num = str(10**-e-c) + return len(num) + e - (num < "231") - 1 + + def log10(self, context=None): + """Returns the base 10 logarithm of self.""" + + if context is None: + context = getcontext() + + # log10(NaN) = NaN + ans = self._check_nans(context=context) + if ans: + return ans + + # log10(0.0) == -Infinity + if not self: + return negInf + + # log10(Infinity) = Infinity + if self._isinfinity() == 1: + return Inf + + # log10(negative or -Infinity) raises InvalidOperation + if self._sign == 1: + return context._raise_error(InvalidOperation, + 'log10 of a negative value') + + # log10(10**n) = n + if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1): + # answer may need rounding + ans = Decimal(self._exp + len(self._int) - 1) + else: + # result is irrational, so necessarily inexact + op = _WorkRep(self) + c, e = op.int, op.exp + p = context.prec + + # correctly rounded result: repeatedly increase precision + # until result is unambiguously roundable + places = p-self._log10_exp_bound()+2 + while True: + coeff = _dlog10(c, e, places) + # assert len(str(abs(coeff)))-p >= 1 + if coeff % (5*10**(len(str(abs(coeff)))-p-1)): + break + places += 3 + ans = Decimal((int(coeff<0), list(map(int, str(abs(coeff)))), + -places)) + + context = context._shallow_copy() + rounding = context._set_rounding(ROUND_HALF_EVEN) + ans = ans._fix(context) + context.rounding = rounding + return ans + + def logb(self, context=None): + """ Returns the exponent of the magnitude of self's MSD. + + The result is the integer which is the exponent of the magnitude + of the most significant digit of self (as though it were truncated + to a single digit while maintaining the value of that digit and + without limiting the resulting exponent). + """ + # logb(NaN) = NaN + ans = self._check_nans(context=context) + if ans: + return ans + + if context is None: + context = getcontext() + + # logb(+/-Inf) = +Inf + if self._isinfinity(): + return Inf + + # logb(0) = -Inf, DivisionByZero + if not self: + return context._raise_error(DivisionByZero, 'logb(0)', 1) + + # otherwise, simply return the adjusted exponent of self, as a + # Decimal. Note that no attempt is made to fit the result + # into the current context. + return Decimal(self.adjusted()) + + def _islogical(self): + """Return True if self is a logical operand. + + For being logical, it must be a finite numbers with a sign of 0, + an exponent of 0, and a coefficient whose digits must all be + either 0 or 1. + """ + if self._sign != 0 or self._exp != 0: + return False + for dig in self._int: + if dig not in (0, 1): + return False + return True + + def _fill_logical(self, context, opa, opb): + dif = context.prec - len(opa) + if dif > 0: + opa = (0,)*dif + opa + elif dif < 0: + opa = opa[-context.prec:] + dif = context.prec - len(opb) + if dif > 0: + opb = (0,)*dif + opb + elif dif < 0: + opb = opb[-context.prec:] + return opa, opb + + def logical_and(self, other, context=None): + """Applies an 'and' operation between self and other's digits.""" + if context is None: + context = getcontext() + if not self._islogical() or not other._islogical(): + return context._raise_error(InvalidOperation) + + # fill to context.prec + (opa, opb) = self._fill_logical(context, self._int, other._int) + + # make the operation, and clean starting zeroes + result = [a&b for a,b in zip(opa,opb)] + for i,d in enumerate(result): + if d == 1: + break + result = tuple(result[i:]) + + # if empty, we must have at least a zero + if not result: + result = (0,) + return Decimal((0, result, 0)) + + def logical_invert(self, context=None): + """Invert all its digits.""" + if context is None: + context = getcontext() + return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context) + + def logical_or(self, other, context=None): + """Applies an 'or' operation between self and other's digits.""" + if context is None: + context = getcontext() + if not self._islogical() or not other._islogical(): + return context._raise_error(InvalidOperation) + + # fill to context.prec + (opa, opb) = self._fill_logical(context, self._int, other._int) + + # make the operation, and clean starting zeroes + result = [a|b for a,b in zip(opa,opb)] + for i,d in enumerate(result): + if d == 1: + break + result = tuple(result[i:]) + + # if empty, we must have at least a zero + if not result: + result = (0,) + return Decimal((0, result, 0)) + + def logical_xor(self, other, context=None): + """Applies an 'xor' operation between self and other's digits.""" + if context is None: + context = getcontext() + if not self._islogical() or not other._islogical(): + return context._raise_error(InvalidOperation) + + # fill to context.prec + (opa, opb) = self._fill_logical(context, self._int, other._int) + + # make the operation, and clean starting zeroes + result = [a^b for a,b in zip(opa,opb)] + for i,d in enumerate(result): + if d == 1: + break + result = tuple(result[i:]) + + # if empty, we must have at least a zero + if not result: + result = (0,) + return Decimal((0, result, 0)) + + def max_mag(self, other, context=None): + """Compares the values numerically with their sign ignored.""" + other = _convert_other(other, raiseit=True) + + if context is None: + context = getcontext() + + if self._is_special or other._is_special: + # If one operand is a quiet NaN and the other is number, then the + # number is always returned + sn = self._isnan() + on = other._isnan() + if sn or on: + if on == 1 and sn != 2: + return self._fix_nan(context) + if sn == 1 and on != 2: + return other._fix_nan(context) + return self._check_nans(other, context) + + c = self.copy_abs().__cmp__(other.copy_abs()) + if c == 0: + c = self.compare_total(other) + + if c == -1: + ans = other + else: + ans = self + + if context._rounding_decision == ALWAYS_ROUND: + return ans._fix(context) + return ans + + def min_mag(self, other, context=None): + """Compares the values numerically with their sign ignored.""" + other = _convert_other(other, raiseit=True) + + if context is None: + context = getcontext() + + if self._is_special or other._is_special: + # If one operand is a quiet NaN and the other is number, then the + # number is always returned + sn = self._isnan() + on = other._isnan() + if sn or on: + if on == 1 and sn != 2: + return self._fix_nan(context) + if sn == 1 and on != 2: + return other._fix_nan(context) + return self._check_nans(other, context) + + c = self.copy_abs().__cmp__(other.copy_abs()) + if c == 0: + c = self.compare_total(other) + + if c == -1: + ans = self + else: + ans = other + + if context._rounding_decision == ALWAYS_ROUND: + return ans._fix(context) + return ans + + def next_minus(self, context=None): + """Returns the largest representable number smaller than itself.""" + if context is None: + context = getcontext() + + ans = self._check_nans(context=context) + if ans: + return ans + + if self._isinfinity() == -1: + return negInf + if self._isinfinity() == 1: + return Decimal((0, (9,)*context.prec, context.Etop())) + + context = context.copy() + context._set_rounding(ROUND_FLOOR) + context._ignore_all_flags() + new_self = self._fix(context) + if new_self != self: + return new_self + return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context) + + def next_plus(self, context=None): + """Returns the smallest representable number larger than itself.""" + if context is None: + context = getcontext() + + ans = self._check_nans(context=context) + if ans: + return ans + + if self._isinfinity() == 1: + return Inf + if self._isinfinity() == -1: + return Decimal((1, (9,)*context.prec, context.Etop())) + + context = context.copy() + context._set_rounding(ROUND_CEILING) + context._ignore_all_flags() + new_self = self._fix(context) + if new_self != self: + return new_self + return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context) + + def next_toward(self, other, context=None): + """Returns the number closest to self, in the direction towards other. + + The result is the closest representable number to self + (excluding self) that is in the direction towards other, + unless both have the same value. If the two operands are + numerically equal, then the result is a copy of self with the + sign set to be the same as the sign of other. + """ + other = _convert_other(other, raiseit=True) + + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return ans + + comparison = self.__cmp__(other) + if comparison == 0: + return Decimal((other._sign, self._int, self._exp)) + + if comparison == -1: + ans = self.next_plus(context) + else: # comparison == 1 + ans = self.next_minus(context) + + # decide which flags to raise using value of ans + if ans._isinfinity(): + context._raise_error(Overflow, + 'Infinite result from next_toward', + ans._sign) + context._raise_error(Rounded) + context._raise_error(Inexact) + elif ans.adjusted() < context.Emin: + context._raise_error(Underflow) + context._raise_error(Subnormal) + context._raise_error(Rounded) + context._raise_error(Inexact) + # if precision == 1 then we don't raise Clamped for a + # result 0E-Etiny. + if not ans: + context._raise_error(Clamped) + + return ans + + def number_class(self, context=None): + """Returns an indication of the class of self. + + The class is one of the following strings: + -sNaN + -NaN + -Infinity + -Normal + -Subnormal + -Zero + +Zero + +Subnormal + +Normal + +Infinity + """ + if self.is_snan(): + return "sNaN" + if self.is_qnan(): + return "NaN" + inf = self._isinfinity() + if inf == 1: + return "+Infinity" + if inf == -1: + return "-Infinity" + if self.is_zero(): + if self._sign: + return "-Zero" + else: + return "+Zero" + if context is None: + context = getcontext() + if self.is_subnormal(context=context): + if self._sign: + return "-Subnormal" + else: + return "+Subnormal" + # just a normal, regular, boring number, :) + if self._sign: + return "-Normal" + else: + return "+Normal" + + def radix(self): + """Just returns 10, as this is Decimal, :)""" + return Decimal(10) + + def rotate(self, other, context=None): + """Returns a rotated copy of self, value-of-other times.""" + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return ans + + if other._exp != 0: + return context._raise_error(InvalidOperation) + if not (-context.prec <= int(other) <= context.prec): + return context._raise_error(InvalidOperation) + + if self._isinfinity(): + return Decimal(self) + + # get values, pad if necessary + torot = int(other) + rotdig = self._int + topad = context.prec - len(rotdig) + if topad: + rotdig = ((0,)*topad) + rotdig + + # let's rotate! + rotated = rotdig[torot:] + rotdig[:torot] + + # clean starting zeroes + for i,d in enumerate(rotated): + if d != 0: + break + rotated = rotated[i:] + + return Decimal((self._sign, rotated, self._exp)) + + + def scaleb (self, other, context=None): + """Returns self operand after adding the second value to its exp.""" + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return ans + + if other._exp != 0: + return context._raise_error(InvalidOperation) + liminf = -2 * (context.Emax + context.prec) + limsup = 2 * (context.Emax + context.prec) + if not (liminf <= int(other) <= limsup): + return context._raise_error(InvalidOperation) + + if self._isinfinity(): + return Decimal(self) + + d = Decimal((self._sign, self._int, self._exp + int(other))) + d = d._fix(context) + return d + + def shift(self, other, context=None): + """Returns a shifted copy of self, value-of-other times.""" + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return ans + + if other._exp != 0: + return context._raise_error(InvalidOperation) + if not (-context.prec <= int(other) <= context.prec): + return context._raise_error(InvalidOperation) + + if self._isinfinity(): + return Decimal(self) + + # get values, pad if necessary + torot = int(other) + if not torot: + return Decimal(self) + rotdig = self._int + topad = context.prec - len(rotdig) + if topad: + rotdig = ((0,)*topad) + rotdig + + # let's shift! + if torot < 0: + rotated = rotdig[:torot] + else: + rotated = (rotdig + ((0,) * torot)) + rotated = rotated[-context.prec:] + + # clean starting zeroes + if rotated: + for i,d in enumerate(rotated): + if d != 0: + break + rotated = rotated[i:] + else: + rotated = (0,) + + return Decimal((self._sign, rotated, self._exp)) + + # Support for pickling, copy, and deepcopy def __reduce__(self): return (self.__class__, (str(self),)) @@ -2426,6 +3616,9 @@ def create_decimal(self, num='0'): """Creates a new Decimal instance but using self as context.""" d = Decimal(num, context=self) + if d._isnan() and len(d._int) > self.prec - self._clamp: + return self._raise_error(ConversionSyntax, + "diagnostic info too long in NaN") return d._fix(self) # Methods @@ -2460,6 +3653,17 @@ def _apply(self, a): return str(a._fix(self)) + def canonical(self, a): + """Returns the same Decimal object. + + As we do not have different encodings for the same number, the + received object already is in its canonical form. + + >>> ExtendedContext.canonical(Decimal('2.50')) + Decimal("2.50") + """ + return a.canonical(context=self) + def compare(self, a, b): """Compares values numerically. @@ -2489,6 +3693,110 @@ """ return a.compare(b, context=self) + def compare_signal(self, a, b): + """Compares the values of the two operands numerically. + + It's pretty much like compare(), but all NaNs signal, with signaling + NaNs taking precedence over quiet NaNs. + + >>> c = ExtendedContext + >>> c.compare_signal(Decimal('2.1'), Decimal('3')) + Decimal("-1") + >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) + Decimal("0") + >>> c.flags[InvalidOperation] = 0 + >>> print(c.flags[InvalidOperation]) + 0 + >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) + Decimal("NaN") + >>> print(c.flags[InvalidOperation]) + 1 + >>> c.flags[InvalidOperation] = 0 + >>> print(c.flags[InvalidOperation]) + 0 + >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) + Decimal("NaN") + >>> print(c.flags[InvalidOperation]) + 1 + """ + return a.compare_signal(b, context=self) + + def compare_total(self, a, b): + """Compares two operands using their abstract representation. + + This is not like the standard compare, which use their numerical + value. Note that a total ordering is defined for all possible abstract + representations. + + >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) + Decimal("-1") + >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) + Decimal("-1") + >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) + Decimal("-1") + >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) + Decimal("0") + >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) + Decimal("1") + >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) + Decimal("-1") + """ + return a.compare_total(b) + + def compare_total_mag(self, a, b): + """Compares two operands using their abstract representation ignoring sign. + + Like compare_total, but with operand's sign ignored and assumed to be 0. + """ + return a.compare_total_mag(b) + + def copy_abs(self, a): + """Returns a copy of the operand with the sign set to 0. + + >>> ExtendedContext.copy_abs(Decimal('2.1')) + Decimal("2.1") + >>> ExtendedContext.copy_abs(Decimal('-100')) + Decimal("100") + """ + return a.copy_abs() + + def copy_decimal(self, a): + """Returns a copy of the decimal objet. + + >>> ExtendedContext.copy_decimal(Decimal('2.1')) + Decimal("2.1") + >>> ExtendedContext.copy_decimal(Decimal('-1.00')) + Decimal("-1.00") + """ + return Decimal(a) + + def copy_negate(self, a): + """Returns a copy of the operand with the sign inverted. + + >>> ExtendedContext.copy_negate(Decimal('101.5')) + Decimal("-101.5") + >>> ExtendedContext.copy_negate(Decimal('-101.5')) + Decimal("101.5") + """ + return a.copy_negate() + + def copy_sign(self, a, b): + """Copies the second operand's sign to the first one. + + In detail, it returns a copy of the first operand with the sign + equal to the sign of the second operand. + + >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) + Decimal("1.50") + >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) + Decimal("1.50") + >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) + Decimal("-1.50") + >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) + Decimal("-1.50") + """ + return a.copy_sign(b) + def divide(self, a, b): """Decimal division in a specified context. @@ -2530,6 +3838,316 @@ def divmod(self, a, b): return a.__divmod__(b, context=self) + def exp(self, a): + """Returns e ** a. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.exp(Decimal('-Infinity')) + Decimal("0") + >>> c.exp(Decimal('-1')) + Decimal("0.367879441") + >>> c.exp(Decimal('0')) + Decimal("1") + >>> c.exp(Decimal('1')) + Decimal("2.71828183") + >>> c.exp(Decimal('0.693147181')) + Decimal("2.00000000") + >>> c.exp(Decimal('+Infinity')) + Decimal("Infinity") + """ + return a.exp(context=self) + + def fma(self, a, b, c): + """Returns a multiplied by b, plus c. + + The first two operands are multiplied together, using multiply, + the third operand is then added to the result of that + multiplication, using add, all with only one final rounding. + + >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) + Decimal("22") + >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) + Decimal("-8") + >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) + Decimal("1.38435736E+12") + """ + return a.fma(b, c, context=self) + + def is_canonical(self, a): + """Returns 1 if the operand is canonical; otherwise returns 0. + + >>> ExtendedContext.is_canonical(Decimal('2.50')) + Decimal("1") + """ + return Dec_p1 + + def is_finite(self, a): + """Returns 1 if the operand is finite, otherwise returns 0. + + For it to be finite, it must be neither infinite nor a NaN. + + >>> ExtendedContext.is_finite(Decimal('2.50')) + Decimal("1") + >>> ExtendedContext.is_finite(Decimal('-0.3')) + Decimal("1") + >>> ExtendedContext.is_finite(Decimal('0')) + Decimal("1") + >>> ExtendedContext.is_finite(Decimal('Inf')) + Decimal("0") + >>> ExtendedContext.is_finite(Decimal('NaN')) + Decimal("0") + """ + return a.is_finite() + + def is_infinite(self, a): + """Returns 1 if the operand is an Infinite, otherwise returns 0. + + >>> ExtendedContext.is_infinite(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.is_infinite(Decimal('-Inf')) + Decimal("1") + >>> ExtendedContext.is_infinite(Decimal('NaN')) + Decimal("0") + """ + return a.is_infinite() + + def is_nan(self, a): + """Returns 1 if the operand is qNaN or sNaN, otherwise returns 0. + + >>> ExtendedContext.is_nan(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.is_nan(Decimal('NaN')) + Decimal("1") + >>> ExtendedContext.is_nan(Decimal('-sNaN')) + Decimal("1") + """ + return a.is_nan() + + def is_normal(self, a): + """Returns 1 if the operand is a normal number, otherwise returns 0. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.is_normal(Decimal('2.50')) + Decimal("1") + >>> c.is_normal(Decimal('0.1E-999')) + Decimal("0") + >>> c.is_normal(Decimal('0.00')) + Decimal("0") + >>> c.is_normal(Decimal('-Inf')) + Decimal("0") + >>> c.is_normal(Decimal('NaN')) + Decimal("0") + """ + return a.is_normal(context=self) + + def is_qnan(self, a): + """Returns 1 if the operand is a quiet NaN, otherwise returns 0. + + >>> ExtendedContext.is_qnan(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.is_qnan(Decimal('NaN')) + Decimal("1") + >>> ExtendedContext.is_qnan(Decimal('sNaN')) + Decimal("0") + """ + return a.is_qnan() + + def is_signed(self, a): + """Returns 1 if the operand is negative, otherwise returns 0. + + >>> ExtendedContext.is_signed(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.is_signed(Decimal('-12')) + Decimal("1") + >>> ExtendedContext.is_signed(Decimal('-0')) + Decimal("1") + """ + return a.is_signed() + + def is_snan(self, a): + """Returns 1 if the operand is a signaling NaN, otherwise returns 0. + + >>> ExtendedContext.is_snan(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.is_snan(Decimal('NaN')) + Decimal("0") + >>> ExtendedContext.is_snan(Decimal('sNaN')) + Decimal("1") + """ + return a.is_snan() + + def is_subnormal(self, a): + """Returns 1 if the operand is subnormal, otherwise returns 0. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.is_subnormal(Decimal('2.50')) + Decimal("0") + >>> c.is_subnormal(Decimal('0.1E-999')) + Decimal("1") + >>> c.is_subnormal(Decimal('0.00')) + Decimal("0") + >>> c.is_subnormal(Decimal('-Inf')) + Decimal("0") + >>> c.is_subnormal(Decimal('NaN')) + Decimal("0") + """ + return a.is_subnormal(context=self) + + def is_zero(self, a): + """Returns 1 if the operand is a zero, otherwise returns 0. + + >>> ExtendedContext.is_zero(Decimal('0')) + Decimal("1") + >>> ExtendedContext.is_zero(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.is_zero(Decimal('-0E+2')) + Decimal("1") + """ + return a.is_zero() + + def ln(self, a): + """Returns the natural (base e) logarithm of the operand. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.ln(Decimal('0')) + Decimal("-Infinity") + >>> c.ln(Decimal('1.000')) + Decimal("0") + >>> c.ln(Decimal('2.71828183')) + Decimal("1.00000000") + >>> c.ln(Decimal('10')) + Decimal("2.30258509") + >>> c.ln(Decimal('+Infinity')) + Decimal("Infinity") + """ + return a.ln(context=self) + + def log10(self, a): + """Returns the base 10 logarithm of the operand. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.log10(Decimal('0')) + Decimal("-Infinity") + >>> c.log10(Decimal('0.001')) + Decimal("-3") + >>> c.log10(Decimal('1.000')) + Decimal("0") + >>> c.log10(Decimal('2')) + Decimal("0.301029996") + >>> c.log10(Decimal('10')) + Decimal("1") + >>> c.log10(Decimal('70')) + Decimal("1.84509804") + >>> c.log10(Decimal('+Infinity')) + Decimal("Infinity") + """ + return a.log10(context=self) + + def logb(self, a): + """ Returns the exponent of the magnitude of the operand's MSD. + + The result is the integer which is the exponent of the magnitude + of the most significant digit of the operand (as though the + operand were truncated to a single digit while maintaining the + value of that digit and without limiting the resulting exponent). + + >>> ExtendedContext.logb(Decimal('250')) + Decimal("2") + >>> ExtendedContext.logb(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.logb(Decimal('0.03')) + Decimal("-2") + >>> ExtendedContext.logb(Decimal('0')) + Decimal("-Infinity") + """ + return a.logb(context=self) + + def logical_and(self, a, b): + """Applies the logical operation 'and' between each operand's digits. + + The operands must be both logical numbers. + + >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) + Decimal("0") + >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) + Decimal("0") + >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) + Decimal("0") + >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) + Decimal("1") + >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) + Decimal("1000") + >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) + Decimal("10") + """ + return a.logical_and(b, context=self) + + def logical_invert(self, a): + """Invert all the digits in the operand. + + The operand must be a logical number. + + >>> ExtendedContext.logical_invert(Decimal('0')) + Decimal("111111111") + >>> ExtendedContext.logical_invert(Decimal('1')) + Decimal("111111110") + >>> ExtendedContext.logical_invert(Decimal('111111111')) + Decimal("0") + >>> ExtendedContext.logical_invert(Decimal('101010101')) + Decimal("10101010") + """ + return a.logical_invert(context=self) + + def logical_or(self, a, b): + """Applies the logical operation 'or' between each operand's digits. + + The operands must be both logical numbers. + + >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) + Decimal("0") + >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) + Decimal("1") + >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) + Decimal("1") + >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) + Decimal("1") + >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) + Decimal("1110") + >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) + Decimal("1110") + """ + return a.logical_or(b, context=self) + + def logical_xor(self, a, b): + """Applies the logical operation 'xor' between each operand's digits. + + The operands must be both logical numbers. + + >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) + Decimal("0") + >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) + Decimal("1") + >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) + Decimal("1") + >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) + Decimal("0") + >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) + Decimal("110") + >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) + Decimal("1101") + """ + return a.logical_xor(b, context=self) + def max(self, a,b): """max compares two values numerically and returns the maximum. @@ -2550,6 +4168,10 @@ """ return a.max(b, context=self) + def max_mag(self, a, b): + """Compares the values numerically with their sign ignored.""" + return a.max_mag(b, context=self) + def min(self, a,b): """min compares two values numerically and returns the minimum. @@ -2570,6 +4192,10 @@ """ return a.min(b, context=self) + def min_mag(self, a, b): + """Compares the values numerically with their sign ignored.""" + return a.min_mag(b, context=self) + def minus(self, a): """Minus corresponds to unary prefix minus in Python. @@ -2605,6 +4231,68 @@ """ return a.__mul__(b, context=self) + def next_minus(self, a): + """Returns the largest representable number smaller than a. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> ExtendedContext.next_minus(Decimal('1')) + Decimal("0.999999999") + >>> c.next_minus(Decimal('1E-1007')) + Decimal("0E-1007") + >>> ExtendedContext.next_minus(Decimal('-1.00000003')) + Decimal("-1.00000004") + >>> c.next_minus(Decimal('Infinity')) + Decimal("9.99999999E+999") + """ + return a.next_minus(context=self) + + def next_plus(self, a): + """Returns the smallest representable number larger than a. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> ExtendedContext.next_plus(Decimal('1')) + Decimal("1.00000001") + >>> c.next_plus(Decimal('-1E-1007')) + Decimal("-0E-1007") + >>> ExtendedContext.next_plus(Decimal('-1.00000003')) + Decimal("-1.00000002") + >>> c.next_plus(Decimal('-Infinity')) + Decimal("-9.99999999E+999") + """ + return a.next_plus(context=self) + + def next_toward(self, a, b): + """Returns the number closest to a, in direction towards b. + + The result is the closest representable number from the first + operand (but not the first operand) that is in the direction + towards the second operand, unless the operands have the same + value. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.next_toward(Decimal('1'), Decimal('2')) + Decimal("1.00000001") + >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) + Decimal("-0E-1007") + >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) + Decimal("-1.00000002") + >>> c.next_toward(Decimal('1'), Decimal('0')) + Decimal("0.999999999") + >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) + Decimal("0E-1007") + >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) + Decimal("-1.00000004") + >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) + Decimal("-0.00") + """ + return a.next_toward(b, context=self) + def normalize(self, a): """normalize reduces an operand to its simplest form. @@ -2626,6 +4314,53 @@ """ return a.normalize(context=self) + def number_class(self, a): + """Returns an indication of the class of the operand. + + The class is one of the following strings: + -sNaN + -NaN + -Infinity + -Normal + -Subnormal + -Zero + +Zero + +Subnormal + +Normal + +Infinity + + >>> c = Context(ExtendedContext) + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.number_class(Decimal('Infinity')) + '+Infinity' + >>> c.number_class(Decimal('1E-10')) + '+Normal' + >>> c.number_class(Decimal('2.50')) + '+Normal' + >>> c.number_class(Decimal('0.1E-999')) + '+Subnormal' + >>> c.number_class(Decimal('0')) + '+Zero' + >>> c.number_class(Decimal('-0')) + '-Zero' + >>> c.number_class(Decimal('-0.1E-999')) + '-Subnormal' + >>> c.number_class(Decimal('-1E-10')) + '-Normal' + >>> c.number_class(Decimal('-2.50')) + '-Normal' + >>> c.number_class(Decimal('-Infinity')) + '-Infinity' + >>> c.number_class(Decimal('NaN')) + 'NaN' + >>> c.number_class(Decimal('-NaN')) + 'NaN' + >>> c.number_class(Decimal('sNaN')) + 'sNaN' + """ + return a.number_class(context=self) + def plus(self, a): """Plus corresponds to unary prefix plus in Python. @@ -2643,49 +4378,69 @@ def power(self, a, b, modulo=None): """Raises a to the power of b, to modulo if given. - The right-hand operand must be a whole number whose integer part (after - any exponent has been applied) has no more than 9 digits and whose - fractional part (if any) is all zeros before any rounding. The operand - may be positive, negative, or zero; if negative, the absolute value of - the power is used, and the left-hand operand is inverted (divided into - 1) before use. - - If the increased precision needed for the intermediate calculations - exceeds the capabilities of the implementation then an Invalid - operation condition is raised. - - If, when raising to a negative power, an underflow occurs during the - division into 1, the operation is not halted at that point but - continues. - - >>> ExtendedContext.power(Decimal('2'), Decimal('3')) + With two arguments, compute a**b. If a is negative then b + must be integral. The result will be inexact unless b is + integral and the result is finite and can be expressed exactly + in 'precision' digits. + + With three arguments, compute (a**b) % modulo. For the + three argument form, the following restrictions on the + arguments hold: + + - all three arguments must be integral + - b must be nonnegative + - at least one of a or b must be nonzero + - modulo must be nonzero and have at most 'precision' digits + + The result of pow(a, b, modulo) is identical to the result + that would be obtained by computing (a**b) % modulo with + unbounded precision, but is computed more efficiently. It is + always exact. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.power(Decimal('2'), Decimal('3')) Decimal("8") - >>> ExtendedContext.power(Decimal('2'), Decimal('-3')) + >>> c.power(Decimal('-2'), Decimal('3')) + Decimal("-8") + >>> c.power(Decimal('2'), Decimal('-3')) Decimal("0.125") - >>> ExtendedContext.power(Decimal('1.7'), Decimal('8')) + >>> c.power(Decimal('1.7'), Decimal('8')) Decimal("69.7575744") - >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-2')) + >>> c.power(Decimal('10'), Decimal('0.301029996')) + Decimal("2.00000000") + >>> c.power(Decimal('Infinity'), Decimal('-1')) Decimal("0") - >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-1')) - Decimal("0") - >>> ExtendedContext.power(Decimal('Infinity'), Decimal('0')) + >>> c.power(Decimal('Infinity'), Decimal('0')) Decimal("1") - >>> ExtendedContext.power(Decimal('Infinity'), Decimal('1')) - Decimal("Infinity") - >>> ExtendedContext.power(Decimal('Infinity'), Decimal('2')) + >>> c.power(Decimal('Infinity'), Decimal('1')) Decimal("Infinity") - >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-2')) - Decimal("0") - >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-1')) + >>> c.power(Decimal('-Infinity'), Decimal('-1')) Decimal("-0") - >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('0')) + >>> c.power(Decimal('-Infinity'), Decimal('0')) Decimal("1") - >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('1')) + >>> c.power(Decimal('-Infinity'), Decimal('1')) Decimal("-Infinity") - >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('2')) + >>> c.power(Decimal('-Infinity'), Decimal('2')) Decimal("Infinity") - >>> ExtendedContext.power(Decimal('0'), Decimal('0')) + >>> c.power(Decimal('0'), Decimal('0')) Decimal("NaN") + + >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) + Decimal("11") + >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) + Decimal("-11") + >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) + Decimal("1") + >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) + Decimal("11") + >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) + Decimal("11729830") + >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) + Decimal("-0") + >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) + Decimal("1") """ return a.__pow__(b, modulo, context=self) @@ -2740,6 +4495,14 @@ """ return a.quantize(b, context=self) + def radix(self): + """Just returns 10, as this is Decimal, :) + + >>> ExtendedContext.radix() + Decimal("10") + """ + return Decimal(10) + def remainder(self, a, b): """Returns the remainder from integer division. @@ -2794,6 +4557,28 @@ """ return a.remainder_near(b, context=self) + def rotate(self, a, b): + """Returns a rotated copy of a, b times. + + The coefficient of the result is a rotated copy of the digits in + the coefficient of the first operand. The number of places of + rotation is taken from the absolute value of the second operand, + with the rotation being to the left if the second operand is + positive or to the right otherwise. + + >>> ExtendedContext.rotate(Decimal('34'), Decimal('8')) + Decimal("400000003") + >>> ExtendedContext.rotate(Decimal('12'), Decimal('9')) + Decimal("12") + >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2')) + Decimal("891234567") + >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0')) + Decimal("123456789") + >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2')) + Decimal("345678912") + """ + return a.rotate(b, context=self) + def same_quantum(self, a, b): """Returns True if the two operands have the same exponent. @@ -2811,6 +4596,41 @@ """ return a.same_quantum(b) + def scaleb (self, a, b): + """Returns the first operand after adding the second value its exp. + + >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) + Decimal("0.0750") + >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) + Decimal("7.50") + >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) + Decimal("7.50E+3") + """ + return a.scaleb (b, context=self) + + def shift(self, a, b): + """Returns a shifted copy of a, b times. + + The coefficient of the result is a shifted copy of the digits + in the coefficient of the first operand. The number of places + to shift is taken from the absolute value of the second operand, + with the shift being to the left if the second operand is + positive or to the right otherwise. Digits shifted into the + coefficient are zeros. + + >>> ExtendedContext.shift(Decimal('34'), Decimal('8')) + Decimal("400000000") + >>> ExtendedContext.shift(Decimal('12'), Decimal('9')) + Decimal("0") + >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2')) + Decimal("1234567") + >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0')) + Decimal("123456789") + >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2')) + Decimal("345678900") + """ + return a.shift(b, context=self) + def sqrt(self, a): """Square root of a non-negative number to context precision. @@ -2866,7 +4686,36 @@ """ return a.__str__(context=self) - def to_integral(self, a): + def to_integral_exact(self, a): + """Rounds to an integer. + + When the operand has a negative exponent, the result is the same + as using the quantize() operation using the given operand as the + left-hand-operand, 1E+0 as the right-hand-operand, and the precision + of the operand as the precision setting; Inexact and Rounded flags + are allowed in this operation. The rounding mode is taken from the + context. + + >>> ExtendedContext.to_integral_exact(Decimal('2.1')) + Decimal("2") + >>> ExtendedContext.to_integral_exact(Decimal('100')) + Decimal("100") + >>> ExtendedContext.to_integral_exact(Decimal('100.0')) + Decimal("100") + >>> ExtendedContext.to_integral_exact(Decimal('101.5')) + Decimal("102") + >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) + Decimal("-102") + >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) + Decimal("1.0E+6") + >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) + Decimal("7.89E+77") + >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) + Decimal("-Infinity") + """ + return a.to_integral_exact(context=self) + + def to_integral_value(self, a): """Rounds to an integer. When the operand has a negative exponent, the result is the same @@ -2875,29 +4724,32 @@ of the operand as the precision setting, except that no flags will be set. The rounding mode is taken from the context. - >>> ExtendedContext.to_integral(Decimal('2.1')) + >>> ExtendedContext.to_integral_value(Decimal('2.1')) Decimal("2") - >>> ExtendedContext.to_integral(Decimal('100')) + >>> ExtendedContext.to_integral_value(Decimal('100')) Decimal("100") - >>> ExtendedContext.to_integral(Decimal('100.0')) + >>> ExtendedContext.to_integral_value(Decimal('100.0')) Decimal("100") - >>> ExtendedContext.to_integral(Decimal('101.5')) + >>> ExtendedContext.to_integral_value(Decimal('101.5')) Decimal("102") - >>> ExtendedContext.to_integral(Decimal('-101.5')) + >>> ExtendedContext.to_integral_value(Decimal('-101.5')) Decimal("-102") - >>> ExtendedContext.to_integral(Decimal('10E+5')) + >>> ExtendedContext.to_integral_value(Decimal('10E+5')) Decimal("1.0E+6") - >>> ExtendedContext.to_integral(Decimal('7.89E+77')) + >>> ExtendedContext.to_integral_value(Decimal('7.89E+77')) Decimal("7.89E+77") - >>> ExtendedContext.to_integral(Decimal('-Inf')) + >>> ExtendedContext.to_integral_value(Decimal('-Inf')) Decimal("-Infinity") """ - return a.to_integral(context=self) + return a.to_integral_value(context=self) + + # the method name changed, but we provide also the old one, for compatibility + to_integral = to_integral_value class _WorkRep(object): __slots__ = ('sign','int','exp') # sign: 0 or 1 - # int: int or long + # int: int # exp: None, int, or string def __init__(self, value=None): @@ -2930,66 +4782,338 @@ Done during addition. """ - # Yes, the exponent is a long, but the difference between exponents - # must be an int-- otherwise you'd get a big memory problem. - numdigits = int(op1.exp - op2.exp) - if numdigits < 0: - numdigits = -numdigits + if op1.exp < op2.exp: tmp = op2 other = op1 else: tmp = op1 other = op2 - - if shouldround and numdigits > prec + 1: - # Big difference in exponents - check the adjusted exponents + # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1). + # Then adding 10**exp to tmp has the same effect (after rounding) + # as adding any positive quantity smaller than 10**exp; similarly + # for subtraction. So if other is smaller than 10**exp we replace + # it with 10**exp. This avoids tmp.exp - other.exp getting too large. + if shouldround: tmp_len = len(str(tmp.int)) other_len = len(str(other.int)) - if numdigits > (other_len + prec + 1 - tmp_len): - # If the difference in adjusted exps is > prec+1, we know - # other is insignificant, so might as well put a 1 after the - # precision (since this is only for addition). Also stops - # use of massive longs. - - extend = prec + 2 - tmp_len - if extend <= 0: - extend = 1 - tmp.int *= 10 ** extend - tmp.exp -= extend + exp = tmp.exp + min(-1, tmp_len - prec - 2) + if other_len + other.exp - 1 < exp: other.int = 1 - other.exp = tmp.exp - return op1, op2 + other.exp = exp - tmp.int *= 10 ** numdigits - tmp.exp -= numdigits + tmp.int *= 10 ** (tmp.exp - other.exp) + tmp.exp = other.exp return op1, op2 -def _adjust_coefficients(op1, op2): - """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int. +##### Integer arithmetic functions used by ln, log10, exp and __pow__ ##### + +# This function from Tim Peters was taken from here: +# http://mail.python.org/pipermail/python-list/1999-July/007758.html +# The correction being in the function definition is for speed, and +# the whole function is not resolved with math.log because of avoiding +# the use of floats. +def _nbits(n, correction = { + '0': 4, '1': 3, '2': 2, '3': 2, + '4': 1, '5': 1, '6': 1, '7': 1, + '8': 0, '9': 0, 'a': 0, 'b': 0, + 'c': 0, 'd': 0, 'e': 0, 'f': 0}): + """Number of bits in binary representation of the positive integer n, + or 0 if n == 0. + """ + if n < 0: + raise ValueError("The argument to _nbits should be nonnegative.") + hex_n = "%x" % n + return 4*len(hex_n) - correction[hex_n[0]] + +def _sqrt_nearest(n, a): + """Closest integer to the square root of the positive integer n. a is + an initial approximation to the square root. Any positive integer + will do for a, but the closer a is to the square root of n the + faster convergence will be. + + """ + if n <= 0 or a <= 0: + raise ValueError("Both arguments to _sqrt_nearest should be positive.") + + b=0 + while a != b: + b, a = a, a--n//a>>1 + return a + +def _rshift_nearest(x, shift): + """Given an integer x and a nonnegative integer shift, return closest + integer to x / 2**shift; use round-to-even in case of a tie. + + """ + b, q = 1 << shift, x >> shift + return q + (2*(x & (b-1)) + (q&1) > b) + +def _div_nearest(a, b): + """Closest integer to a/b, a and b positive integers; rounds to even + in the case of a tie. - Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp. + """ + q, r = divmod(a, b) + return q + (2*r + (q&1) > b) + +def _ilog(x, M, L = 8): + """Integer approximation to M*log(x/M), with absolute error boundable + in terms only of x/M. + + Given positive integers x and M, return an integer approximation to + M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference + between the approximation and the exact result is at most 22. For + L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In + both cases these are upper bounds on the error; it will usually be + much smaller.""" + + # The basic algorithm is the following: let log1p be the function + # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use + # the reduction + # + # log1p(y) = 2*log1p(y/(1+sqrt(1+y))) + # + # repeatedly until the argument to log1p is small (< 2**-L in + # absolute value). For small y we can use the Taylor series + # expansion + # + # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T + # + # truncating at T such that y**T is small enough. The whole + # computation is carried out in a form of fixed-point arithmetic, + # with a real number z being represented by an integer + # approximation to z*M. To avoid loss of precision, the y below + # is actually an integer approximation to 2**R*y*M, where R is the + # number of reductions performed so far. + + y = x-M + # argument reduction; R = number of reductions performed + R = 0 + while (R <= L and abs(y) << L-R >= M or + R > L and abs(y) >> R-L >= M): + y = _div_nearest((M*y) << 1, + M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M)) + R += 1 + + # Taylor series with T terms + T = -int(-10*len(str(M))//(3*L)) + yshift = _rshift_nearest(y, R) + w = _div_nearest(M, T) + for k in range(T-1, 0, -1): + w = _div_nearest(M, k) - _div_nearest(yshift*w, M) + + return _div_nearest(w*y, M) + +def _dlog10(c, e, p): + """Given integers c, e and p with c > 0, p >= 0, compute an integer + approximation to 10**p * log10(c*10**e), with an absolute error of + at most 1. Assumes that c*10**e is not exactly 1.""" + + # increase precision by 2; compensate for this by dividing + # final result by 100 + p += 2 + + # write c*10**e as d*10**f with either: + # f >= 0 and 1 <= d <= 10, or + # f <= 0 and 0.1 <= d <= 1. + # Thus for c*10**e close to 1, f = 0 + l = len(str(c)) + f = e+l - (e+l >= 1) + + if p > 0: + M = 10**p + k = e+p-f + if k >= 0: + c *= 10**k + else: + c = _div_nearest(c, 10**-k) + + log_d = _ilog(c, M) # error < 5 + 22 = 27 + log_10 = _ilog(10*M, M) # error < 15 + log_d = _div_nearest(log_d*M, log_10) + log_tenpower = f*M # exact + else: + log_d = 0 # error < 2.31 + log_tenpower = div_nearest(f, 10**-p) # error < 0.5 + + return _div_nearest(log_tenpower+log_d, 100) + +def _dlog(c, e, p): + """Given integers c, e and p with c > 0, compute an integer + approximation to 10**p * log(c*10**e), with an absolute error of + at most 1. Assumes that c*10**e is not exactly 1.""" + + # Increase precision by 2. The precision increase is compensated + # for at the end with a division by 100. + p += 2 + + # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10, + # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e) + # as 10**p * log(d) + 10**p*f * log(10). + l = len(str(c)) + f = e+l - (e+l >= 1) + + # compute approximation to 10**p*log(d), with error < 27 + if p > 0: + k = e+p-f + if k >= 0: + c *= 10**k + else: + c = _div_nearest(c, 10**-k) # error of <= 0.5 in c + + # _ilog magnifies existing error in c by a factor of at most 10 + log_d = _ilog(c, 10**p) # error < 5 + 22 = 27 + else: + # p <= 0: just approximate the whole thing by 0; error < 2.31 + log_d = 0 + + # compute approximation to 10**p*f*log(10), with error < 17 + if f: + sign_f = [-1, 1][f > 0] + if p >= 0: + M = 10**p * abs(f) + else: + M = _div_nearest(abs(f), 10**-p) # M = 10**p*|f|, error <= 0.5 + + if M: + f_log_ten = sign_f*_ilog(10*M, M) # M*log(10), error <= 1.2 + 15 < 17 + else: + f_log_ten = 0 + else: + f_log_ten = 0 + + # error in sum < 17+27 = 44; error after division < 0.44 + 0.5 < 1 + return _div_nearest(f_log_ten + log_d, 100) - Used on _WorkRep instances during division. +def _iexp(x, M, L=8): + """Given integers x and M, M > 0, such that x/M is small in absolute + value, compute an integer approximation to M*exp(x/M). For 0 <= + x/M <= 2.4, the absolute error in the result is bounded by 60 (and + is usually much smaller).""" + + # Algorithm: to compute exp(z) for a real number z, first divide z + # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then + # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor + # series + # + # expm1(x) = x + x**2/2! + x**3/3! + ... + # + # Now use the identity + # + # expm1(2x) = expm1(x)*(expm1(x)+2) + # + # R times to compute the sequence expm1(z/2**R), + # expm1(z/2**(R-1)), ... , exp(z/2), exp(z). + + # Find R such that x/2**R/M <= 2**-L + R = _nbits((x< M + T = -int(-10*len(str(M))//(3*L)) + y = _div_nearest(x, T) + Mshift = M<= 0: + cshift = c*10**shift + else: + cshift = c//10**-shift + quot, rem = divmod(cshift, log10) + + # reduce remainder back to original precision + rem = _div_nearest(rem, 10**extra) + + # error in result of _iexp < 120; error after division < 0.62 + return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3 + +def _dpower(xc, xe, yc, ye, p): + """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and + y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: + + 10**(p-1) <= c <= 10**p, and + (c-1)*10**e < x**y < (c+1)*10**e + + in other words, c*10**e is an approximation to x**y with p digits + of precision, and with an error in c of at most 1. (This is + almost, but not quite, the same as the error being < 1ulp: when c + == 10**(p-1) we can only guarantee error < 10ulp.) + + We assume that: x is positive and not equal to 1, and y is nonzero. """ - adjust = 0 - # If op1 is smaller, make it larger - while op2.int > op1.int: - op1.int *= 10 - op1.exp -= 1 - adjust += 1 - - # If op2 is too small, make it larger - while op1.int >= (10 * op2.int): - op2.int *= 10 - op2.exp -= 1 - adjust -= 1 - return op1, op2, adjust + # Find b such that 10**(b-1) <= |y| <= 10**b + b = len(str(abs(yc))) + ye + + # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point + lxc = _dlog(xc, xe, p+b+1) + + # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) + shift = ye-b + if shift >= 0: + pc = lxc*yc*10**shift + else: + pc = _div_nearest(lxc*yc, 10**-shift) + + if pc == 0: + # we prefer a result that isn't exactly 1; this makes it + # easier to compute a correctly rounded result in __pow__ + if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: + coeff, exp = 10**(p-1)+1, 1-p + else: + coeff, exp = 10**p-1, -p + else: + coeff, exp = _dexp(pc, -(p+1), p+1) + coeff = _div_nearest(coeff, 10) + exp += 1 + + return coeff, exp + +def _log10_lb(c, correction = { + '1': 100, '2': 70, '3': 53, '4': 40, '5': 31, + '6': 23, '7': 16, '8': 10, '9': 5}): + """Compute a lower bound for 100*log10(c) for a positive integer c.""" + if c <= 0: + raise ValueError("The argument to _log10_lb should be nonnegative.") + str_c = str(c) + return 100*len(str_c) - correction[str_c[0]] ##### Helper Functions #################################################### -def _convert_other(other): +def _convert_other(other, raiseit=False): """Convert other to Decimal. Verifies that it's ok to use in an implicit construction. @@ -2998,6 +5122,8 @@ return other if isinstance(other, int): return Decimal(other) + if raiseit: + raise TypeError("Unable to convert %s to Decimal" % other) return NotImplemented _infinity_map = { @@ -3085,12 +5211,16 @@ # Reusable defaults Inf = Decimal('Inf') negInf = Decimal('-Inf') +NaN = Decimal('NaN') +Dec_0 = Decimal(0) +Dec_p1 = Decimal(1) +Dec_n1 = Decimal(-1) +Dec_p2 = Decimal(2) +Dec_n2 = Decimal(-2) # Infsign[sign] is infinity w/ that sign Infsign = (Inf, negInf) -NaN = Decimal('NaN') - ##### crud for parsing strings ############################################# import re Modified: python/branches/py3k/Lib/distutils/command/build_scripts.py ============================================================================== --- python/branches/py3k/Lib/distutils/command/build_scripts.py (original) +++ python/branches/py3k/Lib/distutils/command/build_scripts.py Wed Sep 19 05:06:30 2007 @@ -102,7 +102,8 @@ outf.write("#!%s%s\n" % (os.path.join( sysconfig.get_config_var("BINDIR"), - "python" + sysconfig.get_config_var("EXE")), + "python" + sysconfig.get_config_var("VERSION") + + sysconfig.get_config_var("EXE")), post_interp)) outf.writelines(f.readlines()) outf.close() Modified: python/branches/py3k/Lib/httplib.py ============================================================================== --- python/branches/py3k/Lib/httplib.py (original) +++ python/branches/py3k/Lib/httplib.py Wed Sep 19 05:06:30 2007 @@ -985,12 +985,12 @@ "Connect to a host on a given (SSL) port." sock = socket.create_connection((self.host, self.port), self.timeout) - self.sock = ssl.sslsocket(sock, self.key_file, self.cert_file) + self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file) def FakeSocket (sock, sslobj): warnings.warn("FakeSocket is deprecated, and won't be in 3.x. " + - "Use the result of ssl.sslsocket directly instead.", + "Use the result of ssl.wrap_socket() directly instead.", DeprecationWarning, stacklevel=2) return sslobj Modified: python/branches/py3k/Lib/imaplib.py ============================================================================== --- python/branches/py3k/Lib/imaplib.py (original) +++ python/branches/py3k/Lib/imaplib.py Wed Sep 19 05:06:30 2007 @@ -1147,7 +1147,7 @@ self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, port)) - self.sslobj = ssl.sslsocket(self.sock, self.keyfile, self.certfile) + self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile) def read(self, size): @@ -1199,7 +1199,7 @@ def ssl(self): """Return SSLObject instance used to communicate with the IMAP4 server. - ssl = ssl.sslsocket(.socket) + ssl = ssl.wrap_socket(.socket) """ return self.sslobj Modified: python/branches/py3k/Lib/platform.py ============================================================================== --- python/branches/py3k/Lib/platform.py (original) +++ python/branches/py3k/Lib/platform.py Wed Sep 19 05:06:30 2007 @@ -1142,6 +1142,12 @@ machine = '' if processor == 'unknown': processor = '' + + # normalize name + if system == 'Microsoft' and release == 'Windows': + system = 'Windows' + release = 'Vista' + _uname_cache = system,node,release,version,machine,processor return _uname_cache Modified: python/branches/py3k/Lib/poplib.py ============================================================================== --- python/branches/py3k/Lib/poplib.py (original) +++ python/branches/py3k/Lib/poplib.py Wed Sep 19 05:06:30 2007 @@ -348,7 +348,7 @@ if not self.sock: raise socket.error(msg) self.file = self.sock.makefile('rb') - self.sslobj = ssl.sslsocket(self.sock, self.keyfile, self.certfile) + self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile) self._debugging = 0 self.welcome = self._getresp() Modified: python/branches/py3k/Lib/repr.py ============================================================================== --- python/branches/py3k/Lib/repr.py (original) +++ python/branches/py3k/Lib/repr.py Wed Sep 19 05:06:30 2007 @@ -1,4 +1,4 @@ -"""Redo the `...` (representation) but with limits on most sizes.""" +"""Redo the builtin repr() (representation) but with limits on most sizes.""" __all__ = ["Repr","repr"] @@ -57,11 +57,11 @@ return self._repr_iterable(x, level, header, '])', self.maxarray) def repr_set(self, x, level): - x = sorted(x) + x = _possibly_sorted(x) return self._repr_iterable(x, level, 'set([', '])', self.maxset) def repr_frozenset(self, x, level): - x = sorted(x) + x = _possibly_sorted(x) return self._repr_iterable(x, level, 'frozenset([', '])', self.maxfrozenset) @@ -75,7 +75,7 @@ newlevel = level - 1 repr1 = self.repr1 pieces = [] - for key in islice(sorted(x), self.maxdict): + for key in islice(_possibly_sorted(x), self.maxdict): keyrepr = repr1(key, newlevel) valrepr = repr1(x[key], newlevel) pieces.append('%s: %s' % (keyrepr, valrepr)) @@ -105,7 +105,7 @@ s = __builtin__.repr(x) # Bugs in x.__repr__() can cause arbitrary # exceptions -- then make up something - except: + except Exception: return '<%s instance at %x>' % (x.__class__.__name__, id(x)) if len(s) > self.maxother: i = max(0, (self.maxother-3)//2) @@ -113,5 +113,15 @@ s = s[:i] + '...' + s[len(s)-j:] return s + +def _possibly_sorted(x): + # Since not all sequences of items can be sorted and comparison + # functions may raise arbitrary exceptions, return an unsorted + # sequence in that case. + try: + return sorted(x) + except Exception: + return list(x) + aRepr = Repr() repr = aRepr.repr Modified: python/branches/py3k/Lib/smtplib.py ============================================================================== --- python/branches/py3k/Lib/smtplib.py (original) +++ python/branches/py3k/Lib/smtplib.py Wed Sep 19 05:06:30 2007 @@ -588,7 +588,7 @@ if resp == 220: if not _have_ssl: raise RuntimeError("No SSL support included in this Python") - self.sock = ssl.sslsocket(self.sock, keyfile, certfile) + self.sock = ssl.wrap_socket(self.sock, keyfile, certfile) self.file = SSLFakeFile(self.sock) return (resp, reply) @@ -721,7 +721,7 @@ def _get_socket(self, host, port, timeout): if self.debuglevel > 0: print('connect:', (host, port), file=stderr) self.sock = socket.create_connection((host, port), timeout) - self.sock = ssl.sslsocket(self.sock, self.keyfile, self.certfile) + self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile) self.file = SSLFakeFile(self.sock) __all__.append("SMTP_SSL") Modified: python/branches/py3k/Lib/socket.py ============================================================================== --- python/branches/py3k/Lib/socket.py (original) +++ python/branches/py3k/Lib/socket.py Wed Sep 19 05:06:30 2007 @@ -56,13 +56,13 @@ def ssl(sock, keyfile=None, certfile=None): # we do an internal import here because the ssl # module imports the socket module - warnings.warn("socket.ssl() is deprecated. Use ssl.sslsocket() instead.", + warnings.warn("socket.ssl() is deprecated. Use ssl.wrap_socket() instead.", DeprecationWarning, stacklevel=2) return _realssl.sslwrap_simple(sock, keyfile, certfile) # we need to import the same constants we used to... + from _ssl import SSLError as sslerror from _ssl import \ - sslerror, \ RAND_add, \ RAND_egd, \ RAND_status, \ Modified: python/branches/py3k/Lib/ssl.py ============================================================================== --- python/branches/py3k/Lib/ssl.py (original) +++ python/branches/py3k/Lib/ssl.py Wed Sep 19 05:06:30 2007 @@ -8,11 +8,11 @@ Object types: - sslsocket -- subtype of socket.socket which does SSL over the socket + SSLSocket -- subtype of socket.socket which does SSL over the socket Exceptions: - sslerror -- exception raised for I/O errors + SSLError -- exception raised for I/O errors Functions: @@ -57,12 +57,14 @@ PROTOCOL_TLSv1 """ -import os, sys +import os, sys, textwrap import _ssl # if we can't import it, let the error propagate -from _ssl import sslerror + +from _ssl import SSLError from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED from _ssl import PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1 +from _ssl import RAND_status, RAND_egd, RAND_add from _ssl import \ SSL_ERROR_ZERO_RETURN, \ SSL_ERROR_WANT_READ, \ @@ -76,9 +78,9 @@ from socket import socket from socket import getnameinfo as _getnameinfo +import base64 # for DER-to-PEM translation - -class sslsocket (socket): +class SSLSocket (socket): """This class implements a subtype of socket.socket that wraps the underlying OS socket in an SSL context when necessary, and @@ -121,14 +123,21 @@ return self._sslobj.write(data) - def getpeercert(self): + def getpeercert(self, binary_form=False): """Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not validated.""" - return self._sslobj.peer_certificate() + return self._sslobj.peer_certificate(binary_form) + + def cipher (self): + + if not self._sslobj: + return None + else: + return self._sslobj.cipher() def send (self, data, flags=0): if self._sslobj: @@ -174,21 +183,12 @@ else: return socket.recv_from(self, addr, buflen, flags) - def ssl_shutdown(self): - - """Shuts down the SSL channel over this socket (if active), - without closing the socket connection.""" - - if self._sslobj: - self._sslobj.shutdown() - self._sslobj = None - def shutdown(self, how): - self.ssl_shutdown() + self._sslobj = None socket.shutdown(self, how) def close(self): - self.ssl_shutdown() + self._sslobj = None socket.close(self) def connect(self, addr): @@ -199,7 +199,7 @@ # Here we assume that the socket is client-side, and not # connected at the time of the call. We connect it, then wrap it. if self._sslobj: - raise ValueError("attempt to connect already-connected sslsocket!") + raise ValueError("attempt to connect already-connected SSLSocket!") socket.connect(self, addr) self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile, self.cert_reqs, self.ssl_version, @@ -212,11 +212,261 @@ SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) - return (sslsocket(newsock, True, self.keyfile, self.certfile, - self.cert_reqs, self.ssl_version, - self.ca_certs), addr) + return (SSLSocket(newsock, True, self.keyfile, self.certfile, + self.cert_reqs, self.ssl_version, + self.ca_certs), addr) + def makefile(self, mode='r', bufsize=-1): + + """Ouch. Need to make and return a file-like object that + works with the SSL connection.""" + + if self._sslobj: + return SSLFileStream(self._sslobj, mode, bufsize) + else: + return socket.makefile(self, mode, bufsize) + + +class SSLFileStream: + + """A class to simulate a file stream on top of a socket. + Most of this is just lifted from the socket module, and + adjusted to work with an SSL stream instead of a socket.""" + + + default_bufsize = 8192 + name = "" + + __slots__ = ["mode", "bufsize", "softspace", + # "closed" is a property, see below + "_sslobj", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", + "_close", "_fileno"] + + def __init__(self, sslobj, mode='rb', bufsize=-1, close=False): + self._sslobj = sslobj + self.mode = mode # Not actually used in this version + if bufsize < 0: + bufsize = self.default_bufsize + self.bufsize = bufsize + self.softspace = False + if bufsize == 0: + self._rbufsize = 1 + elif bufsize == 1: + self._rbufsize = self.default_bufsize + else: + self._rbufsize = bufsize + self._wbufsize = bufsize + self._rbuf = "" # A string + self._wbuf = [] # A list of strings + self._close = close + self._fileno = -1 + + def _getclosed(self): + return self._sslobj is None + closed = property(_getclosed, doc="True if the file is closed") + + def fileno(self): + return self._fileno + + def close(self): + try: + if self._sslobj: + self.flush() + finally: + if self._close and self._sslobj: + self._sslobj.close() + self._sslobj = None + + def __del__(self): + try: + self.close() + except: + # close() may fail if __init__ didn't complete + pass + + def flush(self): + if self._wbuf: + buffer = "".join(self._wbuf) + self._wbuf = [] + count = 0 + while (count < len(buffer)): + written = self._sslobj.write(buffer) + count += written + buffer = buffer[written:] + + def write(self, data): + data = str(data) # XXX Should really reject non-string non-buffers + if not data: + return + self._wbuf.append(data) + if (self._wbufsize == 0 or + self._wbufsize == 1 and '\n' in data or + self._get_wbuf_len() >= self._wbufsize): + self.flush() + + def writelines(self, list): + # XXX We could do better here for very long lists + # XXX Should really reject non-string non-buffers + self._wbuf.extend(filter(None, map(str, list))) + if (self._wbufsize <= 1 or + self._get_wbuf_len() >= self._wbufsize): + self.flush() + + def _get_wbuf_len(self): + buf_len = 0 + for x in self._wbuf: + buf_len += len(x) + return buf_len + + def read(self, size=-1): + data = self._rbuf + if size < 0: + # Read until EOF + buffers = [] + if data: + buffers.append(data) + self._rbuf = "" + if self._rbufsize <= 1: + recv_size = self.default_bufsize + else: + recv_size = self._rbufsize + while True: + data = self._sslobj.read(recv_size) + if not data: + break + buffers.append(data) + return "".join(buffers) + else: + # Read until size bytes or EOF seen, whichever comes first + buf_len = len(data) + if buf_len >= size: + self._rbuf = data[size:] + return data[:size] + buffers = [] + if data: + buffers.append(data) + self._rbuf = "" + while True: + left = size - buf_len + recv_size = max(self._rbufsize, left) + data = self._sslobj.read(recv_size) + if not data: + break + buffers.append(data) + n = len(data) + if n >= left: + self._rbuf = data[left:] + buffers[-1] = data[:left] + break + buf_len += n + return "".join(buffers) + + def readline(self, size=-1): + data = self._rbuf + if size < 0: + # Read until \n or EOF, whichever comes first + if self._rbufsize <= 1: + # Speed up unbuffered case + assert data == "" + buffers = [] + while data != "\n": + data = self._sslobj.read(1) + if not data: + break + buffers.append(data) + return "".join(buffers) + nl = data.find('\n') + if nl >= 0: + nl += 1 + self._rbuf = data[nl:] + return data[:nl] + buffers = [] + if data: + buffers.append(data) + self._rbuf = "" + while True: + data = self._sslobj.read(self._rbufsize) + if not data: + break + buffers.append(data) + nl = data.find('\n') + if nl >= 0: + nl += 1 + self._rbuf = data[nl:] + buffers[-1] = data[:nl] + break + return "".join(buffers) + else: + # Read until size bytes or \n or EOF seen, whichever comes first + nl = data.find('\n', 0, size) + if nl >= 0: + nl += 1 + self._rbuf = data[nl:] + return data[:nl] + buf_len = len(data) + if buf_len >= size: + self._rbuf = data[size:] + return data[:size] + buffers = [] + if data: + buffers.append(data) + self._rbuf = "" + while True: + data = self._sslobj.read(self._rbufsize) + if not data: + break + buffers.append(data) + left = size - buf_len + nl = data.find('\n', 0, left) + if nl >= 0: + nl += 1 + self._rbuf = data[nl:] + buffers[-1] = data[:nl] + break + n = len(data) + if n >= left: + self._rbuf = data[left:] + buffers[-1] = data[:left] + break + buf_len += n + return "".join(buffers) + + def readlines(self, sizehint=0): + total = 0 + list = [] + while True: + line = self.readline() + if not line: + break + list.append(line) + total += len(line) + if sizehint and total >= sizehint: + break + return list + + # Iterator protocols + + def __iter__(self): + return self + + def next(self): + line = self.readline() + if not line: + raise StopIteration + return line + + + + +def wrap_socket(sock, keyfile=None, certfile=None, + server_side=False, cert_reqs=CERT_NONE, + ssl_version=PROTOCOL_SSLv23, ca_certs=None): + + return SSLSocket(sock, keyfile=keyfile, certfile=certfile, + server_side=server_side, cert_reqs=cert_reqs, + ssl_version=ssl_version, ca_certs=ca_certs) + # some utility functions def cert_time_to_seconds(cert_time): @@ -228,6 +478,71 @@ import time return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT")) +PEM_HEADER = "-----BEGIN CERTIFICATE-----" +PEM_FOOTER = "-----END CERTIFICATE-----" + +def DER_cert_to_PEM_cert(der_cert_bytes): + + """Takes a certificate in binary DER format and returns the + PEM version of it as a string.""" + + if hasattr(base64, 'standard_b64encode'): + # preferred because older API gets line-length wrong + f = base64.standard_b64encode(der_cert_bytes) + return (PEM_HEADER + '\n' + + textwrap.fill(f, 64) + + PEM_FOOTER + '\n') + else: + return (PEM_HEADER + '\n' + + base64.encodestring(der_cert_bytes) + + PEM_FOOTER + '\n') + +def PEM_cert_to_DER_cert(pem_cert_string): + + """Takes a certificate in ASCII PEM format and returns the + DER-encoded version of it as a byte sequence""" + + if not pem_cert_string.startswith(PEM_HEADER): + raise ValueError("Invalid PEM encoding; must start with %s" + % PEM_HEADER) + if not pem_cert_string.strip().endswith(PEM_FOOTER): + raise ValueError("Invalid PEM encoding; must end with %s" + % PEM_FOOTER) + d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] + return base64.decodestring(d) + +def get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None): + + """Retrieve the certificate from the server at the specified address, + and return it as a PEM-encoded string. + If 'ca_certs' is specified, validate the server cert against it. + If 'ssl_version' is specified, use it in the connection attempt.""" + + host, port = addr + if (ca_certs is not None): + cert_reqs = CERT_REQUIRED + else: + cert_reqs = CERT_NONE + s = wrap_socket(socket(), ssl_version=ssl_version, + cert_reqs=cert_reqs, ca_certs=ca_certs) + s.connect(addr) + dercert = s.getpeercert(True) + s.close() + return DER_cert_to_PEM_cert(dercert) + +def get_protocol_name (protocol_code): + if protocol_code == PROTOCOL_TLSv1: + return "TLSv1" + elif protocol_code == PROTOCOL_SSLv23: + return "SSLv23" + elif protocol_code == PROTOCOL_SSLv2: + return "SSLv2" + elif protocol_code == PROTOCOL_SSLv3: + return "SSLv3" + else: + return "" + + # a replacement for the old socket.ssl function def sslwrap_simple (sock, keyfile=None, certfile=None): Modified: python/branches/py3k/Lib/test/decimaltestdata/abs.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/abs.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/abs.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- abs.decTest -- decimal absolute value -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- This set of tests primarily tests the existence of the operator. -- Additon, subtraction, rounding, and more overflows are tested @@ -106,9 +106,9 @@ absx215 abs 0.999E-999 -> 1.00E-999 Inexact Rounded Subnormal Underflow absx216 abs 0.099E-999 -> 1.0E-1000 Inexact Rounded Subnormal Underflow absx217 abs 0.009E-999 -> 1E-1001 Inexact Rounded Subnormal Underflow -absx218 abs 0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -absx219 abs 0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -absx220 abs 0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow +absx218 abs 0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +absx219 abs 0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +absx220 abs 0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped absx230 abs -1.00E-999 -> 1.00E-999 absx231 abs -0.1E-999 -> 1E-1000 Subnormal @@ -119,9 +119,9 @@ absx235 abs -0.999E-999 -> 1.00E-999 Inexact Rounded Subnormal Underflow absx236 abs -0.099E-999 -> 1.0E-1000 Inexact Rounded Subnormal Underflow absx237 abs -0.009E-999 -> 1E-1001 Inexact Rounded Subnormal Underflow -absx238 abs -0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -absx239 abs -0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -absx240 abs -0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow +absx238 abs -0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +absx239 abs -0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +absx240 abs -0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped -- long operand tests maxexponent: 999 Modified: python/branches/py3k/Lib/test/decimaltestdata/add.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/add.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/add.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------- +------/cancell---------------------------------------------------------- -- add.decTest -- decimal addition -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 precision: 9 rounding: half_up @@ -86,6 +86,7 @@ addx049 add '10000e+9' '7000' -> '10000000007000' addx050 add '10000e+9' '70000' -> '10000000070000' addx051 add '10000e+9' '700000' -> '10000000700000' +addx052 add '10000e+9' '7000000' -> '10000007000000' -- examples from decarith addx053 add '12' '7.00' -> '19.00' @@ -216,7 +217,7 @@ addx167 add '1.11' '7E+12' -> '7000000000001.11' addx168 add '-1' '7E+12' -> '6999999999999' --- 123456789012345 123456789012345 1 23456789012345 +-- 123456789012345 123456789012345 1 23456789012345 addx170 add '0.444444444444444' '0.555555555555563' -> '1.00000000000001' Inexact Rounded addx171 add '0.444444444444444' '0.555555555555562' -> '1.00000000000001' Inexact Rounded addx172 add '0.444444444444444' '0.555555555555561' -> '1.00000000000001' Inexact Rounded @@ -396,6 +397,7 @@ addx361 add 0E+50 10000E+1 -> 1.0000E+5 addx362 add 10000E+1 0E-50 -> 100000.0 Rounded addx363 add 10000E+1 10000E-50 -> 100000.0 Rounded Inexact +addx364 add 9.999999E+92 -9.999999E+92 -> 0E+86 -- a curiosity from JSR 13 testing rounding: half_down @@ -568,7 +570,7 @@ rounding: down addx561 add 1e-398 9.000000000000000E+384 -> 9.000000000000000E+384 Inexact Rounded addx562 add 0 9.000000000000000E+384 -> 9.000000000000000E+384 Rounded --- and using decimal64 bounds... +-- and using decimal64 bounds (see also ddadd.decTest) precision: 16 maxExponent: +384 minExponent: -383 @@ -576,6 +578,7 @@ addx563 add 1e-388 9.000000000000000E+374 -> 9.000000000000000E+374 Inexact Rounded addx564 add 0 9.000000000000000E+374 -> 9.000000000000000E+374 Rounded + -- some more residue effects with extreme rounding precision: 9 rounding: half_up @@ -955,26 +958,26 @@ addx912 add 0.10E-999 0 -> 1.0E-1000 Subnormal addx913 add 0.100E-999 0 -> 1.0E-1000 Subnormal Rounded addx914 add 0.01E-999 0 -> 1E-1001 Subnormal --- next is rounded to Emin +-- next is rounded to Nmin addx915 add 0.999E-999 0 -> 1.00E-999 Inexact Rounded Subnormal Underflow addx916 add 0.099E-999 0 -> 1.0E-1000 Inexact Rounded Subnormal Underflow addx917 add 0.009E-999 0 -> 1E-1001 Inexact Rounded Subnormal Underflow -addx918 add 0.001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow -addx919 add 0.0009E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow -addx920 add 0.0001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow +addx918 add 0.001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +addx919 add 0.0009E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +addx920 add 0.0001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped addx930 add -1.00E-999 0 -> -1.00E-999 addx931 add -0.1E-999 0 -> -1E-1000 Subnormal addx932 add -0.10E-999 0 -> -1.0E-1000 Subnormal addx933 add -0.100E-999 0 -> -1.0E-1000 Subnormal Rounded addx934 add -0.01E-999 0 -> -1E-1001 Subnormal --- next is rounded to Emin +-- next is rounded to Nmin addx935 add -0.999E-999 0 -> -1.00E-999 Inexact Rounded Subnormal Underflow addx936 add -0.099E-999 0 -> -1.0E-1000 Inexact Rounded Subnormal Underflow addx937 add -0.009E-999 0 -> -1E-1001 Inexact Rounded Subnormal Underflow -addx938 add -0.001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow -addx939 add -0.0009E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow -addx940 add -0.0001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow +addx938 add -0.001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +addx939 add -0.0009E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +addx940 add -0.0001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped -- some non-zero subnormal adds addx950 add 1.00E-999 0.1E-999 -> 1.10E-999 @@ -995,12 +998,43 @@ addx964 add 0.100E-999 -0.1E-999 -> 0E-1001 Clamped addx965 add 0.01E-999 -0.1E-999 -> -9E-1001 Subnormal addx966 add 0.999E-999 -0.1E-999 -> 9.0E-1000 Inexact Rounded Subnormal Underflow -addx967 add 0.099E-999 -0.1E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow +addx967 add 0.099E-999 -0.1E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped addx968 add 0.009E-999 -0.1E-999 -> -9E-1001 Inexact Rounded Subnormal Underflow addx969 add 0.001E-999 -0.1E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow addx970 add 0.0009E-999 -0.1E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow addx971 add 0.0001E-999 -0.1E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow +-- some 'real' numbers +maxExponent: 384 +minExponent: -383 +precision: 8 +addx566 add 99999061735E-394 0E-394 -> 9.999906E-384 Inexact Rounded Underflow Subnormal +precision: 7 +addx567 add 99999061735E-394 0E-394 -> 9.99991E-384 Inexact Rounded Underflow Subnormal +precision: 6 +addx568 add 99999061735E-394 0E-394 -> 9.9999E-384 Inexact Rounded Underflow Subnormal + +-- now the case where we can get underflow but the result is normal +-- [note this can't happen if the operands are also bounded, as we +-- cannot represent 1E-399, for example] +precision: 16 +rounding: half_up +maxExponent: 384 +minExponent: -383 + +addx571 add 1E-383 0 -> 1E-383 +addx572 add 1E-384 0 -> 1E-384 Subnormal +addx573 add 1E-383 1E-384 -> 1.1E-383 +addx574 subtract 1E-383 1E-384 -> 9E-384 Subnormal + +-- Here we explore the boundary of rounding a subnormal to Nmin +addx575 subtract 1E-383 1E-398 -> 9.99999999999999E-384 Subnormal +addx576 subtract 1E-383 1E-398 -> 9.99999999999999E-384 Subnormal +addx577 subtract 1E-383 1E-399 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +addx578 subtract 1E-383 1E-400 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +addx579 subtract 1E-383 1E-401 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +addx580 subtract 1E-383 1E-402 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded + -- check overflow edge case precision: 7 rounding: half_up @@ -1106,21 +1140,1565 @@ addx1139 add 1000E-101 -1e-200 -> 9.99E-99 Subnormal Inexact Rounded Underflow addx1140 add 100E-101 -1e-200 -> 9.9E-100 Subnormal Inexact Rounded Underflow addx1141 add 10E-101 -1e-200 -> 9E-101 Subnormal Inexact Rounded Underflow -addx1142 add 1E-101 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow -addx1143 add 0E-101 -1e-200 -> -0E-101 Subnormal Inexact Rounded Underflow -addx1144 add 1E-102 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow +addx1142 add 1E-101 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow Clamped +addx1143 add 0E-101 -1e-200 -> -0E-101 Subnormal Inexact Rounded Underflow Clamped +addx1144 add 1E-102 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow Clamped addx1151 add 10000E-102 -1e-200 -> 9.99E-99 Subnormal Inexact Rounded Underflow addx1152 add 1000E-102 -1e-200 -> 9.9E-100 Subnormal Inexact Rounded Underflow addx1153 add 100E-102 -1e-200 -> 9E-101 Subnormal Inexact Rounded Underflow -addx1154 add 10E-102 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow -addx1155 add 1E-102 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow -addx1156 add 0E-102 -1e-200 -> -0E-101 Subnormal Inexact Rounded Underflow -addx1157 add 1E-103 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow +addx1154 add 10E-102 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow Clamped +addx1155 add 1E-102 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow Clamped +addx1156 add 0E-102 -1e-200 -> -0E-101 Subnormal Inexact Rounded Underflow Clamped +addx1157 add 1E-103 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow Clamped + +addx1160 add 100E-105 -1e-101 -> -0E-101 Subnormal Inexact Rounded Underflow Clamped +addx1161 add 100E-105 -1e-201 -> 0E-101 Subnormal Inexact Rounded Underflow Clamped + +-- tests based on Gunnar Degnbol's edge case +precision: 15 +rounding: half_up +maxExponent: 384 +minexponent: -383 + +addx1200 add 1E15 -0.5 -> 1.00000000000000E+15 Inexact Rounded +addx1201 add 1E15 -0.50 -> 1.00000000000000E+15 Inexact Rounded +addx1210 add 1E15 -0.51 -> 999999999999999 Inexact Rounded +addx1211 add 1E15 -0.501 -> 999999999999999 Inexact Rounded +addx1212 add 1E15 -0.5001 -> 999999999999999 Inexact Rounded +addx1213 add 1E15 -0.50001 -> 999999999999999 Inexact Rounded +addx1214 add 1E15 -0.500001 -> 999999999999999 Inexact Rounded +addx1215 add 1E15 -0.5000001 -> 999999999999999 Inexact Rounded +addx1216 add 1E15 -0.50000001 -> 999999999999999 Inexact Rounded +addx1217 add 1E15 -0.500000001 -> 999999999999999 Inexact Rounded +addx1218 add 1E15 -0.5000000001 -> 999999999999999 Inexact Rounded +addx1219 add 1E15 -0.50000000001 -> 999999999999999 Inexact Rounded +addx1220 add 1E15 -0.500000000001 -> 999999999999999 Inexact Rounded +addx1221 add 1E15 -0.5000000000001 -> 999999999999999 Inexact Rounded +addx1222 add 1E15 -0.50000000000001 -> 999999999999999 Inexact Rounded +addx1223 add 1E15 -0.500000000000001 -> 999999999999999 Inexact Rounded +addx1224 add 1E15 -0.5000000000000001 -> 999999999999999 Inexact Rounded +addx1225 add 1E15 -0.5000000000000000 -> 1.00000000000000E+15 Inexact Rounded +addx1230 add 1E15 -5000000.000000001 -> 999999995000000 Inexact Rounded + +precision: 16 + +addx1300 add 1E16 -0.5 -> 1.000000000000000E+16 Inexact Rounded +addx1310 add 1E16 -0.51 -> 9999999999999999 Inexact Rounded +addx1311 add 1E16 -0.501 -> 9999999999999999 Inexact Rounded +addx1312 add 1E16 -0.5001 -> 9999999999999999 Inexact Rounded +addx1313 add 1E16 -0.50001 -> 9999999999999999 Inexact Rounded +addx1314 add 1E16 -0.500001 -> 9999999999999999 Inexact Rounded +addx1315 add 1E16 -0.5000001 -> 9999999999999999 Inexact Rounded +addx1316 add 1E16 -0.50000001 -> 9999999999999999 Inexact Rounded +addx1317 add 1E16 -0.500000001 -> 9999999999999999 Inexact Rounded +addx1318 add 1E16 -0.5000000001 -> 9999999999999999 Inexact Rounded +addx1319 add 1E16 -0.50000000001 -> 9999999999999999 Inexact Rounded +addx1320 add 1E16 -0.500000000001 -> 9999999999999999 Inexact Rounded +addx1321 add 1E16 -0.5000000000001 -> 9999999999999999 Inexact Rounded +addx1322 add 1E16 -0.50000000000001 -> 9999999999999999 Inexact Rounded +addx1323 add 1E16 -0.500000000000001 -> 9999999999999999 Inexact Rounded +addx1324 add 1E16 -0.5000000000000001 -> 9999999999999999 Inexact Rounded +addx1325 add 1E16 -0.5000000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1326 add 1E16 -0.500000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1327 add 1E16 -0.50000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1328 add 1E16 -0.5000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1329 add 1E16 -0.500000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1330 add 1E16 -0.50000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1331 add 1E16 -0.5000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1332 add 1E16 -0.500000000 -> 1.000000000000000E+16 Inexact Rounded +addx1333 add 1E16 -0.50000000 -> 1.000000000000000E+16 Inexact Rounded +addx1334 add 1E16 -0.5000000 -> 1.000000000000000E+16 Inexact Rounded +addx1335 add 1E16 -0.500000 -> 1.000000000000000E+16 Inexact Rounded +addx1336 add 1E16 -0.50000 -> 1.000000000000000E+16 Inexact Rounded +addx1337 add 1E16 -0.5000 -> 1.000000000000000E+16 Inexact Rounded +addx1338 add 1E16 -0.500 -> 1.000000000000000E+16 Inexact Rounded +addx1339 add 1E16 -0.50 -> 1.000000000000000E+16 Inexact Rounded + +addx1340 add 1E16 -5000000.000010001 -> 9999999995000000 Inexact Rounded +addx1341 add 1E16 -5000000.000000001 -> 9999999995000000 Inexact Rounded + +addx1349 add 9999999999999999 0.4 -> 9999999999999999 Inexact Rounded +addx1350 add 9999999999999999 0.49 -> 9999999999999999 Inexact Rounded +addx1351 add 9999999999999999 0.499 -> 9999999999999999 Inexact Rounded +addx1352 add 9999999999999999 0.4999 -> 9999999999999999 Inexact Rounded +addx1353 add 9999999999999999 0.49999 -> 9999999999999999 Inexact Rounded +addx1354 add 9999999999999999 0.499999 -> 9999999999999999 Inexact Rounded +addx1355 add 9999999999999999 0.4999999 -> 9999999999999999 Inexact Rounded +addx1356 add 9999999999999999 0.49999999 -> 9999999999999999 Inexact Rounded +addx1357 add 9999999999999999 0.499999999 -> 9999999999999999 Inexact Rounded +addx1358 add 9999999999999999 0.4999999999 -> 9999999999999999 Inexact Rounded +addx1359 add 9999999999999999 0.49999999999 -> 9999999999999999 Inexact Rounded +addx1360 add 9999999999999999 0.499999999999 -> 9999999999999999 Inexact Rounded +addx1361 add 9999999999999999 0.4999999999999 -> 9999999999999999 Inexact Rounded +addx1362 add 9999999999999999 0.49999999999999 -> 9999999999999999 Inexact Rounded +addx1363 add 9999999999999999 0.499999999999999 -> 9999999999999999 Inexact Rounded +addx1364 add 9999999999999999 0.4999999999999999 -> 9999999999999999 Inexact Rounded +addx1365 add 9999999999999999 0.5000000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1367 add 9999999999999999 0.500000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1368 add 9999999999999999 0.50000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1369 add 9999999999999999 0.5000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1370 add 9999999999999999 0.500000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1371 add 9999999999999999 0.50000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1372 add 9999999999999999 0.5000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1373 add 9999999999999999 0.500000000 -> 1.000000000000000E+16 Inexact Rounded +addx1374 add 9999999999999999 0.50000000 -> 1.000000000000000E+16 Inexact Rounded +addx1375 add 9999999999999999 0.5000000 -> 1.000000000000000E+16 Inexact Rounded +addx1376 add 9999999999999999 0.500000 -> 1.000000000000000E+16 Inexact Rounded +addx1377 add 9999999999999999 0.50000 -> 1.000000000000000E+16 Inexact Rounded +addx1378 add 9999999999999999 0.5000 -> 1.000000000000000E+16 Inexact Rounded +addx1379 add 9999999999999999 0.500 -> 1.000000000000000E+16 Inexact Rounded +addx1380 add 9999999999999999 0.50 -> 1.000000000000000E+16 Inexact Rounded +addx1381 add 9999999999999999 0.5 -> 1.000000000000000E+16 Inexact Rounded +addx1382 add 9999999999999999 0.5000000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1383 add 9999999999999999 0.500000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1384 add 9999999999999999 0.50000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1385 add 9999999999999999 0.5000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1386 add 9999999999999999 0.500000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1387 add 9999999999999999 0.50000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1388 add 9999999999999999 0.5000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1389 add 9999999999999999 0.500000001 -> 1.000000000000000E+16 Inexact Rounded +addx1390 add 9999999999999999 0.50000001 -> 1.000000000000000E+16 Inexact Rounded +addx1391 add 9999999999999999 0.5000001 -> 1.000000000000000E+16 Inexact Rounded +addx1392 add 9999999999999999 0.500001 -> 1.000000000000000E+16 Inexact Rounded +addx1393 add 9999999999999999 0.50001 -> 1.000000000000000E+16 Inexact Rounded +addx1394 add 9999999999999999 0.5001 -> 1.000000000000000E+16 Inexact Rounded +addx1395 add 9999999999999999 0.501 -> 1.000000000000000E+16 Inexact Rounded +addx1396 add 9999999999999999 0.51 -> 1.000000000000000E+16 Inexact Rounded + +-- More GD edge cases, where difference between the unadjusted +-- exponents is larger than the maximum precision and one side is 0 +precision: 15 +rounding: half_up +maxExponent: 384 +minexponent: -383 + +addx1400 add 0 1.23456789012345 -> 1.23456789012345 +addx1401 add 0 1.23456789012345E-1 -> 0.123456789012345 +addx1402 add 0 1.23456789012345E-2 -> 0.0123456789012345 +addx1403 add 0 1.23456789012345E-3 -> 0.00123456789012345 +addx1404 add 0 1.23456789012345E-4 -> 0.000123456789012345 +addx1405 add 0 1.23456789012345E-5 -> 0.0000123456789012345 +addx1406 add 0 1.23456789012345E-6 -> 0.00000123456789012345 +addx1407 add 0 1.23456789012345E-7 -> 1.23456789012345E-7 +addx1408 add 0 1.23456789012345E-8 -> 1.23456789012345E-8 +addx1409 add 0 1.23456789012345E-9 -> 1.23456789012345E-9 +addx1410 add 0 1.23456789012345E-10 -> 1.23456789012345E-10 +addx1411 add 0 1.23456789012345E-11 -> 1.23456789012345E-11 +addx1412 add 0 1.23456789012345E-12 -> 1.23456789012345E-12 +addx1413 add 0 1.23456789012345E-13 -> 1.23456789012345E-13 +addx1414 add 0 1.23456789012345E-14 -> 1.23456789012345E-14 +addx1415 add 0 1.23456789012345E-15 -> 1.23456789012345E-15 +addx1416 add 0 1.23456789012345E-16 -> 1.23456789012345E-16 +addx1417 add 0 1.23456789012345E-17 -> 1.23456789012345E-17 +addx1418 add 0 1.23456789012345E-18 -> 1.23456789012345E-18 +addx1419 add 0 1.23456789012345E-19 -> 1.23456789012345E-19 + +-- same, precision 16.. +precision: 16 +addx1420 add 0 1.123456789012345 -> 1.123456789012345 +addx1421 add 0 1.123456789012345E-1 -> 0.1123456789012345 +addx1422 add 0 1.123456789012345E-2 -> 0.01123456789012345 +addx1423 add 0 1.123456789012345E-3 -> 0.001123456789012345 +addx1424 add 0 1.123456789012345E-4 -> 0.0001123456789012345 +addx1425 add 0 1.123456789012345E-5 -> 0.00001123456789012345 +addx1426 add 0 1.123456789012345E-6 -> 0.000001123456789012345 +addx1427 add 0 1.123456789012345E-7 -> 1.123456789012345E-7 +addx1428 add 0 1.123456789012345E-8 -> 1.123456789012345E-8 +addx1429 add 0 1.123456789012345E-9 -> 1.123456789012345E-9 +addx1430 add 0 1.123456789012345E-10 -> 1.123456789012345E-10 +addx1431 add 0 1.123456789012345E-11 -> 1.123456789012345E-11 +addx1432 add 0 1.123456789012345E-12 -> 1.123456789012345E-12 +addx1433 add 0 1.123456789012345E-13 -> 1.123456789012345E-13 +addx1434 add 0 1.123456789012345E-14 -> 1.123456789012345E-14 +addx1435 add 0 1.123456789012345E-15 -> 1.123456789012345E-15 +addx1436 add 0 1.123456789012345E-16 -> 1.123456789012345E-16 +addx1437 add 0 1.123456789012345E-17 -> 1.123456789012345E-17 +addx1438 add 0 1.123456789012345E-18 -> 1.123456789012345E-18 +addx1439 add 0 1.123456789012345E-19 -> 1.123456789012345E-19 + +-- same, reversed 0 +addx1440 add 1.123456789012345 0 -> 1.123456789012345 +addx1441 add 1.123456789012345E-1 0 -> 0.1123456789012345 +addx1442 add 1.123456789012345E-2 0 -> 0.01123456789012345 +addx1443 add 1.123456789012345E-3 0 -> 0.001123456789012345 +addx1444 add 1.123456789012345E-4 0 -> 0.0001123456789012345 +addx1445 add 1.123456789012345E-5 0 -> 0.00001123456789012345 +addx1446 add 1.123456789012345E-6 0 -> 0.000001123456789012345 +addx1447 add 1.123456789012345E-7 0 -> 1.123456789012345E-7 +addx1448 add 1.123456789012345E-8 0 -> 1.123456789012345E-8 +addx1449 add 1.123456789012345E-9 0 -> 1.123456789012345E-9 +addx1450 add 1.123456789012345E-10 0 -> 1.123456789012345E-10 +addx1451 add 1.123456789012345E-11 0 -> 1.123456789012345E-11 +addx1452 add 1.123456789012345E-12 0 -> 1.123456789012345E-12 +addx1453 add 1.123456789012345E-13 0 -> 1.123456789012345E-13 +addx1454 add 1.123456789012345E-14 0 -> 1.123456789012345E-14 +addx1455 add 1.123456789012345E-15 0 -> 1.123456789012345E-15 +addx1456 add 1.123456789012345E-16 0 -> 1.123456789012345E-16 +addx1457 add 1.123456789012345E-17 0 -> 1.123456789012345E-17 +addx1458 add 1.123456789012345E-18 0 -> 1.123456789012345E-18 +addx1459 add 1.123456789012345E-19 0 -> 1.123456789012345E-19 + +-- same, Es on the 0 +addx1460 add 1.123456789012345 0E-0 -> 1.123456789012345 +addx1461 add 1.123456789012345 0E-1 -> 1.123456789012345 +addx1462 add 1.123456789012345 0E-2 -> 1.123456789012345 +addx1463 add 1.123456789012345 0E-3 -> 1.123456789012345 +addx1464 add 1.123456789012345 0E-4 -> 1.123456789012345 +addx1465 add 1.123456789012345 0E-5 -> 1.123456789012345 +addx1466 add 1.123456789012345 0E-6 -> 1.123456789012345 +addx1467 add 1.123456789012345 0E-7 -> 1.123456789012345 +addx1468 add 1.123456789012345 0E-8 -> 1.123456789012345 +addx1469 add 1.123456789012345 0E-9 -> 1.123456789012345 +addx1470 add 1.123456789012345 0E-10 -> 1.123456789012345 +addx1471 add 1.123456789012345 0E-11 -> 1.123456789012345 +addx1472 add 1.123456789012345 0E-12 -> 1.123456789012345 +addx1473 add 1.123456789012345 0E-13 -> 1.123456789012345 +addx1474 add 1.123456789012345 0E-14 -> 1.123456789012345 +addx1475 add 1.123456789012345 0E-15 -> 1.123456789012345 +-- next four flag Rounded because the 0 extends the result +addx1476 add 1.123456789012345 0E-16 -> 1.123456789012345 Rounded +addx1477 add 1.123456789012345 0E-17 -> 1.123456789012345 Rounded +addx1478 add 1.123456789012345 0E-18 -> 1.123456789012345 Rounded +addx1479 add 1.123456789012345 0E-19 -> 1.123456789012345 Rounded + +-- sum of two opposite-sign operands is exactly 0 and floor => -0 +precision: 16 +maxExponent: 384 +minexponent: -383 + +rounding: half_up +-- exact zeros from zeros +addx1500 add 0 0E-19 -> 0E-19 +addx1501 add -0 0E-19 -> 0E-19 +addx1502 add 0 -0E-19 -> 0E-19 +addx1503 add -0 -0E-19 -> -0E-19 +addx1504 add 0E-400 0E-19 -> 0E-398 Clamped +addx1505 add -0E-400 0E-19 -> 0E-398 Clamped +addx1506 add 0E-400 -0E-19 -> 0E-398 Clamped +addx1507 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1511 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1512 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1513 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1514 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx1515 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1516 add -1E-401 1E-401 -> 0E-398 Clamped +addx1517 add 1E-401 -1E-401 -> 0E-398 Clamped +addx1518 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: half_down +-- exact zeros from zeros +addx1520 add 0 0E-19 -> 0E-19 +addx1521 add -0 0E-19 -> 0E-19 +addx1522 add 0 -0E-19 -> 0E-19 +addx1523 add -0 -0E-19 -> -0E-19 +addx1524 add 0E-400 0E-19 -> 0E-398 Clamped +addx1525 add -0E-400 0E-19 -> 0E-398 Clamped +addx1526 add 0E-400 -0E-19 -> 0E-398 Clamped +addx1527 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1531 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1532 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1533 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1534 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx1535 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1536 add -1E-401 1E-401 -> 0E-398 Clamped +addx1537 add 1E-401 -1E-401 -> 0E-398 Clamped +addx1538 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: half_even +-- exact zeros from zeros +addx1540 add 0 0E-19 -> 0E-19 +addx1541 add -0 0E-19 -> 0E-19 +addx1542 add 0 -0E-19 -> 0E-19 +addx1543 add -0 -0E-19 -> -0E-19 +addx1544 add 0E-400 0E-19 -> 0E-398 Clamped +addx1545 add -0E-400 0E-19 -> 0E-398 Clamped +addx1546 add 0E-400 -0E-19 -> 0E-398 Clamped +addx1547 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1551 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1552 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1553 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1554 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx1555 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1556 add -1E-401 1E-401 -> 0E-398 Clamped +addx1557 add 1E-401 -1E-401 -> 0E-398 Clamped +addx1558 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: up +-- exact zeros from zeros +addx1560 add 0 0E-19 -> 0E-19 +addx1561 add -0 0E-19 -> 0E-19 +addx1562 add 0 -0E-19 -> 0E-19 +addx1563 add -0 -0E-19 -> -0E-19 +addx1564 add 0E-400 0E-19 -> 0E-398 Clamped +addx1565 add -0E-400 0E-19 -> 0E-398 Clamped +addx1566 add 0E-400 -0E-19 -> 0E-398 Clamped +addx1567 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1571 add 1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx1572 add -1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx1573 add 1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +addx1574 add -1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +-- some exact zeros from non-zeros +addx1575 add 1E-401 1E-401 -> 1E-398 Subnormal Inexact Rounded Underflow +addx1576 add -1E-401 1E-401 -> 0E-398 Clamped +addx1577 add 1E-401 -1E-401 -> 0E-398 Clamped +addx1578 add -1E-401 -1E-401 -> -1E-398 Subnormal Inexact Rounded Underflow + +rounding: down +-- exact zeros from zeros +addx1580 add 0 0E-19 -> 0E-19 +addx1581 add -0 0E-19 -> 0E-19 +addx1582 add 0 -0E-19 -> 0E-19 +addx1583 add -0 -0E-19 -> -0E-19 +addx1584 add 0E-400 0E-19 -> 0E-398 Clamped +addx1585 add -0E-400 0E-19 -> 0E-398 Clamped +addx1586 add 0E-400 -0E-19 -> 0E-398 Clamped +addx1587 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1591 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1592 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1593 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1594 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx1595 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1596 add -1E-401 1E-401 -> 0E-398 Clamped +addx1597 add 1E-401 -1E-401 -> 0E-398 Clamped +addx1598 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: ceiling +-- exact zeros from zeros +addx1600 add 0 0E-19 -> 0E-19 +addx1601 add -0 0E-19 -> 0E-19 +addx1602 add 0 -0E-19 -> 0E-19 +addx1603 add -0 -0E-19 -> -0E-19 +addx1604 add 0E-400 0E-19 -> 0E-398 Clamped +addx1605 add -0E-400 0E-19 -> 0E-398 Clamped +addx1606 add 0E-400 -0E-19 -> 0E-398 Clamped +addx1607 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1611 add 1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx1612 add -1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx1613 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1614 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx1615 add 1E-401 1E-401 -> 1E-398 Subnormal Inexact Rounded Underflow +addx1616 add -1E-401 1E-401 -> 0E-398 Clamped +addx1617 add 1E-401 -1E-401 -> 0E-398 Clamped +addx1618 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +-- and the extra-special ugly case; unusual minuses marked by -- * +rounding: floor +-- exact zeros from zeros +addx1620 add 0 0E-19 -> 0E-19 +addx1621 add -0 0E-19 -> -0E-19 -- * +addx1622 add 0 -0E-19 -> -0E-19 -- * +addx1623 add -0 -0E-19 -> -0E-19 +addx1624 add 0E-400 0E-19 -> 0E-398 Clamped +addx1625 add -0E-400 0E-19 -> -0E-398 Clamped -- * +addx1626 add 0E-400 -0E-19 -> -0E-398 Clamped -- * +addx1627 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1631 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1632 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1633 add 1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +addx1634 add -1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +-- some exact zeros from non-zeros +addx1635 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1636 add -1E-401 1E-401 -> -0E-398 Clamped -- * +addx1637 add 1E-401 -1E-401 -> -0E-398 Clamped -- * +addx1638 add -1E-401 -1E-401 -> -1E-398 Subnormal Inexact Rounded Underflow + +-- BigDecimal problem testcases 2006.01.23 +precision: 16 +maxExponent: 384 +minexponent: -383 + +rounding: down +precision: 7 +addx1651 add 10001E+2 -2E+1 -> 1.00008E+6 +precision: 6 +addx1652 add 10001E+2 -2E+1 -> 1.00008E+6 +precision: 5 +addx1653 add 10001E+2 -2E+1 -> 1.0000E+6 Inexact Rounded +precision: 4 +addx1654 add 10001E+2 -2E+1 -> 1.000E+6 Inexact Rounded +precision: 3 +addx1655 add 10001E+2 -2E+1 -> 1.00E+6 Inexact Rounded +precision: 2 +addx1656 add 10001E+2 -2E+1 -> 1.0E+6 Inexact Rounded +precision: 1 +addx1657 add 10001E+2 -2E+1 -> 1E+6 Inexact Rounded + +rounding: half_even +precision: 7 +addx1661 add 10001E+2 -2E+1 -> 1.00008E+6 +precision: 6 +addx1662 add 10001E+2 -2E+1 -> 1.00008E+6 +precision: 5 +addx1663 add 10001E+2 -2E+1 -> 1.0001E+6 Inexact Rounded +precision: 4 +addx1664 add 10001E+2 -2E+1 -> 1.000E+6 Inexact Rounded +precision: 3 +addx1665 add 10001E+2 -2E+1 -> 1.00E+6 Inexact Rounded +precision: 2 +addx1666 add 10001E+2 -2E+1 -> 1.0E+6 Inexact Rounded +precision: 1 +addx1667 add 10001E+2 -2E+1 -> 1E+6 Inexact Rounded + +rounding: up +precision: 7 +addx1671 add 10001E+2 -2E+1 -> 1.00008E+6 +precision: 6 +addx1672 add 10001E+2 -2E+1 -> 1.00008E+6 +precision: 5 +addx1673 add 10001E+2 -2E+1 -> 1.0001E+6 Inexact Rounded +precision: 4 +addx1674 add 10001E+2 -2E+1 -> 1.001E+6 Inexact Rounded +precision: 3 +addx1675 add 10001E+2 -2E+1 -> 1.01E+6 Inexact Rounded +precision: 2 +addx1676 add 10001E+2 -2E+1 -> 1.1E+6 Inexact Rounded +precision: 1 +addx1677 add 10001E+2 -2E+1 -> 2E+6 Inexact Rounded + +precision: 34 +rounding: half_up +maxExponent: 6144 +minExponent: -6143 +-- Examples from SQL proposal (Krishna Kulkarni) +addx1701 add 130E-2 120E-2 -> 2.50 +addx1702 add 130E-2 12E-1 -> 2.50 +addx1703 add 130E-2 1E0 -> 2.30 +addx1704 add 1E2 1E4 -> 1.01E+4 +addx1705 subtract 130E-2 120E-2 -> 0.10 +addx1706 subtract 130E-2 12E-1 -> 0.10 +addx1707 subtract 130E-2 1E0 -> 0.30 +addx1708 subtract 1E2 1E4 -> -9.9E+3 + +------------------------------------------------------------------------ +-- Same as above, using decimal64 default parameters -- +------------------------------------------------------------------------ +precision: 16 +rounding: half_even +maxExponent: 384 +minexponent: -383 + +-- [first group are 'quick confidence check'] +addx6001 add 1 1 -> 2 +addx6002 add 2 3 -> 5 +addx6003 add '5.75' '3.3' -> 9.05 +addx6004 add '5' '-3' -> 2 +addx6005 add '-5' '-3' -> -8 +addx6006 add '-7' '2.5' -> -4.5 +addx6007 add '0.7' '0.3' -> 1.0 +addx6008 add '1.25' '1.25' -> 2.50 +addx6009 add '1.23456789' '1.00000000' -> '2.23456789' +addx6010 add '1.23456789' '1.00000011' -> '2.23456800' + +addx6011 add '0.44444444444444444' '0.55555555555555555' -> '1.000000000000000' Inexact Rounded +addx6012 add '0.44444444444444440' '0.55555555555555555' -> '1.000000000000000' Inexact Rounded +addx6013 add '0.44444444444444444' '0.55555555555555550' -> '0.9999999999999999' Inexact Rounded +addx6014 add '0.444444444444444449' '0' -> '0.4444444444444444' Inexact Rounded +addx6015 add '0.4444444444444444499' '0' -> '0.4444444444444444' Inexact Rounded +addx6016 add '0.44444444444444444999' '0' -> '0.4444444444444444' Inexact Rounded +addx6017 add '0.44444444444444445000' '0' -> '0.4444444444444444' Inexact Rounded +addx6018 add '0.44444444444444445001' '0' -> '0.4444444444444445' Inexact Rounded +addx6019 add '0.4444444444444444501' '0' -> '0.4444444444444445' Inexact Rounded +addx6020 add '0.444444444444444451' '0' -> '0.4444444444444445' Inexact Rounded + +addx6021 add 0 1 -> 1 +addx6022 add 1 1 -> 2 +addx6023 add 2 1 -> 3 +addx6024 add 3 1 -> 4 +addx6025 add 4 1 -> 5 +addx6026 add 5 1 -> 6 +addx6027 add 6 1 -> 7 +addx6028 add 7 1 -> 8 +addx6029 add 8 1 -> 9 +addx6030 add 9 1 -> 10 + +-- some carrying effects +addx6031 add '0.9998' '0.0000' -> '0.9998' +addx6032 add '0.9998' '0.0001' -> '0.9999' +addx6033 add '0.9998' '0.0002' -> '1.0000' +addx6034 add '0.9998' '0.0003' -> '1.0001' + +addx6035 add '70' '10000e+16' -> '1.000000000000000E+20' Inexact Rounded +addx6036 add '700' '10000e+16' -> '1.000000000000000E+20' Inexact Rounded +addx6037 add '7000' '10000e+16' -> '1.000000000000000E+20' Inexact Rounded +addx6038 add '70000' '10000e+16' -> '1.000000000000001E+20' Inexact Rounded +addx6039 add '700000' '10000e+16' -> '1.000000000000007E+20' Rounded + +-- symmetry: +addx6040 add '10000e+16' '70' -> '1.000000000000000E+20' Inexact Rounded +addx6041 add '10000e+16' '700' -> '1.000000000000000E+20' Inexact Rounded +addx6042 add '10000e+16' '7000' -> '1.000000000000000E+20' Inexact Rounded +addx6044 add '10000e+16' '70000' -> '1.000000000000001E+20' Inexact Rounded +addx6045 add '10000e+16' '700000' -> '1.000000000000007E+20' Rounded + +addx6046 add '10000e+9' '7' -> '10000000000007' +addx6047 add '10000e+9' '70' -> '10000000000070' +addx6048 add '10000e+9' '700' -> '10000000000700' +addx6049 add '10000e+9' '7000' -> '10000000007000' +addx6050 add '10000e+9' '70000' -> '10000000070000' +addx6051 add '10000e+9' '700000' -> '10000000700000' + +-- examples from decarith +addx6053 add '12' '7.00' -> '19.00' +addx6054 add '1.3' '-1.07' -> '0.23' +addx6055 add '1.3' '-1.30' -> '0.00' +addx6056 add '1.3' '-2.07' -> '-0.77' +addx6057 add '1E+2' '1E+4' -> '1.01E+4' + +-- from above +addx6061 add 1 '0.1' -> '1.1' +addx6062 add 1 '0.01' -> '1.01' +addx6063 add 1 '0.001' -> '1.001' +addx6064 add 1 '0.0001' -> '1.0001' +addx6065 add 1 '0.00001' -> '1.00001' +addx6066 add 1 '0.000001' -> '1.000001' +addx6067 add 1 '0.0000001' -> '1.0000001' +addx6068 add 1 '0.00000001' -> '1.00000001' + +-- cancellation to integer +addx6069 add 99999999999999123456789 -99999999999999E+9 -> 123456789 + +-- some funny zeros [in case of bad signum] +addx6070 add 1 0 -> 1 +addx6071 add 1 0. -> 1 +addx6072 add 1 .0 -> 1.0 +addx6073 add 1 0.0 -> 1.0 +addx6074 add 1 0.00 -> 1.00 +addx6075 add 0 1 -> 1 +addx6076 add 0. 1 -> 1 +addx6077 add .0 1 -> 1.0 +addx6078 add 0.0 1 -> 1.0 +addx6079 add 0.00 1 -> 1.00 -addx1160 add 100E-105 -1e-101 -> -0E-101 Subnormal Inexact Rounded Underflow -addx1161 add 100E-105 -1e-201 -> 0E-101 Subnormal Inexact Rounded Underflow +-- some carries +addx6080 add 9999999999999998 1 -> 9999999999999999 +addx6081 add 9999999999999999 1 -> 1.000000000000000E+16 Rounded +addx6082 add 999999999999999 1 -> 1000000000000000 +addx6083 add 9999999999999 1 -> 10000000000000 +addx6084 add 99999999999 1 -> 100000000000 +addx6085 add 999999999 1 -> 1000000000 +addx6086 add 9999999 1 -> 10000000 +addx6087 add 99999 1 -> 100000 +addx6088 add 999 1 -> 1000 +addx6089 add 9 1 -> 10 + + +-- more LHS swaps +addx6090 add '-56267E-10' 0 -> '-0.0000056267' +addx6091 add '-56267E-6' 0 -> '-0.056267' +addx6092 add '-56267E-5' 0 -> '-0.56267' +addx6093 add '-56267E-4' 0 -> '-5.6267' +addx6094 add '-56267E-3' 0 -> '-56.267' +addx6095 add '-56267E-2' 0 -> '-562.67' +addx6096 add '-56267E-1' 0 -> '-5626.7' +addx6097 add '-56267E-0' 0 -> '-56267' +addx6098 add '-5E-10' 0 -> '-5E-10' +addx6099 add '-5E-7' 0 -> '-5E-7' +addx6100 add '-5E-6' 0 -> '-0.000005' +addx6101 add '-5E-5' 0 -> '-0.00005' +addx6102 add '-5E-4' 0 -> '-0.0005' +addx6103 add '-5E-1' 0 -> '-0.5' +addx6104 add '-5E0' 0 -> '-5' +addx6105 add '-5E1' 0 -> '-50' +addx6106 add '-5E5' 0 -> '-500000' +addx6107 add '-5E15' 0 -> '-5000000000000000' +addx6108 add '-5E16' 0 -> '-5.000000000000000E+16' Rounded +addx6109 add '-5E17' 0 -> '-5.000000000000000E+17' Rounded +addx6110 add '-5E18' 0 -> '-5.000000000000000E+18' Rounded +addx6111 add '-5E100' 0 -> '-5.000000000000000E+100' Rounded +-- more RHS swaps +addx6113 add 0 '-56267E-10' -> '-0.0000056267' +addx6114 add 0 '-56267E-6' -> '-0.056267' +addx6116 add 0 '-56267E-5' -> '-0.56267' +addx6117 add 0 '-56267E-4' -> '-5.6267' +addx6119 add 0 '-56267E-3' -> '-56.267' +addx6120 add 0 '-56267E-2' -> '-562.67' +addx6121 add 0 '-56267E-1' -> '-5626.7' +addx6122 add 0 '-56267E-0' -> '-56267' +addx6123 add 0 '-5E-10' -> '-5E-10' +addx6124 add 0 '-5E-7' -> '-5E-7' +addx6125 add 0 '-5E-6' -> '-0.000005' +addx6126 add 0 '-5E-5' -> '-0.00005' +addx6127 add 0 '-5E-4' -> '-0.0005' +addx6128 add 0 '-5E-1' -> '-0.5' +addx6129 add 0 '-5E0' -> '-5' +addx6130 add 0 '-5E1' -> '-50' +addx6131 add 0 '-5E5' -> '-500000' +addx6132 add 0 '-5E15' -> '-5000000000000000' +addx6133 add 0 '-5E16' -> '-5.000000000000000E+16' Rounded +addx6134 add 0 '-5E17' -> '-5.000000000000000E+17' Rounded +addx6135 add 0 '-5E18' -> '-5.000000000000000E+18' Rounded +addx6136 add 0 '-5E100' -> '-5.000000000000000E+100' Rounded + +-- related +addx6137 add 1 '0E-19' -> '1.000000000000000' Rounded +addx6138 add -1 '0E-19' -> '-1.000000000000000' Rounded +addx6139 add '0E-19' 1 -> '1.000000000000000' Rounded +addx6140 add '0E-19' -1 -> '-1.000000000000000' Rounded +addx6141 add 1E+11 0.0000 -> '100000000000.0000' +addx6142 add 1E+11 0.00000 -> '100000000000.0000' Rounded +addx6143 add 0.000 1E+12 -> '1000000000000.000' +addx6144 add 0.0000 1E+12 -> '1000000000000.000' Rounded + +-- [some of the next group are really constructor tests] +addx6146 add '00.0' 0 -> '0.0' +addx6147 add '0.00' 0 -> '0.00' +addx6148 add 0 '0.00' -> '0.00' +addx6149 add 0 '00.0' -> '0.0' +addx6150 add '00.0' '0.00' -> '0.00' +addx6151 add '0.00' '00.0' -> '0.00' +addx6152 add '3' '.3' -> '3.3' +addx6153 add '3.' '.3' -> '3.3' +addx6154 add '3.0' '.3' -> '3.3' +addx6155 add '3.00' '.3' -> '3.30' +addx6156 add '3' '3' -> '6' +addx6157 add '3' '+3' -> '6' +addx6158 add '3' '-3' -> '0' +addx6159 add '0.3' '-0.3' -> '0.0' +addx6160 add '0.03' '-0.03' -> '0.00' + +-- try borderline precision, with carries, etc. +addx6161 add '1E+13' '-1' -> '9999999999999' +addx6162 add '1E+13' '1.11' -> '10000000000001.11' +addx6163 add '1.11' '1E+13' -> '10000000000001.11' +addx6164 add '-1' '1E+13' -> '9999999999999' +addx6165 add '7E+13' '-1' -> '69999999999999' +addx6166 add '7E+13' '1.11' -> '70000000000001.11' +addx6167 add '1.11' '7E+13' -> '70000000000001.11' +addx6168 add '-1' '7E+13' -> '69999999999999' + +-- 1234567890123456 1234567890123456 1 234567890123456 +addx6170 add '0.4444444444444444' '0.5555555555555563' -> '1.000000000000001' Inexact Rounded +addx6171 add '0.4444444444444444' '0.5555555555555562' -> '1.000000000000001' Inexact Rounded +addx6172 add '0.4444444444444444' '0.5555555555555561' -> '1.000000000000000' Inexact Rounded +addx6173 add '0.4444444444444444' '0.5555555555555560' -> '1.000000000000000' Inexact Rounded +addx6174 add '0.4444444444444444' '0.5555555555555559' -> '1.000000000000000' Inexact Rounded +addx6175 add '0.4444444444444444' '0.5555555555555558' -> '1.000000000000000' Inexact Rounded +addx6176 add '0.4444444444444444' '0.5555555555555557' -> '1.000000000000000' Inexact Rounded +addx6177 add '0.4444444444444444' '0.5555555555555556' -> '1.000000000000000' Rounded +addx6178 add '0.4444444444444444' '0.5555555555555555' -> '0.9999999999999999' +addx6179 add '0.4444444444444444' '0.5555555555555554' -> '0.9999999999999998' +addx6180 add '0.4444444444444444' '0.5555555555555553' -> '0.9999999999999997' +addx6181 add '0.4444444444444444' '0.5555555555555552' -> '0.9999999999999996' +addx6182 add '0.4444444444444444' '0.5555555555555551' -> '0.9999999999999995' +addx6183 add '0.4444444444444444' '0.5555555555555550' -> '0.9999999999999994' + +-- and some more, including residue effects and different roundings +rounding: half_up +addx6200 add '6543210123456789' 0 -> '6543210123456789' +addx6201 add '6543210123456789' 0.000000001 -> '6543210123456789' Inexact Rounded +addx6202 add '6543210123456789' 0.000001 -> '6543210123456789' Inexact Rounded +addx6203 add '6543210123456789' 0.1 -> '6543210123456789' Inexact Rounded +addx6204 add '6543210123456789' 0.4 -> '6543210123456789' Inexact Rounded +addx6205 add '6543210123456789' 0.49 -> '6543210123456789' Inexact Rounded +addx6206 add '6543210123456789' 0.499999 -> '6543210123456789' Inexact Rounded +addx6207 add '6543210123456789' 0.499999999 -> '6543210123456789' Inexact Rounded +addx6208 add '6543210123456789' 0.5 -> '6543210123456790' Inexact Rounded +addx6209 add '6543210123456789' 0.500000001 -> '6543210123456790' Inexact Rounded +addx6210 add '6543210123456789' 0.500001 -> '6543210123456790' Inexact Rounded +addx6211 add '6543210123456789' 0.51 -> '6543210123456790' Inexact Rounded +addx6212 add '6543210123456789' 0.6 -> '6543210123456790' Inexact Rounded +addx6213 add '6543210123456789' 0.9 -> '6543210123456790' Inexact Rounded +addx6214 add '6543210123456789' 0.99999 -> '6543210123456790' Inexact Rounded +addx6215 add '6543210123456789' 0.999999999 -> '6543210123456790' Inexact Rounded +addx6216 add '6543210123456789' 1 -> '6543210123456790' +addx6217 add '6543210123456789' 1.000000001 -> '6543210123456790' Inexact Rounded +addx6218 add '6543210123456789' 1.00001 -> '6543210123456790' Inexact Rounded +addx6219 add '6543210123456789' 1.1 -> '6543210123456790' Inexact Rounded + +rounding: half_even +addx6220 add '6543210123456789' 0 -> '6543210123456789' +addx6221 add '6543210123456789' 0.000000001 -> '6543210123456789' Inexact Rounded +addx6222 add '6543210123456789' 0.000001 -> '6543210123456789' Inexact Rounded +addx6223 add '6543210123456789' 0.1 -> '6543210123456789' Inexact Rounded +addx6224 add '6543210123456789' 0.4 -> '6543210123456789' Inexact Rounded +addx6225 add '6543210123456789' 0.49 -> '6543210123456789' Inexact Rounded +addx6226 add '6543210123456789' 0.499999 -> '6543210123456789' Inexact Rounded +addx6227 add '6543210123456789' 0.499999999 -> '6543210123456789' Inexact Rounded +addx6228 add '6543210123456789' 0.5 -> '6543210123456790' Inexact Rounded +addx6229 add '6543210123456789' 0.500000001 -> '6543210123456790' Inexact Rounded +addx6230 add '6543210123456789' 0.500001 -> '6543210123456790' Inexact Rounded +addx6231 add '6543210123456789' 0.51 -> '6543210123456790' Inexact Rounded +addx6232 add '6543210123456789' 0.6 -> '6543210123456790' Inexact Rounded +addx6233 add '6543210123456789' 0.9 -> '6543210123456790' Inexact Rounded +addx6234 add '6543210123456789' 0.99999 -> '6543210123456790' Inexact Rounded +addx6235 add '6543210123456789' 0.999999999 -> '6543210123456790' Inexact Rounded +addx6236 add '6543210123456789' 1 -> '6543210123456790' +addx6237 add '6543210123456789' 1.00000001 -> '6543210123456790' Inexact Rounded +addx6238 add '6543210123456789' 1.00001 -> '6543210123456790' Inexact Rounded +addx6239 add '6543210123456789' 1.1 -> '6543210123456790' Inexact Rounded +-- critical few with even bottom digit... +addx6240 add '6543210123456788' 0.499999999 -> '6543210123456788' Inexact Rounded +addx6241 add '6543210123456788' 0.5 -> '6543210123456788' Inexact Rounded +addx6242 add '6543210123456788' 0.500000001 -> '6543210123456789' Inexact Rounded + +rounding: down +addx6250 add '6543210123456789' 0 -> '6543210123456789' +addx6251 add '6543210123456789' 0.000000001 -> '6543210123456789' Inexact Rounded +addx6252 add '6543210123456789' 0.000001 -> '6543210123456789' Inexact Rounded +addx6253 add '6543210123456789' 0.1 -> '6543210123456789' Inexact Rounded +addx6254 add '6543210123456789' 0.4 -> '6543210123456789' Inexact Rounded +addx6255 add '6543210123456789' 0.49 -> '6543210123456789' Inexact Rounded +addx6256 add '6543210123456789' 0.499999 -> '6543210123456789' Inexact Rounded +addx6257 add '6543210123456789' 0.499999999 -> '6543210123456789' Inexact Rounded +addx6258 add '6543210123456789' 0.5 -> '6543210123456789' Inexact Rounded +addx6259 add '6543210123456789' 0.500000001 -> '6543210123456789' Inexact Rounded +addx6260 add '6543210123456789' 0.500001 -> '6543210123456789' Inexact Rounded +addx6261 add '6543210123456789' 0.51 -> '6543210123456789' Inexact Rounded +addx6262 add '6543210123456789' 0.6 -> '6543210123456789' Inexact Rounded +addx6263 add '6543210123456789' 0.9 -> '6543210123456789' Inexact Rounded +addx6264 add '6543210123456789' 0.99999 -> '6543210123456789' Inexact Rounded +addx6265 add '6543210123456789' 0.999999999 -> '6543210123456789' Inexact Rounded +addx6266 add '6543210123456789' 1 -> '6543210123456790' +addx6267 add '6543210123456789' 1.00000001 -> '6543210123456790' Inexact Rounded +addx6268 add '6543210123456789' 1.00001 -> '6543210123456790' Inexact Rounded +addx6269 add '6543210123456789' 1.1 -> '6543210123456790' Inexact Rounded + +-- 1 in last place tests +rounding: half_even +addx6301 add -1 1 -> 0 +addx6302 add 0 1 -> 1 +addx6303 add 1 1 -> 2 +addx6304 add 12 1 -> 13 +addx6305 add 98 1 -> 99 +addx6306 add 99 1 -> 100 +addx6307 add 100 1 -> 101 +addx6308 add 101 1 -> 102 +addx6309 add -1 -1 -> -2 +addx6310 add 0 -1 -> -1 +addx6311 add 1 -1 -> 0 +addx6312 add 12 -1 -> 11 +addx6313 add 98 -1 -> 97 +addx6314 add 99 -1 -> 98 +addx6315 add 100 -1 -> 99 +addx6316 add 101 -1 -> 100 + +addx6321 add -0.01 0.01 -> 0.00 +addx6322 add 0.00 0.01 -> 0.01 +addx6323 add 0.01 0.01 -> 0.02 +addx6324 add 0.12 0.01 -> 0.13 +addx6325 add 0.98 0.01 -> 0.99 +addx6326 add 0.99 0.01 -> 1.00 +addx6327 add 1.00 0.01 -> 1.01 +addx6328 add 1.01 0.01 -> 1.02 +addx6329 add -0.01 -0.01 -> -0.02 +addx6330 add 0.00 -0.01 -> -0.01 +addx6331 add 0.01 -0.01 -> 0.00 +addx6332 add 0.12 -0.01 -> 0.11 +addx6333 add 0.98 -0.01 -> 0.97 +addx6334 add 0.99 -0.01 -> 0.98 +addx6335 add 1.00 -0.01 -> 0.99 +addx6336 add 1.01 -0.01 -> 1.00 + +-- some more cases where adding 0 affects the coefficient +addx6340 add 1E+3 0 -> 1000 +addx6341 add 1E+15 0 -> 1000000000000000 +addx6342 add 1E+16 0 -> 1.000000000000000E+16 Rounded +addx6343 add 1E+17 0 -> 1.000000000000000E+17 Rounded +-- which simply follow from these cases ... +addx6344 add 1E+3 1 -> 1001 +addx6345 add 1E+15 1 -> 1000000000000001 +addx6346 add 1E+16 1 -> 1.000000000000000E+16 Inexact Rounded +addx6347 add 1E+17 1 -> 1.000000000000000E+17 Inexact Rounded +addx6348 add 1E+3 7 -> 1007 +addx6349 add 1E+15 7 -> 1000000000000007 +addx6350 add 1E+16 7 -> 1.000000000000001E+16 Inexact Rounded +addx6351 add 1E+17 7 -> 1.000000000000000E+17 Inexact Rounded + +-- tryzeros cases +addx6361 add 0E+50 10000E+1 -> 1.0000E+5 +addx6362 add 10000E+1 0E-50 -> 100000.0000000000 Rounded +addx6363 add 10000E+1 10000E-50 -> 100000.0000000000 Rounded Inexact +addx6364 add 12.34 0e-398 -> 12.34000000000000 Rounded + +-- ulp replacement tests +addx6400 add 1 77e-14 -> 1.00000000000077 +addx6401 add 1 77e-15 -> 1.000000000000077 +addx6402 add 1 77e-16 -> 1.000000000000008 Inexact Rounded +addx6403 add 1 77e-17 -> 1.000000000000001 Inexact Rounded +addx6404 add 1 77e-18 -> 1.000000000000000 Inexact Rounded +addx6405 add 1 77e-19 -> 1.000000000000000 Inexact Rounded +addx6406 add 1 77e-99 -> 1.000000000000000 Inexact Rounded + +addx6410 add 10 77e-14 -> 10.00000000000077 +addx6411 add 10 77e-15 -> 10.00000000000008 Inexact Rounded +addx6412 add 10 77e-16 -> 10.00000000000001 Inexact Rounded +addx6413 add 10 77e-17 -> 10.00000000000000 Inexact Rounded +addx6414 add 10 77e-18 -> 10.00000000000000 Inexact Rounded +addx6415 add 10 77e-19 -> 10.00000000000000 Inexact Rounded +addx6416 add 10 77e-99 -> 10.00000000000000 Inexact Rounded + +addx6420 add 77e-14 1 -> 1.00000000000077 +addx6421 add 77e-15 1 -> 1.000000000000077 +addx6422 add 77e-16 1 -> 1.000000000000008 Inexact Rounded +addx6423 add 77e-17 1 -> 1.000000000000001 Inexact Rounded +addx6424 add 77e-18 1 -> 1.000000000000000 Inexact Rounded +addx6425 add 77e-19 1 -> 1.000000000000000 Inexact Rounded +addx6426 add 77e-99 1 -> 1.000000000000000 Inexact Rounded + +addx6430 add 77e-14 10 -> 10.00000000000077 +addx6431 add 77e-15 10 -> 10.00000000000008 Inexact Rounded +addx6432 add 77e-16 10 -> 10.00000000000001 Inexact Rounded +addx6433 add 77e-17 10 -> 10.00000000000000 Inexact Rounded +addx6434 add 77e-18 10 -> 10.00000000000000 Inexact Rounded +addx6435 add 77e-19 10 -> 10.00000000000000 Inexact Rounded +addx6436 add 77e-99 10 -> 10.00000000000000 Inexact Rounded + +-- negative ulps +addx6440 add 1 -77e-14 -> 0.99999999999923 +addx6441 add 1 -77e-15 -> 0.999999999999923 +addx6442 add 1 -77e-16 -> 0.9999999999999923 +addx6443 add 1 -77e-17 -> 0.9999999999999992 Inexact Rounded +addx6444 add 1 -77e-18 -> 0.9999999999999999 Inexact Rounded +addx6445 add 1 -77e-19 -> 1.000000000000000 Inexact Rounded +addx6446 add 1 -77e-99 -> 1.000000000000000 Inexact Rounded + +addx6450 add 10 -77e-14 -> 9.99999999999923 +addx6451 add 10 -77e-15 -> 9.999999999999923 +addx6452 add 10 -77e-16 -> 9.999999999999992 Inexact Rounded +addx6453 add 10 -77e-17 -> 9.999999999999999 Inexact Rounded +addx6454 add 10 -77e-18 -> 10.00000000000000 Inexact Rounded +addx6455 add 10 -77e-19 -> 10.00000000000000 Inexact Rounded +addx6456 add 10 -77e-99 -> 10.00000000000000 Inexact Rounded + +addx6460 add -77e-14 1 -> 0.99999999999923 +addx6461 add -77e-15 1 -> 0.999999999999923 +addx6462 add -77e-16 1 -> 0.9999999999999923 +addx6463 add -77e-17 1 -> 0.9999999999999992 Inexact Rounded +addx6464 add -77e-18 1 -> 0.9999999999999999 Inexact Rounded +addx6465 add -77e-19 1 -> 1.000000000000000 Inexact Rounded +addx6466 add -77e-99 1 -> 1.000000000000000 Inexact Rounded + +addx6470 add -77e-14 10 -> 9.99999999999923 +addx6471 add -77e-15 10 -> 9.999999999999923 +addx6472 add -77e-16 10 -> 9.999999999999992 Inexact Rounded +addx6473 add -77e-17 10 -> 9.999999999999999 Inexact Rounded +addx6474 add -77e-18 10 -> 10.00000000000000 Inexact Rounded +addx6475 add -77e-19 10 -> 10.00000000000000 Inexact Rounded +addx6476 add -77e-99 10 -> 10.00000000000000 Inexact Rounded + +-- negative ulps +addx6480 add -1 77e-14 -> -0.99999999999923 +addx6481 add -1 77e-15 -> -0.999999999999923 +addx6482 add -1 77e-16 -> -0.9999999999999923 +addx6483 add -1 77e-17 -> -0.9999999999999992 Inexact Rounded +addx6484 add -1 77e-18 -> -0.9999999999999999 Inexact Rounded +addx6485 add -1 77e-19 -> -1.000000000000000 Inexact Rounded +addx6486 add -1 77e-99 -> -1.000000000000000 Inexact Rounded + +addx6490 add -10 77e-14 -> -9.99999999999923 +addx6491 add -10 77e-15 -> -9.999999999999923 +addx6492 add -10 77e-16 -> -9.999999999999992 Inexact Rounded +addx6493 add -10 77e-17 -> -9.999999999999999 Inexact Rounded +addx6494 add -10 77e-18 -> -10.00000000000000 Inexact Rounded +addx6495 add -10 77e-19 -> -10.00000000000000 Inexact Rounded +addx6496 add -10 77e-99 -> -10.00000000000000 Inexact Rounded + +addx6500 add 77e-14 -1 -> -0.99999999999923 +addx6501 add 77e-15 -1 -> -0.999999999999923 +addx6502 add 77e-16 -1 -> -0.9999999999999923 +addx6503 add 77e-17 -1 -> -0.9999999999999992 Inexact Rounded +addx6504 add 77e-18 -1 -> -0.9999999999999999 Inexact Rounded +addx6505 add 77e-19 -1 -> -1.000000000000000 Inexact Rounded +addx6506 add 77e-99 -1 -> -1.000000000000000 Inexact Rounded + +addx6510 add 77e-14 -10 -> -9.99999999999923 +addx6511 add 77e-15 -10 -> -9.999999999999923 +addx6512 add 77e-16 -10 -> -9.999999999999992 Inexact Rounded +addx6513 add 77e-17 -10 -> -9.999999999999999 Inexact Rounded +addx6514 add 77e-18 -10 -> -10.00000000000000 Inexact Rounded +addx6515 add 77e-19 -10 -> -10.00000000000000 Inexact Rounded +addx6516 add 77e-99 -10 -> -10.00000000000000 Inexact Rounded + + +-- long operands +addx6521 add 101234562345678000 0 -> 1.012345623456780E+17 Rounded +addx6522 add 0 101234562345678000 -> 1.012345623456780E+17 Rounded +addx6523 add 10123456234567800 0 -> 1.012345623456780E+16 Rounded +addx6524 add 0 10123456234567800 -> 1.012345623456780E+16 Rounded +addx6525 add 10123456234567890 0 -> 1.012345623456789E+16 Rounded +addx6526 add 0 10123456234567890 -> 1.012345623456789E+16 Rounded +addx6527 add 10123456234567891 0 -> 1.012345623456789E+16 Inexact Rounded +addx6528 add 0 10123456234567891 -> 1.012345623456789E+16 Inexact Rounded +addx6529 add 101234562345678901 0 -> 1.012345623456789E+17 Inexact Rounded +addx6530 add 0 101234562345678901 -> 1.012345623456789E+17 Inexact Rounded +addx6531 add 10123456234567896 0 -> 1.012345623456790E+16 Inexact Rounded +addx6532 add 0 10123456234567896 -> 1.012345623456790E+16 Inexact Rounded + +-- verify a query +rounding: down +addx6561 add 1e-398 9.000000000000000E+384 -> 9.000000000000000E+384 Inexact Rounded +addx6562 add 0 9.000000000000000E+384 -> 9.000000000000000E+384 Rounded +-- and using decimal64 bounds... +rounding: down +addx6563 add 1e-388 9.000000000000000E+374 -> 9.000000000000000E+374 Inexact Rounded +addx6564 add 0 9.000000000000000E+374 -> 9.000000000000000E+374 Rounded + +-- more zeros, etc. +rounding: half_even + +addx6701 add 5.00 1.00E-3 -> 5.00100 +addx6702 add 00.00 0.000 -> 0.000 +addx6703 add 00.00 0E-3 -> 0.000 +addx6704 add 0E-3 00.00 -> 0.000 + +addx6710 add 0E+3 00.00 -> 0.00 +addx6711 add 0E+3 00.0 -> 0.0 +addx6712 add 0E+3 00. -> 0 +addx6713 add 0E+3 00.E+1 -> 0E+1 +addx6714 add 0E+3 00.E+2 -> 0E+2 +addx6715 add 0E+3 00.E+3 -> 0E+3 +addx6716 add 0E+3 00.E+4 -> 0E+3 +addx6717 add 0E+3 00.E+5 -> 0E+3 +addx6718 add 0E+3 -00.0 -> 0.0 +addx6719 add 0E+3 -00. -> 0 +addx6731 add 0E+3 -00.E+1 -> 0E+1 + +addx6720 add 00.00 0E+3 -> 0.00 +addx6721 add 00.0 0E+3 -> 0.0 +addx6722 add 00. 0E+3 -> 0 +addx6723 add 00.E+1 0E+3 -> 0E+1 +addx6724 add 00.E+2 0E+3 -> 0E+2 +addx6725 add 00.E+3 0E+3 -> 0E+3 +addx6726 add 00.E+4 0E+3 -> 0E+3 +addx6727 add 00.E+5 0E+3 -> 0E+3 +addx6728 add -00.00 0E+3 -> 0.00 +addx6729 add -00.0 0E+3 -> 0.0 +addx6730 add -00. 0E+3 -> 0 + +addx6732 add 0 0 -> 0 +addx6733 add 0 -0 -> 0 +addx6734 add -0 0 -> 0 +addx6735 add -0 -0 -> -0 -- IEEE 854 special case + +addx6736 add 1 -1 -> 0 +addx6737 add -1 -1 -> -2 +addx6738 add 1 1 -> 2 +addx6739 add -1 1 -> 0 + +addx6741 add 0 -1 -> -1 +addx6742 add -0 -1 -> -1 +addx6743 add 0 1 -> 1 +addx6744 add -0 1 -> 1 +addx6745 add -1 0 -> -1 +addx6746 add -1 -0 -> -1 +addx6747 add 1 0 -> 1 +addx6748 add 1 -0 -> 1 + +addx6751 add 0.0 -1 -> -1.0 +addx6752 add -0.0 -1 -> -1.0 +addx6753 add 0.0 1 -> 1.0 +addx6754 add -0.0 1 -> 1.0 +addx6755 add -1.0 0 -> -1.0 +addx6756 add -1.0 -0 -> -1.0 +addx6757 add 1.0 0 -> 1.0 +addx6758 add 1.0 -0 -> 1.0 + +addx6761 add 0 -1.0 -> -1.0 +addx6762 add -0 -1.0 -> -1.0 +addx6763 add 0 1.0 -> 1.0 +addx6764 add -0 1.0 -> 1.0 +addx6765 add -1 0.0 -> -1.0 +addx6766 add -1 -0.0 -> -1.0 +addx6767 add 1 0.0 -> 1.0 +addx6768 add 1 -0.0 -> 1.0 + +addx6771 add 0.0 -1.0 -> -1.0 +addx6772 add -0.0 -1.0 -> -1.0 +addx6773 add 0.0 1.0 -> 1.0 +addx6774 add -0.0 1.0 -> 1.0 +addx6775 add -1.0 0.0 -> -1.0 +addx6776 add -1.0 -0.0 -> -1.0 +addx6777 add 1.0 0.0 -> 1.0 +addx6778 add 1.0 -0.0 -> 1.0 + +-- Specials +addx6780 add -Inf -Inf -> -Infinity +addx6781 add -Inf -1000 -> -Infinity +addx6782 add -Inf -1 -> -Infinity +addx6783 add -Inf -0 -> -Infinity +addx6784 add -Inf 0 -> -Infinity +addx6785 add -Inf 1 -> -Infinity +addx6786 add -Inf 1000 -> -Infinity +addx6787 add -1000 -Inf -> -Infinity +addx6788 add -Inf -Inf -> -Infinity +addx6789 add -1 -Inf -> -Infinity +addx6790 add -0 -Inf -> -Infinity +addx6791 add 0 -Inf -> -Infinity +addx6792 add 1 -Inf -> -Infinity +addx6793 add 1000 -Inf -> -Infinity +addx6794 add Inf -Inf -> NaN Invalid_operation + +addx6800 add Inf -Inf -> NaN Invalid_operation +addx6801 add Inf -1000 -> Infinity +addx6802 add Inf -1 -> Infinity +addx6803 add Inf -0 -> Infinity +addx6804 add Inf 0 -> Infinity +addx6805 add Inf 1 -> Infinity +addx6806 add Inf 1000 -> Infinity +addx6807 add Inf Inf -> Infinity +addx6808 add -1000 Inf -> Infinity +addx6809 add -Inf Inf -> NaN Invalid_operation +addx6810 add -1 Inf -> Infinity +addx6811 add -0 Inf -> Infinity +addx6812 add 0 Inf -> Infinity +addx6813 add 1 Inf -> Infinity +addx6814 add 1000 Inf -> Infinity +addx6815 add Inf Inf -> Infinity + +addx6821 add NaN -Inf -> NaN +addx6822 add NaN -1000 -> NaN +addx6823 add NaN -1 -> NaN +addx6824 add NaN -0 -> NaN +addx6825 add NaN 0 -> NaN +addx6826 add NaN 1 -> NaN +addx6827 add NaN 1000 -> NaN +addx6828 add NaN Inf -> NaN +addx6829 add NaN NaN -> NaN +addx6830 add -Inf NaN -> NaN +addx6831 add -1000 NaN -> NaN +addx6832 add -1 NaN -> NaN +addx6833 add -0 NaN -> NaN +addx6834 add 0 NaN -> NaN +addx6835 add 1 NaN -> NaN +addx6836 add 1000 NaN -> NaN +addx6837 add Inf NaN -> NaN + +addx6841 add sNaN -Inf -> NaN Invalid_operation +addx6842 add sNaN -1000 -> NaN Invalid_operation +addx6843 add sNaN -1 -> NaN Invalid_operation +addx6844 add sNaN -0 -> NaN Invalid_operation +addx6845 add sNaN 0 -> NaN Invalid_operation +addx6846 add sNaN 1 -> NaN Invalid_operation +addx6847 add sNaN 1000 -> NaN Invalid_operation +addx6848 add sNaN NaN -> NaN Invalid_operation +addx6849 add sNaN sNaN -> NaN Invalid_operation +addx6850 add NaN sNaN -> NaN Invalid_operation +addx6851 add -Inf sNaN -> NaN Invalid_operation +addx6852 add -1000 sNaN -> NaN Invalid_operation +addx6853 add -1 sNaN -> NaN Invalid_operation +addx6854 add -0 sNaN -> NaN Invalid_operation +addx6855 add 0 sNaN -> NaN Invalid_operation +addx6856 add 1 sNaN -> NaN Invalid_operation +addx6857 add 1000 sNaN -> NaN Invalid_operation +addx6858 add Inf sNaN -> NaN Invalid_operation +addx6859 add NaN sNaN -> NaN Invalid_operation + +-- propagating NaNs +addx6861 add NaN1 -Inf -> NaN1 +addx6862 add +NaN2 -1000 -> NaN2 +addx6863 add NaN3 1000 -> NaN3 +addx6864 add NaN4 Inf -> NaN4 +addx6865 add NaN5 +NaN6 -> NaN5 +addx6866 add -Inf NaN7 -> NaN7 +addx6867 add -1000 NaN8 -> NaN8 +addx6868 add 1000 NaN9 -> NaN9 +addx6869 add Inf +NaN10 -> NaN10 +addx6871 add sNaN11 -Inf -> NaN11 Invalid_operation +addx6872 add sNaN12 -1000 -> NaN12 Invalid_operation +addx6873 add sNaN13 1000 -> NaN13 Invalid_operation +addx6874 add sNaN14 NaN17 -> NaN14 Invalid_operation +addx6875 add sNaN15 sNaN18 -> NaN15 Invalid_operation +addx6876 add NaN16 sNaN19 -> NaN19 Invalid_operation +addx6877 add -Inf +sNaN20 -> NaN20 Invalid_operation +addx6878 add -1000 sNaN21 -> NaN21 Invalid_operation +addx6879 add 1000 sNaN22 -> NaN22 Invalid_operation +addx6880 add Inf sNaN23 -> NaN23 Invalid_operation +addx6881 add +NaN25 +sNaN24 -> NaN24 Invalid_operation +addx6882 add -NaN26 NaN28 -> -NaN26 +addx6883 add -sNaN27 sNaN29 -> -NaN27 Invalid_operation +addx6884 add 1000 -NaN30 -> -NaN30 +addx6885 add 1000 -sNaN31 -> -NaN31 Invalid_operation + +-- now the case where we can get underflow but the result is normal +-- [note this can't happen if the operands are also bounded, as we +-- cannot represent 1E-399, for example] + +addx6571 add 1E-383 0 -> 1E-383 +addx6572 add 1E-384 0 -> 1E-384 Subnormal +addx6573 add 1E-383 1E-384 -> 1.1E-383 +addx6574 subtract 1E-383 1E-384 -> 9E-384 Subnormal + +-- Here we explore the boundary of rounding a subnormal to Nmin +addx6575 subtract 1E-383 1E-398 -> 9.99999999999999E-384 Subnormal +addx6576 subtract 1E-383 1E-398 -> 9.99999999999999E-384 Subnormal +addx6577 subtract 1E-383 1E-399 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +addx6578 subtract 1E-383 1E-400 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +addx6579 subtract 1E-383 1E-401 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +addx6580 subtract 1E-383 1E-402 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded + +-- check overflow edge case +-- 1234567890123456 +addx6972 apply 9.999999999999999E+384 -> 9.999999999999999E+384 +addx6973 add 9.999999999999999E+384 1 -> 9.999999999999999E+384 Inexact Rounded +addx6974 add 9999999999999999E+369 1 -> 9.999999999999999E+384 Inexact Rounded +addx6975 add 9999999999999999E+369 1E+369 -> Infinity Overflow Inexact Rounded +addx6976 add 9999999999999999E+369 9E+368 -> Infinity Overflow Inexact Rounded +addx6977 add 9999999999999999E+369 8E+368 -> Infinity Overflow Inexact Rounded +addx6978 add 9999999999999999E+369 7E+368 -> Infinity Overflow Inexact Rounded +addx6979 add 9999999999999999E+369 6E+368 -> Infinity Overflow Inexact Rounded +addx6980 add 9999999999999999E+369 5E+368 -> Infinity Overflow Inexact Rounded +addx6981 add 9999999999999999E+369 4E+368 -> 9.999999999999999E+384 Inexact Rounded +addx6982 add 9999999999999999E+369 3E+368 -> 9.999999999999999E+384 Inexact Rounded +addx6983 add 9999999999999999E+369 2E+368 -> 9.999999999999999E+384 Inexact Rounded +addx6984 add 9999999999999999E+369 1E+368 -> 9.999999999999999E+384 Inexact Rounded + +addx6985 apply -9.999999999999999E+384 -> -9.999999999999999E+384 +addx6986 add -9.999999999999999E+384 -1 -> -9.999999999999999E+384 Inexact Rounded +addx6987 add -9999999999999999E+369 -1 -> -9.999999999999999E+384 Inexact Rounded +addx6988 add -9999999999999999E+369 -1E+369 -> -Infinity Overflow Inexact Rounded +addx6989 add -9999999999999999E+369 -9E+368 -> -Infinity Overflow Inexact Rounded +addx6990 add -9999999999999999E+369 -8E+368 -> -Infinity Overflow Inexact Rounded +addx6991 add -9999999999999999E+369 -7E+368 -> -Infinity Overflow Inexact Rounded +addx6992 add -9999999999999999E+369 -6E+368 -> -Infinity Overflow Inexact Rounded +addx6993 add -9999999999999999E+369 -5E+368 -> -Infinity Overflow Inexact Rounded +addx6994 add -9999999999999999E+369 -4E+368 -> -9.999999999999999E+384 Inexact Rounded +addx6995 add -9999999999999999E+369 -3E+368 -> -9.999999999999999E+384 Inexact Rounded +addx6996 add -9999999999999999E+369 -2E+368 -> -9.999999999999999E+384 Inexact Rounded +addx6997 add -9999999999999999E+369 -1E+368 -> -9.999999999999999E+384 Inexact Rounded + +-- And for round down full and subnormal results +rounding: down +addx61100 add 1e+2 -1e-383 -> 99.99999999999999 Rounded Inexact +addx61101 add 1e+1 -1e-383 -> 9.999999999999999 Rounded Inexact +addx61103 add +1 -1e-383 -> 0.9999999999999999 Rounded Inexact +addx61104 add 1e-1 -1e-383 -> 0.09999999999999999 Rounded Inexact +addx61105 add 1e-2 -1e-383 -> 0.009999999999999999 Rounded Inexact +addx61106 add 1e-3 -1e-383 -> 0.0009999999999999999 Rounded Inexact +addx61107 add 1e-4 -1e-383 -> 0.00009999999999999999 Rounded Inexact +addx61108 add 1e-5 -1e-383 -> 0.000009999999999999999 Rounded Inexact +addx61109 add 1e-6 -1e-383 -> 9.999999999999999E-7 Rounded Inexact + +rounding: ceiling +addx61110 add -1e+2 +1e-383 -> -99.99999999999999 Rounded Inexact +addx61111 add -1e+1 +1e-383 -> -9.999999999999999 Rounded Inexact +addx61113 add -1 +1e-383 -> -0.9999999999999999 Rounded Inexact +addx61114 add -1e-1 +1e-383 -> -0.09999999999999999 Rounded Inexact +addx61115 add -1e-2 +1e-383 -> -0.009999999999999999 Rounded Inexact +addx61116 add -1e-3 +1e-383 -> -0.0009999999999999999 Rounded Inexact +addx61117 add -1e-4 +1e-383 -> -0.00009999999999999999 Rounded Inexact +addx61118 add -1e-5 +1e-383 -> -0.000009999999999999999 Rounded Inexact +addx61119 add -1e-6 +1e-383 -> -9.999999999999999E-7 Rounded Inexact + +-- tests based on Gunnar Degnbol's edge case +rounding: half_even + +addx61300 add 1E16 -0.5 -> 1.000000000000000E+16 Inexact Rounded +addx61310 add 1E16 -0.51 -> 9999999999999999 Inexact Rounded +addx61311 add 1E16 -0.501 -> 9999999999999999 Inexact Rounded +addx61312 add 1E16 -0.5001 -> 9999999999999999 Inexact Rounded +addx61313 add 1E16 -0.50001 -> 9999999999999999 Inexact Rounded +addx61314 add 1E16 -0.500001 -> 9999999999999999 Inexact Rounded +addx61315 add 1E16 -0.5000001 -> 9999999999999999 Inexact Rounded +addx61316 add 1E16 -0.50000001 -> 9999999999999999 Inexact Rounded +addx61317 add 1E16 -0.500000001 -> 9999999999999999 Inexact Rounded +addx61318 add 1E16 -0.5000000001 -> 9999999999999999 Inexact Rounded +addx61319 add 1E16 -0.50000000001 -> 9999999999999999 Inexact Rounded +addx61320 add 1E16 -0.500000000001 -> 9999999999999999 Inexact Rounded +addx61321 add 1E16 -0.5000000000001 -> 9999999999999999 Inexact Rounded +addx61322 add 1E16 -0.50000000000001 -> 9999999999999999 Inexact Rounded +addx61323 add 1E16 -0.500000000000001 -> 9999999999999999 Inexact Rounded +addx61324 add 1E16 -0.5000000000000001 -> 9999999999999999 Inexact Rounded +addx61325 add 1E16 -0.5000000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61326 add 1E16 -0.500000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61327 add 1E16 -0.50000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61328 add 1E16 -0.5000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61329 add 1E16 -0.500000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61330 add 1E16 -0.50000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61331 add 1E16 -0.5000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61332 add 1E16 -0.500000000 -> 1.000000000000000E+16 Inexact Rounded +addx61333 add 1E16 -0.50000000 -> 1.000000000000000E+16 Inexact Rounded +addx61334 add 1E16 -0.5000000 -> 1.000000000000000E+16 Inexact Rounded +addx61335 add 1E16 -0.500000 -> 1.000000000000000E+16 Inexact Rounded +addx61336 add 1E16 -0.50000 -> 1.000000000000000E+16 Inexact Rounded +addx61337 add 1E16 -0.5000 -> 1.000000000000000E+16 Inexact Rounded +addx61338 add 1E16 -0.500 -> 1.000000000000000E+16 Inexact Rounded +addx61339 add 1E16 -0.50 -> 1.000000000000000E+16 Inexact Rounded + +addx61340 add 1E16 -5000000.000010001 -> 9999999995000000 Inexact Rounded +addx61341 add 1E16 -5000000.000000001 -> 9999999995000000 Inexact Rounded + +addx61349 add 9999999999999999 0.4 -> 9999999999999999 Inexact Rounded +addx61350 add 9999999999999999 0.49 -> 9999999999999999 Inexact Rounded +addx61351 add 9999999999999999 0.499 -> 9999999999999999 Inexact Rounded +addx61352 add 9999999999999999 0.4999 -> 9999999999999999 Inexact Rounded +addx61353 add 9999999999999999 0.49999 -> 9999999999999999 Inexact Rounded +addx61354 add 9999999999999999 0.499999 -> 9999999999999999 Inexact Rounded +addx61355 add 9999999999999999 0.4999999 -> 9999999999999999 Inexact Rounded +addx61356 add 9999999999999999 0.49999999 -> 9999999999999999 Inexact Rounded +addx61357 add 9999999999999999 0.499999999 -> 9999999999999999 Inexact Rounded +addx61358 add 9999999999999999 0.4999999999 -> 9999999999999999 Inexact Rounded +addx61359 add 9999999999999999 0.49999999999 -> 9999999999999999 Inexact Rounded +addx61360 add 9999999999999999 0.499999999999 -> 9999999999999999 Inexact Rounded +addx61361 add 9999999999999999 0.4999999999999 -> 9999999999999999 Inexact Rounded +addx61362 add 9999999999999999 0.49999999999999 -> 9999999999999999 Inexact Rounded +addx61363 add 9999999999999999 0.499999999999999 -> 9999999999999999 Inexact Rounded +addx61364 add 9999999999999999 0.4999999999999999 -> 9999999999999999 Inexact Rounded +addx61365 add 9999999999999999 0.5000000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61367 add 9999999999999999 0.500000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61368 add 9999999999999999 0.50000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61369 add 9999999999999999 0.5000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61370 add 9999999999999999 0.500000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61371 add 9999999999999999 0.50000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61372 add 9999999999999999 0.5000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61373 add 9999999999999999 0.500000000 -> 1.000000000000000E+16 Inexact Rounded +addx61374 add 9999999999999999 0.50000000 -> 1.000000000000000E+16 Inexact Rounded +addx61375 add 9999999999999999 0.5000000 -> 1.000000000000000E+16 Inexact Rounded +addx61376 add 9999999999999999 0.500000 -> 1.000000000000000E+16 Inexact Rounded +addx61377 add 9999999999999999 0.50000 -> 1.000000000000000E+16 Inexact Rounded +addx61378 add 9999999999999999 0.5000 -> 1.000000000000000E+16 Inexact Rounded +addx61379 add 9999999999999999 0.500 -> 1.000000000000000E+16 Inexact Rounded +addx61380 add 9999999999999999 0.50 -> 1.000000000000000E+16 Inexact Rounded +addx61381 add 9999999999999999 0.5 -> 1.000000000000000E+16 Inexact Rounded +addx61382 add 9999999999999999 0.5000000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61383 add 9999999999999999 0.500000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61384 add 9999999999999999 0.50000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61385 add 9999999999999999 0.5000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61386 add 9999999999999999 0.500000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61387 add 9999999999999999 0.50000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61388 add 9999999999999999 0.5000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61389 add 9999999999999999 0.500000001 -> 1.000000000000000E+16 Inexact Rounded +addx61390 add 9999999999999999 0.50000001 -> 1.000000000000000E+16 Inexact Rounded +addx61391 add 9999999999999999 0.5000001 -> 1.000000000000000E+16 Inexact Rounded +addx61392 add 9999999999999999 0.500001 -> 1.000000000000000E+16 Inexact Rounded +addx61393 add 9999999999999999 0.50001 -> 1.000000000000000E+16 Inexact Rounded +addx61394 add 9999999999999999 0.5001 -> 1.000000000000000E+16 Inexact Rounded +addx61395 add 9999999999999999 0.501 -> 1.000000000000000E+16 Inexact Rounded +addx61396 add 9999999999999999 0.51 -> 1.000000000000000E+16 Inexact Rounded + +-- More GD edge cases, where difference between the unadjusted +-- exponents is larger than the maximum precision and one side is 0 +addx61420 add 0 1.123456789012345 -> 1.123456789012345 +addx61421 add 0 1.123456789012345E-1 -> 0.1123456789012345 +addx61422 add 0 1.123456789012345E-2 -> 0.01123456789012345 +addx61423 add 0 1.123456789012345E-3 -> 0.001123456789012345 +addx61424 add 0 1.123456789012345E-4 -> 0.0001123456789012345 +addx61425 add 0 1.123456789012345E-5 -> 0.00001123456789012345 +addx61426 add 0 1.123456789012345E-6 -> 0.000001123456789012345 +addx61427 add 0 1.123456789012345E-7 -> 1.123456789012345E-7 +addx61428 add 0 1.123456789012345E-8 -> 1.123456789012345E-8 +addx61429 add 0 1.123456789012345E-9 -> 1.123456789012345E-9 +addx61430 add 0 1.123456789012345E-10 -> 1.123456789012345E-10 +addx61431 add 0 1.123456789012345E-11 -> 1.123456789012345E-11 +addx61432 add 0 1.123456789012345E-12 -> 1.123456789012345E-12 +addx61433 add 0 1.123456789012345E-13 -> 1.123456789012345E-13 +addx61434 add 0 1.123456789012345E-14 -> 1.123456789012345E-14 +addx61435 add 0 1.123456789012345E-15 -> 1.123456789012345E-15 +addx61436 add 0 1.123456789012345E-16 -> 1.123456789012345E-16 +addx61437 add 0 1.123456789012345E-17 -> 1.123456789012345E-17 +addx61438 add 0 1.123456789012345E-18 -> 1.123456789012345E-18 +addx61439 add 0 1.123456789012345E-19 -> 1.123456789012345E-19 + +-- same, reversed 0 +addx61440 add 1.123456789012345 0 -> 1.123456789012345 +addx61441 add 1.123456789012345E-1 0 -> 0.1123456789012345 +addx61442 add 1.123456789012345E-2 0 -> 0.01123456789012345 +addx61443 add 1.123456789012345E-3 0 -> 0.001123456789012345 +addx61444 add 1.123456789012345E-4 0 -> 0.0001123456789012345 +addx61445 add 1.123456789012345E-5 0 -> 0.00001123456789012345 +addx61446 add 1.123456789012345E-6 0 -> 0.000001123456789012345 +addx61447 add 1.123456789012345E-7 0 -> 1.123456789012345E-7 +addx61448 add 1.123456789012345E-8 0 -> 1.123456789012345E-8 +addx61449 add 1.123456789012345E-9 0 -> 1.123456789012345E-9 +addx61450 add 1.123456789012345E-10 0 -> 1.123456789012345E-10 +addx61451 add 1.123456789012345E-11 0 -> 1.123456789012345E-11 +addx61452 add 1.123456789012345E-12 0 -> 1.123456789012345E-12 +addx61453 add 1.123456789012345E-13 0 -> 1.123456789012345E-13 +addx61454 add 1.123456789012345E-14 0 -> 1.123456789012345E-14 +addx61455 add 1.123456789012345E-15 0 -> 1.123456789012345E-15 +addx61456 add 1.123456789012345E-16 0 -> 1.123456789012345E-16 +addx61457 add 1.123456789012345E-17 0 -> 1.123456789012345E-17 +addx61458 add 1.123456789012345E-18 0 -> 1.123456789012345E-18 +addx61459 add 1.123456789012345E-19 0 -> 1.123456789012345E-19 + +-- same, Es on the 0 +addx61460 add 1.123456789012345 0E-0 -> 1.123456789012345 +addx61461 add 1.123456789012345 0E-1 -> 1.123456789012345 +addx61462 add 1.123456789012345 0E-2 -> 1.123456789012345 +addx61463 add 1.123456789012345 0E-3 -> 1.123456789012345 +addx61464 add 1.123456789012345 0E-4 -> 1.123456789012345 +addx61465 add 1.123456789012345 0E-5 -> 1.123456789012345 +addx61466 add 1.123456789012345 0E-6 -> 1.123456789012345 +addx61467 add 1.123456789012345 0E-7 -> 1.123456789012345 +addx61468 add 1.123456789012345 0E-8 -> 1.123456789012345 +addx61469 add 1.123456789012345 0E-9 -> 1.123456789012345 +addx61470 add 1.123456789012345 0E-10 -> 1.123456789012345 +addx61471 add 1.123456789012345 0E-11 -> 1.123456789012345 +addx61472 add 1.123456789012345 0E-12 -> 1.123456789012345 +addx61473 add 1.123456789012345 0E-13 -> 1.123456789012345 +addx61474 add 1.123456789012345 0E-14 -> 1.123456789012345 +addx61475 add 1.123456789012345 0E-15 -> 1.123456789012345 +-- next four flag Rounded because the 0 extends the result +addx61476 add 1.123456789012345 0E-16 -> 1.123456789012345 Rounded +addx61477 add 1.123456789012345 0E-17 -> 1.123456789012345 Rounded +addx61478 add 1.123456789012345 0E-18 -> 1.123456789012345 Rounded +addx61479 add 1.123456789012345 0E-19 -> 1.123456789012345 Rounded + +-- sum of two opposite-sign operands is exactly 0 and floor => -0 +rounding: half_up +-- exact zeros from zeros +addx61500 add 0 0E-19 -> 0E-19 +addx61501 add -0 0E-19 -> 0E-19 +addx61502 add 0 -0E-19 -> 0E-19 +addx61503 add -0 -0E-19 -> -0E-19 +addx61504 add 0E-400 0E-19 -> 0E-398 Clamped +addx61505 add -0E-400 0E-19 -> 0E-398 Clamped +addx61506 add 0E-400 -0E-19 -> 0E-398 Clamped +addx61507 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61511 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61512 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61513 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61514 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx61515 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61516 add -1E-401 1E-401 -> 0E-398 Clamped +addx61517 add 1E-401 -1E-401 -> 0E-398 Clamped +addx61518 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: half_down +-- exact zeros from zeros +addx61520 add 0 0E-19 -> 0E-19 +addx61521 add -0 0E-19 -> 0E-19 +addx61522 add 0 -0E-19 -> 0E-19 +addx61523 add -0 -0E-19 -> -0E-19 +addx61524 add 0E-400 0E-19 -> 0E-398 Clamped +addx61525 add -0E-400 0E-19 -> 0E-398 Clamped +addx61526 add 0E-400 -0E-19 -> 0E-398 Clamped +addx61527 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61531 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61532 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61533 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61534 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx61535 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61536 add -1E-401 1E-401 -> 0E-398 Clamped +addx61537 add 1E-401 -1E-401 -> 0E-398 Clamped +addx61538 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: half_even +-- exact zeros from zeros +addx61540 add 0 0E-19 -> 0E-19 +addx61541 add -0 0E-19 -> 0E-19 +addx61542 add 0 -0E-19 -> 0E-19 +addx61543 add -0 -0E-19 -> -0E-19 +addx61544 add 0E-400 0E-19 -> 0E-398 Clamped +addx61545 add -0E-400 0E-19 -> 0E-398 Clamped +addx61546 add 0E-400 -0E-19 -> 0E-398 Clamped +addx61547 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61551 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61552 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61553 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61554 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx61555 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61556 add -1E-401 1E-401 -> 0E-398 Clamped +addx61557 add 1E-401 -1E-401 -> 0E-398 Clamped +addx61558 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: up +-- exact zeros from zeros +addx61560 add 0 0E-19 -> 0E-19 +addx61561 add -0 0E-19 -> 0E-19 +addx61562 add 0 -0E-19 -> 0E-19 +addx61563 add -0 -0E-19 -> -0E-19 +addx61564 add 0E-400 0E-19 -> 0E-398 Clamped +addx61565 add -0E-400 0E-19 -> 0E-398 Clamped +addx61566 add 0E-400 -0E-19 -> 0E-398 Clamped +addx61567 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61571 add 1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx61572 add -1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx61573 add 1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +addx61574 add -1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +-- some exact zeros from non-zeros +addx61575 add 1E-401 1E-401 -> 1E-398 Subnormal Inexact Rounded Underflow +addx61576 add -1E-401 1E-401 -> 0E-398 Clamped +addx61577 add 1E-401 -1E-401 -> 0E-398 Clamped +addx61578 add -1E-401 -1E-401 -> -1E-398 Subnormal Inexact Rounded Underflow + +rounding: down +-- exact zeros from zeros +addx61580 add 0 0E-19 -> 0E-19 +addx61581 add -0 0E-19 -> 0E-19 +addx61582 add 0 -0E-19 -> 0E-19 +addx61583 add -0 -0E-19 -> -0E-19 +addx61584 add 0E-400 0E-19 -> 0E-398 Clamped +addx61585 add -0E-400 0E-19 -> 0E-398 Clamped +addx61586 add 0E-400 -0E-19 -> 0E-398 Clamped +addx61587 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61591 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61592 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61593 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61594 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx61595 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61596 add -1E-401 1E-401 -> 0E-398 Clamped +addx61597 add 1E-401 -1E-401 -> 0E-398 Clamped +addx61598 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: ceiling +-- exact zeros from zeros +addx61600 add 0 0E-19 -> 0E-19 +addx61601 add -0 0E-19 -> 0E-19 +addx61602 add 0 -0E-19 -> 0E-19 +addx61603 add -0 -0E-19 -> -0E-19 +addx61604 add 0E-400 0E-19 -> 0E-398 Clamped +addx61605 add -0E-400 0E-19 -> 0E-398 Clamped +addx61606 add 0E-400 -0E-19 -> 0E-398 Clamped +addx61607 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61611 add 1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx61612 add -1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx61613 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61614 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx61615 add 1E-401 1E-401 -> 1E-398 Subnormal Inexact Rounded Underflow +addx61616 add -1E-401 1E-401 -> 0E-398 Clamped +addx61617 add 1E-401 -1E-401 -> 0E-398 Clamped +addx61618 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +-- and the extra-special ugly case; unusual minuses marked by -- * +rounding: floor +-- exact zeros from zeros +addx61620 add 0 0E-19 -> 0E-19 +addx61621 add -0 0E-19 -> -0E-19 -- * +addx61622 add 0 -0E-19 -> -0E-19 -- * +addx61623 add -0 -0E-19 -> -0E-19 +addx61624 add 0E-400 0E-19 -> 0E-398 Clamped +addx61625 add -0E-400 0E-19 -> -0E-398 Clamped -- * +addx61626 add 0E-400 -0E-19 -> -0E-398 Clamped -- * +addx61627 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61631 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61632 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61633 add 1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +addx61634 add -1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +-- some exact zeros from non-zeros +addx61635 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61636 add -1E-401 1E-401 -> -0E-398 Clamped -- * +addx61637 add 1E-401 -1E-401 -> -0E-398 Clamped -- * +addx61638 add -1E-401 -1E-401 -> -1E-398 Subnormal Inexact Rounded Underflow + +-- Examples from SQL proposal (Krishna Kulkarni) +addx61701 add 130E-2 120E-2 -> 2.50 +addx61702 add 130E-2 12E-1 -> 2.50 +addx61703 add 130E-2 1E0 -> 2.30 +addx61704 add 1E2 1E4 -> 1.01E+4 +addx61705 subtract 130E-2 120E-2 -> 0.10 +addx61706 subtract 130E-2 12E-1 -> 0.10 +addx61707 subtract 130E-2 1E0 -> 0.30 +addx61708 subtract 1E2 1E4 -> -9.9E+3 + +-- Gappy coefficients; check residue handling even with full coefficient gap +rounding: half_even + +addx62001 add 1234567890123456 1 -> 1234567890123457 +addx62002 add 1234567890123456 0.6 -> 1234567890123457 Inexact Rounded +addx62003 add 1234567890123456 0.06 -> 1234567890123456 Inexact Rounded +addx62004 add 1234567890123456 6E-3 -> 1234567890123456 Inexact Rounded +addx62005 add 1234567890123456 6E-4 -> 1234567890123456 Inexact Rounded +addx62006 add 1234567890123456 6E-5 -> 1234567890123456 Inexact Rounded +addx62007 add 1234567890123456 6E-6 -> 1234567890123456 Inexact Rounded +addx62008 add 1234567890123456 6E-7 -> 1234567890123456 Inexact Rounded +addx62009 add 1234567890123456 6E-8 -> 1234567890123456 Inexact Rounded +addx62010 add 1234567890123456 6E-9 -> 1234567890123456 Inexact Rounded +addx62011 add 1234567890123456 6E-10 -> 1234567890123456 Inexact Rounded +addx62012 add 1234567890123456 6E-11 -> 1234567890123456 Inexact Rounded +addx62013 add 1234567890123456 6E-12 -> 1234567890123456 Inexact Rounded +addx62014 add 1234567890123456 6E-13 -> 1234567890123456 Inexact Rounded +addx62015 add 1234567890123456 6E-14 -> 1234567890123456 Inexact Rounded +addx62016 add 1234567890123456 6E-15 -> 1234567890123456 Inexact Rounded +addx62017 add 1234567890123456 6E-16 -> 1234567890123456 Inexact Rounded +addx62018 add 1234567890123456 6E-17 -> 1234567890123456 Inexact Rounded +addx62019 add 1234567890123456 6E-18 -> 1234567890123456 Inexact Rounded +addx62020 add 1234567890123456 6E-19 -> 1234567890123456 Inexact Rounded +addx62021 add 1234567890123456 6E-20 -> 1234567890123456 Inexact Rounded + +-- widening second argument at gap +addx62030 add 12345678 1 -> 12345679 +addx62031 add 12345678 0.1 -> 12345678.1 +addx62032 add 12345678 0.12 -> 12345678.12 +addx62033 add 12345678 0.123 -> 12345678.123 +addx62034 add 12345678 0.1234 -> 12345678.1234 +addx62035 add 12345678 0.12345 -> 12345678.12345 +addx62036 add 12345678 0.123456 -> 12345678.123456 +addx62037 add 12345678 0.1234567 -> 12345678.1234567 +addx62038 add 12345678 0.12345678 -> 12345678.12345678 +addx62039 add 12345678 0.123456789 -> 12345678.12345679 Inexact Rounded +addx62040 add 12345678 0.123456785 -> 12345678.12345678 Inexact Rounded +addx62041 add 12345678 0.1234567850 -> 12345678.12345678 Inexact Rounded +addx62042 add 12345678 0.1234567851 -> 12345678.12345679 Inexact Rounded +addx62043 add 12345678 0.12345678501 -> 12345678.12345679 Inexact Rounded +addx62044 add 12345678 0.123456785001 -> 12345678.12345679 Inexact Rounded +addx62045 add 12345678 0.1234567850001 -> 12345678.12345679 Inexact Rounded +addx62046 add 12345678 0.12345678500001 -> 12345678.12345679 Inexact Rounded +addx62047 add 12345678 0.123456785000001 -> 12345678.12345679 Inexact Rounded +addx62048 add 12345678 0.1234567850000001 -> 12345678.12345679 Inexact Rounded +addx62049 add 12345678 0.1234567850000000 -> 12345678.12345678 Inexact Rounded +-- 90123456 +rounding: half_even +addx62050 add 12345678 0.0234567750000000 -> 12345678.02345678 Inexact Rounded +addx62051 add 12345678 0.0034567750000000 -> 12345678.00345678 Inexact Rounded +addx62052 add 12345678 0.0004567750000000 -> 12345678.00045678 Inexact Rounded +addx62053 add 12345678 0.0000567750000000 -> 12345678.00005678 Inexact Rounded +addx62054 add 12345678 0.0000067750000000 -> 12345678.00000678 Inexact Rounded +addx62055 add 12345678 0.0000007750000000 -> 12345678.00000078 Inexact Rounded +addx62056 add 12345678 0.0000000750000000 -> 12345678.00000008 Inexact Rounded +addx62057 add 12345678 0.0000000050000000 -> 12345678.00000000 Inexact Rounded +addx62060 add 12345678 0.0234567750000001 -> 12345678.02345678 Inexact Rounded +addx62061 add 12345678 0.0034567750000001 -> 12345678.00345678 Inexact Rounded +addx62062 add 12345678 0.0004567750000001 -> 12345678.00045678 Inexact Rounded +addx62063 add 12345678 0.0000567750000001 -> 12345678.00005678 Inexact Rounded +addx62064 add 12345678 0.0000067750000001 -> 12345678.00000678 Inexact Rounded +addx62065 add 12345678 0.0000007750000001 -> 12345678.00000078 Inexact Rounded +addx62066 add 12345678 0.0000000750000001 -> 12345678.00000008 Inexact Rounded +addx62067 add 12345678 0.0000000050000001 -> 12345678.00000001 Inexact Rounded +-- far-out residues (full coefficient gap is 16+15 digits) +rounding: up +addx62070 add 12345678 1E-8 -> 12345678.00000001 +addx62071 add 12345678 1E-9 -> 12345678.00000001 Inexact Rounded +addx62072 add 12345678 1E-10 -> 12345678.00000001 Inexact Rounded +addx62073 add 12345678 1E-11 -> 12345678.00000001 Inexact Rounded +addx62074 add 12345678 1E-12 -> 12345678.00000001 Inexact Rounded +addx62075 add 12345678 1E-13 -> 12345678.00000001 Inexact Rounded +addx62076 add 12345678 1E-14 -> 12345678.00000001 Inexact Rounded +addx62077 add 12345678 1E-15 -> 12345678.00000001 Inexact Rounded +addx62078 add 12345678 1E-16 -> 12345678.00000001 Inexact Rounded +addx62079 add 12345678 1E-17 -> 12345678.00000001 Inexact Rounded +addx62080 add 12345678 1E-18 -> 12345678.00000001 Inexact Rounded +addx62081 add 12345678 1E-19 -> 12345678.00000001 Inexact Rounded +addx62082 add 12345678 1E-20 -> 12345678.00000001 Inexact Rounded +addx62083 add 12345678 1E-25 -> 12345678.00000001 Inexact Rounded +addx62084 add 12345678 1E-30 -> 12345678.00000001 Inexact Rounded +addx62085 add 12345678 1E-31 -> 12345678.00000001 Inexact Rounded +addx62086 add 12345678 1E-32 -> 12345678.00000001 Inexact Rounded +addx62087 add 12345678 1E-33 -> 12345678.00000001 Inexact Rounded +addx62088 add 12345678 1E-34 -> 12345678.00000001 Inexact Rounded +addx62089 add 12345678 1E-35 -> 12345678.00000001 Inexact Rounded + +-- payload decapitate +precision: 5 +addx62100 add 11 sNaN123456789 -> NaN56789 Invalid_operation +addx62101 add -11 -sNaN123456789 -> -NaN56789 Invalid_operation +addx62102 add 11 NaN123456789 -> NaN56789 +addx62103 add -11 -NaN123456789 -> -NaN56789 -- Null tests addx9990 add 10 # -> NaN Invalid_operation Modified: python/branches/py3k/Lib/test/decimaltestdata/base.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/base.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/base.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- base.decTest -- base decimal <--> string conversions -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,8 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 +extended: 1 -- This file tests base conversions from string to a decimal number -- and back to a string (in either Scientific or Engineering form) @@ -26,11 +27,10 @@ -- to conform to emax and precision settings (that is, numbers will -- conform to rules and exponent will be in permitted range). -precision: 15 +precision: 16 rounding: half_up -maxExponent: 999999999 -minExponent: -999999999 -extended: 1 +maxExponent: 384 +minExponent: -383 basx001 toSci 0 -> 0 basx002 toSci 1 -> 1 @@ -73,41 +73,62 @@ -- String [many more examples are implicitly tested elsewhere] -- strings without E cannot generate E in result -basx100 toSci "12" -> '12' -basx101 toSci "-76" -> '-76' -basx102 toSci "12.76" -> '12.76' -basx103 toSci "+12.76" -> '12.76' -basx104 toSci "012.76" -> '12.76' -basx105 toSci "+0.003" -> '0.003' -basx106 toSci "17." -> '17' -basx107 toSci ".5" -> '0.5' -basx108 toSci "044" -> '44' -basx109 toSci "0044" -> '44' -basx110 toSci "0.0005" -> '0.0005' -basx111 toSci "00.00005" -> '0.00005' -basx112 toSci "0.000005" -> '0.000005' -basx113 toSci "0.0000050" -> '0.0000050' -basx114 toSci "0.0000005" -> '5E-7' -basx115 toSci "0.00000005" -> '5E-8' -basx116 toSci "12345678.543210" -> '12345678.543210' -basx117 toSci "2345678.543210" -> '2345678.543210' -basx118 toSci "345678.543210" -> '345678.543210' -basx119 toSci "0345678.54321" -> '345678.54321' -basx120 toSci "345678.5432" -> '345678.5432' -basx121 toSci "+345678.5432" -> '345678.5432' -basx122 toSci "+0345678.5432" -> '345678.5432' -basx123 toSci "+00345678.5432" -> '345678.5432' -basx124 toSci "-345678.5432" -> '-345678.5432' -basx125 toSci "-0345678.5432" -> '-345678.5432' -basx126 toSci "-00345678.5432" -> '-345678.5432' +basx040 toSci "12" -> '12' +basx041 toSci "-76" -> '-76' +basx042 toSci "12.76" -> '12.76' +basx043 toSci "+12.76" -> '12.76' +basx044 toSci "012.76" -> '12.76' +basx045 toSci "+0.003" -> '0.003' +basx046 toSci "17." -> '17' +basx047 toSci ".5" -> '0.5' +basx048 toSci "044" -> '44' +basx049 toSci "0044" -> '44' +basx050 toSci "0.0005" -> '0.0005' +basx051 toSci "00.00005" -> '0.00005' +basx052 toSci "0.000005" -> '0.000005' +basx053 toSci "0.0000050" -> '0.0000050' +basx054 toSci "0.0000005" -> '5E-7' +basx055 toSci "0.00000005" -> '5E-8' +basx056 toSci "12345678.543210" -> '12345678.543210' +basx057 toSci "2345678.543210" -> '2345678.543210' +basx058 toSci "345678.543210" -> '345678.543210' +basx059 toSci "0345678.54321" -> '345678.54321' +basx060 toSci "345678.5432" -> '345678.5432' +basx061 toSci "+345678.5432" -> '345678.5432' +basx062 toSci "+0345678.5432" -> '345678.5432' +basx063 toSci "+00345678.5432" -> '345678.5432' +basx064 toSci "-345678.5432" -> '-345678.5432' +basx065 toSci "-0345678.5432" -> '-345678.5432' +basx066 toSci "-00345678.5432" -> '-345678.5432' -- examples -basx127 toSci "5E-6" -> '0.000005' -basx128 toSci "50E-7" -> '0.0000050' -basx129 toSci "5E-7" -> '5E-7' - +basx067 toSci "5E-6" -> '0.000005' +basx068 toSci "50E-7" -> '0.0000050' +basx069 toSci "5E-7" -> '5E-7' -- [No exotics as no Unicode] +-- rounded with dots in all (including edge) places +basx071 toSci .1234567890123456123 -> 0.1234567890123456 Inexact Rounded +basx072 toSci 1.234567890123456123 -> 1.234567890123456 Inexact Rounded +basx073 toSci 12.34567890123456123 -> 12.34567890123456 Inexact Rounded +basx074 toSci 123.4567890123456123 -> 123.4567890123456 Inexact Rounded +basx075 toSci 1234.567890123456123 -> 1234.567890123456 Inexact Rounded +basx076 toSci 12345.67890123456123 -> 12345.67890123456 Inexact Rounded +basx077 toSci 123456.7890123456123 -> 123456.7890123456 Inexact Rounded +basx078 toSci 1234567.890123456123 -> 1234567.890123456 Inexact Rounded +basx079 toSci 12345678.90123456123 -> 12345678.90123456 Inexact Rounded +basx080 toSci 123456789.0123456123 -> 123456789.0123456 Inexact Rounded +basx081 toSci 1234567890.123456123 -> 1234567890.123456 Inexact Rounded +basx082 toSci 12345678901.23456123 -> 12345678901.23456 Inexact Rounded +basx083 toSci 123456789012.3456123 -> 123456789012.3456 Inexact Rounded +basx084 toSci 1234567890123.456123 -> 1234567890123.456 Inexact Rounded +basx085 toSci 12345678901234.56123 -> 12345678901234.56 Inexact Rounded +basx086 toSci 123456789012345.6123 -> 123456789012345.6 Inexact Rounded +basx087 toSci 1234567890123456.123 -> 1234567890123456 Inexact Rounded +basx088 toSci 12345678901234561.23 -> 1.234567890123456E+16 Inexact Rounded +basx089 toSci 123456789012345612.3 -> 1.234567890123456E+17 Inexact Rounded +basx090 toSci 1234567890123456123. -> 1.234567890123456E+18 Inexact Rounded + -- Numbers with E basx130 toSci "0.000E-1" -> '0.0000' basx131 toSci "0.000E-2" -> '0.00000' @@ -225,21 +246,6 @@ basx262 toSci "0.1265E+8" -> '1.265E+7' basx263 toSci "0.1265E+20" -> '1.265E+19' -basx270 toSci "0.09e999" -> '9E+997' -basx271 toSci "0.9e999" -> '9E+998' -basx272 toSci "9e999" -> '9E+999' -basx273 toSci "9.9e999" -> '9.9E+999' -basx274 toSci "9.99e999" -> '9.99E+999' -basx275 toSci "9.99e-999" -> '9.99E-999' -basx276 toSci "9.9e-999" -> '9.9E-999' -basx277 toSci "9e-999" -> '9E-999' -basx279 toSci "99e-999" -> '9.9E-998' -basx280 toSci "999e-999" -> '9.99E-997' -basx281 toSci '0.9e-998' -> '9E-999' -basx282 toSci '0.09e-997' -> '9E-999' -basx283 toSci '0.1e1000' -> '1E+999' -basx284 toSci '10e-1000' -> '1.0E-999' - -- some more negative zeros [systematic tests below] basx290 toSci "-0.000E-1" -> '-0.0000' basx291 toSci "-0.000E-2" -> '-0.00000' @@ -418,6 +424,22 @@ basx474 toSci 1000000009000 -> 1.00000001E+12 Rounded Inexact basx475 toEng 1000000009000 -> 1.00000001E+12 Rounded Inexact +-- all-nines rounding +precision: 9 +rounding: half_up +basx270 toSci 999999999 -> 999999999 +basx271 toSci 9999999990 -> 9.99999999E+9 Rounded +basx272 toSci 9999999991 -> 9.99999999E+9 Rounded Inexact +basx273 toSci 9999999992 -> 9.99999999E+9 Rounded Inexact +basx274 toSci 9999999993 -> 9.99999999E+9 Rounded Inexact +basx275 toSci 9999999994 -> 9.99999999E+9 Rounded Inexact +basx276 toSci 9999999995 -> 1.00000000E+10 Rounded Inexact +basx277 toSci 9999999996 -> 1.00000000E+10 Rounded Inexact +basx278 toSci 9999999997 -> 1.00000000E+10 Rounded Inexact +basx279 toSci 9999999998 -> 1.00000000E+10 Rounded Inexact +basx280 toSci 9999999999 -> 1.00000000E+10 Rounded Inexact +basx281 toSci 9999999999999999 -> 1.00000000E+16 Rounded Inexact + -- check rounding modes heeded precision: 5 rounding: ceiling @@ -425,11 +447,11 @@ bsrx402 toSci 1.234549 -> 1.2346 Rounded Inexact bsrx403 toSci 1.234550 -> 1.2346 Rounded Inexact bsrx404 toSci 1.234551 -> 1.2346 Rounded Inexact -rounding: down +rounding: up bsrx405 toSci 1.23450 -> 1.2345 Rounded -bsrx406 toSci 1.234549 -> 1.2345 Rounded Inexact -bsrx407 toSci 1.234550 -> 1.2345 Rounded Inexact -bsrx408 toSci 1.234551 -> 1.2345 Rounded Inexact +bsrx406 toSci 1.234549 -> 1.2346 Rounded Inexact +bsrx407 toSci 1.234550 -> 1.2346 Rounded Inexact +bsrx408 toSci 1.234551 -> 1.2346 Rounded Inexact rounding: floor bsrx410 toSci 1.23450 -> 1.2345 Rounded bsrx411 toSci 1.234549 -> 1.2345 Rounded Inexact @@ -464,11 +486,11 @@ bsrx502 toSci -1.234549 -> -1.2345 Rounded Inexact bsrx503 toSci -1.234550 -> -1.2345 Rounded Inexact bsrx504 toSci -1.234551 -> -1.2345 Rounded Inexact -rounding: down +rounding: up bsrx505 toSci -1.23450 -> -1.2345 Rounded -bsrx506 toSci -1.234549 -> -1.2345 Rounded Inexact -bsrx507 toSci -1.234550 -> -1.2345 Rounded Inexact -bsrx508 toSci -1.234551 -> -1.2345 Rounded Inexact +bsrx506 toSci -1.234549 -> -1.2346 Rounded Inexact +bsrx507 toSci -1.234550 -> -1.2346 Rounded Inexact +bsrx508 toSci -1.234551 -> -1.2346 Rounded Inexact rounding: floor bsrx510 toSci -1.23450 -> -1.2345 Rounded bsrx511 toSci -1.234549 -> -1.2346 Rounded Inexact @@ -498,6 +520,24 @@ bsrx534 toSci -1.234650 -> -1.2347 Rounded Inexact bsrx535 toSci -1.234551 -> -1.2346 Rounded Inexact +-- a few larger exponents +maxExponent: 999999999 +minExponent: -999999999 +basx480 toSci "0.09e999" -> '9E+997' +basx481 toSci "0.9e999" -> '9E+998' +basx482 toSci "9e999" -> '9E+999' +basx483 toSci "9.9e999" -> '9.9E+999' +basx484 toSci "9.99e999" -> '9.99E+999' +basx485 toSci "9.99e-999" -> '9.99E-999' +basx486 toSci "9.9e-999" -> '9.9E-999' +basx487 toSci "9e-999" -> '9E-999' +basx489 toSci "99e-999" -> '9.9E-998' +basx490 toSci "999e-999" -> '9.99E-997' +basx491 toSci '0.9e-998' -> '9E-999' +basx492 toSci '0.09e-997' -> '9E-999' +basx493 toSci '0.1e1000' -> '1E+999' +basx494 toSci '10e-1000' -> '1.0E-999' + rounding: half_up precision: 9 @@ -580,32 +620,23 @@ basx574 toSci "xNaN" -> NaN Conversion_syntax basx575 toSci "0sNaN" -> NaN Conversion_syntax --- subnormals and overflows -basx576 toSci '99e999999999' -> Infinity Overflow Inexact Rounded -basx577 toSci '999e999999999' -> Infinity Overflow Inexact Rounded -basx578 toSci '0.9e-999999999' -> 9E-1000000000 Subnormal -basx579 toSci '0.09e-999999999' -> 9E-1000000001 Subnormal -basx580 toSci '0.1e1000000000' -> 1E+999999999 -basx581 toSci '10e-1000000000' -> 1.0E-999999999 -basx582 toSci '0.9e9999999999' -> Infinity Overflow Inexact Rounded -basx583 toSci '99e-9999999999' -> 0E-1000000007 Underflow Subnormal Inexact Rounded -basx584 toSci '111e9999999999' -> Infinity Overflow Inexact Rounded -basx585 toSci '1111e-9999999999' -> 0E-1000000007 Underflow Subnormal Inexact Rounded -basx586 toSci '1111e-99999999999' -> 0E-1000000007 Underflow Subnormal Inexact Rounded -basx587 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded --- negatives the same -basx588 toSci '-99e999999999' -> -Infinity Overflow Inexact Rounded -basx589 toSci '-999e999999999' -> -Infinity Overflow Inexact Rounded -basx590 toSci '-0.9e-999999999' -> -9E-1000000000 Subnormal -basx591 toSci '-0.09e-999999999' -> -9E-1000000001 Subnormal -basx592 toSci '-0.1e1000000000' -> -1E+999999999 -basx593 toSci '-10e-1000000000' -> -1.0E-999999999 -basx594 toSci '-0.9e9999999999' -> -Infinity Overflow Inexact Rounded -basx595 toSci '-99e-9999999999' -> -0E-1000000007 Underflow Subnormal Inexact Rounded -basx596 toSci '-111e9999999999' -> -Infinity Overflow Inexact Rounded -basx597 toSci '-1111e-9999999999' -> -0E-1000000007 Underflow Subnormal Inexact Rounded -basx598 toSci '-1111e-99999999999' -> -0E-1000000007 Underflow Subnormal Inexact Rounded -basx599 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded +-- some baddies with dots and Es and dots and specials +basx576 toSci 'e+1' -> NaN Conversion_syntax +basx577 toSci '.e+1' -> NaN Conversion_syntax +basx578 toSci '+.e+1' -> NaN Conversion_syntax +basx579 toSci '-.e+' -> NaN Conversion_syntax +basx580 toSci '-.e' -> NaN Conversion_syntax +basx581 toSci 'E+1' -> NaN Conversion_syntax +basx582 toSci '.E+1' -> NaN Conversion_syntax +basx583 toSci '+.E+1' -> NaN Conversion_syntax +basx584 toSci '-.E+' -> NaN Conversion_syntax +basx585 toSci '-.E' -> NaN Conversion_syntax + +basx586 toSci '.NaN' -> NaN Conversion_syntax +basx587 toSci '-.NaN' -> NaN Conversion_syntax +basx588 toSci '+.sNaN' -> NaN Conversion_syntax +basx589 toSci '+.Inf' -> NaN Conversion_syntax +basx590 toSci '.Infinity' -> NaN Conversion_syntax -- Zeros basx601 toSci 0.000000000 -> 0E-9 @@ -686,6 +717,17 @@ basx678 toSci 0.00E-8 -> 0E-10 basx679 toSci 0.00E-9 -> 0E-11 +basx680 toSci 000000. -> 0 +basx681 toSci 00000. -> 0 +basx682 toSci 0000. -> 0 +basx683 toSci 000. -> 0 +basx684 toSci 00. -> 0 +basx685 toSci 0. -> 0 +basx686 toSci +00000. -> 0 +basx687 toSci -00000. -> -0 +basx688 toSci +0. -> 0 +basx689 toSci -0. -> -0 + -- Specials precision: 4 basx700 toSci "NaN" -> NaN @@ -868,6 +910,62 @@ basx878 toEng 0.00E-8 -> 0.0E-9 basx879 toEng 0.00E-9 -> 0.00E-9 + +rounding: half_up +precision: 9 +-- subnormals and overflows +basx906 toSci '99e999999999' -> Infinity Overflow Inexact Rounded +basx907 toSci '999e999999999' -> Infinity Overflow Inexact Rounded +basx908 toSci '0.9e-999999999' -> 9E-1000000000 Subnormal +basx909 toSci '0.09e-999999999' -> 9E-1000000001 Subnormal +basx910 toSci '0.1e1000000000' -> 1E+999999999 +basx911 toSci '10e-1000000000' -> 1.0E-999999999 +basx912 toSci '0.9e9999999999' -> Infinity Overflow Inexact Rounded +basx913 toSci '99e-9999999999' -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +basx914 toSci '111e9999999999' -> Infinity Overflow Inexact Rounded +basx915 toSci '1111e-9999999999' -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +basx916 toSci '1111e-99999999999' -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +basx917 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded +-- negatives the same +basx918 toSci '-99e999999999' -> -Infinity Overflow Inexact Rounded +basx919 toSci '-999e999999999' -> -Infinity Overflow Inexact Rounded +basx920 toSci '-0.9e-999999999' -> -9E-1000000000 Subnormal +basx921 toSci '-0.09e-999999999' -> -9E-1000000001 Subnormal +basx922 toSci '-0.1e1000000000' -> -1E+999999999 +basx923 toSci '-10e-1000000000' -> -1.0E-999999999 +basx924 toSci '-0.9e9999999999' -> -Infinity Overflow Inexact Rounded +basx925 toSci '-99e-9999999999' -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +basx926 toSci '-111e9999999999' -> -Infinity Overflow Inexact Rounded +basx927 toSci '-1111e-9999999999' -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +basx928 toSci '-1111e-99999999999' -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +basx929 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded + +rounding: ceiling +basx930 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded +basx931 toSci '-7e1000000000' -> -9.99999999E+999999999 Overflow Inexact Rounded +rounding: up +basx932 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded +basx933 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded +rounding: down +basx934 toSci '7e1000000000' -> 9.99999999E+999999999 Overflow Inexact Rounded +basx935 toSci '-7e1000000000' -> -9.99999999E+999999999 Overflow Inexact Rounded +rounding: floor +basx936 toSci '7e1000000000' -> 9.99999999E+999999999 Overflow Inexact Rounded +basx937 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded + +rounding: half_up +basx938 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded +basx939 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded +rounding: half_even +basx940 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded +basx941 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded +rounding: half_down +basx942 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded +basx943 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded + +rounding: half_even + + -- Giga exponent initial tests maxExponent: 999999999 minExponent: -999999999 @@ -987,8 +1085,8 @@ emax226 toSci 1E-8 -> 1E-8 Subnormal emax227 toSci 1E-9 -> 1E-9 Subnormal emax228 toSci 1E-10 -> 1E-10 Subnormal -emax229 toSci 1E-11 -> 0E-10 Underflow Subnormal Inexact Rounded -emax230 toSci 1E-12 -> 0E-10 Underflow Subnormal Inexact Rounded +emax229 toSci 1E-11 -> 0E-10 Underflow Subnormal Inexact Rounded Clamped +emax230 toSci 1E-12 -> 0E-10 Underflow Subnormal Inexact Rounded Clamped maxexponent: 7 minexponent: -7 @@ -1003,7 +1101,7 @@ maxexponent: 9 minexponent: -9 -emax240 toSci 1E-21 -> 0E-17 Subnormal Underflow Inexact Rounded +emax240 toSci 1E-21 -> 0E-17 Subnormal Underflow Inexact Rounded Clamped emax241 toSci 1E-10 -> 1E-10 Subnormal emax242 toSci 1E-9 -> 1E-9 emax243 toSci 1E-8 -> 1E-8 @@ -1015,7 +1113,7 @@ maxexponent: 10 -- boundary minexponent: -10 -emax250 toSci 1E-21 -> 0E-18 Underflow Subnormal Inexact Rounded +emax250 toSci 1E-21 -> 0E-18 Underflow Subnormal Inexact Rounded Clamped emax251 toSci 1E-11 -> 1E-11 Subnormal emax252 toSci 1E-10 -> 1E-10 emax253 toSci 1E-9 -> 1E-9 @@ -1025,7 +1123,7 @@ emax257 toSci 1E+10 -> 1E+10 emax258 toSci 1E+11 -> Infinity Overflow Inexact Rounded -emax260 toSci 1.00E-21 -> 0E-18 Underflow Subnormal Inexact Rounded +emax260 toSci 1.00E-21 -> 0E-18 Underflow Subnormal Inexact Rounded Clamped emax261 toSci 1.00E-11 -> 1.00E-11 Subnormal emax262 toSci 1.00E-10 -> 1.00E-10 emax263 toSci 1.00E-9 -> 1.00E-9 @@ -1034,7 +1132,7 @@ emax266 toSci 1.00E+9 -> 1.00E+9 emax267 toSci 1.00E+10 -> 1.00E+10 emax268 toSci 1.00E+11 -> Infinity Overflow Inexact Rounded -emax270 toSci 9.99E-21 -> 0E-18 Underflow Subnormal Inexact Rounded +emax270 toSci 9.99E-21 -> 0E-18 Underflow Subnormal Inexact Rounded Clamped emax271 toSci 9.99E-11 -> 9.99E-11 Subnormal emax272 toSci 9.99E-10 -> 9.99E-10 emax273 toSci 9.99E-9 -> 9.99E-9 @@ -1046,7 +1144,7 @@ maxexponent: 99 minexponent: -99 -emax280 toSci 1E-120 -> 0E-107 Underflow Subnormal Inexact Rounded +emax280 toSci 1E-120 -> 0E-107 Underflow Subnormal Inexact Rounded Clamped emax281 toSci 1E-100 -> 1E-100 Subnormal emax282 toSci 1E-99 -> 1E-99 emax283 toSci 1E-98 -> 1E-98 @@ -1093,7 +1191,7 @@ maxexponent: 999999999 minexponent: -999999999 -emax347 toSci 1E-1000000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +emax347 toSci 1E-1000000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped emax348 toSci 1E-1000000007 -> 1E-1000000007 Subnormal emax349 toSci 1E-1000000000 -> 1E-1000000000 Subnormal emax350 toSci 1E-999999999 -> 1E-999999999 @@ -1103,7 +1201,7 @@ emax354 toSci 1.000E-999999999 -> 1.000E-999999999 emax355 toSci 1.000E+999999999 -> 1.000E+999999999 emax356 toSci 1.000E+1000000000 -> Infinity Overflow Inexact Rounded -emax357 toSci 1.001E-1000000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +emax357 toSci 1.001E-1000000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped emax358 toSci 1.001E-1000000007 -> 1E-1000000007 Subnormal Inexact Rounded Underflow emax359 toSci 1.001E-1000000000 -> 1.001E-1000000000 Subnormal emax360 toSci 1.001E-999999999 -> 1.001E-999999999 @@ -1113,7 +1211,7 @@ emax364 toSci 9.000E-999999999 -> 9.000E-999999999 emax365 toSci 9.000E+999999999 -> 9.000E+999999999 emax366 toSci 9.000E+1000000000 -> Infinity Overflow Inexact Rounded -emax367 toSci 9.999E-1000000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +emax367 toSci 9.999E-1000000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped emax368 toSci 9.999E-1000000008 -> 1E-1000000007 Underflow Subnormal Inexact Rounded emax369 toSci 9.999E-1000000007 -> 1.0E-1000000006 Underflow Subnormal Inexact Rounded emax370 toSci 9.999E-1000000000 -> 9.999E-1000000000 Subnormal @@ -1129,11 +1227,11 @@ emax379 toSci -1.000E-999999999 -> -1.000E-999999999 emax380 toSci -1.000E+999999999 -> -1.000E+999999999 emax381 toSci -1.000E+1000000000 -> -Infinity Overflow Inexact Rounded -emax382 toSci -1.001E-1000000008 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +emax382 toSci -1.001E-1000000008 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped emax383 toSci -1.001E-999999999 -> -1.001E-999999999 emax384 toSci -1.001E+999999999 -> -1.001E+999999999 emax385 toSci -1.001E+1000000000 -> -Infinity Overflow Inexact Rounded -emax386 toSci -9.000E-1000000123 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +emax386 toSci -9.000E-1000000123 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped emax387 toSci -9.000E-999999999 -> -9.000E-999999999 emax388 toSci -9.000E+999999999 -> -9.000E+999999999 emax389 toSci -9.000E+1000000000 -> -Infinity Overflow Inexact Rounded @@ -1168,11 +1266,11 @@ emax417 toSci 0.000250E-999 -> 2E-1003 Underflow Subnormal Inexact Rounded emax418 toSci 0.000251E-999 -> 3E-1003 Underflow Subnormal Inexact Rounded emax419 toSci 0.00009E-999 -> 1E-1003 Underflow Subnormal Inexact Rounded -emax420 toSci 0.00005E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded -emax421 toSci 0.00003E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded -emax422 toSci 0.000009E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded -emax423 toSci 0.000005E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded -emax424 toSci 0.000003E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded +emax420 toSci 0.00005E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +emax421 toSci 0.00003E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +emax422 toSci 0.000009E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +emax423 toSci 0.000005E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +emax424 toSci 0.000003E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped emax425 toSci 0.001049E-999 -> 1.0E-1002 Underflow Subnormal Inexact Rounded emax426 toSci 0.001050E-999 -> 1.0E-1002 Underflow Subnormal Inexact Rounded @@ -1223,9 +1321,9 @@ emax473 toSci 0.0099999E-999 -> 1.00E-1001 Underflow Subnormal Inexact Rounded emax474 toSci 0.00099999E-999 -> 1.0E-1002 Underflow Subnormal Inexact Rounded emax475 toSci 0.000099999E-999 -> 1E-1003 Underflow Subnormal Inexact Rounded -emax476 toSci 0.0000099999E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded -emax477 toSci 0.00000099999E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded -emax478 toSci 0.000000099999E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded +emax476 toSci 0.0000099999E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +emax477 toSci 0.00000099999E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +emax478 toSci 0.000000099999E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped -- Exponents with insignificant leading zeros precision: 16 @@ -1248,9 +1346,9 @@ basx1021 tosci 1e+2147483649 -> Infinity Overflow Inexact Rounded basx1022 tosci 1e+2147483648 -> Infinity Overflow Inexact Rounded basx1023 tosci 1e+2147483647 -> Infinity Overflow Inexact Rounded -basx1024 tosci 1e-2147483647 -> 0E-1000000014 Underflow Subnormal Inexact Rounded -basx1025 tosci 1e-2147483648 -> 0E-1000000014 Underflow Subnormal Inexact Rounded -basx1026 tosci 1e-2147483649 -> 0E-1000000014 Underflow Subnormal Inexact Rounded +basx1024 tosci 1e-2147483647 -> 0E-1000000014 Underflow Subnormal Inexact Rounded Clamped +basx1025 tosci 1e-2147483648 -> 0E-1000000014 Underflow Subnormal Inexact Rounded Clamped +basx1026 tosci 1e-2147483649 -> 0E-1000000014 Underflow Subnormal Inexact Rounded Clamped -- same unbalanced precision: 7 maxExponent: 96 @@ -1258,9 +1356,9 @@ basx1031 tosci 1e+2147483649 -> Infinity Overflow Inexact Rounded basx1032 tosci 1e+2147483648 -> Infinity Overflow Inexact Rounded basx1033 tosci 1e+2147483647 -> Infinity Overflow Inexact Rounded -basx1034 tosci 1e-2147483647 -> 0E-101 Underflow Subnormal Inexact Rounded -basx1035 tosci 1e-2147483648 -> 0E-101 Underflow Subnormal Inexact Rounded -basx1036 tosci 1e-2147483649 -> 0E-101 Underflow Subnormal Inexact Rounded +basx1034 tosci 1e-2147483647 -> 0E-101 Underflow Subnormal Inexact Rounded Clamped +basx1035 tosci 1e-2147483648 -> 0E-101 Underflow Subnormal Inexact Rounded Clamped +basx1036 tosci 1e-2147483649 -> 0E-101 Underflow Subnormal Inexact Rounded Clamped -- check for double-rounded subnormals precision: 5 @@ -1270,3 +1368,44 @@ basx1042 toSci 1.52445E-80 -> 1.524E-80 Inexact Rounded Subnormal Underflow basx1043 toSci 1.52446E-80 -> 1.524E-80 Inexact Rounded Subnormal Underflow +-- clamped zeros [see also clamp.decTest] +precision: 34 +maxExponent: 6144 +minExponent: -6143 + +basx1061 apply 0e+10000 -> 0E+6144 Clamped +basx1062 apply 0e-10000 -> 0E-6176 Clamped +basx1063 apply -0e+10000 -> -0E+6144 Clamped +basx1064 apply -0e-10000 -> -0E-6176 Clamped + +precision: 16 +maxExponent: 384 +minExponent: -383 + +basx1065 apply 0e+10000 -> 0E+384 Clamped +basx1066 apply 0e-10000 -> 0E-398 Clamped +basx1067 apply -0e+10000 -> -0E+384 Clamped +basx1068 apply -0e-10000 -> -0E-398 Clamped + +-- same with IEEE clamping +clamp: 1 + +precision: 34 +maxExponent: 6144 +minExponent: -6143 + +basx1071 apply 0e+10000 -> 0E+6111 Clamped +basx1072 apply 0e-10000 -> 0E-6176 Clamped +basx1073 apply -0e+10000 -> -0E+6111 Clamped +basx1074 apply -0e-10000 -> -0E-6176 Clamped + +precision: 16 +maxExponent: 384 +minExponent: -383 + +basx1075 apply 0e+10000 -> 0E+369 Clamped +basx1076 apply 0e-10000 -> 0E-398 Clamped +basx1077 apply -0e+10000 -> -0E+369 Clamped +basx1078 apply -0e-10000 -> -0E-398 Clamped + + Modified: python/branches/py3k/Lib/test/decimaltestdata/clamp.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/clamp.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/clamp.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- clamp.decTest -- clamped exponent tests (format-independent) -- --- Copyright (c) IBM Corporation, 2000, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 2000, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- This set of tests uses the same limits as the 8-byte concrete -- representation, but applies clamping without using format-specific @@ -73,10 +73,10 @@ clam093 apply 1.00000000001e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded clam094 apply 1.00000000000001e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded clam095 apply 1.000000000000001e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded -clam096 apply 0.1e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded -clam097 apply 0.00000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded -clam098 apply 0.00000000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded -clam099 apply 0.000000000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded +clam096 apply 0.1e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded Clamped +clam097 apply 0.00000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded Clamped +clam098 apply 0.00000000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded Clamped +clam099 apply 0.000000000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded Clamped -- Same again, negatives -- Nmax and similar @@ -112,10 +112,10 @@ clam193 apply -1.00000000001e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded clam194 apply -1.00000000000001e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded clam195 apply -1.000000000000001e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded -clam196 apply -0.1e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded -clam197 apply -0.00000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded -clam198 apply -0.00000000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded -clam199 apply -0.000000000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded +clam196 apply -0.1e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded Clamped +clam197 apply -0.00000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded Clamped +clam198 apply -0.00000000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded Clamped +clam199 apply -0.000000000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded Clamped -- zeros clam401 apply 0E-500 -> 0E-398 Clamped @@ -184,6 +184,20 @@ clam671 apply 9E+369 -> 9E+369 clam673 apply 9E+368 -> 9E+368 +-- subnormals clamped to 0-Etiny +precision: 16 +maxExponent: 384 +minExponent: -383 +clam681 apply 7E-398 -> 7E-398 Subnormal +clam682 apply 0E-398 -> 0E-398 +clam683 apply 7E-399 -> 1E-398 Subnormal Underflow Inexact Rounded +clam684 apply 4E-399 -> 0E-398 Clamped Subnormal Underflow Inexact Rounded +clam685 apply 7E-400 -> 0E-398 Clamped Subnormal Underflow Inexact Rounded +clam686 apply 7E-401 -> 0E-398 Clamped Subnormal Underflow Inexact Rounded +clam687 apply 0E-399 -> 0E-398 Clamped +clam688 apply 0E-400 -> 0E-398 Clamped +clam689 apply 0E-401 -> 0E-398 Clamped + -- example from documentation precision: 7 rounding: half_even Modified: python/branches/py3k/Lib/test/decimaltestdata/compare.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/compare.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/compare.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ --- compare.decTest -- decimal comparison -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +-- compare.decTest -- decimal comparison that allows quiet NaNs -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,11 +17,11 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- Note that we cannot assume add/subtract tests cover paths adequately, -- here, because the code might be quite different (comparison cannot --- overflow or underflow, so actual subtractions are not necesary). +-- overflow or underflow, so actual subtractions are not necessary). extended: 1 @@ -112,10 +112,10 @@ -- now some cases which might overflow if subtract were used maxexponent: 999999999 minexponent: -999999999 -comx090 compare 9.99999999E+999999999 9.99999999E+999999999 -> 0 -comx091 compare -9.99999999E+999999999 9.99999999E+999999999 -> -1 -comx092 compare 9.99999999E+999999999 -9.99999999E+999999999 -> 1 -comx093 compare -9.99999999E+999999999 -9.99999999E+999999999 -> 0 +comx095 compare 9.99999999E+999999999 9.99999999E+999999999 -> 0 +comx096 compare -9.99999999E+999999999 9.99999999E+999999999 -> -1 +comx097 compare 9.99999999E+999999999 -9.99999999E+999999999 -> 1 +comx098 compare -9.99999999E+999999999 -9.99999999E+999999999 -> 0 -- some differing length/exponent cases comx100 compare 7.0 7.0 -> 0 @@ -265,6 +265,21 @@ comx449 compare -8 -.9E+1 -> 1 comx450 compare -8 -90E-1 -> 1 +-- misalignment traps for little-endian +comx451 compare 1.0 0.1 -> 1 +comx452 compare 0.1 1.0 -> -1 +comx453 compare 10.0 0.1 -> 1 +comx454 compare 0.1 10.0 -> -1 +comx455 compare 100 1.0 -> 1 +comx456 compare 1.0 100 -> -1 +comx457 compare 1000 10.0 -> 1 +comx458 compare 10.0 1000 -> -1 +comx459 compare 10000 100.0 -> 1 +comx460 compare 100.0 10000 -> -1 +comx461 compare 100000 1000.0 -> 1 +comx462 compare 1000.0 100000 -> -1 +comx463 compare 1000000 10000.0 -> 1 +comx464 compare 10000.0 1000000 -> -1 -- testcases that subtract to lots of zeros at boundaries [pgr] precision: 40 @@ -362,7 +377,7 @@ comx569 compare 1E+13 1 -> 1 comx570 compare 1E+14 1 -> 1 comx571 compare 1E+15 1 -> 1 --- similar with an useful coefficient, one side only +-- similar with a useful coefficient, one side only comx580 compare 0.000000987654321 1E-15 -> 1 comx581 compare 0.000000987654321 1E-14 -> 1 comx582 compare 0.000000987654321 1E-13 -> 1 @@ -712,6 +727,32 @@ comx907 compare -1e-777777777 1e-411111111 -> -1 comx908 compare -1e-777777777 -1e-411111111 -> 1 +-- spread zeros +comx910 compare 0E-383 0 -> 0 +comx911 compare 0E-383 -0 -> 0 +comx912 compare -0E-383 0 -> 0 +comx913 compare -0E-383 -0 -> 0 +comx914 compare 0E-383 0E+384 -> 0 +comx915 compare 0E-383 -0E+384 -> 0 +comx916 compare -0E-383 0E+384 -> 0 +comx917 compare -0E-383 -0E+384 -> 0 +comx918 compare 0 0E+384 -> 0 +comx919 compare 0 -0E+384 -> 0 +comx920 compare -0 0E+384 -> 0 +comx921 compare -0 -0E+384 -> 0 +comx930 compare 0E+384 0 -> 0 +comx931 compare 0E+384 -0 -> 0 +comx932 compare -0E+384 0 -> 0 +comx933 compare -0E+384 -0 -> 0 +comx934 compare 0E+384 0E-383 -> 0 +comx935 compare 0E+384 -0E-383 -> 0 +comx936 compare -0E+384 0E-383 -> 0 +comx937 compare -0E+384 -0E-383 -> 0 +comx938 compare 0 0E-383 -> 0 +comx939 compare 0 -0E-383 -> 0 +comx940 compare -0 0E-383 -> 0 +comx941 compare -0 -0E-383 -> 0 + -- Null tests comx990 compare 10 # -> NaN Invalid_operation comx991 compare # 10 -> NaN Invalid_operation Deleted: /python/branches/py3k/Lib/test/decimaltestdata/decimal128.decTest ============================================================================== --- /python/branches/py3k/Lib/test/decimaltestdata/decimal128.decTest Wed Sep 19 05:06:30 2007 +++ (empty file) @@ -1,441 +0,0 @@ ------------------------------------------------------------------------- --- decimal128.decTest -- decimal sixteen-byte format testcases -- --- Copyright (c) IBM Corporation, 2000, 2003. All rights reserved. -- ------------------------------------------------------------------------- --- Please see the document "General Decimal Arithmetic Testcases" -- --- at http://www2.hursley.ibm.com/decimal for the description of -- --- these testcases. -- --- -- --- These testcases are experimental ('beta' versions), and they -- --- may contain errors. They are offered on an as-is basis. In -- --- particular, achieving the same results as the tests here is not -- --- a guarantee that an implementation complies with any Standard -- --- or specification. The tests are not exhaustive. -- --- -- --- Please send comments, suggestions, and corrections to the author: -- --- Mike Cowlishaw, IBM Fellow -- --- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- --- mfc at uk.ibm.com -- ------------------------------------------------------------------------- -version: 2.39 - --- This set of tests is for the sixteen-byte concrete representation. --- Its characteristics are: --- --- 1 bit sign --- 5 bits combination field --- 12 bits exponent continuation --- 110 bits coefficient continuation --- --- Total exponent length 14 bits --- Total coefficient length 114 bits (34 digits) --- --- Elimit = 12287 (maximum encoded exponent) --- Emax = 6144 (largest exponent value) --- Emin = -6143 (smallest exponent value) --- bias = 6176 (subtracted from encoded exponent) = -Etiny - -extended: 1 -precision: 34 -rounding: half_up -maxExponent: 6144 -minExponent: -6143 - --- General testcases --- (mostly derived from the Strawman 4 document and examples) -decg001 apply #A20780000000000000000000000003D0 -> -7.50 -decg002 apply -7.50 -> #A20780000000000000000000000003D0 - --- Normality -decf010 apply 1234567890123456789012345678901234 -> #2608134b9c1e28e56f3c127177823534 -decf011 apply 1234567890123456789012345678901234.0 -> #2608134b9c1e28e56f3c127177823534 Rounded -decf012 apply 1234567890123456789012345678901234.1 -> #2608134b9c1e28e56f3c127177823534 Rounded Inexact -decf013 apply -1234567890123456789012345678901234 -> #a608134b9c1e28e56f3c127177823534 -decf014 apply -1234567890123456789012345678901234.0 -> #a608134b9c1e28e56f3c127177823534 Rounded -decf015 apply -1234567890123456789012345678901234.1 -> #a608134b9c1e28e56f3c127177823534 Rounded Inexact - - --- Nmax and similar -decf022 apply 9.999999999999999999999999999999999E+6144 -> #77ffcff3fcff3fcff3fcff3fcff3fcff -decf023 apply #77ffcff3fcff3fcff3fcff3fcff3fcff -> 9.999999999999999999999999999999999E+6144 -decf024 apply 1.234567890123456789012345678901234E+6144 -> #47ffd34b9c1e28e56f3c127177823534 -decf025 apply #47ffd34b9c1e28e56f3c127177823534 -> 1.234567890123456789012345678901234E+6144 --- fold-downs (more below) -decf030 apply 1.23E+6144 -> #47ffd300000000000000000000000000 Clamped -decf031 apply #47ffd300000000000000000000000000 -> 1.230000000000000000000000000000000E+6144 -decf032 apply 1E+6144 -> #47ffc000000000000000000000000000 Clamped -decf033 apply #47ffc000000000000000000000000000 -> 1.000000000000000000000000000000000E+6144 - --- overflows -maxExponent: 9999 -- set high so conversion causes the overflow -minExponent: -9999 -decf040 apply 10E+6144 -> #78000000000000000000000000000000 Overflow Rounded Inexact -decf041 apply 1.000000000000000E+6145 -> #78000000000000000000000000000000 Overflow Rounded Inexact -maxExponent: 6144 -minExponent: -6143 - -decf051 apply 12345 -> #220800000000000000000000000049c5 -decf052 apply #220800000000000000000000000049c5 -> 12345 -decf053 apply 1234 -> #22080000000000000000000000000534 -decf054 apply #22080000000000000000000000000534 -> 1234 -decf055 apply 123 -> #220800000000000000000000000000a3 -decf056 apply #220800000000000000000000000000a3 -> 123 -decf057 apply 12 -> #22080000000000000000000000000012 -decf058 apply #22080000000000000000000000000012 -> 12 -decf059 apply 1 -> #22080000000000000000000000000001 -decf060 apply #22080000000000000000000000000001 -> 1 -decf061 apply 1.23 -> #220780000000000000000000000000a3 -decf062 apply #220780000000000000000000000000a3 -> 1.23 -decf063 apply 123.45 -> #220780000000000000000000000049c5 -decf064 apply #220780000000000000000000000049c5 -> 123.45 - --- Nmin and below -decf071 apply 1E-6143 -> #00084000000000000000000000000001 -decf072 apply #00084000000000000000000000000001 -> 1E-6143 -decf073 apply 1.000000000000000000000000000000000E-6143 -> #04000000000000000000000000000000 -decf074 apply #04000000000000000000000000000000 -> 1.000000000000000000000000000000000E-6143 -decf075 apply 1.000000000000000000000000000000001E-6143 -> #04000000000000000000000000000001 -decf076 apply #04000000000000000000000000000001 -> 1.000000000000000000000000000000001E-6143 - -decf077 apply 0.100000000000000000000000000000000E-6143 -> #00000800000000000000000000000000 Subnormal -decf078 apply #00000800000000000000000000000000 -> 1.00000000000000000000000000000000E-6144 Subnormal -decf079 apply 0.000000000000000000000000000000010E-6143 -> #00000000000000000000000000000010 Subnormal -decf080 apply #00000000000000000000000000000010 -> 1.0E-6175 Subnormal -decf081 apply 0.00000000000000000000000000000001E-6143 -> #00004000000000000000000000000001 Subnormal -decf082 apply #00004000000000000000000000000001 -> 1E-6175 Subnormal -decf083 apply 0.000000000000000000000000000000001E-6143 -> #00000000000000000000000000000001 Subnormal -decf084 apply #00000000000000000000000000000001 -> 1E-6176 Subnormal - --- underflows -decf090 apply 1e-6176 -> #00000000000000000000000000000001 Subnormal -decf091 apply 1.9e-6176 -> #00000000000000000000000000000002 Subnormal Underflow Inexact Rounded -decf092 apply 1.1e-6176 -> #00000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf093 apply 1.00000000001e-6176 -> #00000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf094 apply 1.00000000000001e-6176 -> #00000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf095 apply 1.000000000000001e-6176 -> #00000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf096 apply 0.1e-6176 -> #00000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf097 apply 0.00000000001e-6176 -> #00000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf098 apply 0.00000000000001e-6176 -> #00000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf099 apply 0.000000000000001e-6176 -> #00000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf100 apply 999999999999999999999999999999999e-6176 -> #00000ff3fcff3fcff3fcff3fcff3fcff Subnormal - --- same again, negatives --- Nmax and similar -decf122 apply -9.999999999999999999999999999999999E+6144 -> #f7ffcff3fcff3fcff3fcff3fcff3fcff -decf123 apply #f7ffcff3fcff3fcff3fcff3fcff3fcff -> -9.999999999999999999999999999999999E+6144 -decf124 apply -1.234567890123456789012345678901234E+6144 -> #c7ffd34b9c1e28e56f3c127177823534 -decf125 apply #c7ffd34b9c1e28e56f3c127177823534 -> -1.234567890123456789012345678901234E+6144 --- fold-downs (more below) -decf130 apply -1.23E+6144 -> #c7ffd300000000000000000000000000 Clamped -decf131 apply #c7ffd300000000000000000000000000 -> -1.230000000000000000000000000000000E+6144 -decf132 apply -1E+6144 -> #c7ffc000000000000000000000000000 Clamped -decf133 apply #c7ffc000000000000000000000000000 -> -1.000000000000000000000000000000000E+6144 - --- overflows -maxExponent: 9999 -- set high so conversion causes the overflow -minExponent: -9999 -decf140 apply -10E+6144 -> #f8000000000000000000000000000000 Overflow Rounded Inexact -decf141 apply -1.000000000000000E+6145 -> #f8000000000000000000000000000000 Overflow Rounded Inexact -maxExponent: 6144 -minExponent: -6143 - -decf151 apply -12345 -> #a20800000000000000000000000049c5 -decf152 apply #a20800000000000000000000000049c5 -> -12345 -decf153 apply -1234 -> #a2080000000000000000000000000534 -decf154 apply #a2080000000000000000000000000534 -> -1234 -decf155 apply -123 -> #a20800000000000000000000000000a3 -decf156 apply #a20800000000000000000000000000a3 -> -123 -decf157 apply -12 -> #a2080000000000000000000000000012 -decf158 apply #a2080000000000000000000000000012 -> -12 -decf159 apply -1 -> #a2080000000000000000000000000001 -decf160 apply #a2080000000000000000000000000001 -> -1 -decf161 apply -1.23 -> #a20780000000000000000000000000a3 -decf162 apply #a20780000000000000000000000000a3 -> -1.23 -decf163 apply -123.45 -> #a20780000000000000000000000049c5 -decf164 apply #a20780000000000000000000000049c5 -> -123.45 - --- Nmin and below -decf171 apply -1E-6143 -> #80084000000000000000000000000001 -decf172 apply #80084000000000000000000000000001 -> -1E-6143 -decf173 apply -1.000000000000000000000000000000000E-6143 -> #84000000000000000000000000000000 -decf174 apply #84000000000000000000000000000000 -> -1.000000000000000000000000000000000E-6143 -decf175 apply -1.000000000000000000000000000000001E-6143 -> #84000000000000000000000000000001 -decf176 apply #84000000000000000000000000000001 -> -1.000000000000000000000000000000001E-6143 - -decf177 apply -0.100000000000000000000000000000000E-6143 -> #80000800000000000000000000000000 Subnormal -decf178 apply #80000800000000000000000000000000 -> -1.00000000000000000000000000000000E-6144 Subnormal -decf179 apply -0.000000000000000000000000000000010E-6143 -> #80000000000000000000000000000010 Subnormal -decf180 apply #80000000000000000000000000000010 -> -1.0E-6175 Subnormal -decf181 apply -0.00000000000000000000000000000001E-6143 -> #80004000000000000000000000000001 Subnormal -decf182 apply #80004000000000000000000000000001 -> -1E-6175 Subnormal -decf183 apply -0.000000000000000000000000000000001E-6143 -> #80000000000000000000000000000001 Subnormal -decf184 apply #80000000000000000000000000000001 -> -1E-6176 Subnormal - --- underflows -decf190 apply -1e-6176 -> #80000000000000000000000000000001 Subnormal -decf191 apply -1.9e-6176 -> #80000000000000000000000000000002 Subnormal Underflow Inexact Rounded -decf192 apply -1.1e-6176 -> #80000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf193 apply -1.00000000001e-6176 -> #80000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf194 apply -1.00000000000001e-6176 -> #80000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf195 apply -1.000000000000001e-6176 -> #80000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf196 apply -0.1e-6176 -> #80000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf197 apply -0.00000000001e-6176 -> #80000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf198 apply -0.00000000000001e-6176 -> #80000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf199 apply -0.000000000000001e-6176 -> #80000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf200 apply -999999999999999999999999999999999e-6176 -> #80000ff3fcff3fcff3fcff3fcff3fcff Subnormal - --- zeros -decf400 apply 0E-8000 -> #00000000000000000000000000000000 Clamped -decf401 apply 0E-6177 -> #00000000000000000000000000000000 Clamped -decf402 apply 0E-6176 -> #00000000000000000000000000000000 -decf403 apply #00000000000000000000000000000000 -> 0E-6176 -decf404 apply 0.000000000000000000000000000000000E-6143 -> #00000000000000000000000000000000 -decf405 apply #00000000000000000000000000000000 -> 0E-6176 -decf406 apply 0E-2 -> #22078000000000000000000000000000 -decf407 apply #22078000000000000000000000000000 -> 0.00 -decf408 apply 0 -> #22080000000000000000000000000000 -decf409 apply #22080000000000000000000000000000 -> 0 -decf410 apply 0E+3 -> #2208c000000000000000000000000000 -decf411 apply #2208c000000000000000000000000000 -> 0E+3 -decf412 apply 0E+6111 -> #43ffc000000000000000000000000000 -decf413 apply #43ffc000000000000000000000000000 -> 0E+6111 --- clamped zeros... -decf414 apply 0E+6112 -> #43ffc000000000000000000000000000 Clamped -decf415 apply #43ffc000000000000000000000000000 -> 0E+6111 -decf416 apply 0E+6144 -> #43ffc000000000000000000000000000 Clamped -decf417 apply #43ffc000000000000000000000000000 -> 0E+6111 -decf418 apply 0E+8000 -> #43ffc000000000000000000000000000 Clamped -decf419 apply #43ffc000000000000000000000000000 -> 0E+6111 - --- negative zeros -decf420 apply -0E-8000 -> #80000000000000000000000000000000 Clamped -decf421 apply -0E-6177 -> #80000000000000000000000000000000 Clamped -decf422 apply -0E-6176 -> #80000000000000000000000000000000 -decf423 apply #80000000000000000000000000000000 -> -0E-6176 -decf424 apply -0.000000000000000000000000000000000E-6143 -> #80000000000000000000000000000000 -decf425 apply #80000000000000000000000000000000 -> -0E-6176 -decf426 apply -0E-2 -> #a2078000000000000000000000000000 -decf427 apply #a2078000000000000000000000000000 -> -0.00 -decf428 apply -0 -> #a2080000000000000000000000000000 -decf429 apply #a2080000000000000000000000000000 -> -0 -decf430 apply -0E+3 -> #a208c000000000000000000000000000 -decf431 apply #a208c000000000000000000000000000 -> -0E+3 -decf432 apply -0E+6111 -> #c3ffc000000000000000000000000000 -decf433 apply #c3ffc000000000000000000000000000 -> -0E+6111 --- clamped zeros... -decf434 apply -0E+6112 -> #c3ffc000000000000000000000000000 Clamped -decf435 apply #c3ffc000000000000000000000000000 -> -0E+6111 -decf436 apply -0E+6144 -> #c3ffc000000000000000000000000000 Clamped -decf437 apply #c3ffc000000000000000000000000000 -> -0E+6111 -decf438 apply -0E+8000 -> #c3ffc000000000000000000000000000 Clamped -decf439 apply #c3ffc000000000000000000000000000 -> -0E+6111 - --- Specials -decf500 apply Infinity -> #78000000000000000000000000000000 -decf501 apply #78787878787878787878787878787878 -> #78000000000000000000000000000000 -decf502 apply #78000000000000000000000000000000 -> Infinity -decf503 apply #79797979797979797979797979797979 -> #78000000000000000000000000000000 -decf504 apply #79000000000000000000000000000000 -> Infinity -decf505 apply #7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a -> #78000000000000000000000000000000 -decf506 apply #7a000000000000000000000000000000 -> Infinity -decf507 apply #7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b -> #78000000000000000000000000000000 -decf508 apply #7b000000000000000000000000000000 -> Infinity - -decf509 apply NaN -> #7c000000000000000000000000000000 -decf510 apply #7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c -> #7c003c7c7c7c7c7c7c7c7c7c7c7c7c7c -decf511 apply #7c000000000000000000000000000000 -> NaN -decf512 apply #7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d -> #7c003d7d7d7d7d7d7d7d7d7d7d7d7d7d -decf513 apply #7d000000000000000000000000000000 -> NaN -decf514 apply #7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e -> #7e003e7e7c7e7e7e7e7c7e7e7e7e7c7e -decf515 apply #7e000000000000000000000000000000 -> sNaN -decf516 apply #7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f -> #7e003f7f7c7f7f7f7f7c7f7f7f7f7c7f -decf517 apply #7f000000000000000000000000000000 -> sNaN -decf518 apply #7fffffffffffffffffffffffffffffff -> sNaN999999999999999999999999999999999 -decf519 apply #7fffffffffffffffffffffffffffffff -> #7e000ff3fcff3fcff3fcff3fcff3fcff - -decf520 apply -Infinity -> #f8000000000000000000000000000000 -decf521 apply #f8787878787878787878787878787878 -> #f8000000000000000000000000000000 -decf522 apply #f8000000000000000000000000000000 -> -Infinity -decf523 apply #f9797979797979797979797979797979 -> #f8000000000000000000000000000000 -decf524 apply #f9000000000000000000000000000000 -> -Infinity -decf525 apply #fa7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a -> #f8000000000000000000000000000000 -decf526 apply #fa000000000000000000000000000000 -> -Infinity -decf527 apply #fb7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b -> #f8000000000000000000000000000000 -decf528 apply #fb000000000000000000000000000000 -> -Infinity - -decf529 apply -NaN -> #fc000000000000000000000000000000 -decf530 apply #fc7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c -> #fc003c7c7c7c7c7c7c7c7c7c7c7c7c7c -decf531 apply #fc000000000000000000000000000000 -> -NaN -decf532 apply #fd7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d -> #fc003d7d7d7d7d7d7d7d7d7d7d7d7d7d -decf533 apply #fd000000000000000000000000000000 -> -NaN -decf534 apply #fe7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e -> #fe003e7e7c7e7e7e7e7c7e7e7e7e7c7e -decf535 apply #fe000000000000000000000000000000 -> -sNaN -decf536 apply #ff7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f -> #fe003f7f7c7f7f7f7f7c7f7f7f7f7c7f -decf537 apply #ff000000000000000000000000000000 -> -sNaN -decf538 apply #ffffffffffffffffffffffffffffffff -> -sNaN999999999999999999999999999999999 -decf539 apply #ffffffffffffffffffffffffffffffff -> #fe000ff3fcff3fcff3fcff3fcff3fcff - -decf540 apply NaN -> #7c000000000000000000000000000000 -decf541 apply NaN0 -> #7c000000000000000000000000000000 -decf542 apply NaN1 -> #7c000000000000000000000000000001 -decf543 apply NaN12 -> #7c000000000000000000000000000012 -decf544 apply NaN79 -> #7c000000000000000000000000000079 -decf545 apply NaN12345 -> #7c0000000000000000000000000049c5 -decf546 apply NaN123456 -> #7c000000000000000000000000028e56 -decf547 apply NaN799799 -> #7c0000000000000000000000000f7fdf -decf548 apply NaN799799799799799799799799799799799 -> #7c003dff7fdff7fdff7fdff7fdff7fdf -decf549 apply NaN999999999999999999999999999999999 -> #7c000ff3fcff3fcff3fcff3fcff3fcff -decf550 apply NaN1234567890123456789012345678901234 -> #7c000000000000000000000000000000 -- too many digits - --- fold-down full sequence -decf600 apply 1E+6145 -> #78000000000000000000000000000000 Overflow Inexact Rounded -decf601 apply 1E+6144 -> #47ffc000000000000000000000000000 Clamped -decf602 apply #47ffc000000000000000000000000000 -> 1.000000000000000000000000000000000E+6144 -decf603 apply 1E+6143 -> #43ffc800000000000000000000000000 Clamped -decf604 apply #43ffc800000000000000000000000000 -> 1.00000000000000000000000000000000E+6143 -decf605 apply 1E+6142 -> #43ffc100000000000000000000000000 Clamped -decf606 apply #43ffc100000000000000000000000000 -> 1.0000000000000000000000000000000E+6142 -decf607 apply 1E+6141 -> #43ffc010000000000000000000000000 Clamped -decf608 apply #43ffc010000000000000000000000000 -> 1.000000000000000000000000000000E+6141 -decf609 apply 1E+6140 -> #43ffc002000000000000000000000000 Clamped -decf610 apply #43ffc002000000000000000000000000 -> 1.00000000000000000000000000000E+6140 -decf611 apply 1E+6139 -> #43ffc000400000000000000000000000 Clamped -decf612 apply #43ffc000400000000000000000000000 -> 1.0000000000000000000000000000E+6139 -decf613 apply 1E+6138 -> #43ffc000040000000000000000000000 Clamped -decf614 apply #43ffc000040000000000000000000000 -> 1.000000000000000000000000000E+6138 -decf615 apply 1E+6137 -> #43ffc000008000000000000000000000 Clamped -decf616 apply #43ffc000008000000000000000000000 -> 1.00000000000000000000000000E+6137 -decf617 apply 1E+6136 -> #43ffc000001000000000000000000000 Clamped -decf618 apply #43ffc000001000000000000000000000 -> 1.0000000000000000000000000E+6136 -decf619 apply 1E+6135 -> #43ffc000000100000000000000000000 Clamped -decf620 apply #43ffc000000100000000000000000000 -> 1.000000000000000000000000E+6135 -decf621 apply 1E+6134 -> #43ffc000000020000000000000000000 Clamped -decf622 apply #43ffc000000020000000000000000000 -> 1.00000000000000000000000E+6134 -decf623 apply 1E+6133 -> #43ffc000000004000000000000000000 Clamped -decf624 apply #43ffc000000004000000000000000000 -> 1.0000000000000000000000E+6133 -decf625 apply 1E+6132 -> #43ffc000000000400000000000000000 Clamped -decf626 apply #43ffc000000000400000000000000000 -> 1.000000000000000000000E+6132 -decf627 apply 1E+6131 -> #43ffc000000000080000000000000000 Clamped -decf628 apply #43ffc000000000080000000000000000 -> 1.00000000000000000000E+6131 -decf629 apply 1E+6130 -> #43ffc000000000010000000000000000 Clamped -decf630 apply #43ffc000000000010000000000000000 -> 1.0000000000000000000E+6130 -decf631 apply 1E+6129 -> #43ffc000000000001000000000000000 Clamped -decf632 apply #43ffc000000000001000000000000000 -> 1.000000000000000000E+6129 -decf633 apply 1E+6128 -> #43ffc000000000000200000000000000 Clamped -decf634 apply #43ffc000000000000200000000000000 -> 1.00000000000000000E+6128 -decf635 apply 1E+6127 -> #43ffc000000000000040000000000000 Clamped -decf636 apply #43ffc000000000000040000000000000 -> 1.0000000000000000E+6127 -decf637 apply 1E+6126 -> #43ffc000000000000004000000000000 Clamped -decf638 apply #43ffc000000000000004000000000000 -> 1.000000000000000E+6126 -decf639 apply 1E+6125 -> #43ffc000000000000000800000000000 Clamped -decf640 apply #43ffc000000000000000800000000000 -> 1.00000000000000E+6125 -decf641 apply 1E+6124 -> #43ffc000000000000000100000000000 Clamped -decf642 apply #43ffc000000000000000100000000000 -> 1.0000000000000E+6124 -decf643 apply 1E+6123 -> #43ffc000000000000000010000000000 Clamped -decf644 apply #43ffc000000000000000010000000000 -> 1.000000000000E+6123 -decf645 apply 1E+6122 -> #43ffc000000000000000002000000000 Clamped -decf646 apply #43ffc000000000000000002000000000 -> 1.00000000000E+6122 -decf647 apply 1E+6121 -> #43ffc000000000000000000400000000 Clamped -decf648 apply #43ffc000000000000000000400000000 -> 1.0000000000E+6121 -decf649 apply 1E+6120 -> #43ffc000000000000000000040000000 Clamped -decf650 apply #43ffc000000000000000000040000000 -> 1.000000000E+6120 -decf651 apply 1E+6119 -> #43ffc000000000000000000008000000 Clamped -decf652 apply #43ffc000000000000000000008000000 -> 1.00000000E+6119 -decf653 apply 1E+6118 -> #43ffc000000000000000000001000000 Clamped -decf654 apply #43ffc000000000000000000001000000 -> 1.0000000E+6118 -decf655 apply 1E+6117 -> #43ffc000000000000000000000100000 Clamped -decf656 apply #43ffc000000000000000000000100000 -> 1.000000E+6117 -decf657 apply 1E+6116 -> #43ffc000000000000000000000020000 Clamped -decf658 apply #43ffc000000000000000000000020000 -> 1.00000E+6116 -decf659 apply 1E+6115 -> #43ffc000000000000000000000004000 Clamped -decf660 apply #43ffc000000000000000000000004000 -> 1.0000E+6115 -decf661 apply 1E+6114 -> #43ffc000000000000000000000000400 Clamped -decf662 apply #43ffc000000000000000000000000400 -> 1.000E+6114 -decf663 apply 1E+6113 -> #43ffc000000000000000000000000080 Clamped -decf664 apply #43ffc000000000000000000000000080 -> 1.00E+6113 -decf665 apply 1E+6112 -> #43ffc000000000000000000000000010 Clamped -decf666 apply #43ffc000000000000000000000000010 -> 1.0E+6112 -decf667 apply 1E+6111 -> #43ffc000000000000000000000000001 -decf668 apply #43ffc000000000000000000000000001 -> 1E+6111 -decf669 apply 1E+6110 -> #43ff8000000000000000000000000001 -decf670 apply #43ff8000000000000000000000000001 -> 1E+6110 - --- Selected DPD codes -decf700 apply #22080000000000000000000000000000 -> 0 -decf701 apply #22080000000000000000000000000009 -> 9 -decf702 apply #22080000000000000000000000000010 -> 10 -decf703 apply #22080000000000000000000000000019 -> 19 -decf704 apply #22080000000000000000000000000020 -> 20 -decf705 apply #22080000000000000000000000000029 -> 29 -decf706 apply #22080000000000000000000000000030 -> 30 -decf707 apply #22080000000000000000000000000039 -> 39 -decf708 apply #22080000000000000000000000000040 -> 40 -decf709 apply #22080000000000000000000000000049 -> 49 -decf710 apply #22080000000000000000000000000050 -> 50 -decf711 apply #22080000000000000000000000000059 -> 59 -decf712 apply #22080000000000000000000000000060 -> 60 -decf713 apply #22080000000000000000000000000069 -> 69 -decf714 apply #22080000000000000000000000000070 -> 70 -decf715 apply #22080000000000000000000000000071 -> 71 -decf716 apply #22080000000000000000000000000072 -> 72 -decf717 apply #22080000000000000000000000000073 -> 73 -decf718 apply #22080000000000000000000000000074 -> 74 -decf719 apply #22080000000000000000000000000075 -> 75 -decf720 apply #22080000000000000000000000000076 -> 76 -decf721 apply #22080000000000000000000000000077 -> 77 -decf722 apply #22080000000000000000000000000078 -> 78 -decf723 apply #22080000000000000000000000000079 -> 79 - -decf730 apply #2208000000000000000000000000029e -> 994 -decf731 apply #2208000000000000000000000000029f -> 995 -decf732 apply #220800000000000000000000000002a0 -> 520 -decf733 apply #220800000000000000000000000002a1 -> 521 - --- DPD: one of each of the huffman groups -decf740 apply #220800000000000000000000000003f7 -> 777 -decf741 apply #220800000000000000000000000003f8 -> 778 -decf742 apply #220800000000000000000000000003eb -> 787 -decf743 apply #2208000000000000000000000000037d -> 877 -decf744 apply #2208000000000000000000000000039f -> 997 -decf745 apply #220800000000000000000000000003bf -> 979 -decf746 apply #220800000000000000000000000003df -> 799 -decf747 apply #2208000000000000000000000000006e -> 888 - - --- DPD all-highs cases (includes the 24 redundant codes) -decf750 apply #2208000000000000000000000000006e -> 888 -decf751 apply #2208000000000000000000000000016e -> 888 -decf752 apply #2208000000000000000000000000026e -> 888 -decf753 apply #2208000000000000000000000000036e -> 888 -decf754 apply #2208000000000000000000000000006f -> 889 -decf755 apply #2208000000000000000000000000016f -> 889 -decf756 apply #2208000000000000000000000000026f -> 889 -decf757 apply #2208000000000000000000000000036f -> 889 - -decf760 apply #2208000000000000000000000000007e -> 898 -decf761 apply #2208000000000000000000000000017e -> 898 -decf762 apply #2208000000000000000000000000027e -> 898 -decf763 apply #2208000000000000000000000000037e -> 898 -decf764 apply #2208000000000000000000000000007f -> 899 -decf765 apply #2208000000000000000000000000017f -> 899 -decf766 apply #2208000000000000000000000000027f -> 899 -decf767 apply #2208000000000000000000000000037f -> 899 - -decf770 apply #220800000000000000000000000000ee -> 988 -decf771 apply #220800000000000000000000000001ee -> 988 -decf772 apply #220800000000000000000000000002ee -> 988 -decf773 apply #220800000000000000000000000003ee -> 988 -decf774 apply #220800000000000000000000000000ef -> 989 -decf775 apply #220800000000000000000000000001ef -> 989 -decf776 apply #220800000000000000000000000002ef -> 989 -decf777 apply #220800000000000000000000000003ef -> 989 - -decf780 apply #220800000000000000000000000000fe -> 998 -decf781 apply #220800000000000000000000000001fe -> 998 -decf782 apply #220800000000000000000000000002fe -> 998 -decf783 apply #220800000000000000000000000003fe -> 998 -decf784 apply #220800000000000000000000000000ff -> 999 -decf785 apply #220800000000000000000000000001ff -> 999 -decf786 apply #220800000000000000000000000002ff -> 999 -decf787 apply #220800000000000000000000000003ff -> 999 - Deleted: /python/branches/py3k/Lib/test/decimaltestdata/decimal32.decTest ============================================================================== --- /python/branches/py3k/Lib/test/decimaltestdata/decimal32.decTest Wed Sep 19 05:06:30 2007 +++ (empty file) @@ -1,385 +0,0 @@ ------------------------------------------------------------------------- --- decimal32.decTest -- decimal four-byte format testcases -- --- Copyright (c) IBM Corporation, 2000, 2003. All rights reserved. -- ------------------------------------------------------------------------- --- Please see the document "General Decimal Arithmetic Testcases" -- --- at http://www2.hursley.ibm.com/decimal for the description of -- --- these testcases. -- --- -- --- These testcases are experimental ('beta' versions), and they -- --- may contain errors. They are offered on an as-is basis. In -- --- particular, achieving the same results as the tests here is not -- --- a guarantee that an implementation complies with any Standard -- --- or specification. The tests are not exhaustive. -- --- -- --- Please send comments, suggestions, and corrections to the author: -- --- Mike Cowlishaw, IBM Fellow -- --- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- --- mfc at uk.ibm.com -- ------------------------------------------------------------------------- -version: 2.39 - --- This set of tests is for the four-byte concrete representation. --- Its characteristics are: --- --- 1 bit sign --- 5 bits combination field --- 6 bits exponent continuation --- 20 bits coefficient continuation --- --- Total exponent length 8 bits --- Total coefficient length 24 bits (7 digits) --- --- Elimit = 191 (maximum encoded exponent) --- Emax = 96 (largest exponent value) --- Emin = -95 (smallest exponent value) --- bias = 101 (subtracted from encoded exponent) = -Etiny - -extended: 1 -precision: 7 -rounding: half_up -maxExponent: 96 -minExponent: -95 - --- General testcases --- (mostly derived from the Strawman 4 document and examples) -decd001 apply #A23003D0 -> -7.50 -decd002 apply -7.50 -> #A23003D0 - --- Normality -decd010 apply 1234567 -> #2654d2e7 -decd011 apply 1234567.0 -> #2654d2e7 Rounded -decd012 apply 1234567.1 -> #2654d2e7 Rounded Inexact -decd013 apply -1234567 -> #a654d2e7 -decd014 apply -1234567.0 -> #a654d2e7 Rounded -decd015 apply -1234567.1 -> #a654d2e7 Rounded Inexact - - --- Nmax and similar -decd022 apply 9.999999E+96 -> #77f3fcff -decd023 apply #77f3fcff -> 9.999999E+96 -decd024 apply 1.234567E+96 -> #47f4d2e7 -decd025 apply #47f4d2e7 -> 1.234567E+96 --- fold-downs (more below) -decd030 apply 1.23E+96 -> #47f4c000 Clamped -decd031 apply #47f4c000 -> 1.230000E+96 -decd032 apply 1E+96 -> #47f00000 Clamped -decd033 apply #47f00000 -> 1.000000E+96 - --- overflows -maxExponent: 999 -- set high so conversion causes the overflow -minExponent: -999 -decd040 apply 10E+96 -> #78000000 Overflow Rounded Inexact -decd041 apply 1.000000E+97 -> #78000000 Overflow Rounded Inexact -maxExponent: 96 -minExponent: -95 - -decd051 apply 12345 -> #225049c5 -decd052 apply #225049c5 -> 12345 -decd053 apply 1234 -> #22500534 -decd054 apply #22500534 -> 1234 -decd055 apply 123 -> #225000a3 -decd056 apply #225000a3 -> 123 -decd057 apply 12 -> #22500012 -decd058 apply #22500012 -> 12 -decd059 apply 1 -> #22500001 -decd060 apply #22500001 -> 1 -decd061 apply 1.23 -> #223000a3 -decd062 apply #223000a3 -> 1.23 -decd063 apply 123.45 -> #223049c5 -decd064 apply #223049c5 -> 123.45 - --- Nmin and below -decd071 apply 1E-95 -> #00600001 -decd072 apply #00600001 -> 1E-95 -decd073 apply 1.000000E-95 -> #04000000 -decd074 apply #04000000 -> 1.000000E-95 -decd075 apply 1.000001E-95 -> #04000001 -decd076 apply #04000001 -> 1.000001E-95 - -decd077 apply 0.100000E-95 -> #00020000 Subnormal -decd07x apply 1.00000E-96 -> 1.00000E-96 Subnormal -decd078 apply #00020000 -> 1.00000E-96 Subnormal -decd079 apply 0.000010E-95 -> #00000010 Subnormal -decd080 apply #00000010 -> 1.0E-100 Subnormal -decd081 apply 0.000001E-95 -> #00000001 Subnormal -decd082 apply #00000001 -> 1E-101 Subnormal -decd083 apply 1e-101 -> #00000001 Subnormal -decd084 apply #00000001 -> 1E-101 Subnormal -decd08x apply 1e-101 -> 1E-101 Subnormal - --- underflows -decd090 apply 1e-101 -> #00000001 Subnormal -decd091 apply 1.9e-101 -> #00000002 Subnormal Underflow Inexact Rounded -decd092 apply 1.1e-101 -> #00000001 Subnormal Underflow Inexact Rounded -decd093 apply 1.001e-101 -> #00000001 Subnormal Underflow Inexact Rounded -decd094 apply 1.000001e-101 -> #00000001 Subnormal Underflow Inexact Rounded -decd095 apply 1.0000001e-101 -> #00000001 Subnormal Underflow Inexact Rounded -decd096 apply 0.1e-101 -> #00000000 Subnormal Underflow Inexact Rounded -decd097 apply 0.001e-101 -> #00000000 Subnormal Underflow Inexact Rounded -decd098 apply 0.000001e-101 -> #00000000 Subnormal Underflow Inexact Rounded -decd099 apply 0.0000001e-101 -> #00000000 Subnormal Underflow Inexact Rounded - --- same again, negatives -- - --- Nmax and similar -decd122 apply -9.999999E+96 -> #f7f3fcff -decd123 apply #f7f3fcff -> -9.999999E+96 -decd124 apply -1.234567E+96 -> #c7f4d2e7 -decd125 apply #c7f4d2e7 -> -1.234567E+96 --- fold-downs (more below) -decd130 apply -1.23E+96 -> #c7f4c000 Clamped -decd131 apply #c7f4c000 -> -1.230000E+96 -decd132 apply -1E+96 -> #c7f00000 Clamped -decd133 apply #c7f00000 -> -1.000000E+96 - --- overflows -maxExponent: 999 -- set high so conversion causes the overflow -minExponent: -999 -decd140 apply -10E+96 -> #f8000000 Overflow Rounded Inexact -decd141 apply -1.000000E+97 -> #f8000000 Overflow Rounded Inexact -maxExponent: 96 -minExponent: -95 - -decd151 apply -12345 -> #a25049c5 -decd152 apply #a25049c5 -> -12345 -decd153 apply -1234 -> #a2500534 -decd154 apply #a2500534 -> -1234 -decd155 apply -123 -> #a25000a3 -decd156 apply #a25000a3 -> -123 -decd157 apply -12 -> #a2500012 -decd158 apply #a2500012 -> -12 -decd159 apply -1 -> #a2500001 -decd160 apply #a2500001 -> -1 -decd161 apply -1.23 -> #a23000a3 -decd162 apply #a23000a3 -> -1.23 -decd163 apply -123.45 -> #a23049c5 -decd164 apply #a23049c5 -> -123.45 - --- Nmin and below -decd171 apply -1E-95 -> #80600001 -decd172 apply #80600001 -> -1E-95 -decd173 apply -1.000000E-95 -> #84000000 -decd174 apply #84000000 -> -1.000000E-95 -decd175 apply -1.000001E-95 -> #84000001 -decd176 apply #84000001 -> -1.000001E-95 - -decd177 apply -0.100000E-95 -> #80020000 Subnormal -decd178 apply #80020000 -> -1.00000E-96 Subnormal -decd179 apply -0.000010E-95 -> #80000010 Subnormal -decd180 apply #80000010 -> -1.0E-100 Subnormal -decd181 apply -0.000001E-95 -> #80000001 Subnormal -decd182 apply #80000001 -> -1E-101 Subnormal -decd183 apply -1e-101 -> #80000001 Subnormal -decd184 apply #80000001 -> -1E-101 Subnormal - --- underflows -decd190 apply -1e-101 -> #80000001 Subnormal -decd191 apply -1.9e-101 -> #80000002 Subnormal Underflow Inexact Rounded -decd192 apply -1.1e-101 -> #80000001 Subnormal Underflow Inexact Rounded -decd193 apply -1.001e-101 -> #80000001 Subnormal Underflow Inexact Rounded -decd194 apply -1.000001e-101 -> #80000001 Subnormal Underflow Inexact Rounded -decd195 apply -1.0000001e-101 -> #80000001 Subnormal Underflow Inexact Rounded -decd196 apply -0.1e-101 -> #80000000 Subnormal Underflow Inexact Rounded -decd197 apply -0.001e-101 -> #80000000 Subnormal Underflow Inexact Rounded -decd198 apply -0.000001e-101 -> #80000000 Subnormal Underflow Inexact Rounded -decd199 apply -0.0000001e-101 -> #80000000 Subnormal Underflow Inexact Rounded - --- zeros -decd400 apply 0E-400 -> #00000000 Clamped -decd401 apply 0E-101 -> #00000000 -decd402 apply #00000000 -> 0E-101 -decd403 apply 0.000000E-95 -> #00000000 -decd404 apply #00000000 -> 0E-101 -decd405 apply 0E-2 -> #22300000 -decd406 apply #22300000 -> 0.00 -decd407 apply 0 -> #22500000 -decd408 apply #22500000 -> 0 -decd409 apply 0E+3 -> #22800000 -decd410 apply #22800000 -> 0E+3 -decd411 apply 0E+90 -> #43f00000 -decd412 apply #43f00000 -> 0E+90 --- clamped zeros... -decd413 apply 0E+91 -> #43f00000 Clamped -decd414 apply #43f00000 -> 0E+90 -decd415 apply 0E+96 -> #43f00000 Clamped -decd416 apply #43f00000 -> 0E+90 -decd417 apply 0E+400 -> #43f00000 Clamped -decd418 apply #43f00000 -> 0E+90 - --- negative zeros -decd420 apply -0E-400 -> #80000000 Clamped -decd421 apply -0E-101 -> #80000000 -decd422 apply #80000000 -> -0E-101 -decd423 apply -0.000000E-95 -> #80000000 -decd424 apply #80000000 -> -0E-101 -decd425 apply -0E-2 -> #a2300000 -decd426 apply #a2300000 -> -0.00 -decd427 apply -0 -> #a2500000 -decd428 apply #a2500000 -> -0 -decd429 apply -0E+3 -> #a2800000 -decd430 apply #a2800000 -> -0E+3 -decd431 apply -0E+90 -> #c3f00000 -decd432 apply #c3f00000 -> -0E+90 --- clamped zeros... -decd433 apply -0E+91 -> #c3f00000 Clamped -decd434 apply #c3f00000 -> -0E+90 -decd435 apply -0E+96 -> #c3f00000 Clamped -decd436 apply #c3f00000 -> -0E+90 -decd437 apply -0E+400 -> #c3f00000 Clamped -decd438 apply #c3f00000 -> -0E+90 - --- Specials -decd500 apply Infinity -> #78000000 -decd501 apply #78787878 -> #78000000 -decd502 apply #78000000 -> Infinity -decd503 apply #79797979 -> #78000000 -decd504 apply #79000000 -> Infinity -decd505 apply #7a7a7a7a -> #78000000 -decd506 apply #7a000000 -> Infinity -decd507 apply #7b7b7b7b -> #78000000 -decd508 apply #7b000000 -> Infinity -decd509 apply #7c7c7c7c -> #7c0c7c7c - -decd510 apply NaN -> #7c000000 -decd511 apply #7c000000 -> NaN -decd512 apply #7d7d7d7d -> #7c0d7d7d -decd513 apply #7d000000 -> NaN -decd514 apply #7e7e7e7e -> #7e0e7c7e -decd515 apply #7e000000 -> sNaN -decd516 apply #7f7f7f7f -> #7e0f7c7f -decd517 apply #7f000000 -> sNaN -decd518 apply #7fffffff -> sNaN999999 -decd519 apply #7fffffff -> #7e03fcff - -decd520 apply -Infinity -> #f8000000 -decd521 apply #f8787878 -> #f8000000 -decd522 apply #f8000000 -> -Infinity -decd523 apply #f9797979 -> #f8000000 -decd524 apply #f9000000 -> -Infinity -decd525 apply #fa7a7a7a -> #f8000000 -decd526 apply #fa000000 -> -Infinity -decd527 apply #fb7b7b7b -> #f8000000 -decd528 apply #fb000000 -> -Infinity - -decd529 apply -NaN -> #fc000000 -decd530 apply #fc7c7c7c -> #fc0c7c7c -decd531 apply #fc000000 -> -NaN -decd532 apply #fd7d7d7d -> #fc0d7d7d -decd533 apply #fd000000 -> -NaN -decd534 apply #fe7e7e7e -> #fe0e7c7e -decd535 apply #fe000000 -> -sNaN -decd536 apply #ff7f7f7f -> #fe0f7c7f -decd537 apply #ff000000 -> -sNaN -decd538 apply #ffffffff -> -sNaN999999 -decd539 apply #ffffffff -> #fe03fcff - --- diagnostic NaNs -decd540 apply NaN -> #7c000000 -decd541 apply NaN0 -> #7c000000 -decd542 apply NaN1 -> #7c000001 -decd543 apply NaN12 -> #7c000012 -decd544 apply NaN79 -> #7c000079 -decd545 apply NaN12345 -> #7c0049c5 -decd546 apply NaN123456 -> #7c028e56 -decd547 apply NaN799799 -> #7c0f7fdf -decd548 apply NaN999999 -> #7c03fcff -decd549 apply NaN1234567 -> #7c000000 -- too many digits - - --- fold-down full sequence -decd601 apply 1E+96 -> #47f00000 Clamped -decd602 apply #47f00000 -> 1.000000E+96 -decd603 apply 1E+95 -> #43f20000 Clamped -decd604 apply #43f20000 -> 1.00000E+95 -decd605 apply 1E+94 -> #43f04000 Clamped -decd606 apply #43f04000 -> 1.0000E+94 -decd607 apply 1E+93 -> #43f00400 Clamped -decd608 apply #43f00400 -> 1.000E+93 -decd609 apply 1E+92 -> #43f00080 Clamped -decd610 apply #43f00080 -> 1.00E+92 -decd611 apply 1E+91 -> #43f00010 Clamped -decd612 apply #43f00010 -> 1.0E+91 -decd613 apply 1E+90 -> #43f00001 -decd614 apply #43f00001 -> 1E+90 - - --- Selected DPD codes -decd700 apply #22500000 -> 0 -decd701 apply #22500009 -> 9 -decd702 apply #22500010 -> 10 -decd703 apply #22500019 -> 19 -decd704 apply #22500020 -> 20 -decd705 apply #22500029 -> 29 -decd706 apply #22500030 -> 30 -decd707 apply #22500039 -> 39 -decd708 apply #22500040 -> 40 -decd709 apply #22500049 -> 49 -decd710 apply #22500050 -> 50 -decd711 apply #22500059 -> 59 -decd712 apply #22500060 -> 60 -decd713 apply #22500069 -> 69 -decd714 apply #22500070 -> 70 -decd715 apply #22500071 -> 71 -decd716 apply #22500072 -> 72 -decd717 apply #22500073 -> 73 -decd718 apply #22500074 -> 74 -decd719 apply #22500075 -> 75 -decd720 apply #22500076 -> 76 -decd721 apply #22500077 -> 77 -decd722 apply #22500078 -> 78 -decd723 apply #22500079 -> 79 - -decd730 apply #2250029e -> 994 -decd731 apply #2250029f -> 995 -decd732 apply #225002a0 -> 520 -decd733 apply #225002a1 -> 521 - --- DPD: one of each of the huffman groups -decd740 apply #225003f7 -> 777 -decd741 apply #225003f8 -> 778 -decd742 apply #225003eb -> 787 -decd743 apply #2250037d -> 877 -decd744 apply #2250039f -> 997 -decd745 apply #225003bf -> 979 -decd746 apply #225003df -> 799 -decd747 apply #2250006e -> 888 - - --- DPD all-highs cases (includes the 24 redundant codes) -decd750 apply #2250006e -> 888 -decd751 apply #2250016e -> 888 -decd752 apply #2250026e -> 888 -decd753 apply #2250036e -> 888 -decd754 apply #2250006f -> 889 -decd755 apply #2250016f -> 889 -decd756 apply #2250026f -> 889 -decd757 apply #2250036f -> 889 - -decd760 apply #2250007e -> 898 -decd761 apply #2250017e -> 898 -decd762 apply #2250027e -> 898 -decd763 apply #2250037e -> 898 -decd764 apply #2250007f -> 899 -decd765 apply #2250017f -> 899 -decd766 apply #2250027f -> 899 -decd767 apply #2250037f -> 899 - -decd770 apply #225000ee -> 988 -decd771 apply #225001ee -> 988 -decd772 apply #225002ee -> 988 -decd773 apply #225003ee -> 988 -decd774 apply #225000ef -> 989 -decd775 apply #225001ef -> 989 -decd776 apply #225002ef -> 989 -decd777 apply #225003ef -> 989 - -decd780 apply #225000fe -> 998 -decd781 apply #225001fe -> 998 -decd782 apply #225002fe -> 998 -decd783 apply #225003fe -> 998 -decd784 apply #225000ff -> 999 -decd785 apply #225001ff -> 999 -decd786 apply #225002ff -> 999 -decd787 apply #225003ff -> 999 - Deleted: /python/branches/py3k/Lib/test/decimaltestdata/decimal64.decTest ============================================================================== --- /python/branches/py3k/Lib/test/decimaltestdata/decimal64.decTest Wed Sep 19 05:06:30 2007 +++ (empty file) @@ -1,444 +0,0 @@ ------------------------------------------------------------------------- --- decimal64.decTest -- decimal eight-byte format testcases -- --- Copyright (c) IBM Corporation, 2000, 2003. All rights reserved. -- ------------------------------------------------------------------------- --- Please see the document "General Decimal Arithmetic Testcases" -- --- at http://www2.hursley.ibm.com/decimal for the description of -- --- these testcases. -- --- -- --- These testcases are experimental ('beta' versions), and they -- --- may contain errors. They are offered on an as-is basis. In -- --- particular, achieving the same results as the tests here is not -- --- a guarantee that an implementation complies with any Standard -- --- or specification. The tests are not exhaustive. -- --- -- --- Please send comments, suggestions, and corrections to the author: -- --- Mike Cowlishaw, IBM Fellow -- --- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- --- mfc at uk.ibm.com -- ------------------------------------------------------------------------- -version: 2.39 - --- This set of tests is for the eight-byte concrete representation. --- Its characteristics are: --- --- 1 bit sign --- 5 bits combination field --- 8 bits exponent continuation --- 50 bits coefficient continuation --- --- Total exponent length 10 bits --- Total coefficient length 54 bits (16 digits) --- --- Elimit = 767 (maximum encoded exponent) --- Emax = 384 (largest exponent value) --- Emin = -383 (smallest exponent value) --- bias = 398 (subtracted from encoded exponent) = -Etiny - -extended: 1 -precision: 16 -rounding: half_up -maxExponent: 384 -minExponent: -383 - --- General testcases --- (mostly derived from the Strawman 4 document and examples) -dece001 apply #A2300000000003D0 -> -7.50 -dece002 apply -7.50 -> #A2300000000003D0 - --- Normality -dece010 apply 1234567890123456 -> #263934b9c1e28e56 -dece011 apply 1234567890123456.0 -> #263934b9c1e28e56 Rounded -dece012 apply 1234567890123456.1 -> #263934b9c1e28e56 Rounded Inexact -dece013 apply -1234567890123456 -> #a63934b9c1e28e56 -dece014 apply -1234567890123456.0 -> #a63934b9c1e28e56 Rounded -dece015 apply -1234567890123456.1 -> #a63934b9c1e28e56 Rounded Inexact - - --- Nmax and similar -dece022 apply 9.999999999999999E+384 -> #77fcff3fcff3fcff -dece023 apply #77fcff3fcff3fcff -> 9.999999999999999E+384 -dece024 apply 1.234567890123456E+384 -> #47fd34b9c1e28e56 -dece025 apply #47fd34b9c1e28e56 -> 1.234567890123456E+384 --- fold-downs (more below) -dece030 apply 1.23E+384 -> #47fd300000000000 Clamped -dece031 apply #47fd300000000000 -> 1.230000000000000E+384 -dece032 apply 1E+384 -> #47fc000000000000 Clamped -dece033 apply #47fc000000000000 -> 1.000000000000000E+384 - --- overflows -maxExponent: 999 -- set high so conversion causes the overflow -minExponent: -999 -dece040 apply 10E+384 -> #7800000000000000 Overflow Rounded Inexact -dece041 apply 1.000000000000000E+385 -> #7800000000000000 Overflow Rounded Inexact -maxExponent: 384 -minExponent: -383 - -dece051 apply 12345 -> #22380000000049c5 -dece052 apply #22380000000049c5 -> 12345 -dece053 apply 1234 -> #2238000000000534 -dece054 apply #2238000000000534 -> 1234 -dece055 apply 123 -> #22380000000000a3 -dece056 apply #22380000000000a3 -> 123 -dece057 apply 12 -> #2238000000000012 -dece058 apply #2238000000000012 -> 12 -dece059 apply 1 -> #2238000000000001 -dece060 apply #2238000000000001 -> 1 -dece061 apply 1.23 -> #22300000000000a3 -dece062 apply #22300000000000a3 -> 1.23 -dece063 apply 123.45 -> #22300000000049c5 -dece064 apply #22300000000049c5 -> 123.45 - --- Nmin and below -dece071 apply 1E-383 -> #003c000000000001 -dece072 apply #003c000000000001 -> 1E-383 -dece073 apply 1.000000000000000E-383 -> #0400000000000000 -dece074 apply #0400000000000000 -> 1.000000000000000E-383 -dece075 apply 1.000000000000001E-383 -> #0400000000000001 -dece076 apply #0400000000000001 -> 1.000000000000001E-383 - -dece077 apply 0.100000000000000E-383 -> #0000800000000000 Subnormal -dece078 apply #0000800000000000 -> 1.00000000000000E-384 Subnormal -dece079 apply 0.000000000000010E-383 -> #0000000000000010 Subnormal -dece080 apply #0000000000000010 -> 1.0E-397 Subnormal -dece081 apply 0.00000000000001E-383 -> #0004000000000001 Subnormal -dece082 apply #0004000000000001 -> 1E-397 Subnormal -dece083 apply 0.000000000000001E-383 -> #0000000000000001 Subnormal -dece084 apply #0000000000000001 -> 1E-398 Subnormal - --- underflows -dece090 apply 1e-398 -> #0000000000000001 Subnormal -dece091 apply 1.9e-398 -> #0000000000000002 Subnormal Underflow Inexact Rounded -dece092 apply 1.1e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded -dece093 apply 1.00000000001e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded -dece094 apply 1.00000000000001e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded -dece095 apply 1.000000000000001e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded -dece096 apply 0.1e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded -dece097 apply 0.00000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded -dece098 apply 0.00000000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded -dece099 apply 0.000000000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded - --- Same again, negatives --- Nmax and similar -dece122 apply -9.999999999999999E+384 -> #f7fcff3fcff3fcff -dece123 apply #f7fcff3fcff3fcff -> -9.999999999999999E+384 -dece124 apply -1.234567890123456E+384 -> #c7fd34b9c1e28e56 -dece125 apply #c7fd34b9c1e28e56 -> -1.234567890123456E+384 --- fold-downs (more below) -dece130 apply -1.23E+384 -> #c7fd300000000000 Clamped -dece131 apply #c7fd300000000000 -> -1.230000000000000E+384 -dece132 apply -1E+384 -> #c7fc000000000000 Clamped -dece133 apply #c7fc000000000000 -> -1.000000000000000E+384 - --- overflows -maxExponent: 999 -- set high so conversion causes the overflow -minExponent: -999 -dece140 apply -10E+384 -> #f800000000000000 Overflow Rounded Inexact -dece141 apply -1.000000000000000E+385 -> #f800000000000000 Overflow Rounded Inexact -maxExponent: 384 -minExponent: -383 - -dece151 apply -12345 -> #a2380000000049c5 -dece152 apply #a2380000000049c5 -> -12345 -dece153 apply -1234 -> #a238000000000534 -dece154 apply #a238000000000534 -> -1234 -dece155 apply -123 -> #a2380000000000a3 -dece156 apply #a2380000000000a3 -> -123 -dece157 apply -12 -> #a238000000000012 -dece158 apply #a238000000000012 -> -12 -dece159 apply -1 -> #a238000000000001 -dece160 apply #a238000000000001 -> -1 -dece161 apply -1.23 -> #a2300000000000a3 -dece162 apply #a2300000000000a3 -> -1.23 -dece163 apply -123.45 -> #a2300000000049c5 -dece164 apply #a2300000000049c5 -> -123.45 - --- Nmin and below -dece171 apply -1E-383 -> #803c000000000001 -dece172 apply #803c000000000001 -> -1E-383 -dece173 apply -1.000000000000000E-383 -> #8400000000000000 -dece174 apply #8400000000000000 -> -1.000000000000000E-383 -dece175 apply -1.000000000000001E-383 -> #8400000000000001 -dece176 apply #8400000000000001 -> -1.000000000000001E-383 - -dece177 apply -0.100000000000000E-383 -> #8000800000000000 Subnormal -dece178 apply #8000800000000000 -> -1.00000000000000E-384 Subnormal -dece179 apply -0.000000000000010E-383 -> #8000000000000010 Subnormal -dece180 apply #8000000000000010 -> -1.0E-397 Subnormal -dece181 apply -0.00000000000001E-383 -> #8004000000000001 Subnormal -dece182 apply #8004000000000001 -> -1E-397 Subnormal -dece183 apply -0.000000000000001E-383 -> #8000000000000001 Subnormal -dece184 apply #8000000000000001 -> -1E-398 Subnormal - --- underflows -dece189 apply -1e-398 -> #8000000000000001 Subnormal -dece190 apply -1.0e-398 -> #8000000000000001 Subnormal Rounded -dece191 apply -1.9e-398 -> #8000000000000002 Subnormal Underflow Inexact Rounded -dece192 apply -1.1e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded -dece193 apply -1.00000000001e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded -dece194 apply -1.00000000000001e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded -dece195 apply -1.000000000000001e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded -dece196 apply -0.1e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded -dece197 apply -0.00000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded -dece198 apply -0.00000000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded -dece199 apply -0.000000000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded - --- zeros -dece401 apply 0E-500 -> #0000000000000000 Clamped -dece402 apply 0E-400 -> #0000000000000000 Clamped -dece403 apply 0E-398 -> #0000000000000000 -dece404 apply #0000000000000000 -> 0E-398 -dece405 apply 0.000000000000000E-383 -> #0000000000000000 -dece406 apply #0000000000000000 -> 0E-398 -dece407 apply 0E-2 -> #2230000000000000 -dece408 apply #2230000000000000 -> 0.00 -dece409 apply 0 -> #2238000000000000 -dece410 apply #2238000000000000 -> 0 -dece411 apply 0E+3 -> #2244000000000000 -dece412 apply #2244000000000000 -> 0E+3 -dece413 apply 0E+369 -> #43fc000000000000 -dece414 apply #43fc000000000000 -> 0E+369 --- clamped zeros... -dece415 apply 0E+370 -> #43fc000000000000 Clamped -dece416 apply #43fc000000000000 -> 0E+369 -dece417 apply 0E+384 -> #43fc000000000000 Clamped -dece418 apply #43fc000000000000 -> 0E+369 -dece419 apply 0E+400 -> #43fc000000000000 Clamped -dece420 apply #43fc000000000000 -> 0E+369 -dece421 apply 0E+500 -> #43fc000000000000 Clamped -dece422 apply #43fc000000000000 -> 0E+369 - --- negative zeros -dece431 apply -0E-400 -> #8000000000000000 Clamped -dece432 apply -0E-400 -> #8000000000000000 Clamped -dece433 apply -0E-398 -> #8000000000000000 -dece434 apply #8000000000000000 -> -0E-398 -dece435 apply -0.000000000000000E-383 -> #8000000000000000 -dece436 apply #8000000000000000 -> -0E-398 -dece437 apply -0E-2 -> #a230000000000000 -dece438 apply #a230000000000000 -> -0.00 -dece439 apply -0 -> #a238000000000000 -dece440 apply #a238000000000000 -> -0 -dece441 apply -0E+3 -> #a244000000000000 -dece442 apply #a244000000000000 -> -0E+3 -dece443 apply -0E+369 -> #c3fc000000000000 -dece444 apply #c3fc000000000000 -> -0E+369 --- clamped zeros... -dece445 apply -0E+370 -> #c3fc000000000000 Clamped -dece446 apply #c3fc000000000000 -> -0E+369 -dece447 apply -0E+384 -> #c3fc000000000000 Clamped -dece448 apply #c3fc000000000000 -> -0E+369 -dece449 apply -0E+400 -> #c3fc000000000000 Clamped -dece450 apply #c3fc000000000000 -> -0E+369 -dece451 apply -0E+500 -> #c3fc000000000000 Clamped -dece452 apply #c3fc000000000000 -> -0E+369 - --- Specials -dece500 apply Infinity -> #7800000000000000 -dece501 apply #7878787878787878 -> #7800000000000000 -dece502 apply #7800000000000000 -> Infinity -dece503 apply #7979797979797979 -> #7800000000000000 -dece504 apply #7900000000000000 -> Infinity -dece505 apply #7a7a7a7a7a7a7a7a -> #7800000000000000 -dece506 apply #7a00000000000000 -> Infinity -dece507 apply #7b7b7b7b7b7b7b7b -> #7800000000000000 -dece508 apply #7b00000000000000 -> Infinity - -dece509 apply NaN -> #7c00000000000000 -dece510 apply #7c7c7c7c7c7c7c7c -> #7c007c7c7c7c7c7c -dece511 apply #7c00000000000000 -> NaN -dece512 apply #7d7d7d7d7d7d7d7d -> #7c017d7d7d7d7d7d -dece513 apply #7d00000000000000 -> NaN -dece514 apply #7e7e7e7e7e7e7e7e -> #7e007e7e7e7e7c7e -dece515 apply #7e00000000000000 -> sNaN -dece516 apply #7f7f7f7f7f7f7f7f -> #7e007f7f7f7f7c7f -dece517 apply #7f00000000000000 -> sNaN -dece518 apply #7fffffffffffffff -> sNaN999999999999999 -dece519 apply #7fffffffffffffff -> #7e00ff3fcff3fcff - -dece520 apply -Infinity -> #f800000000000000 -dece521 apply #f878787878787878 -> #f800000000000000 -dece522 apply #f800000000000000 -> -Infinity -dece523 apply #f979797979797979 -> #f800000000000000 -dece524 apply #f900000000000000 -> -Infinity -dece525 apply #fa7a7a7a7a7a7a7a -> #f800000000000000 -dece526 apply #fa00000000000000 -> -Infinity -dece527 apply #fb7b7b7b7b7b7b7b -> #f800000000000000 -dece528 apply #fb00000000000000 -> -Infinity - -dece529 apply -NaN -> #fc00000000000000 -dece530 apply #fc7c7c7c7c7c7c7c -> #fc007c7c7c7c7c7c -dece531 apply #fc00000000000000 -> -NaN -dece532 apply #fd7d7d7d7d7d7d7d -> #fc017d7d7d7d7d7d -dece533 apply #fd00000000000000 -> -NaN -dece534 apply #fe7e7e7e7e7e7e7e -> #fe007e7e7e7e7c7e -dece535 apply #fe00000000000000 -> -sNaN -dece536 apply #ff7f7f7f7f7f7f7f -> #fe007f7f7f7f7c7f -dece537 apply #ff00000000000000 -> -sNaN -dece538 apply #ffffffffffffffff -> -sNaN999999999999999 -dece539 apply #ffffffffffffffff -> #fe00ff3fcff3fcff - --- diagnostic NaNs -dece540 apply NaN -> #7c00000000000000 -dece541 apply NaN0 -> #7c00000000000000 -dece542 apply NaN1 -> #7c00000000000001 -dece543 apply NaN12 -> #7c00000000000012 -dece544 apply NaN79 -> #7c00000000000079 -dece545 apply NaN12345 -> #7c000000000049c5 -dece546 apply NaN123456 -> #7c00000000028e56 -dece547 apply NaN799799 -> #7c000000000f7fdf -dece548 apply NaN799799799799799 -> #7c03dff7fdff7fdf -dece549 apply NaN999999999999999 -> #7c00ff3fcff3fcff -dece550 apply NaN1234567890123456 -> #7c00000000000000 -- too many digits - --- fold-down full sequence -dece601 apply 1E+384 -> #47fc000000000000 Clamped -dece602 apply #47fc000000000000 -> 1.000000000000000E+384 -dece603 apply 1E+383 -> #43fc800000000000 Clamped -dece604 apply #43fc800000000000 -> 1.00000000000000E+383 -dece605 apply 1E+382 -> #43fc100000000000 Clamped -dece606 apply #43fc100000000000 -> 1.0000000000000E+382 -dece607 apply 1E+381 -> #43fc010000000000 Clamped -dece608 apply #43fc010000000000 -> 1.000000000000E+381 -dece609 apply 1E+380 -> #43fc002000000000 Clamped -dece610 apply #43fc002000000000 -> 1.00000000000E+380 -dece611 apply 1E+379 -> #43fc000400000000 Clamped -dece612 apply #43fc000400000000 -> 1.0000000000E+379 -dece613 apply 1E+378 -> #43fc000040000000 Clamped -dece614 apply #43fc000040000000 -> 1.000000000E+378 -dece615 apply 1E+377 -> #43fc000008000000 Clamped -dece616 apply #43fc000008000000 -> 1.00000000E+377 -dece617 apply 1E+376 -> #43fc000001000000 Clamped -dece618 apply #43fc000001000000 -> 1.0000000E+376 -dece619 apply 1E+375 -> #43fc000000100000 Clamped -dece620 apply #43fc000000100000 -> 1.000000E+375 -dece621 apply 1E+374 -> #43fc000000020000 Clamped -dece622 apply #43fc000000020000 -> 1.00000E+374 -dece623 apply 1E+373 -> #43fc000000004000 Clamped -dece624 apply #43fc000000004000 -> 1.0000E+373 -dece625 apply 1E+372 -> #43fc000000000400 Clamped -dece626 apply #43fc000000000400 -> 1.000E+372 -dece627 apply 1E+371 -> #43fc000000000080 Clamped -dece628 apply #43fc000000000080 -> 1.00E+371 -dece629 apply 1E+370 -> #43fc000000000010 Clamped -dece630 apply #43fc000000000010 -> 1.0E+370 -dece631 apply 1E+369 -> #43fc000000000001 -dece632 apply #43fc000000000001 -> 1E+369 -dece633 apply 1E+368 -> #43f8000000000001 -dece634 apply #43f8000000000001 -> 1E+368 --- same with 9s -dece641 apply 9E+384 -> #77fc000000000000 Clamped -dece642 apply #77fc000000000000 -> 9.000000000000000E+384 -dece643 apply 9E+383 -> #43fc8c0000000000 Clamped -dece644 apply #43fc8c0000000000 -> 9.00000000000000E+383 -dece645 apply 9E+382 -> #43fc1a0000000000 Clamped -dece646 apply #43fc1a0000000000 -> 9.0000000000000E+382 -dece647 apply 9E+381 -> #43fc090000000000 Clamped -dece648 apply #43fc090000000000 -> 9.000000000000E+381 -dece649 apply 9E+380 -> #43fc002300000000 Clamped -dece650 apply #43fc002300000000 -> 9.00000000000E+380 -dece651 apply 9E+379 -> #43fc000680000000 Clamped -dece652 apply #43fc000680000000 -> 9.0000000000E+379 -dece653 apply 9E+378 -> #43fc000240000000 Clamped -dece654 apply #43fc000240000000 -> 9.000000000E+378 -dece655 apply 9E+377 -> #43fc000008c00000 Clamped -dece656 apply #43fc000008c00000 -> 9.00000000E+377 -dece657 apply 9E+376 -> #43fc000001a00000 Clamped -dece658 apply #43fc000001a00000 -> 9.0000000E+376 -dece659 apply 9E+375 -> #43fc000000900000 Clamped -dece660 apply #43fc000000900000 -> 9.000000E+375 -dece661 apply 9E+374 -> #43fc000000023000 Clamped -dece662 apply #43fc000000023000 -> 9.00000E+374 -dece663 apply 9E+373 -> #43fc000000006800 Clamped -dece664 apply #43fc000000006800 -> 9.0000E+373 -dece665 apply 9E+372 -> #43fc000000002400 Clamped -dece666 apply #43fc000000002400 -> 9.000E+372 -dece667 apply 9E+371 -> #43fc00000000008c Clamped -dece668 apply #43fc00000000008c -> 9.00E+371 -dece669 apply 9E+370 -> #43fc00000000001a Clamped -dece670 apply #43fc00000000001a -> 9.0E+370 -dece671 apply 9E+369 -> #43fc000000000009 -dece672 apply #43fc000000000009 -> 9E+369 -dece673 apply 9E+368 -> #43f8000000000009 -dece674 apply #43f8000000000009 -> 9E+368 - - --- Selected DPD codes -dece700 apply #2238000000000000 -> 0 -dece701 apply #2238000000000009 -> 9 -dece702 apply #2238000000000010 -> 10 -dece703 apply #2238000000000019 -> 19 -dece704 apply #2238000000000020 -> 20 -dece705 apply #2238000000000029 -> 29 -dece706 apply #2238000000000030 -> 30 -dece707 apply #2238000000000039 -> 39 -dece708 apply #2238000000000040 -> 40 -dece709 apply #2238000000000049 -> 49 -dece710 apply #2238000000000050 -> 50 -dece711 apply #2238000000000059 -> 59 -dece712 apply #2238000000000060 -> 60 -dece713 apply #2238000000000069 -> 69 -dece714 apply #2238000000000070 -> 70 -dece715 apply #2238000000000071 -> 71 -dece716 apply #2238000000000072 -> 72 -dece717 apply #2238000000000073 -> 73 -dece718 apply #2238000000000074 -> 74 -dece719 apply #2238000000000075 -> 75 -dece720 apply #2238000000000076 -> 76 -dece721 apply #2238000000000077 -> 77 -dece722 apply #2238000000000078 -> 78 -dece723 apply #2238000000000079 -> 79 - -dece730 apply #223800000000029e -> 994 -dece731 apply #223800000000029f -> 995 -dece732 apply #22380000000002a0 -> 520 -dece733 apply #22380000000002a1 -> 521 - --- DPD: one of each of the huffman groups -dece740 apply #22380000000003f7 -> 777 -dece741 apply #22380000000003f8 -> 778 -dece742 apply #22380000000003eb -> 787 -dece743 apply #223800000000037d -> 877 -dece744 apply #223800000000039f -> 997 -dece745 apply #22380000000003bf -> 979 -dece746 apply #22380000000003df -> 799 -dece747 apply #223800000000006e -> 888 - - --- DPD all-highs cases (includes the 24 redundant codes) -dece750 apply #223800000000006e -> 888 -dece751 apply #223800000000016e -> 888 -dece752 apply #223800000000026e -> 888 -dece753 apply #223800000000036e -> 888 -dece754 apply #223800000000006f -> 889 -dece755 apply #223800000000016f -> 889 -dece756 apply #223800000000026f -> 889 -dece757 apply #223800000000036f -> 889 - -dece760 apply #223800000000007e -> 898 -dece761 apply #223800000000017e -> 898 -dece762 apply #223800000000027e -> 898 -dece763 apply #223800000000037e -> 898 -dece764 apply #223800000000007f -> 899 -dece765 apply #223800000000017f -> 899 -dece766 apply #223800000000027f -> 899 -dece767 apply #223800000000037f -> 899 - -dece770 apply #22380000000000ee -> 988 -dece771 apply #22380000000001ee -> 988 -dece772 apply #22380000000002ee -> 988 -dece773 apply #22380000000003ee -> 988 -dece774 apply #22380000000000ef -> 989 -dece775 apply #22380000000001ef -> 989 -dece776 apply #22380000000002ef -> 989 -dece777 apply #22380000000003ef -> 989 - -dece780 apply #22380000000000fe -> 998 -dece781 apply #22380000000001fe -> 998 -dece782 apply #22380000000002fe -> 998 -dece783 apply #22380000000003fe -> 998 -dece784 apply #22380000000000ff -> 999 -dece785 apply #22380000000001ff -> 999 -dece786 apply #22380000000002ff -> 999 -dece787 apply #22380000000003ff -> 999 - Modified: python/branches/py3k/Lib/test/decimaltestdata/divide.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/divide.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/divide.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- divide.decTest -- decimal division -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -47,41 +47,45 @@ divx018 divide 2. 2 -> 1 divx019 divide 20 20 -> 1 -divx020 divide 187 187 -> 1 -divx021 divide 5 2 -> 2.5 -divx022 divide 5 2.0 -> 2.5 -divx023 divide 5 2.000 -> 2.5 -divx024 divide 5 0.20 -> 25 -divx025 divide 5 0.200 -> 25 -divx026 divide 10 1 -> 10 -divx027 divide 100 1 -> 100 -divx028 divide 1000 1 -> 1000 -divx029 divide 1000 100 -> 10 - -divx030 divide 1 2 -> 0.5 -divx031 divide 1 4 -> 0.25 -divx032 divide 1 8 -> 0.125 -divx033 divide 1 16 -> 0.0625 -divx034 divide 1 32 -> 0.03125 -divx035 divide 1 64 -> 0.015625 -divx040 divide 1 -2 -> -0.5 -divx041 divide 1 -4 -> -0.25 -divx042 divide 1 -8 -> -0.125 -divx043 divide 1 -16 -> -0.0625 -divx044 divide 1 -32 -> -0.03125 -divx045 divide 1 -64 -> -0.015625 -divx050 divide -1 2 -> -0.5 -divx051 divide -1 4 -> -0.25 -divx052 divide -1 8 -> -0.125 -divx053 divide -1 16 -> -0.0625 -divx054 divide -1 32 -> -0.03125 -divx055 divide -1 64 -> -0.015625 -divx060 divide -1 -2 -> 0.5 -divx061 divide -1 -4 -> 0.25 -divx062 divide -1 -8 -> 0.125 -divx063 divide -1 -16 -> 0.0625 -divx064 divide -1 -32 -> 0.03125 -divx065 divide -1 -64 -> 0.015625 +divx020 divide 187 187 -> 1 +divx021 divide 5 2 -> 2.5 +divx022 divide 50 20 -> 2.5 +divx023 divide 500 200 -> 2.5 +divx024 divide 50.0 20.0 -> 2.5 +divx025 divide 5.00 2.00 -> 2.5 +divx026 divide 5 2.0 -> 2.5 +divx027 divide 5 2.000 -> 2.5 +divx028 divide 5 0.20 -> 25 +divx029 divide 5 0.200 -> 25 +divx030 divide 10 1 -> 10 +divx031 divide 100 1 -> 100 +divx032 divide 1000 1 -> 1000 +divx033 divide 1000 100 -> 10 + +divx035 divide 1 2 -> 0.5 +divx036 divide 1 4 -> 0.25 +divx037 divide 1 8 -> 0.125 +divx038 divide 1 16 -> 0.0625 +divx039 divide 1 32 -> 0.03125 +divx040 divide 1 64 -> 0.015625 +divx041 divide 1 -2 -> -0.5 +divx042 divide 1 -4 -> -0.25 +divx043 divide 1 -8 -> -0.125 +divx044 divide 1 -16 -> -0.0625 +divx045 divide 1 -32 -> -0.03125 +divx046 divide 1 -64 -> -0.015625 +divx047 divide -1 2 -> -0.5 +divx048 divide -1 4 -> -0.25 +divx049 divide -1 8 -> -0.125 +divx050 divide -1 16 -> -0.0625 +divx051 divide -1 32 -> -0.03125 +divx052 divide -1 64 -> -0.015625 +divx053 divide -1 -2 -> 0.5 +divx054 divide -1 -4 -> 0.25 +divx055 divide -1 -8 -> 0.125 +divx056 divide -1 -16 -> 0.0625 +divx057 divide -1 -32 -> 0.03125 +divx058 divide -1 -64 -> 0.015625 divx070 divide 999999999 1 -> 999999999 divx071 divide 999999999.4 1 -> 999999999 Inexact Rounded @@ -763,9 +767,9 @@ divx964 divide 1e-600000000 1e+400000005 -> 1E-1000000005 Subnormal divx965 divide 1e-600000000 1e+400000006 -> 1E-1000000006 Subnormal divx966 divide 1e-600000000 1e+400000007 -> 1E-1000000007 Subnormal -divx967 divide 1e-600000000 1e+400000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -divx968 divide 1e-600000000 1e+400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -divx969 divide 1e-600000000 1e+400000010 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +divx967 divide 1e-600000000 1e+400000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +divx968 divide 1e-600000000 1e+400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +divx969 divide 1e-600000000 1e+400000010 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -- [no equivalent of 'subnormal' for overflow] divx970 divide 1e+600000000 1e-400000001 -> Infinity Overflow Inexact Rounded divx971 divide 1e+600000000 1e-400000002 -> Infinity Overflow Inexact Rounded @@ -779,10 +783,10 @@ divx979 divide 1e+600000000 1e-400000010 -> Infinity Overflow Inexact Rounded -- Sign after overflow and underflow -divx980 divide 1e-600000000 1e+400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -divx981 divide 1e-600000000 -1e+400000009 -> -0E-1000000007 Underflow Subnormal Inexact Rounded -divx982 divide -1e-600000000 1e+400000009 -> -0E-1000000007 Underflow Subnormal Inexact Rounded -divx983 divide -1e-600000000 -1e+400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +divx980 divide 1e-600000000 1e+400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +divx981 divide 1e-600000000 -1e+400000009 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +divx982 divide -1e-600000000 1e+400000009 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +divx983 divide -1e-600000000 -1e+400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped divx984 divide 1e+600000000 1e-400000009 -> Infinity Overflow Inexact Rounded divx985 divide 1e+600000000 -1e-400000009 -> -Infinity Overflow Inexact Rounded divx986 divide -1e+600000000 1e-400000009 -> -Infinity Overflow Inexact Rounded @@ -812,6 +816,38 @@ -- 1.465811965811965811965811965811965811966E+7000 divx1010 divide 343E6000 234E-1000 -> Infinity Overflow Inexact Rounded +precision: 34 +rounding: half_up +maxExponent: 6144 +minExponent: -6143 + +-- Examples from SQL proposal (Krishna Kulkarni) +precision: 7 +divx1021 divide 1E0 1E0 -> 1 +divx1022 divide 1E0 2E0 -> 0.5 +divx1023 divide 1E0 3E0 -> 0.3333333 Inexact Rounded +divx1024 divide 100E-2 1000E-3 -> 1 +divx1025 divide 24E-1 2E0 -> 1.2 +divx1026 divide 2400E-3 2E0 -> 1.200 +divx1027 divide 5E0 2E0 -> 2.5 +divx1028 divide 5E0 20E-1 -> 2.5 +divx1029 divide 5E0 2000E-3 -> 2.5 +divx1030 divide 5E0 2E-1 -> 25 +divx1031 divide 5E0 20E-2 -> 25 +divx1032 divide 480E-2 3E0 -> 1.60 +divx1033 divide 47E-1 2E0 -> 2.35 + +-- ECMAScript bad examples +rounding: half_down +precision: 7 +divx1050 divide 5 9 -> 0.5555556 Inexact Rounded +rounding: half_even +divx1051 divide 5 11 -> 0.4545455 Inexact Rounded + +-- payload decapitate +precision: 5 +divx1055 divide sNaN987654321 1 -> NaN54321 Invalid_operation + -- Null tests divx9998 divide 10 # -> NaN Invalid_operation divx9999 divide # 10 -> NaN Invalid_operation Modified: python/branches/py3k/Lib/test/decimaltestdata/divideint.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/divideint.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/divideint.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- divideint.decTest -- decimal integer division -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -234,6 +234,22 @@ dvix287 divideint 0.1 9999e-999999997 -> NaN Division_impossible dvix288 divideint 0.1 99999e-999999997 -> NaN Division_impossible +-- GD edge cases: lhs smaller than rhs but more digits +dvix301 divideint 0.9 2 -> 0 +dvix302 divideint 0.9 2.0 -> 0 +dvix303 divideint 0.9 2.1 -> 0 +dvix304 divideint 0.9 2.00 -> 0 +dvix305 divideint 0.9 2.01 -> 0 +dvix306 divideint 0.12 1 -> 0 +dvix307 divideint 0.12 1.0 -> 0 +dvix308 divideint 0.12 1.00 -> 0 +dvix309 divideint 0.12 1.0 -> 0 +dvix310 divideint 0.12 1.00 -> 0 +dvix311 divideint 0.12 2 -> 0 +dvix312 divideint 0.12 2.0 -> 0 +dvix313 divideint 0.12 2.1 -> 0 +dvix314 divideint 0.12 2.00 -> 0 +dvix315 divideint 0.12 2.01 -> 0 -- overflow and underflow tests [from divide] maxexponent: 999999999 Modified: python/branches/py3k/Lib/test/decimaltestdata/inexact.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/inexact.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/inexact.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- inexact.decTest -- decimal inexact and rounded edge cases -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 Modified: python/branches/py3k/Lib/test/decimaltestdata/max.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/max.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/max.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- max.decTest -- decimal maximum -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- we assume that base comparison is tested in compare.decTest, so -- these mainly cover special cases and rounding @@ -331,6 +331,33 @@ maxx466 max -1000 -1E+3 -> -1000 maxx467 max -1E+3 -1000 -> -1000 +-- rounding (results treated as though plus) +maxexponent: 999999999 +minexponent: -999999999 +precision: 3 + +maxx470 max 1 .5 -> 1 +maxx471 max 10 5 -> 10 +maxx472 max 100 50 -> 100 +maxx473 max 1000 500 -> 1.00E+3 Rounded +maxx474 max 10000 5000 -> 1.00E+4 Rounded +maxx475 max 6 .5 -> 6 +maxx476 max 66 5 -> 66 +maxx477 max 666 50 -> 666 +maxx478 max 6666 500 -> 6.67E+3 Rounded Inexact +maxx479 max 66666 5000 -> 6.67E+4 Rounded Inexact +maxx480 max 33333 5000 -> 3.33E+4 Rounded Inexact +maxx481 max .5 1 -> 1 +maxx482 max .5 10 -> 10 +maxx483 max .5 100 -> 100 +maxx484 max .5 1000 -> 1.00E+3 Rounded +maxx485 max .5 10000 -> 1.00E+4 Rounded +maxx486 max .5 6 -> 6 +maxx487 max .5 66 -> 66 +maxx488 max .5 666 -> 666 +maxx489 max .5 6666 -> 6.67E+3 Rounded Inexact +maxx490 max .5 66666 -> 6.67E+4 Rounded Inexact +maxx491 max .5 33333 -> 3.33E+4 Rounded Inexact -- overflow tests maxexponent: 999999999 @@ -348,13 +375,13 @@ maxx512 max 0.10E-999 0 -> 1.0E-1000 Subnormal maxx513 max 0.100E-999 0 -> 1.0E-1000 Subnormal Rounded maxx514 max 0.01E-999 0 -> 1E-1001 Subnormal --- next is rounded to Emin +-- next is rounded to Nmin maxx515 max 0.999E-999 0 -> 1.00E-999 Inexact Rounded Subnormal Underflow maxx516 max 0.099E-999 0 -> 1.0E-1000 Inexact Rounded Subnormal Underflow maxx517 max 0.009E-999 0 -> 1E-1001 Inexact Rounded Subnormal Underflow -maxx518 max 0.001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow -maxx519 max 0.0009E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow -maxx520 max 0.0001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow +maxx518 max 0.001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +maxx519 max 0.0009E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +maxx520 max 0.0001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped maxx530 max -1.00E-999 0 -> 0 maxx531 max -0.1E-999 0 -> 0 @@ -368,6 +395,27 @@ maxx539 max -0.0009E-999 0 -> 0 maxx540 max -0.0001E-999 0 -> 0 +-- misalignment traps for little-endian +precision: 9 +maxx551 max 1.0 0.1 -> 1.0 +maxx552 max 0.1 1.0 -> 1.0 +maxx553 max 10.0 0.1 -> 10.0 +maxx554 max 0.1 10.0 -> 10.0 +maxx555 max 100 1.0 -> 100 +maxx556 max 1.0 100 -> 100 +maxx557 max 1000 10.0 -> 1000 +maxx558 max 10.0 1000 -> 1000 +maxx559 max 10000 100.0 -> 10000 +maxx560 max 100.0 10000 -> 10000 +maxx661 max 100000 1000.0 -> 100000 +maxx662 max 1000.0 100000 -> 100000 +maxx663 max 1000000 10000.0 -> 1000000 +maxx664 max 10000.0 1000000 -> 1000000 + +-- payload decapitate +precision: 5 +maxx670 max 11 -sNaN12345678901 -> -NaN78901 Invalid_operation + -- Null tests maxx900 max 10 # -> NaN Invalid_operation maxx901 max # 10 -> NaN Invalid_operation Modified: python/branches/py3k/Lib/test/decimaltestdata/min.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/min.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/min.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- min.decTest -- decimal minimum -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- we assume that base comparison is tested in compare.decTest, so -- these mainly cover special cases and rounding @@ -320,6 +320,34 @@ mnmx466 min -1000 -1E+3 -> -1E+3 mnmx467 min -1E+3 -1000 -> -1E+3 +-- rounding (results treated as though plus) +maxexponent: 999999999 +minexponent: -999999999 +precision: 3 + +mnmx470 min 1 5 -> 1 +mnmx471 min 10 50 -> 10 +mnmx472 min 100 500 -> 100 +mnmx473 min 1000 5000 -> 1.00E+3 Rounded +mnmx474 min 10000 50000 -> 1.00E+4 Rounded +mnmx475 min 6 50 -> 6 +mnmx476 min 66 500 -> 66 +mnmx477 min 666 5000 -> 666 +mnmx478 min 6666 50000 -> 6.67E+3 Rounded Inexact +mnmx479 min 66666 500000 -> 6.67E+4 Rounded Inexact +mnmx480 min 33333 500000 -> 3.33E+4 Rounded Inexact +mnmx481 min 75401 1 -> 1 +mnmx482 min 75402 10 -> 10 +mnmx483 min 75403 100 -> 100 +mnmx484 min 75404 1000 -> 1.00E+3 Rounded +mnmx485 min 75405 10000 -> 1.00E+4 Rounded +mnmx486 min 75406 6 -> 6 +mnmx487 min 75407 66 -> 66 +mnmx488 min 75408 666 -> 666 +mnmx489 min 75409 6666 -> 6.67E+3 Rounded Inexact +mnmx490 min 75410 66666 -> 6.67E+4 Rounded Inexact +mnmx491 min 75411 33333 -> 3.33E+4 Rounded Inexact + -- overflow tests maxexponent: 999999999 @@ -349,14 +377,30 @@ mnmx532 min -0.10E-999 0 -> -1.0E-1000 Subnormal mnmx533 min -0.100E-999 0 -> -1.0E-1000 Subnormal Rounded mnmx534 min -0.01E-999 0 -> -1E-1001 Subnormal --- next is rounded to Emin +-- next is rounded to Nmin mnmx535 min -0.999E-999 0 -> -1.00E-999 Inexact Rounded Subnormal Underflow mnmx536 min -0.099E-999 0 -> -1.0E-1000 Inexact Rounded Subnormal Underflow mnmx537 min -0.009E-999 0 -> -1E-1001 Inexact Rounded Subnormal Underflow -mnmx538 min -0.001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow -mnmx539 min -0.0009E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow -mnmx540 min -0.0001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow +mnmx538 min -0.001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +mnmx539 min -0.0009E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +mnmx540 min -0.0001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +-- misalignment traps for little-endian +precision: 9 +mnmx551 min 1.0 0.1 -> 0.1 +mnmx552 min 0.1 1.0 -> 0.1 +mnmx553 min 10.0 0.1 -> 0.1 +mnmx554 min 0.1 10.0 -> 0.1 +mnmx555 min 100 1.0 -> 1.0 +mnmx556 min 1.0 100 -> 1.0 +mnmx557 min 1000 10.0 -> 10.0 +mnmx558 min 10.0 1000 -> 10.0 +mnmx559 min 10000 100.0 -> 100.0 +mnmx560 min 100.0 10000 -> 100.0 +mnmx561 min 100000 1000.0 -> 1000.0 +mnmx562 min 1000.0 100000 -> 1000.0 +mnmx563 min 1000000 10000.0 -> 10000.0 +mnmx564 min 10000.0 1000000 -> 10000.0 -- Null tests mnm900 min 10 # -> NaN Invalid_operation Modified: python/branches/py3k/Lib/test/decimaltestdata/minus.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/minus.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/minus.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- minus.decTest -- decimal negation -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- This set of tests primarily tests the existence of the operator. -- Subtraction, rounding, and more overflows are tested elsewhere. @@ -127,9 +127,9 @@ minx115 minus 0.999E-999 -> -1.00E-999 Inexact Rounded Subnormal Underflow minx116 minus 0.099E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow minx117 minus 0.009E-999 -> -1E-1001 Inexact Rounded Subnormal Underflow -minx118 minus 0.001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow -minx119 minus 0.0009E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow -minx120 minus 0.0001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow +minx118 minus 0.001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +minx119 minus 0.0009E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +minx120 minus 0.0001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped minx130 minus -1.00E-999 -> 1.00E-999 minx131 minus -0.1E-999 -> 1E-1000 Subnormal @@ -140,9 +140,9 @@ minx135 minus -0.999E-999 -> 1.00E-999 Inexact Rounded Subnormal Underflow minx136 minus -0.099E-999 -> 1.0E-1000 Inexact Rounded Subnormal Underflow minx137 minus -0.009E-999 -> 1E-1001 Inexact Rounded Subnormal Underflow -minx138 minus -0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -minx139 minus -0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -minx140 minus -0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow +minx138 minus -0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +minx139 minus -0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +minx140 minus -0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped -- long operand checks Modified: python/branches/py3k/Lib/test/decimaltestdata/multiply.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/multiply.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/multiply.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- multiply.decTest -- decimal multiplication -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -44,21 +44,28 @@ mulx015 multiply 2.50 4 -> 10.00 precision: 6 mulx016 multiply 2.50 4 -> 10.00 -mulx017 multiply 9.999999999 9.999999999 -> 100.000 Inexact Rounded +mulx017 multiply 9.999999999 9.999999999 -> 100.000 Inexact Rounded +mulx018 multiply 9.999999999 -9.999999999 -> -100.000 Inexact Rounded +mulx019 multiply -9.999999999 9.999999999 -> -100.000 Inexact Rounded +mulx020 multiply -9.999999999 -9.999999999 -> 100.000 Inexact Rounded -- 1999.12.21: next one is a edge case if intermediate longs are used precision: 15 -mulx019 multiply 999999999999 9765625 -> 9.76562499999023E+18 Inexact Rounded +mulx059 multiply 999999999999 9765625 -> 9.76562499999023E+18 Inexact Rounded precision: 30 mulx160 multiply 999999999999 9765625 -> 9765624999990234375 precision: 9 ----- -- zeros, etc. -mulx020 multiply 0 0 -> 0 -mulx021 multiply 0 -0 -> -0 -mulx022 multiply -0 0 -> -0 -mulx023 multiply -0 -0 -> 0 +mulx021 multiply 0 0 -> 0 +mulx022 multiply 0 -0 -> -0 +mulx023 multiply -0 0 -> -0 +mulx024 multiply -0 -0 -> 0 +mulx025 multiply -0.0 -0.0 -> 0.00 +mulx026 multiply -0.0 -0.0 -> 0.00 +mulx027 multiply -0.0 -0.0 -> 0.00 +mulx028 multiply -0.0 -0.0 -> 0.00 mulx030 multiply 5.00 1E-3 -> 0.00500 mulx031 multiply 00.00 0.000 -> 0.00000 mulx032 multiply 00.00 0E-3 -> 0.00000 -- rhs is 0 @@ -94,17 +101,17 @@ -- test some intermediate lengths precision: 9 -mulx080 multiply 0.1 123456789 -> 12345678.9 -mulx081 multiply 0.1 1234567891 -> 123456789 Inexact Rounded -mulx082 multiply 0.1 12345678912 -> 1.23456789E+9 Inexact Rounded -mulx083 multiply 0.1 12345678912345 -> 1.23456789E+12 Inexact Rounded -mulx084 multiply 0.1 123456789 -> 12345678.9 +mulx080 multiply 0.1 123456789 -> 12345678.9 +mulx081 multiply 0.1 1234567891 -> 123456789 Inexact Rounded +mulx082 multiply 0.1 12345678912 -> 1.23456789E+9 Inexact Rounded +mulx083 multiply 0.1 12345678912345 -> 1.23456789E+12 Inexact Rounded +mulx084 multiply 0.1 123456789 -> 12345678.9 precision: 8 -mulx085 multiply 0.1 12345678912 -> 1.2345679E+9 Inexact Rounded -mulx086 multiply 0.1 12345678912345 -> 1.2345679E+12 Inexact Rounded +mulx085 multiply 0.1 12345678912 -> 1.2345679E+9 Inexact Rounded +mulx086 multiply 0.1 12345678912345 -> 1.2345679E+12 Inexact Rounded precision: 7 -mulx087 multiply 0.1 12345678912 -> 1.234568E+9 Inexact Rounded -mulx088 multiply 0.1 12345678912345 -> 1.234568E+12 Inexact Rounded +mulx087 multiply 0.1 12345678912 -> 1.234568E+9 Inexact Rounded +mulx088 multiply 0.1 12345678912345 -> 1.234568E+12 Inexact Rounded precision: 9 mulx090 multiply 123456789 0.1 -> 12345678.9 @@ -280,6 +287,41 @@ precision: 1 mulx278 multiply 30269.587755640502150977251770554 4.8046009735990873395936309640543 -> 1E+5 Inexact Rounded +-- test some edge cases with exact rounding +maxexponent: 9999 +minexponent: -9999 +precision: 9 +mulx301 multiply 9 9 -> 81 +mulx302 multiply 9 90 -> 810 +mulx303 multiply 9 900 -> 8100 +mulx304 multiply 9 9000 -> 81000 +mulx305 multiply 9 90000 -> 810000 +mulx306 multiply 9 900000 -> 8100000 +mulx307 multiply 9 9000000 -> 81000000 +mulx308 multiply 9 90000000 -> 810000000 +mulx309 multiply 9 900000000 -> 8.10000000E+9 Rounded +mulx310 multiply 9 9000000000 -> 8.10000000E+10 Rounded +mulx311 multiply 9 90000000000 -> 8.10000000E+11 Rounded +mulx312 multiply 9 900000000000 -> 8.10000000E+12 Rounded +mulx313 multiply 9 9000000000000 -> 8.10000000E+13 Rounded +mulx314 multiply 9 90000000000000 -> 8.10000000E+14 Rounded +mulx315 multiply 9 900000000000000 -> 8.10000000E+15 Rounded +mulx316 multiply 9 9000000000000000 -> 8.10000000E+16 Rounded +mulx317 multiply 9 90000000000000000 -> 8.10000000E+17 Rounded +mulx318 multiply 9 900000000000000000 -> 8.10000000E+18 Rounded +mulx319 multiply 9 9000000000000000000 -> 8.10000000E+19 Rounded +mulx320 multiply 9 90000000000000000000 -> 8.10000000E+20 Rounded +mulx321 multiply 9 900000000000000000000 -> 8.10000000E+21 Rounded +mulx322 multiply 9 9000000000000000000000 -> 8.10000000E+22 Rounded +mulx323 multiply 9 90000000000000000000000 -> 8.10000000E+23 Rounded + +-- fastpath breakers +precision: 29 +mulx330 multiply 1.491824697641270317824852952837224 1.105170918075647624811707826490246514675628614562883537345747603 -> 1.6487212707001281468486507878 Inexact Rounded +precision: 55 +mulx331 multiply 0.8958341352965282506768545828765117803873717284891040428 0.8958341352965282506768545828765117803873717284891040428 -> 0.8025187979624784829842553829934069955890983696752228299 Inexact Rounded + + -- tryzeros cases precision: 7 rounding: half_up @@ -486,10 +528,10 @@ mulx752 multiply 1e+777777777 -1e+411111111 -> -Infinity Overflow Inexact Rounded mulx753 multiply -1e+777777777 1e+411111111 -> -Infinity Overflow Inexact Rounded mulx754 multiply -1e+777777777 -1e+411111111 -> Infinity Overflow Inexact Rounded -mulx755 multiply 1e-777777777 1e-411111111 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -mulx756 multiply 1e-777777777 -1e-411111111 -> -0E-1000000007 Underflow Subnormal Inexact Rounded -mulx757 multiply -1e-777777777 1e-411111111 -> -0E-1000000007 Underflow Subnormal Inexact Rounded -mulx758 multiply -1e-777777777 -1e-411111111 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +mulx755 multiply 1e-777777777 1e-411111111 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +mulx756 multiply 1e-777777777 -1e-411111111 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +mulx757 multiply -1e-777777777 1e-411111111 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +mulx758 multiply -1e-777777777 -1e-411111111 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -- 'subnormal' boundary (all hard underflow or overflow in base arithemtic) precision: 9 @@ -500,9 +542,9 @@ mulx764 multiply 1e-600000000 1e-400000005 -> 1E-1000000005 Subnormal mulx765 multiply 1e-600000000 1e-400000006 -> 1E-1000000006 Subnormal mulx766 multiply 1e-600000000 1e-400000007 -> 1E-1000000007 Subnormal -mulx767 multiply 1e-600000000 1e-400000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -mulx768 multiply 1e-600000000 1e-400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -mulx769 multiply 1e-600000000 1e-400000010 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +mulx767 multiply 1e-600000000 1e-400000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +mulx768 multiply 1e-600000000 1e-400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +mulx769 multiply 1e-600000000 1e-400000010 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -- [no equivalent of 'subnormal' for overflow] mulx770 multiply 1e+600000000 1e+400000001 -> Infinity Overflow Inexact Rounded mulx771 multiply 1e+600000000 1e+400000002 -> Infinity Overflow Inexact Rounded @@ -520,31 +562,31 @@ mulx780 multiply 1e-600000000 1e-400000007 -> 1E-1000000007 Subnormal mulx781 multiply 1e-600000000 1e-400000008 -> 1E-1000000008 Subnormal mulx782 multiply 1e-600000000 1e-400000097 -> 1E-1000000097 Subnormal -mulx783 multiply 1e-600000000 1e-400000098 -> 0E-1000000097 Underflow Subnormal Inexact Rounded +mulx783 multiply 1e-600000000 1e-400000098 -> 0E-1000000097 Underflow Subnormal Inexact Rounded Clamped precision: 999 mulx784 multiply 1e-600000000 1e-400000997 -> 1E-1000000997 Subnormal -mulx785 multiply 1e-600000000 1e-400000998 -> 0E-1000000997 Underflow Subnormal Inexact Rounded +mulx785 multiply 1e-600000000 1e-400000998 -> 0E-1000000997 Underflow Subnormal Inexact Rounded Clamped -- following testcases [through mulx800] not yet run against code precision: 9999 mulx786 multiply 1e-600000000 1e-400009997 -> 1E-1000009997 Subnormal -mulx787 multiply 1e-600000000 1e-400009998 -> 0E-1000009997 Underflow Subnormal Inexact Rounded +mulx787 multiply 1e-600000000 1e-400009998 -> 0E-1000009997 Underflow Subnormal Inexact Rounded Clamped precision: 99999 mulx788 multiply 1e-600000000 1e-400099997 -> 1E-1000099997 Subnormal -mulx789 multiply 1e-600000000 1e-400099998 -> 0E-1000099997 Underflow Subnormal Inexact Rounded +mulx789 multiply 1e-600000000 1e-400099998 -> 0E-1000099997 Underflow Subnormal Inexact Rounded Clamped precision: 999999 mulx790 multiply 1e-600000000 1e-400999997 -> 1E-1000999997 Subnormal -mulx791 multiply 1e-600000000 1e-400999998 -> 0E-1000999997 Underflow Subnormal Inexact Rounded +mulx791 multiply 1e-600000000 1e-400999998 -> 0E-1000999997 Underflow Subnormal Inexact Rounded Clamped precision: 9999999 mulx792 multiply 1e-600000000 1e-409999997 -> 1E-1009999997 Subnormal -mulx793 multiply 1e-600000000 1e-409999998 -> 0E-1009999997 Underflow Subnormal Inexact Rounded +mulx793 multiply 1e-600000000 1e-409999998 -> 0E-1009999997 Underflow Subnormal Inexact Rounded Clamped precision: 99999999 mulx794 multiply 1e-600000000 1e-499999997 -> 1E-1099999997 Subnormal -mulx795 multiply 1e-600000000 1e-499999998 -> 0E-1099999997 Underflow Subnormal Inexact Rounded +mulx795 multiply 1e-600000000 1e-499999998 -> 0E-1099999997 Underflow Subnormal Inexact Rounded Clamped precision: 999999999 mulx796 multiply 1e-999999999 1e-999999997 -> 1E-1999999996 Subnormal mulx797 multiply 1e-999999999 1e-999999998 -> 1E-1999999997 Subnormal -mulx798 multiply 1e-999999999 1e-999999999 -> 0E-1999999997 Underflow Subnormal Inexact Rounded +mulx798 multiply 1e-999999999 1e-999999999 -> 0E-1999999997 Underflow Subnormal Inexact Rounded Clamped mulx799 multiply 1e-600000000 1e-400000007 -> 1E-1000000007 Subnormal mulx800 multiply 1e-600000000 1e-400000008 -> 1E-1000000008 Subnormal @@ -573,19 +615,19 @@ mulx817 multiply 2.51E-999 1e-4 -> 3E-1003 Underflow Subnormal Inexact Rounded mulx818 multiply 1E-999 1e-4 -> 1E-1003 Subnormal -mulx819 multiply 3E-999 1e-5 -> 0E-1003 Underflow Subnormal Inexact Rounded -mulx820 multiply 5E-999 1e-5 -> 0E-1003 Underflow Subnormal Inexact Rounded +mulx819 multiply 3E-999 1e-5 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +mulx820 multiply 5E-999 1e-5 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped mulx821 multiply 7E-999 1e-5 -> 1E-1003 Underflow Subnormal Inexact Rounded mulx822 multiply 9E-999 1e-5 -> 1E-1003 Underflow Subnormal Inexact Rounded mulx823 multiply 9.9E-999 1e-5 -> 1E-1003 Underflow Subnormal Inexact Rounded mulx824 multiply 1E-999 -1e-4 -> -1E-1003 Subnormal -mulx825 multiply 3E-999 -1e-5 -> -0E-1003 Underflow Subnormal Inexact Rounded -mulx826 multiply -5E-999 1e-5 -> -0E-1003 Underflow Subnormal Inexact Rounded +mulx825 multiply 3E-999 -1e-5 -> -0E-1003 Underflow Subnormal Inexact Rounded Clamped +mulx826 multiply -5E-999 1e-5 -> -0E-1003 Underflow Subnormal Inexact Rounded Clamped mulx827 multiply 7E-999 -1e-5 -> -1E-1003 Underflow Subnormal Inexact Rounded mulx828 multiply -9E-999 1e-5 -> -1E-1003 Underflow Subnormal Inexact Rounded mulx829 multiply 9.9E-999 -1e-5 -> -1E-1003 Underflow Subnormal Inexact Rounded -mulx830 multiply 3.0E-999 -1e-5 -> -0E-1003 Underflow Subnormal Inexact Rounded +mulx830 multiply 3.0E-999 -1e-5 -> -0E-1003 Underflow Subnormal Inexact Rounded Clamped mulx831 multiply 1.0E-501 1e-501 -> 1.0E-1002 Subnormal mulx832 multiply 2.0E-501 2e-501 -> 4.0E-1002 Subnormal @@ -595,7 +637,7 @@ mulx836 multiply 40.0E-501 40e-501 -> 1.6000E-999 -- squares -mulx840 multiply 1E-502 1e-502 -> 0E-1003 Underflow Subnormal Inexact Rounded +mulx840 multiply 1E-502 1e-502 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped mulx841 multiply 1E-501 1e-501 -> 1E-1002 Subnormal mulx842 multiply 2E-501 2e-501 -> 4E-1002 Subnormal mulx843 multiply 4E-501 4e-501 -> 1.6E-1001 Subnormal @@ -604,7 +646,7 @@ mulx846 multiply 40E-501 40e-501 -> 1.600E-999 -- cubes -mulx850 multiply 1E-670 1e-335 -> 0E-1003 Underflow Subnormal Inexact Rounded +mulx850 multiply 1E-670 1e-335 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped mulx851 multiply 1E-668 1e-334 -> 1E-1002 Subnormal mulx852 multiply 4E-668 2e-334 -> 8E-1002 Subnormal mulx853 multiply 9E-668 3e-334 -> 2.7E-1001 Subnormal @@ -612,7 +654,7 @@ mulx855 multiply 25E-668 5e-334 -> 1.25E-1000 Subnormal mulx856 multiply 10E-668 100e-334 -> 1.000E-999 --- test from 0.099 ** 999 at 15 digits +-- test derived from result of 0.099 ** 999 at 15 digits with unlimited exponent precision: 19 mulx860 multiply 6636851557994578716E-520 6636851557994578716E-520 -> 4.40477986028551E-1003 Underflow Subnormal Inexact Rounded @@ -629,14 +671,16 @@ precision: 5 maxexponent: 79 minexponent: -79 -mulx881 multiply 1.2347E-40 1.2347E-40 -> 1.524E-80 Inexact Rounded Subnormal Underflow -mulx882 multiply 1.234E-40 1.234E-40 -> 1.523E-80 Inexact Rounded Subnormal Underflow -mulx883 multiply 1.23E-40 1.23E-40 -> 1.513E-80 Inexact Rounded Subnormal Underflow -mulx884 multiply 1.2E-40 1.2E-40 -> 1.44E-80 Subnormal -mulx885 multiply 1.2E-40 1.2E-41 -> 1.44E-81 Subnormal -mulx886 multiply 1.2E-40 1.2E-42 -> 1.4E-82 Subnormal Inexact Rounded Underflow -mulx887 multiply 1.2E-40 1.3E-42 -> 1.6E-82 Subnormal Inexact Rounded Underflow -mulx888 multiply 1.3E-40 1.3E-42 -> 1.7E-82 Subnormal Inexact Rounded Underflow +mulx881 multiply 1.2347E-40 1.2347E-40 -> 1.524E-80 Inexact Rounded Subnormal Underflow +mulx882 multiply 1.234E-40 1.234E-40 -> 1.523E-80 Inexact Rounded Subnormal Underflow +mulx883 multiply 1.23E-40 1.23E-40 -> 1.513E-80 Inexact Rounded Subnormal Underflow +mulx884 multiply 1.2E-40 1.2E-40 -> 1.44E-80 Subnormal +mulx885 multiply 1.2E-40 1.2E-41 -> 1.44E-81 Subnormal +mulx886 multiply 1.2E-40 1.2E-42 -> 1.4E-82 Subnormal Inexact Rounded Underflow +mulx887 multiply 1.2E-40 1.3E-42 -> 1.6E-82 Subnormal Inexact Rounded Underflow +mulx888 multiply 1.3E-40 1.3E-42 -> 1.7E-82 Subnormal Inexact Rounded Underflow +mulx889 multiply 1.3E-40 1.3E-43 -> 2E-83 Subnormal Inexact Rounded Underflow +mulx890 multiply 1.3E-41 1.3E-43 -> 0E-83 Clamped Subnormal Inexact Rounded Underflow mulx891 multiply 1.2345E-39 1.234E-40 -> 1.5234E-79 Inexact Rounded mulx892 multiply 1.23456E-39 1.234E-40 -> 1.5234E-79 Inexact Rounded @@ -645,7 +689,43 @@ mulx895 multiply 1.2345E-41 1.234E-40 -> 1.52E-81 Inexact Rounded Subnormal Underflow mulx896 multiply 1.23456E-41 1.234E-40 -> 1.52E-81 Inexact Rounded Subnormal Underflow +-- Now explore the case where we get a normal result with Underflow +precision: 16 +rounding: half_up +maxExponent: 384 +minExponent: -383 + +mulx900 multiply 0.3000000000E-191 0.3000000000E-191 -> 9.00000000000000E-384 Subnormal Rounded +mulx901 multiply 0.3000000001E-191 0.3000000001E-191 -> 9.00000000600000E-384 Underflow Inexact Subnormal Rounded +mulx902 multiply 9.999999999999999E-383 0.0999999999999 -> 9.99999999999000E-384 Underflow Inexact Subnormal Rounded +mulx903 multiply 9.999999999999999E-383 0.09999999999999 -> 9.99999999999900E-384 Underflow Inexact Subnormal Rounded +mulx904 multiply 9.999999999999999E-383 0.099999999999999 -> 9.99999999999990E-384 Underflow Inexact Subnormal Rounded +mulx905 multiply 9.999999999999999E-383 0.0999999999999999 -> 9.99999999999999E-384 Underflow Inexact Subnormal Rounded +-- prove operands are exact +mulx906 multiply 9.999999999999999E-383 1 -> 9.999999999999999E-383 +mulx907 multiply 1 0.09999999999999999 -> 0.09999999999999999 +-- the next rounds to Nmin +mulx908 multiply 9.999999999999999E-383 0.09999999999999999 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +mulx909 multiply 9.999999999999999E-383 0.099999999999999999 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +mulx910 multiply 9.999999999999999E-383 0.0999999999999999999 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +mulx911 multiply 9.999999999999999E-383 0.09999999999999999999 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded + + +-- Examples from SQL proposal (Krishna Kulkarni) +precision: 34 +rounding: half_up +maxExponent: 6144 +minExponent: -6143 +mulx1001 multiply 130E-2 120E-2 -> 1.5600 +mulx1002 multiply 130E-2 12E-1 -> 1.560 +mulx1003 multiply 130E-2 1E0 -> 1.30 +mulx1004 multiply 1E2 1E4 -> 1E+6 + +-- payload decapitate +precision: 5 +mulx1010 multiply 11 -sNaN1234567890 -> -NaN67890 Invalid_operation + -- Null tests -mulx900 multiply 10 # -> NaN Invalid_operation -mulx901 multiply # 10 -> NaN Invalid_operation +mulx990 multiply 10 # -> NaN Invalid_operation +mulx991 multiply # 10 -> NaN Invalid_operation Deleted: /python/branches/py3k/Lib/test/decimaltestdata/normalize.decTest ============================================================================== --- /python/branches/py3k/Lib/test/decimaltestdata/normalize.decTest Wed Sep 19 05:06:30 2007 +++ (empty file) @@ -1,225 +0,0 @@ ------------------------------------------------------------------------- --- normalize.decTest -- remove trailing zeros -- --- Copyright (c) IBM Corporation, 2003. All rights reserved. -- ------------------------------------------------------------------------- --- Please see the document "General Decimal Arithmetic Testcases" -- --- at http://www2.hursley.ibm.com/decimal for the description of -- --- these testcases. -- --- -- --- These testcases are experimental ('beta' versions), and they -- --- may contain errors. They are offered on an as-is basis. In -- --- particular, achieving the same results as the tests here is not -- --- a guarantee that an implementation complies with any Standard -- --- or specification. The tests are not exhaustive. -- --- -- --- Please send comments, suggestions, and corrections to the author: -- --- Mike Cowlishaw, IBM Fellow -- --- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- --- mfc at uk.ibm.com -- ------------------------------------------------------------------------- -version: 2.39 - -extended: 1 -precision: 9 -rounding: half_up -maxExponent: 999 -minexponent: -999 - -nrmx001 normalize '1' -> '1' -nrmx002 normalize '-1' -> '-1' -nrmx003 normalize '1.00' -> '1' -nrmx004 normalize '-1.00' -> '-1' -nrmx005 normalize '0' -> '0' -nrmx006 normalize '0.00' -> '0' -nrmx007 normalize '00.0' -> '0' -nrmx008 normalize '00.00' -> '0' -nrmx009 normalize '00' -> '0' -nrmx010 normalize '0E+1' -> '0' -nrmx011 normalize '0E+5' -> '0' - -nrmx012 normalize '-2' -> '-2' -nrmx013 normalize '2' -> '2' -nrmx014 normalize '-2.00' -> '-2' -nrmx015 normalize '2.00' -> '2' -nrmx016 normalize '-0' -> '-0' -nrmx017 normalize '-0.00' -> '-0' -nrmx018 normalize '-00.0' -> '-0' -nrmx019 normalize '-00.00' -> '-0' -nrmx020 normalize '-00' -> '-0' -nrmx021 normalize '-0E+5' -> '-0' -nrmx022 normalize '-0E+1' -> '-0' - -nrmx030 normalize '+0.1' -> '0.1' -nrmx031 normalize '-0.1' -> '-0.1' -nrmx032 normalize '+0.01' -> '0.01' -nrmx033 normalize '-0.01' -> '-0.01' -nrmx034 normalize '+0.001' -> '0.001' -nrmx035 normalize '-0.001' -> '-0.001' -nrmx036 normalize '+0.000001' -> '0.000001' -nrmx037 normalize '-0.000001' -> '-0.000001' -nrmx038 normalize '+0.000000000001' -> '1E-12' -nrmx039 normalize '-0.000000000001' -> '-1E-12' - -nrmx041 normalize 1.1 -> 1.1 -nrmx042 normalize 1.10 -> 1.1 -nrmx043 normalize 1.100 -> 1.1 -nrmx044 normalize 1.110 -> 1.11 -nrmx045 normalize -1.1 -> -1.1 -nrmx046 normalize -1.10 -> -1.1 -nrmx047 normalize -1.100 -> -1.1 -nrmx048 normalize -1.110 -> -1.11 -nrmx049 normalize 9.9 -> 9.9 -nrmx050 normalize 9.90 -> 9.9 -nrmx051 normalize 9.900 -> 9.9 -nrmx052 normalize 9.990 -> 9.99 -nrmx053 normalize -9.9 -> -9.9 -nrmx054 normalize -9.90 -> -9.9 -nrmx055 normalize -9.900 -> -9.9 -nrmx056 normalize -9.990 -> -9.99 - --- some trailing fractional zeros with zeros in units -nrmx060 normalize 10.0 -> 1E+1 -nrmx061 normalize 10.00 -> 1E+1 -nrmx062 normalize 100.0 -> 1E+2 -nrmx063 normalize 100.00 -> 1E+2 -nrmx064 normalize 1.1000E+3 -> 1.1E+3 -nrmx065 normalize 1.10000E+3 -> 1.1E+3 -nrmx066 normalize -10.0 -> -1E+1 -nrmx067 normalize -10.00 -> -1E+1 -nrmx068 normalize -100.0 -> -1E+2 -nrmx069 normalize -100.00 -> -1E+2 -nrmx070 normalize -1.1000E+3 -> -1.1E+3 -nrmx071 normalize -1.10000E+3 -> -1.1E+3 - --- some insignificant trailing zeros with positive exponent -nrmx080 normalize 10E+1 -> 1E+2 -nrmx081 normalize 100E+1 -> 1E+3 -nrmx082 normalize 1.0E+2 -> 1E+2 -nrmx083 normalize 1.0E+3 -> 1E+3 -nrmx084 normalize 1.1E+3 -> 1.1E+3 -nrmx085 normalize 1.00E+3 -> 1E+3 -nrmx086 normalize 1.10E+3 -> 1.1E+3 -nrmx087 normalize -10E+1 -> -1E+2 -nrmx088 normalize -100E+1 -> -1E+3 -nrmx089 normalize -1.0E+2 -> -1E+2 -nrmx090 normalize -1.0E+3 -> -1E+3 -nrmx091 normalize -1.1E+3 -> -1.1E+3 -nrmx092 normalize -1.00E+3 -> -1E+3 -nrmx093 normalize -1.10E+3 -> -1.1E+3 - --- some significant trailing zeros, were we to be trimming -nrmx100 normalize 11 -> 11 -nrmx101 normalize 10 -> 1E+1 -nrmx102 normalize 10. -> 1E+1 -nrmx103 normalize 1.1E+1 -> 11 -nrmx104 normalize 1.0E+1 -> 1E+1 -nrmx105 normalize 1.10E+2 -> 1.1E+2 -nrmx106 normalize 1.00E+2 -> 1E+2 -nrmx107 normalize 1.100E+3 -> 1.1E+3 -nrmx108 normalize 1.000E+3 -> 1E+3 -nrmx109 normalize 1.000000E+6 -> 1E+6 -nrmx110 normalize -11 -> -11 -nrmx111 normalize -10 -> -1E+1 -nrmx112 normalize -10. -> -1E+1 -nrmx113 normalize -1.1E+1 -> -11 -nrmx114 normalize -1.0E+1 -> -1E+1 -nrmx115 normalize -1.10E+2 -> -1.1E+2 -nrmx116 normalize -1.00E+2 -> -1E+2 -nrmx117 normalize -1.100E+3 -> -1.1E+3 -nrmx118 normalize -1.000E+3 -> -1E+3 -nrmx119 normalize -1.00000E+5 -> -1E+5 -nrmx120 normalize -1.000000E+6 -> -1E+6 -nrmx121 normalize -10.00000E+6 -> -1E+7 -nrmx122 normalize -100.0000E+6 -> -1E+8 -nrmx123 normalize -1000.000E+6 -> -1E+9 -nrmx124 normalize -10000.00E+6 -> -1E+10 -nrmx125 normalize -100000.0E+6 -> -1E+11 -nrmx126 normalize -1000000.E+6 -> -1E+12 - --- examples from decArith -nrmx140 normalize '2.1' -> '2.1' -nrmx141 normalize '-2.0' -> '-2' -nrmx142 normalize '1.200' -> '1.2' -nrmx143 normalize '-120' -> '-1.2E+2' -nrmx144 normalize '120.00' -> '1.2E+2' -nrmx145 normalize '0.00' -> '0' - --- overflow tests -maxexponent: 999999999 -minexponent: -999999999 -precision: 3 -nrmx160 normalize 9.999E+999999999 -> Infinity Inexact Overflow Rounded -nrmx161 normalize -9.999E+999999999 -> -Infinity Inexact Overflow Rounded - --- subnormals and underflow -precision: 3 -maxexponent: 999 -minexponent: -999 -nrmx210 normalize 1.00E-999 -> 1E-999 -nrmx211 normalize 0.1E-999 -> 1E-1000 Subnormal -nrmx212 normalize 0.10E-999 -> 1E-1000 Subnormal -nrmx213 normalize 0.100E-999 -> 1E-1000 Subnormal Rounded -nrmx214 normalize 0.01E-999 -> 1E-1001 Subnormal --- next is rounded to Emin -nrmx215 normalize 0.999E-999 -> 1E-999 Inexact Rounded Subnormal Underflow -nrmx216 normalize 0.099E-999 -> 1E-1000 Inexact Rounded Subnormal Underflow -nrmx217 normalize 0.009E-999 -> 1E-1001 Inexact Rounded Subnormal Underflow -nrmx218 normalize 0.001E-999 -> 0 Inexact Rounded Subnormal Underflow -nrmx219 normalize 0.0009E-999 -> 0 Inexact Rounded Subnormal Underflow -nrmx220 normalize 0.0001E-999 -> 0 Inexact Rounded Subnormal Underflow - -nrmx230 normalize -1.00E-999 -> -1E-999 -nrmx231 normalize -0.1E-999 -> -1E-1000 Subnormal -nrmx232 normalize -0.10E-999 -> -1E-1000 Subnormal -nrmx233 normalize -0.100E-999 -> -1E-1000 Subnormal Rounded -nrmx234 normalize -0.01E-999 -> -1E-1001 Subnormal --- next is rounded to Emin -nrmx235 normalize -0.999E-999 -> -1E-999 Inexact Rounded Subnormal Underflow -nrmx236 normalize -0.099E-999 -> -1E-1000 Inexact Rounded Subnormal Underflow -nrmx237 normalize -0.009E-999 -> -1E-1001 Inexact Rounded Subnormal Underflow -nrmx238 normalize -0.001E-999 -> -0 Inexact Rounded Subnormal Underflow -nrmx239 normalize -0.0009E-999 -> -0 Inexact Rounded Subnormal Underflow -nrmx240 normalize -0.0001E-999 -> -0 Inexact Rounded Subnormal Underflow - --- more reshaping -precision: 9 -nrmx260 normalize '56260E-10' -> '0.000005626' -nrmx261 normalize '56260E-5' -> '0.5626' -nrmx262 normalize '56260E-2' -> '562.6' -nrmx263 normalize '56260E-1' -> '5626' -nrmx265 normalize '56260E-0' -> '5.626E+4' -nrmx266 normalize '56260E+0' -> '5.626E+4' -nrmx267 normalize '56260E+1' -> '5.626E+5' -nrmx268 normalize '56260E+2' -> '5.626E+6' -nrmx269 normalize '56260E+3' -> '5.626E+7' -nrmx270 normalize '56260E+4' -> '5.626E+8' -nrmx271 normalize '56260E+5' -> '5.626E+9' -nrmx272 normalize '56260E+6' -> '5.626E+10' -nrmx280 normalize '-56260E-10' -> '-0.000005626' -nrmx281 normalize '-56260E-5' -> '-0.5626' -nrmx282 normalize '-56260E-2' -> '-562.6' -nrmx283 normalize '-56260E-1' -> '-5626' -nrmx285 normalize '-56260E-0' -> '-5.626E+4' -nrmx286 normalize '-56260E+0' -> '-5.626E+4' -nrmx287 normalize '-56260E+1' -> '-5.626E+5' -nrmx288 normalize '-56260E+2' -> '-5.626E+6' -nrmx289 normalize '-56260E+3' -> '-5.626E+7' -nrmx290 normalize '-56260E+4' -> '-5.626E+8' -nrmx291 normalize '-56260E+5' -> '-5.626E+9' -nrmx292 normalize '-56260E+6' -> '-5.626E+10' - - --- specials -nrmx820 normalize 'Inf' -> 'Infinity' -nrmx821 normalize '-Inf' -> '-Infinity' -nrmx822 normalize NaN -> NaN -nrmx823 normalize sNaN -> NaN Invalid_operation -nrmx824 normalize NaN101 -> NaN101 -nrmx825 normalize sNaN010 -> NaN10 Invalid_operation -nrmx827 normalize -NaN -> -NaN -nrmx828 normalize -sNaN -> -NaN Invalid_operation -nrmx829 normalize -NaN101 -> -NaN101 -nrmx830 normalize -sNaN010 -> -NaN10 Invalid_operation - --- Null test -nrmx900 normalize # -> NaN Invalid_operation Modified: python/branches/py3k/Lib/test/decimaltestdata/plus.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/plus.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/plus.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- plus.decTest -- decimal monadic addition -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- This set of tests primarily tests the existence of the operator. -- Addition and rounding, and most overflows, are tested elsewhere. @@ -138,9 +138,9 @@ plux215 plus 0.999E-999 -> 1.00E-999 Inexact Rounded Subnormal Underflow plux216 plus 0.099E-999 -> 1.0E-1000 Inexact Rounded Subnormal Underflow plux217 plus 0.009E-999 -> 1E-1001 Inexact Rounded Subnormal Underflow -plux218 plus 0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -plux219 plus 0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -plux220 plus 0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow +plux218 plus 0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +plux219 plus 0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +plux220 plus 0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped plux230 plus -1.00E-999 -> -1.00E-999 plux231 plus -0.1E-999 -> -1E-1000 Subnormal @@ -151,9 +151,23 @@ plux235 plus -0.999E-999 -> -1.00E-999 Inexact Rounded Subnormal Underflow plux236 plus -0.099E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow plux237 plus -0.009E-999 -> -1E-1001 Inexact Rounded Subnormal Underflow -plux238 plus -0.001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow -plux239 plus -0.0009E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow -plux240 plus -0.0001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow +plux238 plus -0.001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +plux239 plus -0.0009E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +plux240 plus -0.0001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped + +-- subnormals clamped to 0-Etiny +precision: 16 +maxExponent: 384 +minExponent: -383 +plux251 plus 7E-398 -> 7E-398 Subnormal +plux252 plus 0E-398 -> 0E-398 +plux253 plus 7E-399 -> 1E-398 Subnormal Underflow Inexact Rounded +plux254 plus 4E-399 -> 0E-398 Clamped Subnormal Underflow Inexact Rounded +plux255 plus 7E-400 -> 0E-398 Clamped Subnormal Underflow Inexact Rounded +plux256 plus 7E-401 -> 0E-398 Clamped Subnormal Underflow Inexact Rounded +plux257 plus 0E-399 -> 0E-398 Clamped +plux258 plus 0E-400 -> 0E-398 Clamped +plux259 plus 0E-401 -> 0E-398 Clamped -- long operand checks maxexponent: 999 Modified: python/branches/py3k/Lib/test/decimaltestdata/power.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/power.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/power.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ----------------------------------------------------------------------- --- power.decTest -- decimal exponentiation -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +------------------------------------------------------------------------ +-- power.decTest -- decimal exponentiation [power(x, y)] -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,17 +17,17 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 --- This set of testcases tests raising numbers to an integer power only. --- If arbitrary powers were supported, 1 ulp differences would be --- permitted. +-- In addition to the power operator testcases here, see also the file +-- powersqrt.decTest which includes all the tests from +-- squareroot.decTest implemented using power(x, 0.5) extended: 1 -precision: 9 -rounding: half_up -maxExponent: 999 -minexponent: -999 +precision: 16 +rounding: half_even +maxExponent: 384 +minExponent: -383 -- base checks. Note 0**0 is an error. powx001 power '0' '0' -> NaN Invalid_operation @@ -52,51 +52,54 @@ powx022 power '2' '12' -> '4096' powx023 power '2' '15' -> '32768' powx024 power '2' '16' -> '65536' -powx025 power '2' '31' -> '2.14748365E+9' Inexact Rounded +powx025 power '2' '31' -> '2147483648' +-- NB 0 not stripped in next +powx026 power '2' '32' -> '4294967296' + +precision: 9 +powx027 power '2' '31' -> '2.14748365E+9' Inexact Rounded -- NB 0 not stripped in next -powx026 power '2' '32' -> '4.29496730E+9' Inexact Rounded +powx028 power '2' '32' -> '4.29496730E+9' Inexact Rounded precision: 10 -powx027 power '2' '31' -> '2147483648' -powx028 power '2' '32' -> '4294967296' +powx029 power '2' '31' -> '2147483648' +powx030 power '2' '32' -> '4294967296' precision: 9 -powx030 power '3' '2' -> 9 -powx031 power '4' '2' -> 16 -powx032 power '5' '2' -> 25 -powx033 power '6' '2' -> 36 -powx034 power '7' '2' -> 49 -powx035 power '8' '2' -> 64 -powx036 power '9' '2' -> 81 -powx037 power '10' '2' -> 100 -powx038 power '11' '2' -> 121 -powx039 power '12' '2' -> 144 - -powx040 power '3' '3' -> 27 -powx041 power '4' '3' -> 64 -powx042 power '5' '3' -> 125 -powx043 power '6' '3' -> 216 -powx044 power '7' '3' -> 343 - -powx050 power '10' '0' -> 1 -powx051 power '10' '1' -> 10 -powx052 power '10' '2' -> 100 -powx053 power '10' '3' -> 1000 -powx054 power '10' '4' -> 10000 -powx055 power '10' '5' -> 100000 -powx056 power '10' '6' -> 1000000 -powx057 power '10' '7' -> 10000000 -powx058 power '10' '8' -> 100000000 -powx059 power '10' '9' -> 1.00000000E+9 Rounded -powx060 power '10' '22' -> 1.00000000E+22 Rounded -powx061 power '10' '77' -> 1.00000000E+77 Rounded -powx062 power '10' '99' -> 1.00000000E+99 Rounded - -maxexponent: 999999999 -minexponent: -999999999 -powx063 power '10' '999999999' -> '1.00000000E+999999999' Rounded -powx064 power '10' '999999998' -> '1.00000000E+999999998' Rounded -powx065 power '10' '999999997' -> '1.00000000E+999999997' Rounded -powx066 power '10' '333333333' -> '1.00000000E+333333333' Rounded +powx031 power '3' '2' -> 9 +powx032 power '4' '2' -> 16 +powx033 power '5' '2' -> 25 +powx034 power '6' '2' -> 36 +powx035 power '7' '2' -> 49 +powx036 power '8' '2' -> 64 +powx037 power '9' '2' -> 81 +powx038 power '10' '2' -> 100 +powx039 power '11' '2' -> 121 +powx040 power '12' '2' -> 144 + +powx041 power '3' '3' -> 27 +powx042 power '4' '3' -> 64 +powx043 power '5' '3' -> 125 +powx044 power '6' '3' -> 216 +powx045 power '7' '3' -> 343 +powx047 power '-3' '3' -> -27 +powx048 power '-4' '3' -> -64 +powx049 power '-5' '3' -> -125 +powx050 power '-6' '3' -> -216 +powx051 power '-7' '3' -> -343 + +powx052 power '10' '0' -> 1 +powx053 power '10' '1' -> 10 +powx054 power '10' '2' -> 100 +powx055 power '10' '3' -> 1000 +powx056 power '10' '4' -> 10000 +powx057 power '10' '5' -> 100000 +powx058 power '10' '6' -> 1000000 +powx059 power '10' '7' -> 10000000 +powx060 power '10' '8' -> 100000000 +powx061 power '10' '9' -> 1.00000000E+9 Rounded +powx062 power '10' '22' -> 1.00000000E+22 Rounded +powx063 power '10' '77' -> 1.00000000E+77 Rounded +powx064 power '10' '99' -> 1.00000000E+99 Rounded powx070 power '0.3' '0' -> '1' powx071 power '0.3' '1' -> '0.3' @@ -127,71 +130,52 @@ powx095 power 101 7 -> 1.07213535E+14 Inexact Rounded -- negative powers -powx101 power '2' '-1' -> 0.5 -powx102 power '2' '-2' -> 0.25 -powx103 power '2' '-4' -> 0.0625 -powx104 power '2' '-8' -> 0.00390625 -powx105 power '2' '-16' -> 0.0000152587891 Inexact Rounded -powx106 power '2' '-32' -> 2.32830644E-10 Inexact Rounded -powx108 power '2' '-64' -> 5.42101086E-20 Inexact Rounded -powx110 power '10' '-8' -> 1E-8 -powx111 power '10' '-7' -> 1E-7 -powx112 power '10' '-6' -> 0.000001 -powx113 power '10' '-5' -> 0.00001 -powx114 power '10' '-4' -> 0.0001 -powx115 power '10' '-3' -> 0.001 -powx116 power '10' '-2' -> 0.01 -powx117 power '10' '-1' -> 0.1 - -powx118 power '10' '-333333333' -> 1E-333333333 -powx119 power '10' '-999999998' -> 1E-999999998 -powx120 power '10' '-999999999' -> 1E-999999999 -powx121 power '10' '-77' -> '1E-77' -powx122 power '10' '-22' -> '1E-22' - -powx123 power '2' '-1' -> '0.5' -powx124 power '2' '-2' -> '0.25' -powx125 power '2' '-4' -> '0.0625' -powx126 power '0' '-1' -> Infinity Division_by_zero -powx127 power '0' '-2' -> Infinity Division_by_zero -powx128 power -0 '-1' -> -Infinity Division_by_zero -powx129 power -0 '-2' -> Infinity Division_by_zero - --- out-of-range edge cases -powx181 power '7' '999999998' -> 2.10892313E+845098038 Inexact Rounded -powx182 power '7' '999999999' -> 1.47624619E+845098039 Inexact Rounded -powx183 power '7' '1000000000' -> NaN Invalid_operation -powx184 power '7' '1000000001' -> NaN Invalid_operation -powx185 power '7' '10000000000' -> NaN Invalid_operation -powx186 power '7' '-1000000001' -> NaN Invalid_operation -powx187 power '7' '-1000000000' -> NaN Invalid_operation -powx189 power '7' '-999999999' -> 6.77393787E-845098040 Inexact Rounded -powx190 power '7' '-999999998' -> 4.74175651E-845098039 Inexact Rounded - --- some baddies [more below] -powx191 power '2' '2.000001' -> NaN Invalid_operation -powx192 power '2' '2.00000000' -> 4 -powx193 power '2' '2.000000001' -> NaN Invalid_operation -powx194 power '2' '2.0000000001' -> NaN Invalid_operation +powx099 power '1' '-1' -> 1 +powx100 power '3' '-1' -> 0.333333333 Inexact Rounded +powx101 power '2' '-1' -> 0.5 +powx102 power '2' '-2' -> 0.25 +powx103 power '2' '-4' -> 0.0625 +powx104 power '2' '-8' -> 0.00390625 +powx105 power '2' '-16' -> 0.0000152587891 Inexact Rounded +powx106 power '2' '-32' -> 2.32830644E-10 Inexact Rounded +powx108 power '2' '-64' -> 5.42101086E-20 Inexact Rounded +powx110 power '10' '-8' -> 1E-8 +powx111 power '10' '-7' -> 1E-7 +powx112 power '10' '-6' -> 0.000001 +powx113 power '10' '-5' -> 0.00001 +powx114 power '10' '-4' -> 0.0001 +powx115 power '10' '-3' -> 0.001 +powx116 power '10' '-2' -> 0.01 +powx117 power '10' '-1' -> 0.1 +powx121 power '10' '-77' -> '1E-77' +powx122 power '10' '-22' -> '1E-22' + +powx123 power '2' '-1' -> '0.5' +powx124 power '2' '-2' -> '0.25' +powx125 power '2' '-4' -> '0.0625' + +powx126 power '0' '-1' -> Infinity +powx127 power '0' '-2' -> Infinity +powx128 power -0 '-1' -> -Infinity +powx129 power -0 '-2' -> Infinity -- "0.5" tests from original Rexx diagnostics [loop unrolled] -powx200 power 0.5 0 -> 1 -powx201 power 0.5 1 -> 0.5 -powx202 power 0.5 2 -> 0.25 -powx203 power 0.5 3 -> 0.125 -powx204 power 0.5 4 -> 0.0625 -powx205 power 0.5 5 -> 0.03125 -powx206 power 0.5 6 -> 0.015625 -powx207 power 0.5 7 -> 0.0078125 -powx208 power 0.5 8 -> 0.00390625 -powx209 power 0.5 9 -> 0.001953125 -powx210 power 0.5 10 -> 0.0009765625 +powx200 power 0.5 0 -> 1 +powx201 power 0.5 1 -> 0.5 +powx202 power 0.5 2 -> 0.25 +powx203 power 0.5 3 -> 0.125 +powx204 power 0.5 4 -> 0.0625 +powx205 power 0.5 5 -> 0.03125 +powx206 power 0.5 6 -> 0.015625 +powx207 power 0.5 7 -> 0.0078125 +powx208 power 0.5 8 -> 0.00390625 +powx209 power 0.5 9 -> 0.001953125 +powx210 power 0.5 10 -> 0.0009765625 + +powx211 power 1 100000000 -> 1 +powx212 power 1 999999998 -> 1 +powx213 power 1 999999999 -> 1 --- A (rare) case where the last digit is not within 0.5 ULP -precision: 9 -powx215 power "-21971575.0E+31454441" "-7" -> "-4.04549503E-220181139" Inexact Rounded -precision: 20 -powx216 power "-21971575.0E+31454441" "-7" -> "-4.0454950249324891788E-220181139" Inexact Rounded -- The Vienna case. Checks both setup and 1/acc working precision -- Modified 1998.12.14 as RHS no longer rounded before use (must fit) @@ -201,185 +185,64 @@ -- Modified 2002.10.06 -- finally, no input rounding -- With input rounding, result would be 8.74E-2226 precision: 3 +maxexponent: 5000 +minexponent: -5000 powx219 power '123456789E+10' '-1.23000e+2' -> '5.54E-2226' Inexact Rounded --- whole number checks -precision: 9 -powx221 power 1 1234 -> 1 -precision: 4 -powx222 power 1 1234 -> 1 -precision: 3 -powx223 power 1 1234 -> 1 -powx224 power 1 12.34e+2 -> 1 -powx225 power 1 12.3 -> NaN Invalid_operation -powx226 power 1 12.0 -> 1 -powx227 power 1 1.01 -> NaN Invalid_operation -powx228 power 2 1.00 -> 2 -powx229 power 2 2.00 -> 4 -precision: 9 -powx230 power 1 1.0001 -> NaN Invalid_operation -powx231 power 1 1.0000001 -> NaN Invalid_operation -powx232 power 1 1.0000000001 -> NaN Invalid_operation -powx233 power 1 1.0000000000001 -> NaN Invalid_operation -precision: 5 -powx234 power 1 1.0001 -> NaN Invalid_operation -powx235 power 1 1.0000001 -> NaN Invalid_operation -powx236 power 1 1.0000000001 -> NaN Invalid_operation -powx237 power 1 1.0000000000001 -> NaN Invalid_operation -powx238 power 1 1.0000000000001 -> NaN Invalid_operation - -maxexponent: 999999999 -minexponent: -999999999 -powx239 power 1 5.67E-987654321 -> NaN Invalid_operation - -powx240 power 1 100000000 -> 1 -powx241 power 1 999999998 -> 1 -powx242 power 1 999999999 -> 1 -powx243 power 1 1000000000 -> NaN Invalid_operation -powx244 power 1 9999999999 -> NaN Invalid_operation - --- Checks for 'Too much precision needed' --- For x^12, digits+elength+1 = digits+3 -precision: 999999999 -powx249 add 1 1 -> 2 -- check basic operation at this precision -powx250 power 2 12 -> Infinity Overflow -precision: 999999998 -powx251 power 2 12 -> Infinity Overflow -precision: 999999997 -powx252 power 2 12 -> Infinity Overflow -precision: 999999996 -powx253 power 2 12 -> 4096 -precision: 999999995 -powx254 power 2 12 -> 4096 - -- zeros maxexponent: +96 minexponent: -95 precision: 7 -powx260 power 0E-34 3 -> 0E-101 Clamped -powx261 power 0E-33 3 -> 0E-99 -powx262 power 0E-32 3 -> 0E-96 -powx263 power 0E-30 3 -> 0E-90 -powx264 power 0E-10 3 -> 0E-30 -powx265 power 0E-1 3 -> 0.000 -powx266 power 0E+0 3 -> 0 -powx267 power 0 3 -> 0 -powx268 power 0E+1 3 -> 0E+3 -powx269 power 0E+10 3 -> 0E+30 -powx270 power 0E+30 3 -> 0E+90 -powx271 power 0E+32 3 -> 0E+96 -powx272 power 0E+33 3 -> 0E+96 Clamped - --- overflow and underflow tests -maxexponent: 999999999 -minexponent: -999999999 -precision: 9 -powx280 power 9 999999999 -> 3.05550054E+954242508 Inexact Rounded -powx281 power 10 999999999 -> 1.00000000E+999999999 Rounded -powx282 power 10.0001 999999999 -> Infinity Overflow Inexact Rounded -powx283 power 10.1 999999999 -> Infinity Overflow Inexact Rounded -powx284 power 11 999999999 -> Infinity Overflow Inexact Rounded -powx285 power 12 999999999 -> Infinity Overflow Inexact Rounded -powx286 power 999 999999999 -> Infinity Overflow Inexact Rounded -powx287 power 999999 999999999 -> Infinity Overflow Inexact Rounded -powx288 power 999999999 999999999 -> Infinity Overflow Inexact Rounded -powx289 power 9.9E999999999 999999999 -> Infinity Overflow Inexact Rounded - -powx290 power 0.5 999999999 -> 4.33559594E-301029996 Inexact Rounded -powx291 power 0.1 999999999 -> 1E-999999999 -- unrounded -powx292 power 0.09 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx293 power 0.05 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx294 power 0.01 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx295 power 0.0001 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx297 power 0.0000001 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx298 power 0.0000000001 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx299 power 1E-999999999 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped - -powx310 power -9 999999999 -> -3.05550054E+954242508 Inexact Rounded -powx311 power -10 999999999 -> -1.00000000E+999999999 Rounded -powx312 power -10.0001 999999999 -> -Infinity Overflow Inexact Rounded -powx313 power -10.1 999999999 -> -Infinity Overflow Inexact Rounded -powx314 power -11 999999999 -> -Infinity Overflow Inexact Rounded -powx315 power -12 999999999 -> -Infinity Overflow Inexact Rounded -powx316 power -999 999999999 -> -Infinity Overflow Inexact Rounded -powx317 power -999999 999999999 -> -Infinity Overflow Inexact Rounded -powx318 power -999999999 999999999 -> -Infinity Overflow Inexact Rounded -powx319 power -9.9E999999999 999999999 -> -Infinity Overflow Inexact Rounded - -powx320 power -0.5 999999999 -> -4.33559594E-301029996 Inexact Rounded -powx321 power -0.1 999999999 -> -1E-999999999 -powx322 power -0.09 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx323 power -0.05 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx324 power -0.01 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx325 power -0.0001 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx327 power -0.0000001 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx328 power -0.0000000001 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx329 power -1E-999999999 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx223 power 0E-30 3 -> 0 +powx224 power 0E-10 3 -> 0 +powx225 power 0E-1 3 -> 0 +powx226 power 0E+0 3 -> 0 +powx227 power 0 3 -> 0 +powx228 power 0E+1 3 -> 0 +powx229 power 0E+10 3 -> 0 +powx230 power 0E+30 3 -> 0 +powx231 power 3 0E-30 -> 1 +powx232 power 3 0E-10 -> 1 +powx233 power 3 0E-1 -> 1 +powx234 power 3 0E+0 -> 1 +powx235 power 3 0 -> 1 +powx236 power 3 0E+1 -> 1 +powx237 power 3 0E+10 -> 1 +powx238 power 3 0E+30 -> 1 +powx239 power 0E-30 -3 -> Infinity +powx240 power 0E-10 -3 -> Infinity +powx241 power 0E-1 -3 -> Infinity +powx242 power 0E+0 -3 -> Infinity +powx243 power 0 -3 -> Infinity +powx244 power 0E+1 -3 -> Infinity +powx245 power 0E+10 -3 -> Infinity +powx246 power 0E+30 -3 -> Infinity +powx247 power -3 0E-30 -> 1 +powx248 power -3 0E-10 -> 1 +powx249 power -3 0E-1 -> 1 +powx250 power -3 0E+0 -> 1 +powx251 power -3 0 -> 1 +powx252 power -3 0E+1 -> 1 +powx253 power -3 0E+10 -> 1 +powx254 power -3 0E+30 -> 1 --- note no trim of next result -powx330 power -9 999999998 -> 3.39500060E+954242507 Inexact Rounded -powx331 power -10 999999998 -> 1.00000000E+999999998 Rounded -powx332 power -10.0001 999999998 -> Infinity Overflow Inexact Rounded -powx333 power -10.1 999999998 -> Infinity Overflow Inexact Rounded -powx334 power -11 999999998 -> Infinity Overflow Inexact Rounded -powx335 power -12 999999998 -> Infinity Overflow Inexact Rounded -powx336 power -999 999999998 -> Infinity Overflow Inexact Rounded -powx337 power -999999 999999998 -> Infinity Overflow Inexact Rounded -powx338 power -999999999 999999998 -> Infinity Overflow Inexact Rounded -powx339 power -9.9E999999999 999999998 -> Infinity Overflow Inexact Rounded - -powx340 power -0.5 999999998 -> 8.67119187E-301029996 Inexact Rounded -powx341 power -0.1 999999998 -> 1E-999999998 -- NB exact unrounded -powx342 power -0.09 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx343 power -0.05 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx344 power -0.01 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx345 power -0.0001 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx347 power -0.0000001 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx348 power -0.0000000001 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx349 power -1E-999999999 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped - --- some subnormals +-- a few lhs negatives precision: 9 --- [precision is 9, so smallest exponent is -1000000007 -powx350 power 1e-1 500000000 -> 1E-500000000 -powx351 power 1e-2 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx352 power 1e-2 500000000 -> 1E-1000000000 Subnormal -powx353 power 1e-2 500000001 -> 1E-1000000002 Subnormal -powx354 power 1e-2 500000002 -> 1E-1000000004 Subnormal -powx355 power 1e-2 500000003 -> 1E-1000000006 Subnormal -powx356 power 1e-2 500000004 -> 0E-1000000007 Underflow Subnormal Inexact Rounded - -powx360 power 0.010001 500000000 -> 4.34941988E-999978287 Inexact Rounded -powx361 power 0.010000001 500000000 -> 5.18469257E-999999979 Inexact Rounded -powx362 power 0.010000001 500000001 -> 5.18469309E-999999981 Inexact Rounded -powx363 power 0.0100000009 500000000 -> 3.49342003E-999999981 Inexact Rounded -powx364 power 0.0100000001 500000000 -> 1.48413155E-999999998 Inexact Rounded -powx365 power 0.01 500000000 -> 1E-1000000000 Subnormal -powx366 power 0.0099999999 500000000 -> 6.7379E-1000000003 Underflow Subnormal Inexact Rounded -powx367 power 0.0099999998 500000000 -> 4.54E-1000000005 Underflow Subnormal Inexact Rounded -powx368 power 0.0099999997 500000000 -> 3E-1000000007 Underflow Subnormal Inexact Rounded -powx369 power 0.0099999996 500000000 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -powx370 power 0.009 500000000 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped - --- 1/subnormal -> overflow -powx371 power 1e-1 -500000000 -> 1E+500000000 -powx372 power 1e-2 -999999999 -> Infinity Overflow Inexact Rounded -powx373 power 1e-2 -500000000 -> Infinity Overflow Inexact Rounded -powx374 power 1e-2 -500000001 -> Infinity Overflow Inexact Rounded -powx375 power 1e-2 -500000002 -> Infinity Overflow Inexact Rounded -powx376 power 1e-2 -500000003 -> Infinity Overflow Inexact Rounded -powx377 power 1e-2 -500000004 -> Infinity Overflow Inexact Rounded - -powx381 power 0.010001 -500000000 -> 2.29915719E+999978286 Inexact Rounded -powx382 power 0.010000001 -500000000 -> 1.92875467E+999999978 Inexact Rounded -powx383 power 0.010000001 -500000001 -> 1.92875448E+999999980 Inexact Rounded -powx384 power 0.0100000009 -500000000 -> 2.86252438E+999999980 Inexact Rounded -powx385 power 0.0100000001 -500000000 -> 6.73794717E+999999997 Inexact Rounded -powx386 power 0.01 -500000000 -> Infinity Overflow Inexact Rounded -powx387 power 0.009999 -500000000 -> Infinity Overflow Inexact Rounded - --- negative power giving subnormal -powx388 power 100.000001 -500000000 -> 6.7379E-1000000003 Underflow Subnormal Inexact Rounded +maxExponent: 999 +minexponent: -999 +powx260 power -10 '0' -> 1 +powx261 power -10 '1' -> -10 +powx262 power -10 '2' -> 100 +powx263 power -10 '3' -> -1000 +powx264 power -10 '4' -> 10000 +powx265 power -10 '5' -> -100000 +powx266 power -10 '6' -> 1000000 +powx267 power -10 '7' -> -10000000 +powx268 power -10 '8' -> 100000000 +powx269 power -10 '9' -> -1.00000000E+9 Rounded +powx270 power -10 '22' -> 1.00000000E+22 Rounded +powx271 power -10 '77' -> -1.00000000E+77 Rounded +powx272 power -10 '99' -> -1.00000000E+99 Rounded -- some more edge cases precision: 15 @@ -389,8 +252,9 @@ powx392 power 0.099 999 -> 4.360732062E-1004 Underflow Subnormal Inexact Rounded powx393 power 0.098 999 -> 1.71731E-1008 Underflow Subnormal Inexact Rounded powx394 power 0.097 999 -> 6E-1013 Underflow Subnormal Inexact Rounded -powx395 power 0.096 999 -> 0E-1013 Underflow Subnormal Inexact Rounded +powx395 power 0.096 999 -> 0E-1013 Underflow Subnormal Inexact Rounded Clamped powx396 power 0.01 999 -> 0E-1013 Underflow Subnormal Inexact Rounded Clamped +powx397 power 0.02 100000000 -> 0E-1013 Underflow Subnormal Inexact Rounded Clamped -- multiply tests are here to aid checking and test for consistent handling -- of underflow @@ -399,7 +263,7 @@ minexponent: -999 -- squares -mulx400 multiply 1E-502 1e-502 -> 0E-1003 Subnormal Inexact Underflow Rounded +mulx400 multiply 1E-502 1e-502 -> 0E-1003 Subnormal Inexact Underflow Rounded Clamped mulx401 multiply 1E-501 1e-501 -> 1E-1002 Subnormal mulx402 multiply 2E-501 2e-501 -> 4E-1002 Subnormal mulx403 multiply 4E-501 4e-501 -> 1.6E-1001 Subnormal @@ -407,7 +271,7 @@ mulx405 multiply 30E-501 30e-501 -> 9.00E-1000 Subnormal mulx406 multiply 40E-501 40e-501 -> 1.600E-999 -powx400 power 1E-502 2 -> 0E-1003 Underflow Subnormal Inexact Rounded +powx400 power 1E-502 2 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped powx401 power 1E-501 2 -> 1E-1002 Subnormal powx402 power 2E-501 2 -> 4E-1002 Subnormal powx403 power 4E-501 2 -> 1.6E-1001 Subnormal @@ -416,7 +280,7 @@ powx406 power 40E-501 2 -> 1.600E-999 -- cubes -mulx410 multiply 1E-670 1e-335 -> 0E-1003 Underflow Subnormal Inexact Rounded +mulx410 multiply 1E-670 1e-335 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped mulx411 multiply 1E-668 1e-334 -> 1E-1002 Subnormal mulx412 multiply 4E-668 2e-334 -> 8E-1002 Subnormal mulx413 multiply 9E-668 3e-334 -> 2.7E-1001 Subnormal @@ -424,7 +288,7 @@ mulx415 multiply 25E-668 5e-334 -> 1.25E-1000 Subnormal mulx416 multiply 10E-668 100e-334 -> 1.000E-999 -powx410 power 1E-335 3 -> 0E-1003 Underflow Subnormal Inexact Rounded +powx410 power 1E-335 3 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped powx411 power 1E-334 3 -> 1E-1002 Subnormal powx412 power 2E-334 3 -> 8E-1002 Subnormal powx413 power 3E-334 3 -> 2.7E-1001 Subnormal @@ -442,24 +306,24 @@ powx423 power 2.5E+499 -2 -> 1.6E-999 powx424 power 2.5E+500 -2 -> 1.6E-1001 Subnormal powx425 power 2.5E+501 -2 -> 2E-1003 Underflow Subnormal Inexact Rounded -powx426 power 2.5E+502 -2 -> 0E-1003 Underflow Subnormal Inexact Rounded +powx426 power 2.5E+502 -2 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped powx427 power 0.25E+499 -2 -> 1.6E-997 powx428 power 0.25E+500 -2 -> 1.6E-999 powx429 power 0.25E+501 -2 -> 1.6E-1001 Subnormal powx430 power 0.25E+502 -2 -> 2E-1003 Underflow Subnormal Inexact Rounded -powx431 power 0.25E+503 -2 -> 0E-1003 Underflow Subnormal Inexact Rounded +powx431 power 0.25E+503 -2 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped powx432 power 0.04E+499 -2 -> 6.25E-996 powx433 power 0.04E+500 -2 -> 6.25E-998 powx434 power 0.04E+501 -2 -> 6.25E-1000 Subnormal -powx435 power 0.04E+502 -2 -> 6.3E-1002 Underflow Subnormal Inexact Rounded +powx435 power 0.04E+502 -2 -> 6.2E-1002 Underflow Subnormal Inexact Rounded powx436 power 0.04E+503 -2 -> 1E-1003 Underflow Subnormal Inexact Rounded -powx437 power 0.04E+504 -2 -> 0E-1003 Underflow Subnormal Inexact Rounded +powx437 power 0.04E+504 -2 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped powx441 power 0.04E+334 -3 -> 1.5625E-998 powx442 power 0.04E+335 -3 -> 1.56E-1001 Underflow Subnormal Inexact Rounded -powx443 power 0.04E+336 -3 -> 0E-1003 Underflow Subnormal Inexact Rounded +powx443 power 0.04E+336 -3 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped powx444 power 0.25E+333 -3 -> 6.4E-998 powx445 power 0.25E+334 -3 -> 6.4E-1001 Subnormal powx446 power 0.25E+335 -3 -> 1E-1003 Underflow Subnormal Inexact Rounded @@ -467,7 +331,7 @@ -- check sign for cubes and a few squares powx448 power -0.04E+334 -3 -> -1.5625E-998 powx449 power -0.04E+335 -3 -> -1.56E-1001 Underflow Subnormal Inexact Rounded -powx450 power -0.04E+336 -3 -> -0E-1003 Underflow Subnormal Inexact Rounded +powx450 power -0.04E+336 -3 -> -0E-1003 Underflow Subnormal Inexact Rounded Clamped powx451 power -0.25E+333 -3 -> -6.4E-998 powx452 power -0.25E+334 -3 -> -6.4E-1001 Subnormal powx453 power -0.25E+335 -3 -> -1E-1003 Underflow Subnormal Inexact Rounded @@ -475,7 +339,7 @@ powx455 power -0.04E+499 -2 -> 6.25E-996 powx456 power -0.04E+500 -2 -> 6.25E-998 powx457 power -0.04E+501 -2 -> 6.25E-1000 Subnormal -powx458 power -0.04E+502 -2 -> 6.3E-1002 Underflow Subnormal Inexact Rounded +powx458 power -0.04E+502 -2 -> 6.2E-1002 Underflow Subnormal Inexact Rounded -- test -0s precision: 9 @@ -488,123 +352,124 @@ powx566 power -1 0 -> 1 powx567 power -1 -0 -> 1 powx568 power 0 1 -> 0 -powx569 power 0 -1 -> Infinity Division_by_zero +powx569 power 0 -1 -> Infinity powx570 power -0 1 -> -0 -powx571 power -0 -1 -> -Infinity Division_by_zero +powx571 power -0 -1 -> -Infinity powx572 power 0 2 -> 0 -powx573 power 0 -2 -> Infinity Division_by_zero +powx573 power 0 -2 -> Infinity powx574 power -0 2 -> 0 -powx575 power -0 -2 -> Infinity Division_by_zero +powx575 power -0 -2 -> Infinity powx576 power 0 3 -> 0 -powx577 power 0 -3 -> Infinity Division_by_zero +powx577 power 0 -3 -> Infinity powx578 power -0 3 -> -0 -powx579 power -0 -3 -> -Infinity Division_by_zero +powx579 power -0 -3 -> -Infinity -- Specials -powx580 power Inf -Inf -> NaN Invalid_operation +powx580 power Inf -Inf -> 0 powx581 power Inf -1000 -> 0 powx582 power Inf -1 -> 0 -powx583 power Inf -0 -> 1 -powx584 power Inf 0 -> 1 -powx585 power Inf 1 -> Infinity -powx586 power Inf 1000 -> Infinity -powx587 power Inf Inf -> NaN Invalid_operation -powx588 power -1000 Inf -> NaN Invalid_operation -powx589 power -Inf Inf -> NaN Invalid_operation -powx590 power -1 Inf -> NaN Invalid_operation -powx591 power -0 Inf -> NaN Invalid_operation -powx592 power 0 Inf -> NaN Invalid_operation -powx593 power 1 Inf -> NaN Invalid_operation -powx594 power 1000 Inf -> NaN Invalid_operation -powx595 power Inf Inf -> NaN Invalid_operation +powx583 power Inf -0.5 -> 0 +powx584 power Inf -0 -> 1 +powx585 power Inf 0 -> 1 +powx586 power Inf 0.5 -> Infinity +powx587 power Inf 1 -> Infinity +powx588 power Inf 1000 -> Infinity +powx589 power Inf Inf -> Infinity +powx590 power -1000 Inf -> NaN Invalid_operation +powx591 power -Inf Inf -> NaN Invalid_operation +powx592 power -1 Inf -> NaN Invalid_operation +powx593 power -0.5 Inf -> NaN Invalid_operation +powx594 power -0 Inf -> 0 +powx595 power 0 Inf -> 0 +powx596 power 0.5 Inf -> 0 +powx597 power 1 Inf -> 1.00000000 Inexact Rounded +powx598 power 1000 Inf -> Infinity +powx599 power Inf Inf -> Infinity powx600 power -Inf -Inf -> NaN Invalid_operation powx601 power -Inf -1000 -> 0 powx602 power -Inf -1 -> -0 -powx603 power -Inf -0 -> 1 -powx604 power -Inf 0 -> 1 -powx605 power -Inf 1 -> -Infinity -powx606 power -Inf 1000 -> Infinity -powx607 power -Inf Inf -> NaN Invalid_operation -powx608 power -1000 Inf -> NaN Invalid_operation -powx609 power -Inf -Inf -> NaN Invalid_operation -powx610 power -1 -Inf -> NaN Invalid_operation -powx611 power -0 -Inf -> NaN Invalid_operation -powx612 power 0 -Inf -> NaN Invalid_operation -powx613 power 1 -Inf -> NaN Invalid_operation -powx614 power 1000 -Inf -> NaN Invalid_operation -powx615 power Inf -Inf -> NaN Invalid_operation +powx603 power -Inf -0.5 -> NaN Invalid_operation +powx604 power -Inf -0 -> 1 +powx605 power -Inf 0 -> 1 +powx606 power -Inf 0.5 -> NaN Invalid_operation +powx607 power -Inf 1 -> -Infinity +powx608 power -Inf 1000 -> Infinity +powx609 power -Inf Inf -> NaN Invalid_operation +powx610 power -1000 Inf -> NaN Invalid_operation +powx611 power -Inf -Inf -> NaN Invalid_operation +powx612 power -1 -Inf -> NaN Invalid_operation +powx613 power -0.5 -Inf -> NaN Invalid_operation +powx614 power -0 -Inf -> Infinity +powx615 power 0 -Inf -> Infinity +powx616 power 0.5 -Inf -> Infinity +powx617 power 1 -Inf -> 1.00000000 Inexact Rounded +powx618 power 1000 -Inf -> 0 +powx619 power Inf -Inf -> 0 -powx621 power NaN -Inf -> NaN Invalid_operation +powx621 power NaN -Inf -> NaN powx622 power NaN -1000 -> NaN powx623 power NaN -1 -> NaN -powx624 power NaN -0 -> NaN -powx625 power NaN 0 -> NaN -powx626 power NaN 1 -> NaN -powx627 power NaN 1000 -> NaN -powx628 power NaN Inf -> NaN Invalid_operation -powx629 power NaN NaN -> NaN -powx630 power -Inf NaN -> NaN -powx631 power -1000 NaN -> NaN -powx632 power -1 NaN -> NaN -powx633 power -0 NaN -> NaN -powx634 power 0 NaN -> NaN -powx635 power 1 NaN -> NaN -powx636 power 1000 NaN -> NaN -powx637 power Inf NaN -> NaN +powx624 power NaN -0.5 -> NaN +powx625 power NaN -0 -> NaN +powx626 power NaN 0 -> NaN +powx627 power NaN 0.5 -> NaN +powx628 power NaN 1 -> NaN +powx629 power NaN 1000 -> NaN +powx630 power NaN Inf -> NaN +powx631 power NaN NaN -> NaN +powx632 power -Inf NaN -> NaN +powx633 power -1000 NaN -> NaN +powx634 power -1 NaN -> NaN +powx635 power -0 NaN -> NaN +powx636 power 0 NaN -> NaN +powx637 power 1 NaN -> NaN +powx638 power 1000 NaN -> NaN +powx639 power Inf NaN -> NaN powx641 power sNaN -Inf -> NaN Invalid_operation powx642 power sNaN -1000 -> NaN Invalid_operation powx643 power sNaN -1 -> NaN Invalid_operation -powx644 power sNaN -0 -> NaN Invalid_operation -powx645 power sNaN 0 -> NaN Invalid_operation -powx646 power sNaN 1 -> NaN Invalid_operation -powx647 power sNaN 1000 -> NaN Invalid_operation -powx648 power sNaN NaN -> NaN Invalid_operation -powx649 power sNaN sNaN -> NaN Invalid_operation -powx650 power NaN sNaN -> NaN Invalid_operation -powx651 power -Inf sNaN -> NaN Invalid_operation -powx652 power -1000 sNaN -> NaN Invalid_operation -powx653 power -1 sNaN -> NaN Invalid_operation -powx654 power -0 sNaN -> NaN Invalid_operation -powx655 power 0 sNaN -> NaN Invalid_operation -powx656 power 1 sNaN -> NaN Invalid_operation -powx657 power 1000 sNaN -> NaN Invalid_operation -powx658 power Inf sNaN -> NaN Invalid_operation -powx659 power NaN sNaN -> NaN Invalid_operation +powx644 power sNaN -0.5 -> NaN Invalid_operation +powx645 power sNaN -0 -> NaN Invalid_operation +powx646 power sNaN 0 -> NaN Invalid_operation +powx647 power sNaN 0.5 -> NaN Invalid_operation +powx648 power sNaN 1 -> NaN Invalid_operation +powx649 power sNaN 1000 -> NaN Invalid_operation +powx650 power sNaN NaN -> NaN Invalid_operation +powx651 power sNaN sNaN -> NaN Invalid_operation +powx652 power NaN sNaN -> NaN Invalid_operation +powx653 power -Inf sNaN -> NaN Invalid_operation +powx654 power -1000 sNaN -> NaN Invalid_operation +powx655 power -1 sNaN -> NaN Invalid_operation +powx656 power -0.5 sNaN -> NaN Invalid_operation +powx657 power -0 sNaN -> NaN Invalid_operation +powx658 power 0 sNaN -> NaN Invalid_operation +powx659 power 0.5 sNaN -> NaN Invalid_operation +powx660 power 1 sNaN -> NaN Invalid_operation +powx661 power 1000 sNaN -> NaN Invalid_operation +powx662 power Inf sNaN -> NaN Invalid_operation +powx663 power NaN sNaN -> NaN Invalid_operation -- NaN propagation -powx660 power NaN3 sNaN7 -> NaN7 Invalid_operation -powx661 power sNaN8 NaN6 -> NaN8 Invalid_operation -powx662 power 1 sNaN7 -> NaN7 Invalid_operation -powx663 power sNaN8 1 -> NaN8 Invalid_operation -powx664 power Inf sNaN7 -> NaN7 Invalid_operation -powx665 power sNaN8 Inf -> NaN Invalid_operation -powx666 power Inf NaN9 -> NaN9 -powx667 power NaN6 Inf -> NaN Invalid_operation -powx668 power 1 NaN5 -> NaN5 -powx669 power NaN2 1 -> NaN2 -powx670 power NaN2 Nan4 -> NaN2 -powx671 power NaN Nan4 -> NaN -powx672 power NaN345 Nan -> NaN345 -powx673 power Inf -sNaN7 -> -NaN7 Invalid_operation -powx674 power -sNaN8 Inf -> NaN Invalid_operation -powx675 power Inf -NaN9 -> -NaN9 -powx676 power -NaN6 Inf -> NaN Invalid_operation -powx677 power -NaN2 -Nan4 -> -NaN2 - --- Examples from extended specification -powx690 power Inf -2 -> 0 -powx691 power Inf -1 -> 0 -powx692 power Inf 0 -> 1 -powx693 power Inf 1 -> Infinity -powx694 power Inf 2 -> Infinity -powx695 power -Inf -2 -> 0 -powx696 power -Inf -1 -> -0 -powx697 power -Inf 0 -> 1 -powx698 power -Inf 1 -> -Infinity -powx699 power -Inf 2 -> Infinity -powx700 power 0 0 -> NaN Invalid_operation +powx670 power NaN3 sNaN7 -> NaN7 Invalid_operation +powx671 power sNaN8 NaN6 -> NaN8 Invalid_operation +powx672 power 1 sNaN7 -> NaN7 Invalid_operation +powx673 power sNaN8 1 -> NaN8 Invalid_operation +powx674 power Inf sNaN7 -> NaN7 Invalid_operation +powx675 power sNaN8 Inf -> NaN8 Invalid_operation +powx676 power Inf NaN9 -> NaN9 +powx677 power NaN6 Inf -> NaN6 +powx678 power 1 NaN5 -> NaN5 +powx679 power NaN2 1 -> NaN2 +powx680 power NaN2 Nan4 -> NaN2 +powx681 power NaN Nan4 -> NaN +powx682 power NaN345 Nan -> NaN345 +powx683 power Inf -sNaN7 -> -NaN7 Invalid_operation +powx684 power -sNaN8 Inf -> -NaN8 Invalid_operation +powx685 power Inf -NaN9 -> -NaN9 +powx686 power -NaN6 Inf -> -NaN6 +powx687 power -NaN2 -Nan4 -> -NaN2 -- long operand and RHS range checks maxexponent: 999 @@ -616,15 +481,6 @@ powx704 power 1234567891 1 -> 1.23456789E+9 Inexact Rounded powx705 power 12345678901 1 -> 1.23456789E+10 Inexact Rounded powx706 power 1234567896 1 -> 1.23456790E+9 Inexact Rounded -powx707 power 1 12345678000 -> NaN Invalid_operation -powx708 power 1 1234567800 -> NaN Invalid_operation -powx709 power 1 1234567890 -> NaN Invalid_operation -powx710 power 1 11234567891 -> NaN Invalid_operation -powx711 power 1 12345678901 -> NaN Invalid_operation -powx712 power 1 1234567896 -> NaN Invalid_operation -powx713 power 1 -1234567896 -> NaN Invalid_operation -powx714 power 1 1000000000 -> NaN Invalid_operation -powx715 power 1 -1000000000 -> NaN Invalid_operation precision: 15 -- still checking @@ -634,12 +490,182 @@ powx744 power 1234567891 1 -> 1234567891 powx745 power 12345678901 1 -> 12345678901 powx746 power 1234567896 1 -> 1234567896 -powx747 power 1 12345678000 -> NaN Invalid_operation -powx748 power 1 -1234567896 -> NaN Invalid_operation -powx749 power 1 1000000000 -> NaN Invalid_operation -powx740 power 1 -1000000000 -> NaN Invalid_operation --- check for double-rounded subnormals +maxexponent: 999999 +minexponent: -999999 +precision: 9 + +-- near out-of-range edge cases +powx163 power '10' '999999' -> '1.00000000E+999999' Rounded +powx164 power '10' '999998' -> '1.00000000E+999998' Rounded +powx165 power '10' '999997' -> '1.00000000E+999997' Rounded +powx166 power '10' '333333' -> '1.00000000E+333333' Rounded +powx183 power '7' '1000000' -> 1.09651419E+845098 Inexact Rounded +powx184 power '7' '1000001' -> 7.67559934E+845098 Inexact Rounded +powx186 power '7' '-1000001' -> 1.30282986E-845099 Inexact Rounded +powx187 power '7' '-1000000' -> 9.11980901E-845099 Inexact Rounded +powx118 power '10' '-333333' -> 1E-333333 +powx119 power '10' '-999998' -> 1E-999998 +powx120 power '10' '-999999' -> 1E-999999 +powx181 power '7' '999998' -> 2.23778406E+845096 Inexact Rounded +powx182 power '7' '999999' -> 1.56644884E+845097 Inexact Rounded +powx189 power '7' '-999999' -> 6.38386631E-845098 Inexact Rounded +powx190 power '7' '-999998' -> 4.46870641E-845097 Inexact Rounded + +-- overflow and underflow tests +precision: 9 + +powx277 power 9 999999 -> 3.59084629E+954241 Inexact Rounded +powx278 power 9.99999999 999999 -> 9.99000501E+999998 Inexact Rounded +powx279 power 10 999999 -> 1.00000000E+999999 Rounded +powx280 power 10.0000001 999999 -> 1.01005016E+999999 Inexact Rounded +powx281 power 10.000001 999999 -> 1.10517080E+999999 Inexact Rounded +powx282 power 10.00001 999999 -> 2.71827775E+999999 Inexact Rounded +powx283 power 10.0001 999999 -> Infinity Overflow Inexact Rounded +powx285 power 11 999999 -> Infinity Overflow Inexact Rounded +powx286 power 12 999999 -> Infinity Overflow Inexact Rounded +powx287 power 999 999999 -> Infinity Overflow Inexact Rounded +powx288 power 999999999 999999 -> Infinity Overflow Inexact Rounded +powx289 power 9.9E999999999 999999 -> Infinity Overflow Inexact Rounded + +powx290 power 0.5 999999 -> 2.02006812E-301030 Inexact Rounded +powx291 power 0.1 999999 -> 1E-999999 -- unrounded +powx292 power 0.09 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx293 power 0.05 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx294 power 0.01 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx295 power 0.0001 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx297 power 0.0000001 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx298 power 0.0000000001 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx299 power 1E-999999999 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped + +powx310 power -9 999999 -> -3.59084629E+954241 Inexact Rounded +powx311 power -10 999999 -> -1.00000000E+999999 Rounded +powx312 power -10.0001 999999 -> -Infinity Overflow Inexact Rounded +powx313 power -10.1 999999 -> -Infinity Overflow Inexact Rounded +powx314 power -11 999999 -> -Infinity Overflow Inexact Rounded +powx315 power -12 999999 -> -Infinity Overflow Inexact Rounded +powx316 power -999 999999 -> -Infinity Overflow Inexact Rounded +powx317 power -999999 999999 -> -Infinity Overflow Inexact Rounded +powx318 power -999999999 999999 -> -Infinity Overflow Inexact Rounded +powx319 power -9.9E999999999 999999 -> -Infinity Overflow Inexact Rounded + +powx320 power -0.5 999999 -> -2.02006812E-301030 Inexact Rounded +powx321 power -0.1 999999 -> -1E-999999 +powx322 power -0.09 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx323 power -0.05 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx324 power -0.01 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx325 power -0.0001 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx327 power -0.0000001 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx328 power -0.0000000001 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx329 power -1E-999999999 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped + +-- note no trim of next result +powx330 power -9 999998 -> 3.98982921E+954240 Inexact Rounded +powx331 power -10 999998 -> 1.00000000E+999998 Rounded +powx332 power -10.0001 999998 -> Infinity Overflow Inexact Rounded +powx333 power -10.1 999998 -> Infinity Overflow Inexact Rounded +powx334 power -11 999998 -> Infinity Overflow Inexact Rounded +powx335 power -12 999998 -> Infinity Overflow Inexact Rounded +powx336 power -999 999998 -> Infinity Overflow Inexact Rounded +powx337 power -999999 999998 -> Infinity Overflow Inexact Rounded +powx338 power -999999999 999998 -> Infinity Overflow Inexact Rounded +powx339 power -9.9E999999999 999998 -> Infinity Overflow Inexact Rounded + +powx340 power -0.5 999998 -> 4.04013624E-301030 Inexact Rounded +powx341 power -0.1 999998 -> 1E-999998 -- NB exact unrounded +powx342 power -0.09 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx343 power -0.05 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx344 power -0.01 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx345 power -0.0001 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx347 power -0.0000001 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx348 power -0.0000000001 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx349 power -1E-999999999 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped + +-- some subnormals +precision: 9 +-- [precision is 9, so smallest exponent is -1000000007 +powx350 power 1e-1 500000 -> 1E-500000 +powx351 power 1e-2 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx352 power 1e-2 500000 -> 1E-1000000 Subnormal +powx353 power 1e-2 500001 -> 1E-1000002 Subnormal +powx354 power 1e-2 500002 -> 1E-1000004 Subnormal +powx355 power 1e-2 500003 -> 1E-1000006 Subnormal +powx356 power 1e-2 500004 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped + +powx360 power 0.010001 500000 -> 5.17176082E-999979 Inexact Rounded +powx361 power 0.010000001 500000 -> 1.0512711E-1000000 Underflow Subnormal Inexact Rounded +powx362 power 0.010000001 500001 -> 1.05127E-1000002 Underflow Subnormal Inexact Rounded +powx363 power 0.0100000009 500000 -> 1.0460279E-1000000 Underflow Subnormal Inexact Rounded +powx364 power 0.0100000001 500000 -> 1.0050125E-1000000 Underflow Subnormal Inexact Rounded +powx365 power 0.01 500000 -> 1E-1000000 Subnormal +powx366 power 0.0099999999 500000 -> 9.950125E-1000001 Underflow Subnormal Inexact Rounded +powx367 power 0.0099999998 500000 -> 9.900498E-1000001 Underflow Subnormal Inexact Rounded +powx368 power 0.0099999997 500000 -> 9.851119E-1000001 Underflow Subnormal Inexact Rounded +powx369 power 0.0099999996 500000 -> 9.801987E-1000001 Underflow Subnormal Inexact Rounded +powx370 power 0.009 500000 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped + +-- 1/subnormal -> overflow +powx371 power 1e-1 -500000 -> 1E+500000 +powx372 power 1e-2 -999999 -> Infinity Overflow Inexact Rounded +powx373 power 1e-2 -500000 -> Infinity Overflow Inexact Rounded +powx374 power 1e-2 -500001 -> Infinity Overflow Inexact Rounded +powx375 power 1e-2 -500002 -> Infinity Overflow Inexact Rounded +powx376 power 1e-2 -500003 -> Infinity Overflow Inexact Rounded +powx377 power 1e-2 -500004 -> Infinity Overflow Inexact Rounded + +powx381 power 0.010001 -500000 -> 1.93357743E+999978 Inexact Rounded +powx382 power 0.010000001 -500000 -> 9.51229427E+999999 Inexact Rounded +powx383 power 0.010000001 -500001 -> Infinity Overflow Inexact Rounded +powx384 power 0.0100000009 -500000 -> 9.55997484E+999999 Inexact Rounded +powx385 power 0.0100000001 -500000 -> 9.95012479E+999999 Inexact Rounded +powx386 power 0.01 -500000 -> Infinity Overflow Inexact Rounded +powx387 power 0.009999 -500000 -> Infinity Overflow Inexact Rounded + +-- negative power giving subnormal +powx388 power 100.000001 -500000 -> 9.950125E-1000001 Underflow Subnormal Inexact Rounded + + +-- test some 'false integer' boundaries +precision: 16 +rounding: half_even +maxExponent: 384 +minExponent: -383 +powx501 power 100 1E+1 -> 1.000000000000000E+20 Rounded +powx502 power 100 1E+2 -> 1.000000000000000E+200 Rounded +powx503 power 100 1E+3 -> Infinity Overflow Inexact Rounded +powx504 power 100 1E+4 -> Infinity Overflow Inexact Rounded +powx505 power 100 1E+5 -> Infinity Overflow Inexact Rounded +powx506 power 100 1E+6 -> Infinity Overflow Inexact Rounded +powx507 power 100 1E+7 -> Infinity Overflow Inexact Rounded +powx508 power 100 1E+8 -> Infinity Overflow Inexact Rounded +powx509 power 100 1E+9 -> Infinity Overflow Inexact Rounded +powx510 power 100 1E+10 -> Infinity Overflow Inexact Rounded +powx511 power 100 1E+11 -> Infinity Overflow Inexact Rounded +powx512 power 100 1E+12 -> Infinity Overflow Inexact Rounded +powx513 power 100 1E+13 -> Infinity Overflow Inexact Rounded +powx514 power 100 1E+14 -> Infinity Overflow Inexact Rounded +powx515 power 100 1E+15 -> Infinity Overflow Inexact Rounded +powx516 power 100 1E+16 -> Infinity Overflow Inexact Rounded +powx517 power 100 1E+17 -> Infinity Overflow Inexact Rounded +powx518 power 100 1E+18 -> Infinity Overflow Inexact Rounded +powx519 power 100 1E+19 -> Infinity Overflow Inexact Rounded +powx520 power 100 1E+20 -> Infinity Overflow Inexact Rounded +powx521 power 100 1E+21 -> Infinity Overflow Inexact Rounded +powx522 power 100 1E+22 -> Infinity Overflow Inexact Rounded +powx523 power 100 1E+23 -> Infinity Overflow Inexact Rounded +powx524 power 100 1E+24 -> Infinity Overflow Inexact Rounded +powx525 power 100 1E+25 -> Infinity Overflow Inexact Rounded +powx526 power 100 1E+26 -> Infinity Overflow Inexact Rounded +powx527 power 100 1E+27 -> Infinity Overflow Inexact Rounded +powx528 power 100 1E+28 -> Infinity Overflow Inexact Rounded +powx529 power 100 1E+29 -> Infinity Overflow Inexact Rounded +powx530 power 100 1E+30 -> Infinity Overflow Inexact Rounded +powx531 power 100 1E+40 -> Infinity Overflow Inexact Rounded +powx532 power 100 1E+50 -> Infinity Overflow Inexact Rounded +powx533 power 100 1E+100 -> Infinity Overflow Inexact Rounded +powx534 power 100 1E+383 -> Infinity Overflow Inexact Rounded + +-- a check for double-rounded subnormals precision: 5 maxexponent: 79 minexponent: -79 @@ -649,3 +675,950 @@ powx900 power 1 # -> NaN Invalid_operation powx901 power # 1 -> NaN Invalid_operation +---------------------------------------------------------------------- +-- Below here are tests with a precision or context outside of the -- +-- decNumber 'mathematical functions' restricted range. These -- +-- remain supported in decNumber to minimize breakage, but may be -- +-- outside the range of other implementations. -- +---------------------------------------------------------------------- +maxexponent: 999999999 +minexponent: -999999999 +precision: 9 +powx1063 power '10' '999999999' -> '1.00000000E+999999999' Rounded +powx1064 power '10' '999999998' -> '1.00000000E+999999998' Rounded +powx1065 power '10' '999999997' -> '1.00000000E+999999997' Rounded +powx1066 power '10' '333333333' -> '1.00000000E+333333333' Rounded +-- next two are integer-out-of range +powx1183 power '7' '1000000000' -> NaN Invalid_context +powx1184 power '7' '1000000001' -> NaN Invalid_context +powx1186 power '7' '-1000000001' -> 1.38243630E-845098041 Inexact Rounded +powx1187 power '7' '-1000000000' -> 9.67705411E-845098041 Inexact Rounded + +-- out-of-range edge cases +powx1118 power '10' '-333333333' -> 1E-333333333 +powx1119 power '10' '-999999998' -> 1E-999999998 +powx1120 power '10' '-999999999' -> 1E-999999999 +powx1181 power '7' '999999998' -> 2.10892313E+845098038 Inexact Rounded +powx1182 power '7' '999999999' -> 1.47624619E+845098039 Inexact Rounded +powx1189 power '7' '-999999999' -> 6.77393787E-845098040 Inexact Rounded +powx1190 power '7' '-999999998' -> 4.74175651E-845098039 Inexact Rounded + +-- A (rare) case where the last digit is not within 0.5 ULP with classic precision +precision: 9 +powx1215 power "-21971575.0E+31454441" "-7" -> "-4.04549502E-220181139" Inexact Rounded +precision: 20 +powx1216 power "-21971575.0E+31454441" "-7" -> "-4.0454950249324891788E-220181139" Inexact Rounded + +-- overflow and underflow tests +precision: 9 +powx1280 power 9 999999999 -> 3.05550054E+954242508 Inexact Rounded +powx1281 power 10 999999999 -> 1.00000000E+999999999 Rounded +powx1282 power 10.0001 999999999 -> Infinity Overflow Inexact Rounded +powx1283 power 10.1 999999999 -> Infinity Overflow Inexact Rounded +powx1284 power 11 999999999 -> Infinity Overflow Inexact Rounded +powx1285 power 12 999999999 -> Infinity Overflow Inexact Rounded +powx1286 power 999 999999999 -> Infinity Overflow Inexact Rounded +powx1287 power 999999 999999999 -> Infinity Overflow Inexact Rounded +powx1288 power 999999999 999999999 -> Infinity Overflow Inexact Rounded +powx1289 power 9.9E999999999 999999999 -> Infinity Overflow Inexact Rounded + +powx1290 power 0.5 999999999 -> 4.33559594E-301029996 Inexact Rounded +powx1291 power 0.1 999999999 -> 1E-999999999 -- unrounded +powx1292 power 0.09 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1293 power 0.05 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1294 power 0.01 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1295 power 0.0001 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1297 power 0.0000001 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1298 power 0.0000000001 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1299 power 1E-999999999 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped + +powx1310 power -9 999999999 -> -3.05550054E+954242508 Inexact Rounded +powx1311 power -10 999999999 -> -1.00000000E+999999999 Rounded +powx1312 power -10.0001 999999999 -> -Infinity Overflow Inexact Rounded +powx1313 power -10.1 999999999 -> -Infinity Overflow Inexact Rounded +powx1314 power -11 999999999 -> -Infinity Overflow Inexact Rounded +powx1315 power -12 999999999 -> -Infinity Overflow Inexact Rounded +powx1316 power -999 999999999 -> -Infinity Overflow Inexact Rounded +powx1317 power -999999 999999999 -> -Infinity Overflow Inexact Rounded +powx1318 power -999999999 999999999 -> -Infinity Overflow Inexact Rounded +powx1319 power -9.9E999999999 999999999 -> -Infinity Overflow Inexact Rounded + +powx1320 power -0.5 999999999 -> -4.33559594E-301029996 Inexact Rounded +powx1321 power -0.1 999999999 -> -1E-999999999 +powx1322 power -0.09 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1323 power -0.05 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1324 power -0.01 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1325 power -0.0001 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1327 power -0.0000001 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1328 power -0.0000000001 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1329 power -1E-999999999 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped + +-- note no trim of next result +powx1330 power -9 999999998 -> 3.39500060E+954242507 Inexact Rounded +powx1331 power -10 999999998 -> 1.00000000E+999999998 Rounded +powx1332 power -10.0001 999999998 -> Infinity Overflow Inexact Rounded +powx1333 power -10.1 999999998 -> Infinity Overflow Inexact Rounded +powx1334 power -11 999999998 -> Infinity Overflow Inexact Rounded +powx1335 power -12 999999998 -> Infinity Overflow Inexact Rounded +powx1336 power -999 999999998 -> Infinity Overflow Inexact Rounded +powx1337 power -999999 999999998 -> Infinity Overflow Inexact Rounded +powx1338 power -999999999 999999998 -> Infinity Overflow Inexact Rounded +powx1339 power -9.9E999999999 999999998 -> Infinity Overflow Inexact Rounded + +powx1340 power -0.5 999999998 -> 8.67119187E-301029996 Inexact Rounded +powx1341 power -0.1 999999998 -> 1E-999999998 -- NB exact unrounded +powx1342 power -0.09 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1343 power -0.05 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1344 power -0.01 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1345 power -0.0001 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1347 power -0.0000001 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1348 power -0.0000000001 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1349 power -1E-999999999 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped + +-- some subnormals +precision: 9 +-- [precision is 9, so smallest exponent is -1000000007 +powx1350 power 1e-1 500000000 -> 1E-500000000 +powx1351 power 1e-2 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1352 power 1e-2 500000000 -> 1E-1000000000 Subnormal +powx1353 power 1e-2 500000001 -> 1E-1000000002 Subnormal +powx1354 power 1e-2 500000002 -> 1E-1000000004 Subnormal +powx1355 power 1e-2 500000003 -> 1E-1000000006 Subnormal +powx1356 power 1e-2 500000004 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped + +powx1360 power 0.010001 500000000 -> 4.34941988E-999978287 Inexact Rounded +powx1361 power 0.010000001 500000000 -> 5.18469257E-999999979 Inexact Rounded +powx1362 power 0.010000001 500000001 -> 5.18469309E-999999981 Inexact Rounded +powx1363 power 0.0100000009 500000000 -> 3.49342003E-999999981 Inexact Rounded +powx1364 power 0.0100000001 500000000 -> 1.48413155E-999999998 Inexact Rounded +powx1365 power 0.01 500000000 -> 1E-1000000000 Subnormal +powx1366 power 0.0099999999 500000000 -> 6.7379E-1000000003 Underflow Subnormal Inexact Rounded +powx1367 power 0.0099999998 500000000 -> 4.54E-1000000005 Underflow Subnormal Inexact Rounded +powx1368 power 0.0099999997 500000000 -> 3E-1000000007 Underflow Subnormal Inexact Rounded +powx1369 power 0.0099999996 500000000 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1370 power 0.009 500000000 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped + +-- 1/subnormal -> overflow +powx1371 power 1e-1 -500000000 -> 1E+500000000 +powx1372 power 1e-2 -999999999 -> Infinity Overflow Inexact Rounded +powx1373 power 1e-2 -500000000 -> Infinity Overflow Inexact Rounded +powx1374 power 1e-2 -500000001 -> Infinity Overflow Inexact Rounded +powx1375 power 1e-2 -500000002 -> Infinity Overflow Inexact Rounded +powx1376 power 1e-2 -500000003 -> Infinity Overflow Inexact Rounded +powx1377 power 1e-2 -500000004 -> Infinity Overflow Inexact Rounded + +powx1381 power 0.010001 -500000000 -> 2.29915719E+999978286 Inexact Rounded +powx1382 power 0.010000001 -500000000 -> 1.92875467E+999999978 Inexact Rounded +powx1383 power 0.010000001 -500000001 -> 1.92875448E+999999980 Inexact Rounded +powx1384 power 0.0100000009 -500000000 -> 2.86252438E+999999980 Inexact Rounded +powx1385 power 0.0100000001 -500000000 -> 6.73794717E+999999997 Inexact Rounded +powx1386 power 0.01 -500000000 -> Infinity Overflow Inexact Rounded +powx1387 power 0.009999 -500000000 -> Infinity Overflow Inexact Rounded + +-- negative power giving subnormal +powx1388 power 100.000001 -500000000 -> 6.7379E-1000000003 Underflow Subnormal Inexact Rounded + +---------------------------------------------------------------------- +-- Below here are the tests with a non-integer rhs, including the -- +-- tests that previously caused Invalid operation. An integer-only -- +-- (on rhs) implementation should handle all the tests above as -- +-- shown, and would flag most of the following tests as Invalid. -- +---------------------------------------------------------------------- +precision: 16 +rounding: half_even +maxExponent: 384 +minExponent: -383 + +powx2000 power 7 '10000000000' -> Infinity Overflow Inexact Rounded +powx2001 power 2 '2.000001' -> 4.000002772589683 Inexact Rounded +powx2002 power 2 '2.00000000' -> 4 +powx2003 power 2 '2.000000001' -> 4.000000002772589 Inexact Rounded +powx2004 power 2 '2.0000000001' -> 4.000000000277259 Inexact Rounded +powx2005 power 2 '2.00000000001' -> 4.000000000027726 Inexact Rounded +powx2006 power 2 '2.000000000001' -> 4.000000000002773 Inexact Rounded +powx2007 power 2 '2.0000000000001' -> 4.000000000000277 Inexact Rounded +powx2008 power 2 '2.00000000000001' -> 4.000000000000028 Inexact Rounded +powx2009 power 2 '2.000000000000001' -> 4.000000000000003 Inexact Rounded +powx2010 power 2 '2.0000000000000001' -> 4.000000000000000 Inexact Rounded +-- 1 234567890123456 + +powx2011 power 1 1234 -> 1 +precision: 4 +powx2012 power 1 1234 -> 1 +precision: 3 +powx2013 power 1 1234 -> 1 +powx2014 power 1 12.34e+2 -> 1 +powx2015 power 1 12.3 -> 1.00 Inexact Rounded +powx2016 power 1 12.0 -> 1 +powx2017 power 1 1.01 -> 1.00 Inexact Rounded +powx2018 power 2 1.00 -> 2 +powx2019 power 2 2.00 -> 4 +precision: 9 +powx2030 power 1 1.0001 -> 1.00000000 Inexact Rounded +powx2031 power 1 1.0000001 -> 1.00000000 Inexact Rounded +powx2032 power 1 1.0000000001 -> 1.00000000 Inexact Rounded +powx2033 power 1 1.0000000000001 -> 1.00000000 Inexact Rounded +precision: 5 +powx2034 power 1 1.0001 -> 1.0000 Inexact Rounded +powx2035 power 1 1.0000001 -> 1.0000 Inexact Rounded +powx2036 power 1 1.0000000001 -> 1.0000 Inexact Rounded +powx2037 power 1 1.0000000000001 -> 1.0000 Inexact Rounded +powx2038 power 1 1.0000000000001 -> 1.0000 Inexact Rounded + +rounding: ceiling +precision: 3 +powx2039 power 1 1.01 -> 1.00 Inexact Rounded +powx2040 power 1 12.3 -> 1.00 Inexact Rounded +rounding: half_even + +-- 1 ** any integer, including big ones, should be exact +powx2041 power 1 1000000000 -> 1 +powx2042 power 1 9999999999 -> 1 +powx2043 power 1 12345678000 -> 1 +powx2044 power 1 1234567800 -> 1 +powx2045 power 1 1234567890 -> 1 +powx2046 power 1 11234567891 -> 1 +powx2047 power 1 12345678901 -> 1 +powx2048 power 1 1234567896 -> 1 +powx2049 power 1 -1234567896 -> 1 +powx2051 power 1 1000000000 -> 1 +powx2052 power 1 -1000000000 -> 1 +powx2053 power 1 12345678000 -> 1 +powx2054 power 1 -1234567896 -> 1 +powx2055 power 1 1000000000 -> 1 +powx2056 power 1 4300000000 -> 1 +powx2057 power 1 -1000000000 -> 1 +-- negatives ... but not out of range for decNumber +powx2061 power -1 100000 -> 1 +powx2062 power -1 999999 -> -1 +powx2063 power -1 1278000 -> 1 +powx2064 power -1 127803 -> -1 +powx2065 power -1 127890 -> 1 +powx2066 power -1 1167891 -> -1 +powx2067 power -1 1278901 -> -1 +powx2068 power -1 127896 -> 1 +powx2069 power -1 -167897 -> -1 +powx2071 power -1 100000 -> 1 +powx2072 power -1 -100001 -> -1 +powx2073 power -1 1278000 -> 1 +powx2074 power -1 -167896 -> 1 +powx2075 power -1 100000 -> 1 +powx2076 power -1 -100009 -> -1 + +-- The above were derived from the earlier version of power.decTest; +-- now start new tests for power(x,y) for non-integer y +precision: 9 + +-- tests from specification +powx2081 power 2 3 -> '8' +powx2082 power -2 3 -> '-8' +powx2083 power 2 -3 -> '0.125' +powx2084 power 1.7 '8' -> '69.7575744' Inexact Rounded +powx2085 power 10 0.301029996 -> 2.00000000 Inexact Rounded +powx2086 power Infinity '-1' -> '0' +powx2087 power Infinity '0' -> '1' +powx2088 power Infinity '1' -> 'Infinity' +powx2089 power -Infinity '-1' -> '-0' +powx2090 power -Infinity '0' -> '1' +powx2091 power -Infinity '1' -> '-Infinity' +powx2092 power -Infinity '2' -> 'Infinity' +powx2093 power 0 0 -> 'NaN' Invalid_operation + +precision: 16 +rounding: half_even +maxExponent: 384 +minExponent: -383 + +-- basics +powx2100 power 1E-7 1E-7 -> 0.9999983881917339 Inexact Rounded +powx2101 power 0.003 1E-7 -> 0.9999994190858697 Inexact Rounded +powx2102 power 0.7 1E-7 -> 0.9999999643325062 Inexact Rounded +powx2103 power 1.2 1E-7 -> 1.000000018232156 Inexact Rounded +powx2104 power 71 1E-7 -> 1.000000426268079 Inexact Rounded +powx2105 power 9E+9 1E-7 -> 1.000002292051668 Inexact Rounded + +powx2110 power 1E-7 0.003 -> 0.9527961640236519 Inexact Rounded +powx2111 power 0.003 0.003 -> 0.9827235503366797 Inexact Rounded +powx2112 power 0.7 0.003 -> 0.9989305474406207 Inexact Rounded +powx2113 power 1.2 0.003 -> 1.000547114282834 Inexact Rounded +powx2114 power 71 0.003 -> 1.012870156273545 Inexact Rounded +powx2115 power 9E+9 0.003 -> 1.071180671278787 Inexact Rounded + +powx2120 power 1E-7 0.7 -> 0.00001258925411794167 Inexact Rounded +powx2121 power 0.003 0.7 -> 0.01713897630281030 Inexact Rounded +powx2122 power 0.7 0.7 -> 0.7790559126704491 Inexact Rounded +powx2123 power 1.2 0.7 -> 1.136126977198889 Inexact Rounded +powx2124 power 71 0.7 -> 19.76427300093870 Inexact Rounded +powx2125 power 9E+9 0.7 -> 9289016.976853710 Inexact Rounded + +powx2130 power 1E-7 1.2 -> 3.981071705534973E-9 Inexact Rounded +powx2131 power 0.003 1.2 -> 0.0009387403933595694 Inexact Rounded +powx2132 power 0.7 1.2 -> 0.6518049405663864 Inexact Rounded +powx2133 power 1.2 1.2 -> 1.244564747203978 Inexact Rounded +powx2134 power 71 1.2 -> 166.5367244638552 Inexact Rounded +powx2135 power 9E+9 1.2 -> 881233526124.8791 Inexact Rounded + +powx2140 power 1E-7 71 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +powx2141 power 0.003 71 -> 7.509466514979725E-180 Inexact Rounded +powx2142 power 0.7 71 -> 1.004525211269079E-11 Inexact Rounded +powx2143 power 1.2 71 -> 418666.7483186515 Inexact Rounded +powx2144 power 71 71 -> 2.750063734834616E+131 Inexact Rounded +powx2145 power 9E+9 71 -> Infinity Inexact Rounded Overflow + +powx2150 power 1E-7 9E+9 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +powx2151 power 0.003 9E+9 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +powx2152 power 0.7 9E+9 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +powx2153 power 1.2 9E+9 -> Infinity Inexact Rounded Overflow +powx2154 power 71 9E+9 -> Infinity Inexact Rounded Overflow +powx2155 power 9E+9 9E+9 -> Infinity Inexact Rounded Overflow + +-- number line milestones with lhs<1 and lhs>1 + +-- Overflow boundary (Nmax) +powx2202 power 71 207.966651583983200 -> Infinity Inexact Rounded Overflow +powx2201 power 71 207.966651583983199 -> 9.999999999999994E+384 Inexact Rounded +powx2204 power 0.003 -152.603449817093577 -> Infinity Inexact Rounded Overflow +powx2203 power 0.003 -152.603449817093576 -> 9.999999999999994E+384 Inexact Rounded + +-- Nmin boundary +powx2211 power 71 -206.886305341988480 -> 1.000000000000005E-383 Inexact Rounded +powx2212 power 71 -206.886305341988481 -> 1.000000000000001E-383 Inexact Rounded +powx2213 power 71 -206.886305341988482 -> 9.99999999999997E-384 Inexact Rounded Underflow Subnormal +powx2214 power 71 -206.886305341988483 -> 9.99999999999992E-384 Inexact Rounded Underflow Subnormal +-- 9.999999999999924565357019820 + +powx2215 power 0.003 151.810704623238543 -> 1.000000000000009E-383 Inexact Rounded +powx2216 power 0.003 151.810704623238544 -> 1.000000000000003E-383 Inexact Rounded +powx2217 power 0.003 151.810704623238545 -> 9.99999999999997E-384 Inexact Rounded Underflow Subnormal +powx2218 power 0.003 151.810704623238546 -> 9.99999999999991E-384 Inexact Rounded Underflow Subnormal + +-- Ntiny boundary, these edge cases determined using half_up rounding +rounding: half_up +powx2221 power 71 -215.151510469220498 -> 1E-398 Inexact Rounded Underflow Subnormal +powx2222 power 71 -215.151510469220499 -> 1E-398 Inexact Rounded Underflow Subnormal +powx2223 power 71 -215.151510469220500 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +powx2224 power 71 -215.151510469220501 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped + +powx2225 power 0.003 157.875613618285691 -> 1E-398 Inexact Rounded Underflow Subnormal +powx2226 power 0.003 157.875613618285692 -> 1E-398 Inexact Rounded Underflow Subnormal +powx2227 power 0.003 157.875613618285693 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +powx2228 power 0.003 220 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +rounding: half_even + +-- power(10, y) are important ... + +-- Integer powers are exact, unless over/underflow +powx2301 power 10 385 -> Infinity Overflow Inexact Rounded +powx2302 power 10 384 -> 1.000000000000000E+384 Rounded +powx2303 power 10 17 -> 1.000000000000000E+17 Rounded +powx2304 power 10 16 -> 1.000000000000000E+16 Rounded +powx2305 power 10 15 -> 1000000000000000 +powx2306 power 10 10 -> 10000000000 +powx2307 power 10 5 -> 100000 +powx2308 power 10 1 -> 10 +powx2309 power 10 0 -> 1 +powx2310 power 10 -1 -> 0.1 +powx2311 power 10 -5 -> 0.00001 +powx2312 power 10 -6 -> 0.000001 +powx2313 power 10 -7 -> 1E-7 +powx2314 power 10 -8 -> 1E-8 +powx2315 power 10 -9 -> 1E-9 +powx2316 power 10 -10 -> 1E-10 +powx2317 power 10 -383 -> 1E-383 +powx2318 power 10 -384 -> 1E-384 Subnormal +powx2319 power 10 -385 -> 1E-385 Subnormal +powx2320 power 10 -397 -> 1E-397 Subnormal +powx2321 power 10 -398 -> 1E-398 Subnormal +powx2322 power 10 -399 -> 0E-398 Subnormal Underflow Inexact Rounded Clamped +powx2323 power 10 -400 -> 0E-398 Subnormal Underflow Inexact Rounded Clamped + +-- Independent sanity check: 1961 Godfrey & Siddons four-figure logs +powx2351 power 10 0.0000 -> 1 +powx2352 power 10 0.3010 -> 1.999861869632744 Inexact Rounded +powx2353 power 10 0.4771 -> 2.999853181190793 Inexact Rounded +powx2354 power 10 0.6021 -> 4.000368510461250 Inexact Rounded +powx2355 power 10 0.6990 -> 5.000345349769785 Inexact Rounded +powx2356 power 10 0.7782 -> 6.000673538641164 Inexact Rounded +powx2357 power 10 0.8451 -> 7.000031591308969 Inexact Rounded +powx2358 power 10 0.9031 -> 8.000184448550990 Inexact Rounded +powx2359 power 10 0.9542 -> 8.999119108700520 Inexact Rounded +powx2360 power 10 0.9956 -> 9.899197750805841 Inexact Rounded +powx2361 power 10 0.9996 -> 9.990793899844618 Inexact Rounded +precision: 4 +powx2371 power 10 0.0000 -> 1 +powx2372 power 10 0.3010 -> 2.000 Inexact Rounded +powx2373 power 10 0.4771 -> 3.000 Inexact Rounded +powx2374 power 10 0.6021 -> 4.000 Inexact Rounded +powx2375 power 10 0.6990 -> 5.000 Inexact Rounded +powx2376 power 10 0.7782 -> 6.001 Inexact Rounded +powx2377 power 10 0.8451 -> 7.000 Inexact Rounded +powx2378 power 10 0.9031 -> 8.000 Inexact Rounded +powx2379 power 10 0.9542 -> 8.999 Inexact Rounded +powx2380 power 10 0.9956 -> 9.899 Inexact Rounded +powx2381 power 10 0.9996 -> 9.991 Inexact Rounded + +-- 10**x ~=2 (inverse of the test in log10.decTest) +precision: 50 +powx2401 power 10 0.30102999566398119521373889472449302676818988146211 -> 2.0000000000000000000000000000000000000000000000000 Inexact Rounded +precision: 49 +powx2402 power 10 0.3010299956639811952137388947244930267681898814621 -> 2.000000000000000000000000000000000000000000000000 Inexact Rounded +precision: 48 +powx2403 power 10 0.301029995663981195213738894724493026768189881462 -> 2.00000000000000000000000000000000000000000000000 Inexact Rounded +precision: 47 +powx2404 power 10 0.30102999566398119521373889472449302676818988146 -> 2.0000000000000000000000000000000000000000000000 Inexact Rounded +precision: 46 +powx2405 power 10 0.3010299956639811952137388947244930267681898815 -> 2.000000000000000000000000000000000000000000000 Inexact Rounded +precision: 45 +powx2406 power 10 0.301029995663981195213738894724493026768189881 -> 2.00000000000000000000000000000000000000000000 Inexact Rounded +precision: 44 +powx2407 power 10 0.30102999566398119521373889472449302676818988 -> 2.0000000000000000000000000000000000000000000 Inexact Rounded +precision: 43 +powx2408 power 10 0.3010299956639811952137388947244930267681899 -> 2.000000000000000000000000000000000000000000 Inexact Rounded +precision: 42 +powx2409 power 10 0.301029995663981195213738894724493026768190 -> 2.00000000000000000000000000000000000000000 Inexact Rounded +precision: 41 +powx2410 power 10 0.30102999566398119521373889472449302676819 -> 2.0000000000000000000000000000000000000000 Inexact Rounded +precision: 40 +powx2411 power 10 0.3010299956639811952137388947244930267682 -> 2.000000000000000000000000000000000000000 Inexact Rounded +precision: 39 +powx2412 power 10 0.301029995663981195213738894724493026768 -> 2.00000000000000000000000000000000000000 Inexact Rounded +precision: 38 +powx2413 power 10 0.30102999566398119521373889472449302677 -> 2.0000000000000000000000000000000000000 Inexact Rounded +precision: 37 +powx2414 power 10 0.3010299956639811952137388947244930268 -> 2.000000000000000000000000000000000000 Inexact Rounded +precision: 36 +powx2415 power 10 0.301029995663981195213738894724493027 -> 2.00000000000000000000000000000000000 Inexact Rounded +precision: 35 +powx2416 power 10 0.30102999566398119521373889472449303 -> 2.0000000000000000000000000000000000 Inexact Rounded +precision: 34 +powx2417 power 10 0.3010299956639811952137388947244930 -> 2.000000000000000000000000000000000 Inexact Rounded +precision: 33 +powx2418 power 10 0.301029995663981195213738894724493 -> 2.00000000000000000000000000000000 Inexact Rounded +precision: 32 +powx2419 power 10 0.30102999566398119521373889472449 -> 2.0000000000000000000000000000000 Inexact Rounded +precision: 31 +powx2420 power 10 0.3010299956639811952137388947245 -> 2.000000000000000000000000000000 Inexact Rounded +precision: 30 +powx2421 power 10 0.301029995663981195213738894725 -> 2.00000000000000000000000000000 Inexact Rounded +precision: 29 +powx2422 power 10 0.30102999566398119521373889472 -> 2.0000000000000000000000000000 Inexact Rounded +precision: 28 +powx2423 power 10 0.3010299956639811952137388947 -> 2.000000000000000000000000000 Inexact Rounded +precision: 27 +powx2424 power 10 0.301029995663981195213738895 -> 2.00000000000000000000000000 Inexact Rounded +precision: 26 +powx2425 power 10 0.30102999566398119521373889 -> 2.0000000000000000000000000 Inexact Rounded +precision: 25 +powx2426 power 10 0.3010299956639811952137389 -> 2.000000000000000000000000 Inexact Rounded +precision: 24 +powx2427 power 10 0.301029995663981195213739 -> 2.00000000000000000000000 Inexact Rounded +precision: 23 +powx2428 power 10 0.30102999566398119521374 -> 2.0000000000000000000000 Inexact Rounded +precision: 22 +powx2429 power 10 0.3010299956639811952137 -> 2.000000000000000000000 Inexact Rounded +precision: 21 +powx2430 power 10 0.301029995663981195214 -> 2.00000000000000000000 Inexact Rounded +precision: 20 +powx2431 power 10 0.30102999566398119521 -> 2.0000000000000000000 Inexact Rounded +precision: 19 +powx2432 power 10 0.3010299956639811952 -> 2.000000000000000000 Inexact Rounded +precision: 18 +powx2433 power 10 0.301029995663981195 -> 2.00000000000000000 Inexact Rounded +precision: 17 +powx2434 power 10 0.30102999566398120 -> 2.0000000000000000 Inexact Rounded +precision: 16 +powx2435 power 10 0.3010299956639812 -> 2.000000000000000 Inexact Rounded +precision: 15 +powx2436 power 10 0.301029995663981 -> 2.00000000000000 Inexact Rounded +precision: 14 +powx2437 power 10 0.30102999566398 -> 2.0000000000000 Inexact Rounded +precision: 13 +powx2438 power 10 0.3010299956640 -> 2.000000000000 Inexact Rounded +precision: 12 +powx2439 power 10 0.301029995664 -> 2.00000000000 Inexact Rounded +precision: 11 +powx2440 power 10 0.30102999566 -> 2.0000000000 Inexact Rounded +precision: 10 +powx2441 power 10 0.3010299957 -> 2.000000000 Inexact Rounded +precision: 9 +powx2442 power 10 0.301029996 -> 2.00000000 Inexact Rounded +precision: 8 +powx2443 power 10 0.30103000 -> 2.0000000 Inexact Rounded +precision: 7 +powx2444 power 10 0.3010300 -> 2.000000 Inexact Rounded +precision: 6 +powx2445 power 10 0.301030 -> 2.00000 Inexact Rounded +precision: 5 +powx2446 power 10 0.30103 -> 2.0000 Inexact Rounded +precision: 4 +powx2447 power 10 0.3010 -> 2.000 Inexact Rounded +precision: 3 +powx2448 power 10 0.301 -> 2.00 Inexact Rounded +precision: 2 +powx2449 power 10 0.30 -> 2.0 Inexact Rounded +precision: 1 +powx2450 power 10 0.3 -> 2 Inexact Rounded + +maxExponent: 384 +minExponent: -383 +precision: 16 +rounding: half_even + +-- Close-to-e tests +precision: 34 +powx2500 power 10 0.4342944819032518276511289189166048 -> 2.718281828459045235360287471352661 Inexact Rounded +powx2501 power 10 0.4342944819032518276511289189166049 -> 2.718281828459045235360287471352661 Inexact Rounded +powx2502 power 10 0.4342944819032518276511289189166050 -> 2.718281828459045235360287471352662 Inexact Rounded +powx2503 power 10 0.4342944819032518276511289189166051 -> 2.718281828459045235360287471352663 Inexact Rounded +powx2504 power 10 0.4342944819032518276511289189166052 -> 2.718281828459045235360287471352663 Inexact Rounded + +-- e**e, 16->34 +powx2505 power 2.718281828459045 2.718281828459045 -> '15.15426224147925705633739513098219' Inexact Rounded + +-- Sequence around an integer +powx2512 power 10 2.9999999999999999999999999999999997 -> 999.9999999999999999999999999999993 Inexact Rounded +powx2513 power 10 2.9999999999999999999999999999999998 -> 999.9999999999999999999999999999995 Inexact Rounded +powx2514 power 10 2.9999999999999999999999999999999999 -> 999.9999999999999999999999999999998 Inexact Rounded +powx2515 power 10 3.0000000000000000000000000000000000 -> 1000 +powx2516 power 10 3.0000000000000000000000000000000001 -> 1000.000000000000000000000000000000 Inexact Rounded +powx2517 power 10 3.0000000000000000000000000000000002 -> 1000.000000000000000000000000000000 Inexact Rounded +powx2518 power 10 3.0000000000000000000000000000000003 -> 1000.000000000000000000000000000001 Inexact Rounded + +-- randomly generated tests +maxExponent: 384 +minExponent: -383 + +-- P=34, within 0-999 -- positive arg2 +Precision: 34 +powx3201 power 5.301557744131969249145904611290735 369.3175647984435534243813466380579 -> 3.427165676345688240023113326603960E+267 Inexact Rounded +powx3202 power 0.0000000000506875655819165973738225 21.93514102704466434121826965196878 -> 1.498169860033487321566659495340789E-226 Inexact Rounded +powx3203 power 97.88877680721519917858007810494043 5.159898445242793470476673109899554 -> 18705942904.43290467281449559427982 Inexact Rounded +powx3204 power 7.380441015594399747973924380493799 17.93614173904818313507525109033288 -> 3715757985820076.273336082702577274 Inexact Rounded +powx3205 power 2.045623627647350918819219169855040 1082.999652407430697958175966996254 -> 4.208806435006704867447150904279854E+336 Inexact Rounded +powx3206 power 0.0000000762582873112118926142955423 20.30534237055073996975203864170432 -> 2.967574278677013090697130349198877E-145 Inexact Rounded +powx3207 power 0.0000000000194091470907814855660535 14.71164213947722238856835440242911 -> 2.564391397469554735037158345963280E-158 Inexact Rounded +powx3208 power 0.0000000000509434185382818596853504 20.97051498204188277347203735421595 -> 1.420157372748083000927138678417272E-216 Inexact Rounded +powx3209 power 0.0005389217212073307301395750745119 43.96798225485747315858678755538971 -> 1.957850185781292007977898626137240E-144 Inexact Rounded +powx3210 power 498.5690105989136050444077447411198 128.1038813807243375878831104745803 -> 3.882212970903893127009102293596268E+345 Inexact Rounded +powx3211 power 0.0000000935428918637303954281938975 5.736933454863278597460091596496099 -> 4.733219644540496152403967823635195E-41 Inexact Rounded +powx3212 power 8.581586784734161309180363110126352 252.0229459968869784643374981477208 -> 1.907464842458674622356177850049873E+235 Inexact Rounded +powx3213 power 294.1005302951621709143320795278305 155.5466374141708615975111014663722 -> 9.251717033292072959166737280729728E+383 Inexact Rounded +powx3214 power 0.0000000041253343654396865855722090 19.00170974760425576247662125110472 -> 4.779566288553864405790921353593512E-160 Inexact Rounded +powx3215 power 0.0000000000046912257352141395184092 24.66089523148729269098773236636878 -> 4.205126874048597849476723538057527E-280 Inexact Rounded +powx3216 power 0.0000000000036796674296520639450494 22.09713956900694689234335912523078 -> 2.173081843837539818472071316420405E-253 Inexact Rounded +powx3217 power 9.659887100303037657934372148567685 277.3765665424320875993026404492216 -> 1.614974043145519382749740616665041E+273 Inexact Rounded +powx3218 power 0.0000083231310642229204398943076403 29.33123211782131466471359128190372 -> 1.013330439786660210757226597785328E-149 Inexact Rounded +powx3219 power 0.0938084859086450954956863725653664 262.6091918199905272837286784975012 -> 1.262802485286301066967555821509344E-270 Inexact Rounded +powx3220 power 8.194926977580900145696305910223304 184.3705133945546202012995485297248 -> 2.696353910907824016690021495828584E+168 Inexact Rounded +powx3221 power 72.39594594653085161522285114566120 168.7721909489321402152033939836725 -> 7.379858293630460043361584410795031E+313 Inexact Rounded +powx3222 power 0.0000000000003436856010144185445537 26.34329868961274988994452526178983 -> 4.585379573595865689605567720192768E-329 Inexact Rounded +powx3223 power 20.18365633762226550254542489492623 127.2099705237021350103678072707790 -> 1.020919629336979353690271762206060E+166 Inexact Rounded +powx3224 power 0.0000000553723990761530290129268131 8.157597566134754638015199501162405 -> 6.349030513396147480954474615067145E-60 Inexact Rounded +powx3225 power 0.0001028742674265840656614682618035 93.99842317306603797965470281716482 -> 1.455871110222736531854990397769940E-375 Inexact Rounded +powx3226 power 95.90195152775543876489746343266050 143.5992850002211509777720799352475 -> 3.881540015848530405189834366588567E+284 Inexact Rounded +powx3227 power 0.0000000000041783747057233878360333 12.14591167764993506821334760954430 -> 6.190998557456885985124592807383163E-139 Inexact Rounded +powx3228 power 0.5572830497086740798434917090018768 1001.921811263919522230330241349166 -> 3.871145158537170450093833881625838E-255 Inexact Rounded +powx3229 power 516.4754759779093954790813881333232 29.23812463126309057800793645336343 -> 2.110986192408878294012450052929185E+79 Inexact Rounded +powx3230 power 0.0000835892099464584776847299020706 27.64279992884843877453592659341588 -> 1.891535098905506689512376224943293E-113 Inexact Rounded +powx3231 power 72.45836577748571838139900165184955 166.2562890735032545091688015160084 -> 1.784091549041561516923092542939141E+309 Inexact Rounded +powx3232 power 305.1823317643335924007629563009032 83.01065159508472884219290136319623 -> 1.757493136164395229602456782779110E+206 Inexact Rounded +powx3233 power 7.108527102951713603542835791733786 145.7057852766236365450463428821948 -> 1.285934774113104362663619896550528E+124 Inexact Rounded +powx3234 power 6.471393503175464828149365697049824 64.11741937262455725284754171995720 -> 9.978990355881803195280027533011699E+51 Inexact Rounded +powx3235 power 39.72898094138459885662380866268385 239.9677288017447400786672779735168 -> 5.422218208517098335832848487375086E+383 Inexact Rounded +powx3236 power 0.0002865592332736973000183287329933 90.34733869590583787065642532641096 -> 8.293733126976212033209243257136796E-321 Inexact Rounded +powx3237 power 0.0000011343384394864811195077357936 1.926568285528399656789140809399396 -> 3.516055639378350146874261077470142E-12 Inexact Rounded +powx3238 power 0.0000000035321610295065299384889224 7.583861778824284092434085265265582 -> 7.970899823817369764381976286536230E-65 Inexact Rounded +powx3239 power 657.5028301569352677543770758346683 90.55778453811965116200206020172758 -> 1.522530898581564200655160665723268E+255 Inexact Rounded +powx3240 power 8.484756398325748879450577520251447 389.7468292476262478578280531222417 -> 8.595142803587368093392510310811218E+361 Inexact Rounded + +-- P=16, within 0-99 -- positive arg2 +Precision: 16 +powx3101 power 0.0000215524639223 48.37532522355252 -> 1.804663257287277E-226 Inexact Rounded +powx3102 power 00.80705856227999 2706.777535121391 -> 1.029625065876157E-252 Inexact Rounded +powx3103 power 3.445441676383689 428.5185892455830 -> 1.657401683096454E+230 Inexact Rounded +powx3104 power 0.0040158689495826 159.5725558816240 -> 4.255743665762492E-383 Inexact Rounded +powx3105 power 0.0000841553281215 38.32504413453944 -> 6.738653902512052E-157 Inexact Rounded +powx3106 power 0.7322610252571353 502.1254457674118 -> 1.109978126985943E-68 Inexact Rounded +powx3107 power 10.75052532144880 67.34180604734781 -> 2.873015019470189E+69 Inexact Rounded +powx3108 power 26.20425952945617 104.6002671186488 -> 2.301859355777030E+148 Inexact Rounded +powx3109 power 0.0000055737473850 31.16285859005424 -> 1.883348470100446E-164 Inexact Rounded +powx3110 power 61.06096011360700 10.93608439088726 -> 3.382686473028249E+19 Inexact Rounded +powx3111 power 9.340880853257137 179.9094938131726 -> 3.819299795937696E+174 Inexact Rounded +powx3112 power 0.0000050767371756 72.03346394186741 -> 4.216236691569869E-382 Inexact Rounded +powx3113 power 6.838478807860596 47.49665590602285 -> 4.547621630099203E+39 Inexact Rounded +powx3114 power 0.1299324346439081 397.7440523576938 -> 3.065047705553981E-353 Inexact Rounded +powx3115 power 0.0003418047034264 20.00516791512018 -> 4.546189665380487E-70 Inexact Rounded +powx3116 power 0.0001276899611715 78.12968287355703 -> 5.960217405063995E-305 Inexact Rounded +powx3117 power 25.93160588180509 252.6245071004620 -> 1.472171597589146E+357 Inexact Rounded +powx3118 power 35.47516857763178 86.14723037360925 -> 3.324299908481125E+133 Inexact Rounded +powx3119 power 0.0000048171086721 43.31965603038666 -> 4.572331516616228E-231 Inexact Rounded +powx3120 power 17.97652681097851 144.4684576550292 -> 1.842509906097860E+181 Inexact Rounded +powx3121 power 3.622765141518729 305.1948680344950 -> 4.132320967578704E+170 Inexact Rounded +powx3122 power 0.0080959002453519 143.9899444945627 -> 6.474627812947047E-302 Inexact Rounded +powx3123 power 9.841699927276571 299.2466668837188 -> 1.489097656208736E+297 Inexact Rounded +powx3124 power 0.0786659206232355 347.4750796962570 -> 2.05764809646925E-384 Inexact Rounded Underflow Subnormal +powx3125 power 0.0000084459792645 52.47348690745487 -> 6.076251876516942E-267 Inexact Rounded +powx3126 power 27.86589909967504 191.7296537102283 -> 1.157064112989386E+277 Inexact Rounded +powx3127 power 0.0000419907937234 58.44957702730767 -> 1.496950672075162E-256 Inexact Rounded +powx3128 power 0.0000664977739382 80.06749213261876 -> 3.488517620107875E-335 Inexact Rounded +powx3129 power 58.49554484886656 125.8480768373499 -> 2.449089862146640E+222 Inexact Rounded +powx3130 power 15.02820060024449 212.3527988973338 -> 8.307913932682067E+249 Inexact Rounded +powx3131 power 0.0002650089942992 30.92173123678761 -> 2.517827664836147E-111 Inexact Rounded +powx3132 power 0.0007342977426578 69.49168880741123 -> 1.600168665674440E-218 Inexact Rounded +powx3133 power 0.0063816068650629 150.1400094183812 -> 2.705057295799001E-330 Inexact Rounded +powx3134 power 9.912921122728791 297.8274013633411 -> 4.967624993438900E+296 Inexact Rounded +powx3135 power 1.988603563989245 768.4862967922182 -> 2.692842474899596E+229 Inexact Rounded +powx3136 power 8.418014519517691 164.2431359980725 -> 9.106211585888836E+151 Inexact Rounded +powx3137 power 6.068823604450686 120.2955212365837 -> 1.599431918105982E+94 Inexact Rounded +powx3138 power 56.90062738303850 54.90468294683645 -> 2.312839177902428E+96 Inexact Rounded +powx3139 power 5.710905139750871 73.44608752962156 -> 3.775876053709929E+55 Inexact Rounded +powx3140 power 0.0000017446761203 1.223981492228899 -> 8.952936595465635E-8 Inexact Rounded + +-- P=7, within 0-9 -- positive arg2 +Precision: 7 +powx3001 power 8.738689 55.96523 -> 4.878180E+52 Inexact Rounded +powx3002 power 0.0404763 147.4965 -> 3.689722E-206 Inexact Rounded +powx3003 power 0.0604232 76.69778 -> 3.319183E-94 Inexact Rounded +powx3004 power 0.0058855 107.5018 -> 1.768875E-240 Inexact Rounded +powx3005 power 2.058302 1173.050 -> 5.778899E+367 Inexact Rounded +powx3006 power 0.0056998 85.70157 -> 4.716783E-193 Inexact Rounded +powx3007 power 0.8169297 3693.537 -> 4.475962E-325 Inexact Rounded +powx3008 power 0.2810153 659.9568 -> 1.533177E-364 Inexact Rounded +powx3009 power 4.617478 15.68308 -> 2.629748E+10 Inexact Rounded +powx3010 power 0.0296418 244.2302 -> 6.207949E-374 Inexact Rounded +powx3011 power 0.0036456 127.9987 -> 8.120891E-313 Inexact Rounded +powx3012 power 0.5012813 577.5418 -> 6.088802E-174 Inexact Rounded +powx3013 power 0.0033275 119.9800 -> 5.055049E-298 Inexact Rounded +powx3014 power 0.0037652 111.7092 -> 1.560351E-271 Inexact Rounded +powx3015 power 0.6463252 239.0568 -> 4.864564E-46 Inexact Rounded +powx3016 power 4.784378 475.0521 -> 8.964460E+322 Inexact Rounded +powx3017 power 4.610305 563.1791 -> 6.290298E+373 Inexact Rounded +powx3018 power 0.0175167 80.52208 -> 3.623472E-142 Inexact Rounded +powx3019 power 5.238307 356.7944 -> 4.011461E+256 Inexact Rounded +powx3020 power 0.0003527 96.26347 -> 4.377932E-333 Inexact Rounded +powx3021 power 0.0015155 136.0516 -> 2.57113E-384 Inexact Rounded Underflow Subnormal +powx3022 power 5.753573 273.2340 -> 4.373184E+207 Inexact Rounded +powx3023 power 7.778665 332.7917 -> 3.060640E+296 Inexact Rounded +powx3024 power 1.432479 2046.064 -> 2.325829E+319 Inexact Rounded +powx3025 power 5.610516 136.4563 -> 1.607502E+102 Inexact Rounded +powx3026 power 0.0050697 137.4513 -> 3.522315E-316 Inexact Rounded +powx3027 power 5.678737 85.16253 -> 1.713909E+64 Inexact Rounded +powx3028 power 0.0816167 236.1973 -> 9.228802E-258 Inexact Rounded +powx3029 power 0.2602805 562.0157 -> 2.944556E-329 Inexact Rounded +powx3030 power 0.0080936 24.25367 -> 1.839755E-51 Inexact Rounded +powx3031 power 4.092016 82.94603 -> 5.724948E+50 Inexact Rounded +powx3032 power 0.0078255 7.204184 -> 6.675342E-16 Inexact Rounded +powx3033 power 0.9917693 29846.44 -> 7.430177E-108 Inexact Rounded +powx3034 power 1.610380 301.2467 -> 2.170142E+62 Inexact Rounded +powx3035 power 0.0588236 212.1097 -> 1.023196E-261 Inexact Rounded +powx3036 power 2.498069 531.4647 -> 2.054561E+211 Inexact Rounded +powx3037 power 9.964342 326.5438 -> 1.089452E+326 Inexact Rounded +powx3038 power 0.0820626 268.8718 -> 1.107350E-292 Inexact Rounded +powx3039 power 6.176486 360.7779 -> 1.914449E+285 Inexact Rounded +powx3040 power 4.206363 16.17288 -> 1.231314E+10 Inexact Rounded + +-- P=34, within 0-999 -- negative arg2 +Precision: 34 +powx3701 power 376.0915270000109486633402827007902 -35.69822349904102131649243701958463 -> 1.165722831225506457828653413200143E-92 Inexact Rounded +powx3702 power 0.0000000503747440074613191665845314 -9.520308341497979093021813571450575 -> 3.000432478861883953977971226770410E+69 Inexact Rounded +powx3703 power 290.6858731495339778337953407938308 -118.5459048597789693292455673428367 -> 9.357969047113989238392527565200302E-293 Inexact Rounded +powx3704 power 4.598864607620052062908700928454182 -299.8323667698931125720218537483753 -> 2.069641269855413539579128114448478E-199 Inexact Rounded +powx3705 power 2.556952676986830645708349254938903 -425.1755373251941383147998924703593 -> 4.428799777833598654260883861514638E-174 Inexact Rounded +powx3706 power 0.0000005656198763404221986640610118 -32.83361380678301321230028730075315 -> 1.340270622401829145968477601029251E+205 Inexact Rounded +powx3707 power 012.4841978642452960750801410372125 -214.3734291828712962809866663321921 -> 9.319857751170603140459057535971202E-236 Inexact Rounded +powx3708 power 0.0000000056041586148066919174315551 -37.21129049213858341528033343116533 -> 1.118345010652454313186702341873169E+307 Inexact Rounded +powx3709 power 0.0694569218941833767199998804202152 -8.697509072368973932501239815677732 -> 11862866995.51026489032838174290271 Inexact Rounded +powx3710 power 6.380984024259450398729243522354144 -451.0635696889193561457985486366827 -> 8.800353109387322474809325670314330E-364 Inexact Rounded +powx3711 power 786.0264840756809048288007204917801 -43.09935384678762773057342161718540 -> 1.616324183365644133979585419925934E-125 Inexact Rounded +powx3712 power 96.07836427113204744101287948445130 -185.1414572546330024388914720271876 -> 8.586320815218383004023264980018610E-368 Inexact Rounded +powx3713 power 0.0000000002332189796855870659792406 -5.779561613164628076880609893753327 -> 4.678450775876385793618570483345066E+55 Inexact Rounded +powx3714 power 0.7254146672024602242369943237968857 -2115.512891397828615710130092245691 -> 8.539080958041689288202111403102495E+294 Inexact Rounded +powx3715 power 0.0017380543649702864796144008592137 -6.307668017761022788220578633538713 -> 256309141459075651.2275798017695017 Inexact Rounded +powx3716 power 05.29498758952276908267649116142379 -287.3233896734103442991981056134167 -> 1.039130027847489364009368608104291E-208 Inexact Rounded +powx3717 power 15.64403593865932622003462779104178 -110.5296633358063267478609032002475 -> 9.750540276026524527375125980296142E-133 Inexact Rounded +powx3718 power 89.69639006761571087634945077373508 -181.3209914139357665609268339422627 -> 8.335034232277762924539395632025281E-355 Inexact Rounded +powx3719 power 6.974087483731006359914914110135058 -174.6815625746710345173615508179842 -> 4.553072265122011176641590109568031E-148 Inexact Rounded +powx3720 power 0.0034393024010554821130553772681993 -93.60931598413919272595497100497364 -> 4.067468855817145539589988349449394E+230 Inexact Rounded +powx3721 power 63.32834072300379155053737260965633 -168.3926799435088324825751446957616 -> 4.207907835462640471617519501741094E-304 Inexact Rounded +powx3722 power 00.00216088174206276369011255907785 -70.12279562855442784757874508991013 -> 8.000657143378187029609343435067057E+186 Inexact Rounded +powx3723 power 934.5957982703545893572134393004375 -102.2287735565878252484031426026726 -> 2.073813769209257617246544424827240E-304 Inexact Rounded +powx3724 power 107.9116792558793921873995885441177 -44.11941092260869786313838181499158 -> 2.005476533631183268912552168759595E-90 Inexact Rounded +powx3725 power 0.0000000000188049827381428191769262 -19.32118917192242027966847501724073 -> 1.713174297100918857053338286389034E+207 Inexact Rounded +powx3726 power 614.9820907366248142166636259027728 -4.069913257030791586645250035698123 -> 4.462432572576935752713876293746717E-12 Inexact Rounded +powx3727 power 752.0655175769182096165651274049422 -22.59292060348797472013598378334370 -> 1.039881526694635205040192531504131E-65 Inexact Rounded +powx3728 power 72.20446632047659449616175456059013 -175.4705356401853924020842356605072 -> 7.529540175791582421966947814549028E-327 Inexact Rounded +powx3729 power 518.8346486600403405764055847937416 -65.87320268592761588756963215588232 -> 1.420189426992170936958891180073151E-179 Inexact Rounded +powx3730 power 3.457164372003960576453458502270716 -440.3201118177861273814529713443698 -> 6.176418595751201287186292664257369E-238 Inexact Rounded +powx3731 power 7.908352793344189720739467675503991 -298.6646112894719680394152664740255 -> 5.935857120229147638104675057695125E-269 Inexact Rounded +powx3732 power 0.0000004297399403788595027926075086 -22.66504617185071293588817501468339 -> 2.012270405520600820469665145636204E+144 Inexact Rounded +powx3733 power 0.0000008592124097322966354868716443 -9.913109586558030204789520190180906 -> 1.354958763843310237046818832755215E+60 Inexact Rounded +powx3734 power 161.4806080561258105880907470989925 -70.72907837434814261716311990271578 -> 6.632555003698945544941329872901929E-157 Inexact Rounded +powx3735 power 0.0000000090669568624173832705631918 -36.53759624613665940127058439106640 -> 7.161808401023414735428130112941559E+293 Inexact Rounded +powx3736 power 0.0000000000029440295978365709342752 -1.297354238738921988884421117731562 -> 911731060579291.7661267358872917380 Inexact Rounded +powx3737 power 21.37477220144832172175460425143692 -76.95949933640539226475686997477889 -> 4.481741242418091914011962399912885E-103 Inexact Rounded +powx3738 power 0.0000000000186657798201636342150903 -20.18296240350678245567049161730909 -> 3.483954007114900406906338526575672E+216 Inexact Rounded +powx3739 power 0.0006522464792960191985996959126792 -80.03762491483514679886504099194414 -> 9.266548513614215557228467517053035E+254 Inexact Rounded +powx3740 power 0.0000000032851343694200568966168055 -21.53462116926375512242403160008026 -> 4.873201679668455240861376213601189E+182 Inexact Rounded + +-- P=16, within 0-99 -- negative arg2 +Precision: 16 +powx3601 power 0.0000151338748474 -40.84655618364688 -> 7.628470824137755E+196 Inexact Rounded +powx3602 power 0.1542771848654862 -435.8830009466800 -> 6.389817177800744E+353 Inexact Rounded +powx3603 power 48.28477749367364 -218.5929209902050 -> 8.531049532576154E-369 Inexact Rounded +powx3604 power 7.960775891584911 -12.78113732182505 -> 3.053270889769488E-12 Inexact Rounded +powx3605 power 0.9430340651863058 -9010.470056913748 -> 3.313374654923807E+229 Inexact Rounded +powx3606 power 0.0000202661501602 -65.57915207383306 -> 5.997379176536464E+307 Inexact Rounded +powx3607 power 04.33007440798390 -232.0476834666588 -> 2.007827183010456E-148 Inexact Rounded +powx3608 power 0.0000141944643914 -11.32407921958717 -> 7.902934485074846E+54 Inexact Rounded +powx3609 power 0.0000021977758261 -53.53706138253307 -> 8.195631772317815E+302 Inexact Rounded +powx3610 power 39.51297655474188 -19.40370976012326 -> 1.040699608072659E-31 Inexact Rounded +powx3611 power 38.71210232488775 -66.58341618227921 -> 1.886855066146495E-106 Inexact Rounded +powx3612 power 0.0000804235229062 -6.715207948992859 -> 3.134757864389333E+27 Inexact Rounded +powx3613 power 0.0000073547092399 -11.27725685719934 -> 7.781428390953695E+57 Inexact Rounded +powx3614 power 52.72181272599316 -186.1422311607435 -> 2.916601998744177E-321 Inexact Rounded +powx3615 power 0.0969519963083306 -280.8220862151369 -> 3.955906885970987E+284 Inexact Rounded +powx3616 power 94.07263302150081 -148.2031146071230 -> 3.361958990752490E-293 Inexact Rounded +powx3617 power 85.80286965053704 -90.21453695813759 -> 3.715602429645798E-175 Inexact Rounded +powx3618 power 03.52699858152259 -492.0414362539196 -> 4.507309220081092E-270 Inexact Rounded +powx3619 power 0.0508278086396068 -181.0871731572167 -> 2.034428013017949E+234 Inexact Rounded +powx3620 power 0.395576740303172 -915.5524507432392 -> 5.706585187437578E+368 Inexact Rounded +powx3621 power 38.06105826789202 -49.75913753435335 -> 2.273188991431738E-79 Inexact Rounded +powx3622 power 0.0003656748910646 -73.28988491310354 -> 7.768936940568763E+251 Inexact Rounded +powx3623 power 0.0000006373551809 -51.30825234200690 -> 7.697618167701985E+317 Inexact Rounded +powx3624 power 82.41729920673856 -35.73319631625699 -> 3.424042354585529E-69 Inexact Rounded +powx3625 power 0.7845821453127670 -971.4982028897663 -> 2.283415527661089E+102 Inexact Rounded +powx3626 power 4.840983673433497 -182.3730452370515 -> 1.220591407927770E-125 Inexact Rounded +powx3627 power 0.0000006137592139 -2.122139474431484 -> 15231217034839.29 Inexact Rounded +powx3628 power 0.0003657962862984 -35.97993782448099 -> 4.512701319250839E+123 Inexact Rounded +powx3629 power 40.93693004443150 -165.1362408792997 -> 6.044276411057239E-267 Inexact Rounded +powx3630 power 0.2941552583028898 -17.41046264945892 -> 1787833103.503346 Inexact Rounded +powx3631 power 63.99335135369977 -69.92417205168579 -> 5.099359804872509E-127 Inexact Rounded +powx3632 power 0.0000657924467388 -89.14497293588313 -> 6.145878266688521E+372 Inexact Rounded +powx3633 power 11.35071250339147 -323.3705865614542 -> 6.863626248766775E-342 Inexact Rounded +powx3634 power 23.88024718470895 -277.7117513329510 -> 2.006441422612815E-383 Inexact Rounded +powx3635 power 0.0000009111939914 -58.51782946929182 -> 2.954352883996773E+353 Inexact Rounded +powx3636 power 0.0000878179048782 -75.81060420238669 -> 3.306878455207585E+307 Inexact Rounded +powx3637 power 07.39190564273779 -287.5047307244636 -> 1.692080354659805E-250 Inexact Rounded +powx3638 power 0.0000298310819799 -1.844740377759355 -> 222874718.7238888 Inexact Rounded +powx3639 power 0.0000006412929384 -28.24850078229290 -> 8.737164230666529E+174 Inexact Rounded +powx3640 power 0.0000010202965998 -47.17573701956498 -> 4.392845306049341E+282 Inexact Rounded + +-- P=7, within 0-9 -- negative arg2 +Precision: 7 +powx3501 power 0.326324 -71.96509 -> 1.000673E+35 Inexact Rounded +powx3502 power 0.0017635 -0.7186967 -> 95.28419 Inexact Rounded +powx3503 power 8.564155 -253.0899 -> 8.850512E-237 Inexact Rounded +powx3504 power 8.987272 -2.155789 -> 0.008793859 Inexact Rounded +powx3505 power 9.604856 -139.9630 -> 3.073492E-138 Inexact Rounded +powx3506 power 0.8472919 -2539.085 -> 5.372686E+182 Inexact Rounded +powx3507 power 5.312329 -60.32965 -> 1.753121E-44 Inexact Rounded +powx3508 power 0.0338294 -100.5440 -> 7.423939E+147 Inexact Rounded +powx3509 power 0.0017777 -130.8583 -> 7.565629E+359 Inexact Rounded +powx3510 power 8.016154 -405.5689 -> 2.395977E-367 Inexact Rounded +powx3511 power 5.016570 -327.8906 -> 2.203784E-230 Inexact Rounded +powx3512 power 0.8161743 -744.5276 -> 4.786899E+65 Inexact Rounded +powx3513 power 0.0666343 -164.7320 -> 5.951240E+193 Inexact Rounded +powx3514 power 0.0803966 -202.2666 -> 2.715512E+221 Inexact Rounded +powx3515 power 0.0014752 -12.55547 -> 3.518905E+35 Inexact Rounded +powx3516 power 9.737565 -14.69615 -> 2.975672E-15 Inexact Rounded +powx3517 power 0.6634172 -152.7308 -> 1.654458E+27 Inexact Rounded +powx3518 power 0.0009337 -33.32939 -> 9.575039E+100 Inexact Rounded +powx3519 power 8.679922 -224.4194 -> 2.392446E-211 Inexact Rounded +powx3520 power 7.390494 -161.9483 -> 2.088375E-141 Inexact Rounded +powx3521 power 0.4631489 -417.1673 -> 2.821106E+139 Inexact Rounded +powx3522 power 0.0095471 -7.677458 -> 3.231855E+15 Inexact Rounded +powx3523 power 6.566339 -176.1867 -> 9.965633E-145 Inexact Rounded +powx3524 power 2.696128 -26.15501 -> 5.419731E-12 Inexact Rounded +powx3525 power 0.4464366 -852.1893 -> 2.957725E+298 Inexact Rounded +powx3526 power 0.4772006 -921.4111 -> 1.118105E+296 Inexact Rounded +powx3527 power 8.923696 -359.2211 -> 3.501573E-342 Inexact Rounded +powx3528 power 0.0018008 -66.91252 -> 4.402718E+183 Inexact Rounded +powx3529 power 0.0811964 -92.83278 -> 1.701111E+101 Inexact Rounded +powx3530 power 0.0711219 -58.94347 -> 4.644148E+67 Inexact Rounded +powx3531 power 7.958121 -50.66123 -> 2.311161E-46 Inexact Rounded +powx3532 power 6.106466 -81.83610 -> 4.943285E-65 Inexact Rounded +powx3533 power 4.557634 -129.5268 -> 4.737917E-86 Inexact Rounded +powx3534 power 0.0027348 -9.180135 -> 3.383524E+23 Inexact Rounded +powx3535 power 0.0083924 -46.24016 -> 9.996212E+95 Inexact Rounded +powx3536 power 2.138523 -47.25897 -> 2.507009E-16 Inexact Rounded +powx3537 power 1.626728 -1573.830 -> 2.668117E-333 Inexact Rounded +powx3538 power 0.082615 -164.5842 -> 1.717882E+178 Inexact Rounded +powx3539 power 7.636003 -363.6763 -> 8.366174E-322 Inexact Rounded +powx3540 power 0.0021481 -138.0065 -> 1.562505E+368 Inexact Rounded + + +-- Invalid operations due to restrictions +-- [next two probably skipped by most test harnesses] +precision: 100000000 +powx4001 power 1 1.1 -> NaN Invalid_context +precision: 99999999 +powx4002 power 1 1.1 -> NaN Invalid_context + +precision: 9 +maxExponent: 1000000 +minExponent: -999999 +powx4003 power 1 1.1 -> NaN Invalid_context +maxExponent: 999999 +minExponent: -999999 +powx4004 power 1 1.1 -> 1.00000000 Inexact Rounded +maxExponent: 999999 +minExponent: -1000000 +powx4005 power 1 1.1 -> NaN Invalid_context +maxExponent: 999999 +minExponent: -999998 +powx4006 power 1 1.1 -> 1.00000000 Inexact Rounded + +-- operand range violations +powx4007 power 1 1.1E+999999 -> 1 +powx4008 power 1 1.1E+1000000 -> NaN Invalid_operation +powx4009 power 1.1E+999999 1.1 -> Infinity Overflow Inexact Rounded +powx4010 power 1.1E+1000000 1.1 -> NaN Invalid_operation +powx4011 power 1 1.1E-1999997 -> 1.00000000 Inexact Rounded +powx4012 power 1 1.1E-1999998 -> NaN Invalid_operation +powx4013 power 1.1E-1999997 1.1 -> 0E-1000006 Underflow Inexact Rounded Clamped Subnormal +powx4014 power 1.1E-1999998 1.1 -> NaN Invalid_operation + +-- rounding modes -- power is sensitive +precision: 7 +maxExponent: 99 +minExponent: -99 + +-- 0.7 ** 3.3 => 0.30819354053418943822 +-- 0.7 ** 3.4 => 0.29739477638272533854 +-- -1.2 ** 17 => -22.18611106740436992 +-- -1.3 ** 17 => -86.50415919381337933 +-- 0.5 ** 11 => 0.00048828125 +-- 3.15 ** 3 => 31.255875 + +rounding: up +powx4100 power 0.7 3.3 -> 0.3081936 Inexact Rounded +powx4101 power 0.7 3.4 -> 0.2973948 Inexact Rounded +powx4102 power -1.2 17 -> -22.18612 Inexact Rounded +powx4103 power -1.3 17 -> -86.50416 Inexact Rounded +powx4104 power 17 81.27115 -> 9.999974E+99 Inexact Rounded +powx4105 power 17 81.27116 -> Infinity Overflow Inexact Rounded + +rounding: down +powx4120 power 0.7 3.3 -> 0.3081935 Inexact Rounded +powx4121 power 0.7 3.4 -> 0.2973947 Inexact Rounded +powx4122 power -1.2 17 -> -22.18611 Inexact Rounded +powx4123 power -1.3 17 -> -86.50415 Inexact Rounded +powx4124 power 17 81.27115 -> 9.999973E+99 Inexact Rounded +powx4125 power 17 81.27116 -> 9.999999E+99 Overflow Inexact Rounded + +rounding: floor +powx4140 power 0.7 3.3 -> 0.3081935 Inexact Rounded +powx4141 power 0.7 3.4 -> 0.2973947 Inexact Rounded +powx4142 power -1.2 17 -> -22.18612 Inexact Rounded +powx4143 power -1.3 17 -> -86.50416 Inexact Rounded +powx4144 power 17 81.27115 -> 9.999973E+99 Inexact Rounded +powx4145 power 17 81.27116 -> 9.999999E+99 Overflow Inexact Rounded + +rounding: ceiling +powx4160 power 0.7 3.3 -> 0.3081936 Inexact Rounded +powx4161 power 0.7 3.4 -> 0.2973948 Inexact Rounded +powx4162 power -1.2 17 -> -22.18611 Inexact Rounded +powx4163 power -1.3 17 -> -86.50415 Inexact Rounded +powx4164 power 17 81.27115 -> 9.999974E+99 Inexact Rounded +powx4165 power 17 81.27116 -> Infinity Overflow Inexact Rounded + +rounding: half_up +powx4180 power 0.7 3.3 -> 0.3081935 Inexact Rounded +powx4181 power 0.7 3.4 -> 0.2973948 Inexact Rounded +powx4182 power -1.2 17 -> -22.18611 Inexact Rounded +powx4183 power -1.3 17 -> -86.50416 Inexact Rounded +powx4184 power 0.5 11 -> 0.0004882813 Inexact Rounded +powx4185 power 3.15 3 -> 31.25588 Inexact Rounded +powx4186 power 17 81.27115 -> 9.999974E+99 Inexact Rounded +powx4187 power 17 81.27116 -> Infinity Overflow Inexact Rounded + +rounding: half_even +powx4200 power 0.7 3.3 -> 0.3081935 Inexact Rounded +powx4201 power 0.7 3.4 -> 0.2973948 Inexact Rounded +powx4202 power -1.2 17 -> -22.18611 Inexact Rounded +powx4203 power -1.3 17 -> -86.50416 Inexact Rounded +powx4204 power 0.5 11 -> 0.0004882812 Inexact Rounded +powx4205 power 3.15 3 -> 31.25588 Inexact Rounded +powx4206 power 17 81.27115 -> 9.999974E+99 Inexact Rounded +powx4207 power 17 81.27116 -> Infinity Overflow Inexact Rounded + +rounding: half_down +powx4220 power 0.7 3.3 -> 0.3081935 Inexact Rounded +powx4221 power 0.7 3.4 -> 0.2973948 Inexact Rounded +powx4222 power -1.2 17 -> -22.18611 Inexact Rounded +powx4223 power -1.3 17 -> -86.50416 Inexact Rounded +powx4224 power 0.5 11 -> 0.0004882812 Inexact Rounded +powx4225 power 3.15 3 -> 31.25587 Inexact Rounded +powx4226 power -3.15 3 -> -31.25587 Inexact Rounded +powx4227 power 17 81.27115 -> 9.999974E+99 Inexact Rounded +powx4228 power 17 81.27116 -> Infinity Overflow Inexact Rounded + + +-- more rounding tests as per Ilan Nehama's suggestions & analysis +-- these are likely to show > 0.5 ulp error for very small powers +precision: 7 +maxExponent: 96 +minExponent: -95 + +-- For x=nextfp(1)=1.00..001 (where the number of 0s is precision-2) +-- power(x,y)=x when the rounding is up (e.g., toward_pos_inf or +-- ceil) for any y in (0,1]. +rounding: ceiling +powx4301 power 1.000001 0 -> 1 +-- The next test should be skipped for decNumber +powx4302 power 1.000001 1e-101 -> 1.000001 Inexact Rounded +-- The next test should be skipped for decNumber +powx4303 power 1.000001 1e-95 -> 1.000001 Inexact Rounded +powx4304 power 1.000001 1e-10 -> 1.000001 Inexact Rounded +powx4305 power 1.000001 0.1 -> 1.000001 Inexact Rounded +powx4306 power 1.000001 0.1234567 -> 1.000001 Inexact Rounded +powx4307 power 1.000001 0.7 -> 1.000001 Inexact Rounded +powx4308 power 1.000001 0.9999999 -> 1.000001 Inexact Rounded +powx4309 power 1.000001 1.000000 -> 1.000001 +-- power(x,y)=1 when the rounding is down (e.g. toward_zero or +-- floor) for any y in [0,1). +rounding: floor +powx4321 power 1.000001 0 -> 1 +powx4322 power 1.000001 1e-101 -> 1.000000 Inexact Rounded +powx4323 power 1.000001 1e-95 -> 1.000000 Inexact Rounded +powx4324 power 1.000001 1e-10 -> 1.000000 Inexact Rounded +powx4325 power 1.000001 0.1 -> 1.000000 Inexact Rounded +powx4326 power 1.000001 0.1234567 -> 1.000000 Inexact Rounded +powx4327 power 1.000001 0.7 -> 1.000000 Inexact Rounded +powx4328 power 1.000001 0.9999999 -> 1.000000 Inexact Rounded +powx4329 power 1.000001 1.000000 -> 1.000001 + +-- For x=prevfp(1)=0.99..99 (where the number of 9s is precision) +-- power(x,y)=x when the rounding is down for any y in (0,1]. +rounding: floor +powx4341 power 0.9999999 0 -> 1 +-- The next test should be skipped for decNumber +powx4342 power 0.9999999 1e-101 -> 0.9999999 Inexact Rounded +-- The next test should be skipped for decNumber +powx4343 power 0.9999999 1e-95 -> 0.9999999 Inexact Rounded +powx4344 power 0.9999999 1e-10 -> 0.9999999 Inexact Rounded +powx4345 power 0.9999999 0.1 -> 0.9999999 Inexact Rounded +powx4346 power 0.9999999 0.1234567 -> 0.9999999 Inexact Rounded +powx4347 power 0.9999999 0.7 -> 0.9999999 Inexact Rounded +powx4348 power 0.9999999 0.9999999 -> 0.9999999 Inexact Rounded +powx4349 power 0.9999999 1.000000 -> 0.9999999 +-- power(x,y)=1 when the rounding is up for any y in (0,1]. +rounding: ceiling +powx4361 power 0.9999999 0 -> 1 +powx4362 power 0.9999999 1e-101 -> 1.000000 Inexact Rounded +powx4363 power 0.9999999 1e-95 -> 1.000000 Inexact Rounded +powx4364 power 0.9999999 1e-10 -> 1.000000 Inexact Rounded +powx4365 power 0.9999999 0.1 -> 1.000000 Inexact Rounded +powx4366 power 0.9999999 0.1234567 -> 1.000000 Inexact Rounded +powx4367 power 0.9999999 0.7 -> 1.000000 Inexact Rounded +powx4368 power 0.9999999 0.9999999 -> 1.000000 Inexact Rounded +powx4369 power 0.9999999 1.000000 -> 0.9999999 + +-- For x=nextfp(0) +-- power(x,y)=0 when the rounding is down for any y larger than 1. +rounding: floor +powx4382 power 1e-101 0 -> 1 +powx4383 power 1e-101 0.9999999 -> 1E-101 Underflow Subnormal Inexact Rounded +powx4384 power 1e-101 1.000000 -> 1E-101 Subnormal +powx4385 power 1e-101 1.000001 -> 0E-101 Underflow Subnormal Inexact Rounded Clamped +powx4386 power 1e-101 2.000000 -> 0E-101 Underflow Subnormal Inexact Rounded Clamped Modified: python/branches/py3k/Lib/test/decimaltestdata/quantize.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/quantize.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/quantize.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- quantize.decTest -- decimal quantize operation -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,11 +17,12 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- Most of the tests here assume a "regular pattern", where the -- sign and coefficient are +1. -- 2004.03.15 Underflow for quantize is suppressed +-- 2005.06.08 More extensive tests for 'does not fit' extended: 1 precision: 9 @@ -123,10 +124,6 @@ quax124 quantize 1.05 1e-3 -> 1.050 quax125 quantize 1.05 1e-2 -> 1.05 quax126 quantize 1.05 1e-1 -> 1.1 Inexact Rounded -quax127 quantize 1.05 1e0 -> 1 Inexact Rounded -quax128 quantize 1.05 1e-3 -> 1.050 -quax129 quantize 1.05 1e-2 -> 1.05 -quax130 quantize 1.05 1e-1 -> 1.1 Inexact Rounded quax131 quantize 1.05 1e0 -> 1 Inexact Rounded quax132 quantize 1.06 1e-3 -> 1.060 quax133 quantize 1.06 1e-2 -> 1.06 @@ -435,6 +432,102 @@ quax472 quantize 9.999E-15 1e0 -> 0 Inexact Rounded quax473 quantize 9.999E-15 1e1 -> 0E+1 Inexact Rounded +precision: 7 +quax900 quantize 9.999E-15 1e-22 -> NaN Invalid_operation +quax901 quantize 9.999E-15 1e-21 -> 9.999000E-15 +quax902 quantize 9.999E-15 1e-20 -> 9.99900E-15 +quax903 quantize 9.999E-15 1e-19 -> 9.9990E-15 +quax904 quantize 9.999E-15 1e-18 -> 9.999E-15 +quax905 quantize 9.999E-15 1e-17 -> 1.000E-14 Inexact Rounded +quax906 quantize 9.999E-15 1e-16 -> 1.00E-14 Inexact Rounded +quax907 quantize 9.999E-15 1e-15 -> 1.0E-14 Inexact Rounded +quax908 quantize 9.999E-15 1e-14 -> 1E-14 Inexact Rounded +quax909 quantize 9.999E-15 1e-13 -> 0E-13 Inexact Rounded +quax910 quantize 9.999E-15 1e-12 -> 0E-12 Inexact Rounded +quax911 quantize 9.999E-15 1e-11 -> 0E-11 Inexact Rounded +quax912 quantize 9.999E-15 1e-10 -> 0E-10 Inexact Rounded +quax913 quantize 9.999E-15 1e-9 -> 0E-9 Inexact Rounded +quax914 quantize 9.999E-15 1e-8 -> 0E-8 Inexact Rounded +quax915 quantize 9.999E-15 1e-7 -> 0E-7 Inexact Rounded +quax916 quantize 9.999E-15 1e-6 -> 0.000000 Inexact Rounded +quax917 quantize 9.999E-15 1e-5 -> 0.00000 Inexact Rounded +quax918 quantize 9.999E-15 1e-4 -> 0.0000 Inexact Rounded +quax919 quantize 9.999E-15 1e-3 -> 0.000 Inexact Rounded +quax920 quantize 9.999E-15 1e-2 -> 0.00 Inexact Rounded +quax921 quantize 9.999E-15 1e-1 -> 0.0 Inexact Rounded +quax922 quantize 9.999E-15 1e0 -> 0 Inexact Rounded +quax923 quantize 9.999E-15 1e1 -> 0E+1 Inexact Rounded + +precision: 6 +quax930 quantize 9.999E-15 1e-22 -> NaN Invalid_operation +quax931 quantize 9.999E-15 1e-21 -> NaN Invalid_operation +quax932 quantize 9.999E-15 1e-20 -> 9.99900E-15 +quax933 quantize 9.999E-15 1e-19 -> 9.9990E-15 +quax934 quantize 9.999E-15 1e-18 -> 9.999E-15 +quax935 quantize 9.999E-15 1e-17 -> 1.000E-14 Inexact Rounded +quax936 quantize 9.999E-15 1e-16 -> 1.00E-14 Inexact Rounded +quax937 quantize 9.999E-15 1e-15 -> 1.0E-14 Inexact Rounded +quax938 quantize 9.999E-15 1e-14 -> 1E-14 Inexact Rounded +quax939 quantize 9.999E-15 1e-13 -> 0E-13 Inexact Rounded +quax940 quantize 9.999E-15 1e-12 -> 0E-12 Inexact Rounded +quax941 quantize 9.999E-15 1e-11 -> 0E-11 Inexact Rounded +quax942 quantize 9.999E-15 1e-10 -> 0E-10 Inexact Rounded +quax943 quantize 9.999E-15 1e-9 -> 0E-9 Inexact Rounded +quax944 quantize 9.999E-15 1e-8 -> 0E-8 Inexact Rounded +quax945 quantize 9.999E-15 1e-7 -> 0E-7 Inexact Rounded +quax946 quantize 9.999E-15 1e-6 -> 0.000000 Inexact Rounded +quax947 quantize 9.999E-15 1e-5 -> 0.00000 Inexact Rounded +quax948 quantize 9.999E-15 1e-4 -> 0.0000 Inexact Rounded +quax949 quantize 9.999E-15 1e-3 -> 0.000 Inexact Rounded +quax950 quantize 9.999E-15 1e-2 -> 0.00 Inexact Rounded +quax951 quantize 9.999E-15 1e-1 -> 0.0 Inexact Rounded +quax952 quantize 9.999E-15 1e0 -> 0 Inexact Rounded +quax953 quantize 9.999E-15 1e1 -> 0E+1 Inexact Rounded + +precision: 3 +quax960 quantize 9.999E-15 1e-22 -> NaN Invalid_operation +quax961 quantize 9.999E-15 1e-21 -> NaN Invalid_operation +quax962 quantize 9.999E-15 1e-20 -> NaN Invalid_operation +quax963 quantize 9.999E-15 1e-19 -> NaN Invalid_operation +quax964 quantize 9.999E-15 1e-18 -> NaN Invalid_operation +quax965 quantize 9.999E-15 1e-17 -> NaN Invalid_operation +quax966 quantize 9.999E-15 1e-16 -> 1.00E-14 Inexact Rounded +quax967 quantize 9.999E-15 1e-15 -> 1.0E-14 Inexact Rounded +quax968 quantize 9.999E-15 1e-14 -> 1E-14 Inexact Rounded +quax969 quantize 9.999E-15 1e-13 -> 0E-13 Inexact Rounded +quax970 quantize 9.999E-15 1e-12 -> 0E-12 Inexact Rounded +quax971 quantize 9.999E-15 1e-11 -> 0E-11 Inexact Rounded +quax972 quantize 9.999E-15 1e-10 -> 0E-10 Inexact Rounded +quax973 quantize 9.999E-15 1e-9 -> 0E-9 Inexact Rounded +quax974 quantize 9.999E-15 1e-8 -> 0E-8 Inexact Rounded +quax975 quantize 9.999E-15 1e-7 -> 0E-7 Inexact Rounded +quax976 quantize 9.999E-15 1e-6 -> 0.000000 Inexact Rounded +quax977 quantize 9.999E-15 1e-5 -> 0.00000 Inexact Rounded +quax978 quantize 9.999E-15 1e-4 -> 0.0000 Inexact Rounded +quax979 quantize 9.999E-15 1e-3 -> 0.000 Inexact Rounded +quax980 quantize 9.999E-15 1e-2 -> 0.00 Inexact Rounded +quax981 quantize 9.999E-15 1e-1 -> 0.0 Inexact Rounded +quax982 quantize 9.999E-15 1e0 -> 0 Inexact Rounded +quax983 quantize 9.999E-15 1e1 -> 0E+1 Inexact Rounded + +-- Fung Lee's case & similar +precision: 3 +quax1001 quantize 0.000 0.001 -> 0.000 +quax1002 quantize 0.001 0.001 -> 0.001 +quax1003 quantize 0.0012 0.001 -> 0.001 Inexact Rounded +quax1004 quantize 0.0018 0.001 -> 0.002 Inexact Rounded +quax1005 quantize 0.501 0.001 -> 0.501 +quax1006 quantize 0.5012 0.001 -> 0.501 Inexact Rounded +quax1007 quantize 0.5018 0.001 -> 0.502 Inexact Rounded +quax1008 quantize 0.999 0.001 -> 0.999 +quax1009 quantize 0.9992 0.001 -> 0.999 Inexact Rounded +quax1010 quantize 0.9998 0.001 -> NaN Invalid_operation +quax1011 quantize 1.0001 0.001 -> NaN Invalid_operation +quax1012 quantize 1.0051 0.001 -> NaN Invalid_operation +quax1013 quantize 1.0551 0.001 -> NaN Invalid_operation +quax1014 quantize 1.5551 0.001 -> NaN Invalid_operation +quax1015 quantize 1.9999 0.001 -> NaN Invalid_operation + -- long operand checks [rhs checks removed] maxexponent: 999 minexponent: -999 @@ -775,6 +868,81 @@ quax865 quantize 1 1e-2147483648 -> NaN Invalid_operation quax866 quantize 1 1e-2147483649 -> NaN Invalid_operation +-- More from Fung Lee +precision: 16 +rounding: half_up +maxExponent: 384 +minExponent: -383 +quax1021 quantize 8.666666666666000E+384 1.000000000000000E+384 -> 8.666666666666000E+384 +quax1022 quantize 64#8.666666666666000E+384 64#1.000000000000000E+384 -> 8.666666666666000E+384 +quax1023 quantize 64#8.666666666666000E+384 128#1.000000000000000E+384 -> 8.666666666666000E+384 +quax1024 quantize 64#8.666666666666000E+384 64#1E+384 -> 8.666666666666000E+384 +quax1025 quantize 64#8.666666666666000E+384 64#1E+384 -> 64#8.666666666666000E+384 +quax1026 quantize 64#8.666666666666000E+384 128#1E+384 -> 64#9E+384 Inexact Rounded Clamped +quax1027 quantize 64#8.666666666666000E+323 64#1E+31 -> NaN Invalid_operation +quax1028 quantize 64#8.666666666666000E+323 128#1E+31 -> NaN Invalid_operation +quax1029 quantize 64#8.66666666E+3 128#1E+10 -> 64#0E10 Inexact Rounded +quax1030 quantize 8.66666666E+3 1E+3 -> 9E+3 Inexact Rounded + +-- Int and uInt32 edge values for testing conversions +quax1040 quantize -2147483646 0 -> -2147483646 +quax1041 quantize -2147483647 0 -> -2147483647 +quax1042 quantize -2147483648 0 -> -2147483648 +quax1043 quantize -2147483649 0 -> -2147483649 +quax1044 quantize 2147483646 0 -> 2147483646 +quax1045 quantize 2147483647 0 -> 2147483647 +quax1046 quantize 2147483648 0 -> 2147483648 +quax1047 quantize 2147483649 0 -> 2147483649 +quax1048 quantize 4294967294 0 -> 4294967294 +quax1049 quantize 4294967295 0 -> 4294967295 +quax1050 quantize 4294967296 0 -> 4294967296 +quax1051 quantize 4294967297 0 -> 4294967297 +-- and powers of ten for same +quax1101 quantize 5000000000 0 -> 5000000000 +quax1102 quantize 4000000000 0 -> 4000000000 +quax1103 quantize 2000000000 0 -> 2000000000 +quax1104 quantize 1000000000 0 -> 1000000000 +quax1105 quantize 0100000000 0 -> 100000000 +quax1106 quantize 0010000000 0 -> 10000000 +quax1107 quantize 0001000000 0 -> 1000000 +quax1108 quantize 0000100000 0 -> 100000 +quax1109 quantize 0000010000 0 -> 10000 +quax1110 quantize 0000001000 0 -> 1000 +quax1111 quantize 0000000100 0 -> 100 +quax1112 quantize 0000000010 0 -> 10 +quax1113 quantize 0000000001 0 -> 1 +quax1114 quantize 0000000000 0 -> 0 +-- and powers of ten for same +quax1121 quantize -5000000000 0 -> -5000000000 +quax1122 quantize -4000000000 0 -> -4000000000 +quax1123 quantize -2000000000 0 -> -2000000000 +quax1124 quantize -1000000000 0 -> -1000000000 +quax1125 quantize -0100000000 0 -> -100000000 +quax1126 quantize -0010000000 0 -> -10000000 +quax1127 quantize -0001000000 0 -> -1000000 +quax1128 quantize -0000100000 0 -> -100000 +quax1129 quantize -0000010000 0 -> -10000 +quax1130 quantize -0000001000 0 -> -1000 +quax1131 quantize -0000000100 0 -> -100 +quax1132 quantize -0000000010 0 -> -10 +quax1133 quantize -0000000001 0 -> -1 +quax1134 quantize -0000000000 0 -> -0 + +-- Some miscellany +precision: 34 +rounding: half_up +maxExponent: 6144 +minExponent: -6143 +-- 1 2 3 +-- 1 234567890123456789012345678901234 +quax0a1 quantize 8.555555555555555555555555555555555E+6143 1E+6143 -> 9E+6143 Inexact Rounded +quax0a2 quantize 128#8.555555555555555555555555555555555E+6143 128#1E+6143 -> 8.55555555555555555555555555555556E+6143 Rounded Inexact +quax0a3 quantize 128#8.555555555555555555555555555555555E+6144 128#1E+6144 -> 8.555555555555555555555555555555555E+6144 + +-- payload decapitate +precision: 5 +quax62100 quantize 11 -sNaN1234567890 -> -NaN67890 Invalid_operation + -- Null tests -quax900 quantize 10 # -> NaN Invalid_operation -quax901 quantize # 1e10 -> NaN Invalid_operation +quax998 quantize 10 # -> NaN Invalid_operation +quax999 quantize # 1e10 -> NaN Invalid_operation Modified: python/branches/py3k/Lib/test/decimaltestdata/randomBound32.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/randomBound32.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/randomBound32.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- randomBound32.decTest -- decimal testcases -- boundaries near 32 -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.55 -- These testcases test calculations at precisions 31, 32, and 33, to -- exercise the boundaries around 2**5 @@ -90,7 +90,7 @@ divx3008 divide 75353574493.84484153484918212042 -8684111695095849922263044191221 -> -8.677177026223536475531592432118E-21 Inexact Rounded dvix3008 divideint 75353574493.84484153484918212042 -8684111695095849922263044191221 -> -0 mulx3008 multiply 75353574493.84484153484918212042 -8684111695095849922263044191221 -> -6.543788575292743281456830701127E+41 Inexact Rounded -powx3008 power 75353574493.84484153484918212042 -9 -> 1.276630670287906925570645490708E-98 Inexact Rounded +powx3008 power 75353574493.84484153484918212042 -9 -> 1.276630670287906925570645490707E-98 Inexact Rounded remx3008 remainder 75353574493.84484153484918212042 -8684111695095849922263044191221 -> 75353574493.84484153484918212042 subx3008 subtract 75353574493.84484153484918212042 -8684111695095849922263044191221 -> 8684111695095849922338397765715 Inexact Rounded addx3009 add 6907058.216435355874729592373011 2.857005446917670515662398741545 -> 6907061.073440802792400108035410 Inexact Rounded @@ -1040,7 +1040,7 @@ divx3226 divide 47.525676459351505682005359699680E+704 -58631943508436657383369760970210 -> -8.1057651538555854520994438038537E+673 Inexact Rounded dvix3226 divideint 47.525676459351505682005359699680E+704 -58631943508436657383369760970210 -> NaN Division_impossible mulx3226 multiply 47.525676459351505682005359699680E+704 -58631943508436657383369760970210 -> -2.7865227773649353769876975366506E+737 Inexact Rounded -powx3226 power 47.525676459351505682005359699680E+704 -6 -> 8.6782100393941226535150385475463E-4235 Inexact Rounded +powx3226 power 47.525676459351505682005359699680E+704 -6 -> 8.6782100393941226535150385475464E-4235 Inexact Rounded remx3226 remainder 47.525676459351505682005359699680E+704 -58631943508436657383369760970210 -> NaN Division_impossible subx3226 subtract 47.525676459351505682005359699680E+704 -58631943508436657383369760970210 -> 4.7525676459351505682005359699680E+705 Inexact Rounded addx3227 add -74396862273800.625679130772935550 -115616605.52826981284183992013157 -> -74396977890406.153948943614775470 Inexact Rounded Modified: python/branches/py3k/Lib/test/decimaltestdata/randoms.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/randoms.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/randoms.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- randoms.decTest -- decimal random testcases -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 maxexponent: 999999999 @@ -264,7 +264,7 @@ xdiv030 divide -225094.28 -88.7723542 -> 2535.63491 Inexact Rounded xdvi030 divideint -225094.28 -88.7723542 -> 2535 xmul030 multiply -225094.28 -88.7723542 -> 19982149.2 Inexact Rounded -xpow030 power -225094.28 -89 -> -4.36076964E-477 Inexact Rounded +xpow030 power -225094.28 -89 -> -4.36076965E-477 Inexact Rounded xrem030 remainder -225094.28 -88.7723542 -> -56.3621030 xsub030 subtract -225094.28 -88.7723542 -> -225005.508 Inexact Rounded xadd031 add 50.4442340 82.7952169E+880120759 -> 8.27952169E+880120760 Inexact Rounded @@ -295,7 +295,7 @@ xcom034 compare 592.142173E-419941416 -3.46079109E-844011845 -> 1 xdiv034 divide 592.142173E-419941416 -3.46079109E-844011845 -> -1.71100236E+424070431 Inexact Rounded xdvi034 divideint 592.142173E-419941416 -3.46079109E-844011845 -> NaN Division_impossible -xmul034 multiply 592.142173E-419941416 -3.46079109E-844011845 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul034 multiply 592.142173E-419941416 -3.46079109E-844011845 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow034 power 592.142173E-419941416 -3 -> Infinity Overflow Inexact Rounded xrem034 remainder 592.142173E-419941416 -3.46079109E-844011845 -> NaN Division_impossible xsub034 subtract 592.142173E-419941416 -3.46079109E-844011845 -> 5.92142173E-419941414 Inexact Rounded @@ -487,7 +487,7 @@ xcom058 compare 151795163E-371727182 -488.09788E-738852245 -> 1 xdiv058 divide 151795163E-371727182 -488.09788E-738852245 -> -3.10993285E+367125068 Inexact Rounded xdvi058 divideint 151795163E-371727182 -488.09788E-738852245 -> NaN Division_impossible -xmul058 multiply 151795163E-371727182 -488.09788E-738852245 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul058 multiply 151795163E-371727182 -488.09788E-738852245 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow058 power 151795163E-371727182 -5 -> Infinity Overflow Inexact Rounded xrem058 remainder 151795163E-371727182 -488.09788E-738852245 -> NaN Division_impossible xsub058 subtract 151795163E-371727182 -488.09788E-738852245 -> 1.51795163E-371727174 Inexact Rounded @@ -568,7 +568,7 @@ xdiv068 divide -12393257.2 76803689E+949125770 -> -1.61362786E-949125771 Inexact Rounded xdvi068 divideint -12393257.2 76803689E+949125770 -> -0 xmul068 multiply -12393257.2 76803689E+949125770 -> -9.51847872E+949125784 Inexact Rounded -xpow068 power -12393257.2 8 -> 5.56523750E+56 Inexact Rounded +xpow068 power -12393257.2 8 -> 5.56523749E+56 Inexact Rounded xrem068 remainder -12393257.2 76803689E+949125770 -> -12393257.2 xsub068 subtract -12393257.2 76803689E+949125770 -> -7.68036890E+949125777 Inexact Rounded xadd069 add -754771634.E+716555026 -292336.311 -> -7.54771634E+716555034 Inexact Rounded @@ -775,7 +775,7 @@ xcom094 compare -671.507198E-908587890 3057429.32E-555230623 -> -1 xdiv094 divide -671.507198E-908587890 3057429.32E-555230623 -> -2.19631307E-353357271 Inexact Rounded xdvi094 divideint -671.507198E-908587890 3057429.32E-555230623 -> -0 -xmul094 multiply -671.507198E-908587890 3057429.32E-555230623 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul094 multiply -671.507198E-908587890 3057429.32E-555230623 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow094 power -671.507198E-908587890 3 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xrem094 remainder -671.507198E-908587890 3057429.32E-555230623 -> -6.71507198E-908587888 xsub094 subtract -671.507198E-908587890 3057429.32E-555230623 -> -3.05742932E-555230617 Inexact Rounded @@ -856,7 +856,7 @@ xdiv104 divide 553527296. -7924.40185 -> -69850.9877 Inexact Rounded xdvi104 divideint 553527296. -7924.40185 -> -69850 xmul104 multiply 553527296. -7924.40185 -> -4.38637273E+12 Inexact Rounded -xpow104 power 553527296. -7924 -> 2.32397213E-69281 Inexact Rounded +xpow104 power 553527296. -7924 -> 2.32397214E-69281 Inexact Rounded xrem104 remainder 553527296. -7924.40185 -> 7826.77750 xsub104 subtract 553527296. -7924.40185 -> 553535220 Inexact Rounded xadd105 add -38.7465207 64936.2942 -> 64897.5477 Inexact Rounded @@ -919,7 +919,7 @@ xcom112 compare -51.1632090E-753968082 8.96207471E-585797887 -> -1 xdiv112 divide -51.1632090E-753968082 8.96207471E-585797887 -> -5.70885768E-168170195 Inexact Rounded xdvi112 divideint -51.1632090E-753968082 8.96207471E-585797887 -> -0 -xmul112 multiply -51.1632090E-753968082 8.96207471E-585797887 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul112 multiply -51.1632090E-753968082 8.96207471E-585797887 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow112 power -51.1632090E-753968082 9 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xrem112 remainder -51.1632090E-753968082 8.96207471E-585797887 -> -5.11632090E-753968081 xsub112 subtract -51.1632090E-753968082 8.96207471E-585797887 -> -8.96207471E-585797887 Inexact Rounded @@ -989,7 +989,7 @@ xsub120 subtract 14239029. -36527.2221 -> 14275556.2 Inexact Rounded xadd121 add 72333.2654E-544425548 -690.664836E+662155120 -> -6.90664836E+662155122 Inexact Rounded xcom121 compare 72333.2654E-544425548 -690.664836E+662155120 -> 1 -xdiv121 divide 72333.2654E-544425548 -690.664836E+662155120 -> -0E-1000000007 Inexact Rounded Underflow Subnormal +xdiv121 divide 72333.2654E-544425548 -690.664836E+662155120 -> -0E-1000000007 Inexact Rounded Underflow Subnormal Clamped xdvi121 divideint 72333.2654E-544425548 -690.664836E+662155120 -> -0 xmul121 multiply 72333.2654E-544425548 -690.664836E+662155120 -> -4.99580429E+117729579 Inexact Rounded xpow121 power 72333.2654E-544425548 -7 -> Infinity Overflow Inexact Rounded @@ -1005,7 +1005,7 @@ xsub122 subtract -37721.1567E-115787341 -828949864E-76251747 -> 8.28949864E-76251739 Inexact Rounded xadd123 add -2078852.83E-647080089 -119779858.E+734665461 -> -1.19779858E+734665469 Inexact Rounded xcom123 compare -2078852.83E-647080089 -119779858.E+734665461 -> 1 -xdiv123 divide -2078852.83E-647080089 -119779858.E+734665461 -> 0E-1000000007 Inexact Rounded Underflow Subnormal +xdiv123 divide -2078852.83E-647080089 -119779858.E+734665461 -> 0E-1000000007 Inexact Rounded Underflow Subnormal Clamped xdvi123 divideint -2078852.83E-647080089 -119779858.E+734665461 -> 0 xmul123 multiply -2078852.83E-647080089 -119779858.E+734665461 -> 2.49004697E+87585386 Inexact Rounded xpow123 power -2078852.83E-647080089 -1 -> -4.81034533E+647080082 Inexact Rounded @@ -1183,7 +1183,7 @@ xcom145 compare -477067757.E-961684940 7.70122608E-741072245 -> -1 xdiv145 divide -477067757.E-961684940 7.70122608E-741072245 -> -6.19469877E-220612688 Inexact Rounded xdvi145 divideint -477067757.E-961684940 7.70122608E-741072245 -> -0 -xmul145 multiply -477067757.E-961684940 7.70122608E-741072245 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul145 multiply -477067757.E-961684940 7.70122608E-741072245 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow145 power -477067757.E-961684940 8 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xrem145 remainder -477067757.E-961684940 7.70122608E-741072245 -> -4.77067757E-961684932 xsub145 subtract -477067757.E-961684940 7.70122608E-741072245 -> -7.70122608E-741072245 Inexact Rounded @@ -1296,7 +1296,7 @@ xdiv159 divide -18861647. 99794586.7 -> -0.189004711 Inexact Rounded xdvi159 divideint -18861647. 99794586.7 -> -0 xmul159 multiply -18861647. 99794586.7 -> -1.88229027E+15 Inexact Rounded -xpow159 power -18861647. 99794587 -> -4.28957460E+726063462 Inexact Rounded +xpow159 power -18861647. 99794587 -> -4.28957459E+726063462 Inexact Rounded xrem159 remainder -18861647. 99794586.7 -> -18861647.0 xsub159 subtract -18861647. 99794586.7 -> -118656234 Inexact Rounded xadd160 add 322192.407 461.67044 -> 322654.077 Inexact Rounded @@ -1519,7 +1519,7 @@ xcom187 compare -29.356551E-282816139 37141748E-903397821 -> -1 xdiv187 divide -29.356551E-282816139 37141748E-903397821 -> -7.90392283E+620581675 Inexact Rounded xdvi187 divideint -29.356551E-282816139 37141748E-903397821 -> NaN Division_impossible -xmul187 multiply -29.356551E-282816139 37141748E-903397821 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul187 multiply -29.356551E-282816139 37141748E-903397821 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow187 power -29.356551E-282816139 4 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xrem187 remainder -29.356551E-282816139 37141748E-903397821 -> NaN Division_impossible xsub187 subtract -29.356551E-282816139 37141748E-903397821 -> -2.93565510E-282816138 Inexact Rounded @@ -1760,7 +1760,7 @@ xdiv217 divide 7428219.97 667.326760 -> 11131.3084 Inexact Rounded xdvi217 divideint 7428219.97 667.326760 -> 11131 xmul217 multiply 7428219.97 667.326760 -> 4.95704997E+9 Inexact Rounded -xpow217 power 7428219.97 667 -> 7.58808510E+4582 Inexact Rounded +xpow217 power 7428219.97 667 -> 7.58808509E+4582 Inexact Rounded xrem217 remainder 7428219.97 667.326760 -> 205.804440 xsub217 subtract 7428219.97 667.326760 -> 7427552.64 Inexact Rounded xadd218 add -7291.19212 209.64966E-588526476 -> -7291.19212 Inexact Rounded @@ -2200,7 +2200,7 @@ xdiv272 divide 513115529. 27775075.6E+217133352 -> 1.84739562E-217133351 Inexact Rounded xdvi272 divideint 513115529. 27775075.6E+217133352 -> 0 xmul272 multiply 513115529. 27775075.6E+217133352 -> 1.42518226E+217133368 Inexact Rounded -xpow272 power 513115529. 3 -> 1.35096929E+26 Inexact Rounded +xpow272 power 513115529. 3 -> 1.35096928E+26 Inexact Rounded xrem272 remainder 513115529. 27775075.6E+217133352 -> 513115529 xsub272 subtract 513115529. 27775075.6E+217133352 -> -2.77750756E+217133359 Inexact Rounded xadd273 add -247157.208 -532990.453 -> -780147.661 @@ -2327,7 +2327,7 @@ xcom288 compare -4.18074650E-858746879 571035.277E-279409165 -> -1 xdiv288 divide -4.18074650E-858746879 571035.277E-279409165 -> -7.32134540E-579337720 Inexact Rounded xdvi288 divideint -4.18074650E-858746879 571035.277E-279409165 -> -0 -xmul288 multiply -4.18074650E-858746879 571035.277E-279409165 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul288 multiply -4.18074650E-858746879 571035.277E-279409165 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow288 power -4.18074650E-858746879 6 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xrem288 remainder -4.18074650E-858746879 571035.277E-279409165 -> -4.18074650E-858746879 xsub288 subtract -4.18074650E-858746879 571035.277E-279409165 -> -5.71035277E-279409160 Inexact Rounded @@ -2599,7 +2599,7 @@ xcom322 compare 82.4185291E-321919303 -215747737.E-995147400 -> 1 xdiv322 divide 82.4185291E-321919303 -215747737.E-995147400 -> -3.82013412E+673228090 Inexact Rounded xdvi322 divideint 82.4185291E-321919303 -215747737.E-995147400 -> NaN Division_impossible -xmul322 multiply 82.4185291E-321919303 -215747737.E-995147400 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul322 multiply 82.4185291E-321919303 -215747737.E-995147400 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow322 power 82.4185291E-321919303 -2 -> 1.47214396E+643838602 Inexact Rounded xrem322 remainder 82.4185291E-321919303 -215747737.E-995147400 -> NaN Division_impossible xsub322 subtract 82.4185291E-321919303 -215747737.E-995147400 -> 8.24185291E-321919302 Inexact Rounded @@ -2640,7 +2640,7 @@ xdiv327 divide 2512953.3 -3769170.35E-993621645 -> -6.66712583E+993621644 Inexact Rounded xdvi327 divideint 2512953.3 -3769170.35E-993621645 -> NaN Division_impossible xmul327 multiply 2512953.3 -3769170.35E-993621645 -> -9.47174907E-993621633 Inexact Rounded -xpow327 power 2512953.3 -4 -> 2.50762349E-26 Inexact Rounded +xpow327 power 2512953.3 -4 -> 2.50762348E-26 Inexact Rounded xrem327 remainder 2512953.3 -3769170.35E-993621645 -> NaN Division_impossible xsub327 subtract 2512953.3 -3769170.35E-993621645 -> 2512953.30 Inexact Rounded xadd328 add -682.796370 71131.0224 -> 70448.2260 Inexact Rounded @@ -2656,7 +2656,7 @@ xdiv329 divide 89.9997490 -4993.69831 -> -0.0180226644 Inexact Rounded xdvi329 divideint 89.9997490 -4993.69831 -> -0 xmul329 multiply 89.9997490 -4993.69831 -> -449431.594 Inexact Rounded -xpow329 power 89.9997490 -4994 -> 3.30336526E-9760 Inexact Rounded +xpow329 power 89.9997490 -4994 -> 3.30336525E-9760 Inexact Rounded xrem329 remainder 89.9997490 -4993.69831 -> 89.9997490 xsub329 subtract 89.9997490 -4993.69831 -> 5083.69806 Inexact Rounded xadd330 add 76563354.6E-112338836 278271.585E-511481095 -> 7.65633546E-112338829 Inexact Rounded @@ -2821,7 +2821,7 @@ xsub349 subtract -4037911.02E+641367645 29.5713010 -> -4.03791102E+641367651 Inexact Rounded xadd350 add -688755561.E-95301699 978.275312E+913812609 -> 9.78275312E+913812611 Inexact Rounded xcom350 compare -688755561.E-95301699 978.275312E+913812609 -> -1 -xdiv350 divide -688755561.E-95301699 978.275312E+913812609 -> -0E-1000000007 Inexact Rounded Underflow Subnormal +xdiv350 divide -688755561.E-95301699 978.275312E+913812609 -> -0E-1000000007 Inexact Rounded Underflow Subnormal Clamped xdvi350 divideint -688755561.E-95301699 978.275312E+913812609 -> -0 xmul350 multiply -688755561.E-95301699 978.275312E+913812609 -> -6.73792561E+818510921 Inexact Rounded xpow350 power -688755561.E-95301699 10 -> 2.40243244E-953016902 Inexact Rounded @@ -3024,7 +3024,7 @@ xdiv375 divide -5549320.1 -93580684.1 -> 0.0592998454 Inexact Rounded xdvi375 divideint -5549320.1 -93580684.1 -> 0 xmul375 multiply -5549320.1 -93580684.1 -> 5.19309171E+14 Inexact Rounded -xpow375 power -5549320.1 -93580684 -> 4.20662080E-631130572 Inexact Rounded +xpow375 power -5549320.1 -93580684 -> 4.20662079E-631130572 Inexact Rounded xrem375 remainder -5549320.1 -93580684.1 -> -5549320.1 xsub375 subtract -5549320.1 -93580684.1 -> 88031364.0 xadd376 add -14677053.1 -25784.7358 -> -14702837.8 Inexact Rounded @@ -3191,7 +3191,7 @@ xcom396 compare 4880.06442E-382222621 -115627239E-912834031 -> 1 xdiv396 divide 4880.06442E-382222621 -115627239E-912834031 -> -4.22051453E+530611405 Inexact Rounded xdvi396 divideint 4880.06442E-382222621 -115627239E-912834031 -> NaN Division_impossible -xmul396 multiply 4880.06442E-382222621 -115627239E-912834031 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul396 multiply 4880.06442E-382222621 -115627239E-912834031 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow396 power 4880.06442E-382222621 -1 -> 2.04915328E+382222617 Inexact Rounded xrem396 remainder 4880.06442E-382222621 -115627239E-912834031 -> NaN Division_impossible xsub396 subtract 4880.06442E-382222621 -115627239E-912834031 -> 4.88006442E-382222618 Inexact Rounded @@ -3295,7 +3295,7 @@ xcom409 compare -54.3684171E-807210192 1.04592973E-984041807 -> -1 xdiv409 divide -54.3684171E-807210192 1.04592973E-984041807 -> -5.19809463E+176831616 Inexact Rounded xdvi409 divideint -54.3684171E-807210192 1.04592973E-984041807 -> NaN Division_impossible -xmul409 multiply -54.3684171E-807210192 1.04592973E-984041807 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul409 multiply -54.3684171E-807210192 1.04592973E-984041807 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow409 power -54.3684171E-807210192 1 -> -5.43684171E-807210191 xrem409 remainder -54.3684171E-807210192 1.04592973E-984041807 -> NaN Division_impossible xsub409 subtract -54.3684171E-807210192 1.04592973E-984041807 -> -5.43684171E-807210191 Inexact Rounded @@ -3391,7 +3391,7 @@ xcom421 compare -4.09492571E-301749490 434.20199E-749390952 -> -1 xdiv421 divide -4.09492571E-301749490 434.20199E-749390952 -> -9.43092341E+447641459 Inexact Rounded xdvi421 divideint -4.09492571E-301749490 434.20199E-749390952 -> NaN Division_impossible -xmul421 multiply -4.09492571E-301749490 434.20199E-749390952 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul421 multiply -4.09492571E-301749490 434.20199E-749390952 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow421 power -4.09492571E-301749490 4 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xrem421 remainder -4.09492571E-301749490 434.20199E-749390952 -> NaN Division_impossible xsub421 subtract -4.09492571E-301749490 434.20199E-749390952 -> -4.09492571E-301749490 Inexact Rounded @@ -3423,7 +3423,7 @@ xcom425 compare 6.88891136E-935467395 -785049.562E-741671442 -> 1 xdiv425 divide 6.88891136E-935467395 -785049.562E-741671442 -> -8.77512923E-193795959 Inexact Rounded xdvi425 divideint 6.88891136E-935467395 -785049.562E-741671442 -> -0 -xmul425 multiply 6.88891136E-935467395 -785049.562E-741671442 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul425 multiply 6.88891136E-935467395 -785049.562E-741671442 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow425 power 6.88891136E-935467395 -8 -> Infinity Overflow Inexact Rounded xrem425 remainder 6.88891136E-935467395 -785049.562E-741671442 -> 6.88891136E-935467395 xsub425 subtract 6.88891136E-935467395 -785049.562E-741671442 -> 7.85049562E-741671437 Inexact Rounded @@ -3535,7 +3535,7 @@ xcom439 compare 971113.655E-695540249 -419351120E-977743823 -> 1 xdiv439 divide 971113.655E-695540249 -419351120E-977743823 -> -2.31575310E+282203571 Inexact Rounded xdvi439 divideint 971113.655E-695540249 -419351120E-977743823 -> NaN Division_impossible -xmul439 multiply 971113.655E-695540249 -419351120E-977743823 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul439 multiply 971113.655E-695540249 -419351120E-977743823 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow439 power 971113.655E-695540249 -4 -> Infinity Overflow Inexact Rounded xrem439 remainder 971113.655E-695540249 -419351120E-977743823 -> NaN Division_impossible xsub439 subtract 971113.655E-695540249 -419351120E-977743823 -> 9.71113655E-695540244 Inexact Rounded @@ -3600,7 +3600,7 @@ xdiv447 divide -9.95836312 -866466703 -> 1.14930707E-8 Inexact Rounded xdvi447 divideint -9.95836312 -866466703 -> 0 xmul447 multiply -9.95836312 -866466703 -> 8.62859006E+9 Inexact Rounded -xpow447 power -9.95836312 -866466703 -> -6.71744368E-864896630 Inexact Rounded +xpow447 power -9.95836312 -866466703 -> -6.71744369E-864896630 Inexact Rounded xrem447 remainder -9.95836312 -866466703 -> -9.95836312 xsub447 subtract -9.95836312 -866466703 -> 866466693 Inexact Rounded xadd448 add 80919339.2E-967231586 219.824266 -> 219.824266 Inexact Rounded @@ -3616,7 +3616,7 @@ xdiv449 divide 159579.444 -89827.5229 -> -1.77650946 Inexact Rounded xdvi449 divideint 159579.444 -89827.5229 -> -1 xmul449 multiply 159579.444 -89827.5229 -> -1.43346262E+10 Inexact Rounded -xpow449 power 159579.444 -89828 -> 9.69955849E-467374 Inexact Rounded +xpow449 power 159579.444 -89828 -> 9.69955850E-467374 Inexact Rounded xrem449 remainder 159579.444 -89827.5229 -> 69751.9211 xsub449 subtract 159579.444 -89827.5229 -> 249406.967 Inexact Rounded xadd450 add -4.54000153 6966333.74 -> 6966329.20 Inexact Rounded @@ -3640,7 +3640,7 @@ xdiv452 divide -361382575. -7976.15286E+898491169 -> 4.53078798E-898491165 Inexact Rounded xdvi452 divideint -361382575. -7976.15286E+898491169 -> 0 xmul452 multiply -361382575. -7976.15286E+898491169 -> 2.88244266E+898491181 Inexact Rounded -xpow452 power -361382575. -8 -> 3.43765536E-69 Inexact Rounded +xpow452 power -361382575. -8 -> 3.43765537E-69 Inexact Rounded xrem452 remainder -361382575. -7976.15286E+898491169 -> -361382575 xsub452 subtract -361382575. -7976.15286E+898491169 -> 7.97615286E+898491172 Inexact Rounded xadd453 add 7021805.61 1222952.83 -> 8244758.44 @@ -3720,7 +3720,7 @@ xdiv462 divide -51592.2698 -713885.741 -> 0.0722696460 Inexact Rounded xdvi462 divideint -51592.2698 -713885.741 -> 0 xmul462 multiply -51592.2698 -713885.741 -> 3.68309858E+10 Inexact Rounded -xpow462 power -51592.2698 -713886 -> 6.38576921E-3364249 Inexact Rounded +xpow462 power -51592.2698 -713886 -> 6.38576920E-3364249 Inexact Rounded xrem462 remainder -51592.2698 -713885.741 -> -51592.2698 xsub462 subtract -51592.2698 -713885.741 -> 662293.471 Inexact Rounded xadd463 add 51.2279848E+80439745 207.55925E+865165070 -> 2.07559250E+865165072 Inexact Rounded @@ -3768,7 +3768,7 @@ xdiv468 divide -5.32711606 -8447286.21 -> 6.30630468E-7 Inexact Rounded xdvi468 divideint -5.32711606 -8447286.21 -> 0 xmul468 multiply -5.32711606 -8447286.21 -> 44999674.0 Inexact Rounded -xpow468 power -5.32711606 -8447286 -> 9.09138729E-6136888 Inexact Rounded +xpow468 power -5.32711606 -8447286 -> 9.09138728E-6136888 Inexact Rounded xrem468 remainder -5.32711606 -8447286.21 -> -5.32711606 xsub468 subtract -5.32711606 -8447286.21 -> 8447280.88 Inexact Rounded xadd469 add -82272171.8 -776.238587E-372690416 -> -82272171.8 Inexact Rounded @@ -4027,3 +4027,4 @@ xpow500 power -525445087.E+231529167 188227460 -> Infinity Overflow Inexact Rounded xrem500 remainder -525445087.E+231529167 188227460 -> NaN Division_impossible xsub500 subtract -525445087.E+231529167 188227460 -> -5.25445087E+231529175 Inexact Rounded + Modified: python/branches/py3k/Lib/test/decimaltestdata/remainder.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/remainder.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/remainder.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- remainder.decTest -- decimal remainder -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -351,6 +351,17 @@ remx408 remainder 0.55555555 1 -> 0.55555555 remx409 remainder 0.555555555 1 -> 0.555555555 +-- zero signs +remx650 remainder 1 1 -> 0 +remx651 remainder -1 1 -> -0 +remx652 remainder 1 -1 -> 0 +remx653 remainder -1 -1 -> -0 +remx654 remainder 0 1 -> 0 +remx655 remainder -0 1 -> -0 +remx656 remainder 0 -1 -> 0 +remx657 remainder -0 -1 -> -0 +remx658 remainder 0.00 1 -> 0.00 +remx659 remainder -0.00 1 -> -0.00 -- Specials remx680 remainder Inf -Inf -> NaN Invalid_operation Modified: python/branches/py3k/Lib/test/decimaltestdata/remainderNear.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/remainderNear.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/remainderNear.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- remainderNear.decTest -- decimal remainder-near (IEEE remainder) -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.55 extended: 1 precision: 9 Modified: python/branches/py3k/Lib/test/decimaltestdata/rescale.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/rescale.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/rescale.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- rescale.decTest -- decimal rescale operation -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- [obsolete] Quantize.decTest has the improved version @@ -379,7 +379,7 @@ resx446 rescale 0.000999 1 -> 0E+1 Inexact Rounded precision: 8 -resx449 rescale 9.999E-15 -23 -> NaN Invalid_operation +resx449 rescale 9.999E-15 -23 -> NaN Invalid_operation resx450 rescale 9.999E-15 -22 -> 9.9990000E-15 resx451 rescale 9.999E-15 -21 -> 9.999000E-15 resx452 rescale 9.999E-15 -20 -> 9.99900E-15 @@ -405,6 +405,12 @@ resx472 rescale 9.999E-15 0 -> 0 Inexact Rounded resx473 rescale 9.999E-15 1 -> 0E+1 Inexact Rounded +-- [additional tests for "don't fit" edge cases are in +-- quantize.decTest. Here's a critical one.] +precision: 3 +resx480 rescale 0.9999 -3 -> NaN Invalid_operation + + -- long operand checks [rhs checks removed] maxexponent: 999 minexponent: -999 Modified: python/branches/py3k/Lib/test/decimaltestdata/rounding.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/rounding.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/rounding.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- rounding.decTest -- decimal rounding modes testcases -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- These tests require that implementations take account of residues in -- order to get correct results for some rounding modes. Rather than @@ -26,8 +26,11 @@ -- is rounding of negatives (if the latter works for addition, assume it -- works for the others, too).] -- --- Underflow Subnormal and overflow behaviours are tested under the individual --- operators. +-- Round-for-reround (05UP) is tested as a separate block, mostly for +-- 'historical' reasons. +-- +-- Underflow Subnormal and overflow behaviours are tested under the +-- individual operators. extended: 1 precision: 5 -- for easier visual inspection @@ -980,8 +983,8 @@ rounding: down rovx100 multiply 10 9E+999999999 -> 9.9999E+999999999 Overflow Inexact Rounded rovx101 multiply -10 9E+999999999 -> -9.9999E+999999999 Overflow Inexact Rounded -rovx102 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded -rovx104 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded +rovx102 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded Clamped +rovx104 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded Clamped rounding: up rovx110 multiply 10 9E+999999999 -> Infinity Overflow Inexact Rounded @@ -993,31 +996,31 @@ rovx120 multiply 10 9E+999999999 -> Infinity Overflow Inexact Rounded rovx121 multiply -10 9E+999999999 -> -9.9999E+999999999 Overflow Inexact Rounded rovx122 divide 1E-9 9E+999999999 -> 1E-1000000003 Underflow Subnormal Inexact Rounded -rovx124 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded +rovx124 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded Clamped rounding: floor rovx130 multiply 10 9E+999999999 -> 9.9999E+999999999 Overflow Inexact Rounded rovx131 multiply -10 9E+999999999 -> -Infinity Overflow Inexact Rounded -rovx132 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded +rovx132 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded Clamped rovx134 divide -1E-9 9E+999999999 -> -1E-1000000003 Underflow Subnormal Inexact Rounded rounding: half_up rovx140 multiply 10 9E+999999999 -> Infinity Overflow Inexact Rounded rovx141 multiply -10 9E+999999999 -> -Infinity Overflow Inexact Rounded -rovx142 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded -rovx144 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded +rovx142 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded Clamped +rovx144 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded Clamped rounding: half_even rovx150 multiply 10 9E+999999999 -> Infinity Overflow Inexact Rounded rovx151 multiply -10 9E+999999999 -> -Infinity Overflow Inexact Rounded -rovx152 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded -rovx154 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded +rovx152 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded Clamped +rovx154 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded Clamped rounding: half_down rovx160 multiply 10 9E+999999999 -> Infinity Overflow Inexact Rounded rovx161 multiply -10 9E+999999999 -> -Infinity Overflow Inexact Rounded -rovx162 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded -rovx164 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded +rovx162 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded Clamped +rovx164 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded Clamped -- check maximum finite value over a range of precisions rounding: down @@ -1077,3 +1080,224 @@ rmex412 multiply -9.999E+999999999 10 -> -9.99999999E+999999999 Overflow Inexact Rounded rmex413 multiply 9.999E+999999999 10 -> 9.99999999E+999999999 Overflow Inexact Rounded +----- Round-for-reround ----- +rounding: 05up +precision: 5 -- for easier visual inspection +maxExponent: 999 +minexponent: -999 + +-- basic rounding; really is just 0 and 5 up +r05up001 add 12340 0.001 -> 12341 Inexact Rounded +r05up002 add 12341 0.001 -> 12341 Inexact Rounded +r05up003 add 12342 0.001 -> 12342 Inexact Rounded +r05up004 add 12343 0.001 -> 12343 Inexact Rounded +r05up005 add 12344 0.001 -> 12344 Inexact Rounded +r05up006 add 12345 0.001 -> 12346 Inexact Rounded +r05up007 add 12346 0.001 -> 12346 Inexact Rounded +r05up008 add 12347 0.001 -> 12347 Inexact Rounded +r05up009 add 12348 0.001 -> 12348 Inexact Rounded +r05up010 add 12349 0.001 -> 12349 Inexact Rounded + +r05up011 add 12340 0.000 -> 12340 Rounded +r05up012 add 12341 0.000 -> 12341 Rounded +r05up013 add 12342 0.000 -> 12342 Rounded +r05up014 add 12343 0.000 -> 12343 Rounded +r05up015 add 12344 0.000 -> 12344 Rounded +r05up016 add 12345 0.000 -> 12345 Rounded +r05up017 add 12346 0.000 -> 12346 Rounded +r05up018 add 12347 0.000 -> 12347 Rounded +r05up019 add 12348 0.000 -> 12348 Rounded +r05up020 add 12349 0.000 -> 12349 Rounded + +r05up021 add 12340 0.901 -> 12341 Inexact Rounded +r05up022 add 12341 0.901 -> 12341 Inexact Rounded +r05up023 add 12342 0.901 -> 12342 Inexact Rounded +r05up024 add 12343 0.901 -> 12343 Inexact Rounded +r05up025 add 12344 0.901 -> 12344 Inexact Rounded +r05up026 add 12345 0.901 -> 12346 Inexact Rounded +r05up027 add 12346 0.901 -> 12346 Inexact Rounded +r05up028 add 12347 0.901 -> 12347 Inexact Rounded +r05up029 add 12348 0.901 -> 12348 Inexact Rounded +r05up030 add 12349 0.901 -> 12349 Inexact Rounded + +r05up031 add -12340 -0.001 -> -12341 Inexact Rounded +r05up032 add -12341 -0.001 -> -12341 Inexact Rounded +r05up033 add -12342 -0.001 -> -12342 Inexact Rounded +r05up034 add -12343 -0.001 -> -12343 Inexact Rounded +r05up035 add -12344 -0.001 -> -12344 Inexact Rounded +r05up036 add -12345 -0.001 -> -12346 Inexact Rounded +r05up037 add -12346 -0.001 -> -12346 Inexact Rounded +r05up038 add -12347 -0.001 -> -12347 Inexact Rounded +r05up039 add -12348 -0.001 -> -12348 Inexact Rounded +r05up040 add -12349 -0.001 -> -12349 Inexact Rounded + +r05up041 add -12340 0.001 -> -12339 Inexact Rounded +r05up042 add -12341 0.001 -> -12341 Inexact Rounded +r05up043 add -12342 0.001 -> -12341 Inexact Rounded +r05up044 add -12343 0.001 -> -12342 Inexact Rounded +r05up045 add -12344 0.001 -> -12343 Inexact Rounded +r05up046 add -12345 0.001 -> -12344 Inexact Rounded +r05up047 add -12346 0.001 -> -12346 Inexact Rounded +r05up048 add -12347 0.001 -> -12346 Inexact Rounded +r05up049 add -12348 0.001 -> -12347 Inexact Rounded +r05up050 add -12349 0.001 -> -12348 Inexact Rounded + +-- Addition operators ------------------------------------------------- +-- [The first few of these check negative residue possibilities; these +-- cases may be implemented as a negative residue in fastpaths] + +r0adx100 add 12345 -0.1 -> 12344 Inexact Rounded +r0adx101 add 12345 -0.01 -> 12344 Inexact Rounded +r0adx102 add 12345 -0.001 -> 12344 Inexact Rounded +r0adx103 add 12345 -0.00001 -> 12344 Inexact Rounded +r0adx104 add 12345 -0.000001 -> 12344 Inexact Rounded +r0adx105 add 12345 -0.0000001 -> 12344 Inexact Rounded +r0adx106 add 12345 0 -> 12345 +r0adx107 add 12345 0.0000001 -> 12346 Inexact Rounded +r0adx108 add 12345 0.000001 -> 12346 Inexact Rounded +r0adx109 add 12345 0.00001 -> 12346 Inexact Rounded +r0adx110 add 12345 0.0001 -> 12346 Inexact Rounded +r0adx111 add 12345 0.001 -> 12346 Inexact Rounded +r0adx112 add 12345 0.01 -> 12346 Inexact Rounded +r0adx113 add 12345 0.1 -> 12346 Inexact Rounded + +r0adx115 add 12346 0.49999 -> 12346 Inexact Rounded +r0adx116 add 12346 0.5 -> 12346 Inexact Rounded +r0adx117 add 12346 0.50001 -> 12346 Inexact Rounded + +r0adx120 add 12345 0.4 -> 12346 Inexact Rounded +r0adx121 add 12345 0.49 -> 12346 Inexact Rounded +r0adx122 add 12345 0.499 -> 12346 Inexact Rounded +r0adx123 add 12345 0.49999 -> 12346 Inexact Rounded +r0adx124 add 12345 0.5 -> 12346 Inexact Rounded +r0adx125 add 12345 0.50001 -> 12346 Inexact Rounded +r0adx126 add 12345 0.5001 -> 12346 Inexact Rounded +r0adx127 add 12345 0.501 -> 12346 Inexact Rounded +r0adx128 add 12345 0.51 -> 12346 Inexact Rounded +r0adx129 add 12345 0.6 -> 12346 Inexact Rounded + +-- negatives... + +r0sux100 add -12345 -0.1 -> -12346 Inexact Rounded +r0sux101 add -12345 -0.01 -> -12346 Inexact Rounded +r0sux102 add -12345 -0.001 -> -12346 Inexact Rounded +r0sux103 add -12345 -0.00001 -> -12346 Inexact Rounded +r0sux104 add -12345 -0.000001 -> -12346 Inexact Rounded +r0sux105 add -12345 -0.0000001 -> -12346 Inexact Rounded +r0sux106 add -12345 0 -> -12345 +r0sux107 add -12345 0.0000001 -> -12344 Inexact Rounded +r0sux108 add -12345 0.000001 -> -12344 Inexact Rounded +r0sux109 add -12345 0.00001 -> -12344 Inexact Rounded +r0sux110 add -12345 0.0001 -> -12344 Inexact Rounded +r0sux111 add -12345 0.001 -> -12344 Inexact Rounded +r0sux112 add -12345 0.01 -> -12344 Inexact Rounded +r0sux113 add -12345 0.1 -> -12344 Inexact Rounded + +r0sux115 add -12346 0.49999 -> -12346 Inexact Rounded +r0sux116 add -12346 0.5 -> -12346 Inexact Rounded +r0sux117 add -12346 0.50001 -> -12346 Inexact Rounded + +r0sux120 add -12345 0.4 -> -12344 Inexact Rounded +r0sux121 add -12345 0.49 -> -12344 Inexact Rounded +r0sux122 add -12345 0.499 -> -12344 Inexact Rounded +r0sux123 add -12345 0.49999 -> -12344 Inexact Rounded +r0sux124 add -12345 0.5 -> -12344 Inexact Rounded +r0sux125 add -12345 0.50001 -> -12344 Inexact Rounded +r0sux126 add -12345 0.5001 -> -12344 Inexact Rounded +r0sux127 add -12345 0.501 -> -12344 Inexact Rounded +r0sux128 add -12345 0.51 -> -12344 Inexact Rounded +r0sux129 add -12345 0.6 -> -12344 Inexact Rounded + +-- Check cancellation subtractions +-- (The IEEE 854 'curious rule' in $6.3) + +r0zex001 add 0 0 -> 0 +r0zex002 add 0 -0 -> 0 +r0zex003 add -0 0 -> 0 +r0zex004 add -0 -0 -> -0 +r0zex005 add 1 -1 -> 0 +r0zex006 add -1 1 -> 0 +r0zex007 add 1.5 -1.5 -> 0.0 +r0zex008 add -1.5 1.5 -> 0.0 +r0zex009 add 2 -2 -> 0 +r0zex010 add -2 2 -> 0 + + +-- Division operators ------------------------------------------------- + +r0dvx101 divide 12345 1 -> 12345 +r0dvx102 divide 12345 1.0001 -> 12343 Inexact Rounded +r0dvx103 divide 12345 1.001 -> 12332 Inexact Rounded +r0dvx104 divide 12345 1.01 -> 12222 Inexact Rounded +r0dvx105 divide 12345 1.1 -> 11222 Inexact Rounded +r0dvx106 divide 12355 4 -> 3088.7 Inexact Rounded +r0dvx107 divide 12345 4 -> 3086.2 Inexact Rounded +r0dvx108 divide 12355 4.0001 -> 3088.6 Inexact Rounded +r0dvx109 divide 12345 4.0001 -> 3086.1 Inexact Rounded +r0dvx110 divide 12345 4.9 -> 2519.3 Inexact Rounded +r0dvx111 divide 12345 4.99 -> 2473.9 Inexact Rounded +r0dvx112 divide 12345 4.999 -> 2469.4 Inexact Rounded +r0dvx113 divide 12345 4.9999 -> 2469.1 Inexact Rounded +r0dvx114 divide 12345 5 -> 2469 +r0dvx115 divide 12345 5.0001 -> 2468.9 Inexact Rounded +r0dvx116 divide 12345 5.001 -> 2468.6 Inexact Rounded +r0dvx117 divide 12345 5.01 -> 2464.1 Inexact Rounded +r0dvx118 divide 12345 5.1 -> 2420.6 Inexact Rounded + +-- [divideInteger and remainder unaffected] + +-- Multiplication operator -------------------------------------------- + +r0mux101 multiply 12345 1 -> 12345 +r0mux102 multiply 12345 1.0001 -> 12346 Inexact Rounded +r0mux103 multiply 12345 1.001 -> 12357 Inexact Rounded +r0mux104 multiply 12345 1.01 -> 12468 Inexact Rounded +r0mux105 multiply 12345 1.1 -> 13579 Inexact Rounded +r0mux106 multiply 12345 4 -> 49380 +r0mux107 multiply 12345 4.0001 -> 49381 Inexact Rounded +r0mux108 multiply 12345 4.9 -> 60491 Inexact Rounded +r0mux109 multiply 12345 4.99 -> 61601 Inexact Rounded +r0mux110 multiply 12345 4.999 -> 61712 Inexact Rounded +r0mux111 multiply 12345 4.9999 -> 61723 Inexact Rounded +r0mux112 multiply 12345 5 -> 61725 +r0mux113 multiply 12345 5.0001 -> 61726 Inexact Rounded +r0mux114 multiply 12345 5.001 -> 61737 Inexact Rounded +r0mux115 multiply 12345 5.01 -> 61848 Inexact Rounded +r0mux116 multiply 12345 12 -> 1.4814E+5 Rounded +r0mux117 multiply 12345 13 -> 1.6048E+5 Inexact Rounded +r0mux118 multiply 12355 12 -> 1.4826E+5 Rounded +r0mux119 multiply 12355 13 -> 1.6061E+5 Inexact Rounded + + +-- Power operator ----------------------------------------------------- + +r0pox101 power 12345 -5 -> 3.4877E-21 Inexact Rounded +r0pox102 power 12345 -4 -> 4.3056E-17 Inexact Rounded +r0pox103 power 12345 -3 -> 5.3152E-13 Inexact Rounded +r0pox104 power 12345 -2 -> 6.5617E-9 Inexact Rounded +r0pox105 power 12345 -1 -> 0.000081004 Inexact Rounded +r0pox106 power 12345 0 -> 1 +r0pox107 power 12345 1 -> 12345 +r0pox108 power 12345 2 -> 1.5239E+8 Inexact Rounded +r0pox109 power 12345 3 -> 1.8813E+12 Inexact Rounded +r0pox110 power 12345 4 -> 2.3226E+16 Inexact Rounded +r0pox111 power 12345 5 -> 2.8671E+20 Inexact Rounded +r0pox112 power 415 2 -> 1.7222E+5 Inexact Rounded +r0pox113 power 75 3 -> 4.2187E+5 Inexact Rounded + + +-- Underflow Subnormal and overflow values vary with rounding mode and sign +maxexponent: 999999999 +minexponent: -999999999 +-- [round down gives Nmax on first two and .0E... on the next two] +r0ovx100 multiply 10 9E+999999999 -> 9.9999E+999999999 Overflow Inexact Rounded +r0ovx101 multiply -10 9E+999999999 -> -9.9999E+999999999 Overflow Inexact Rounded +r0ovx102 divide 1E-9 9E+999999999 -> 1E-1000000003 Underflow Subnormal Inexact Rounded +r0ovx104 divide -1E-9 9E+999999999 -> -1E-1000000003 Underflow Subnormal Inexact Rounded + +-- reprise rounding mode effect (using multiplies so precision directive used) +precision: 9 +maxexponent: 999999999 +r0mex412 multiply -9.999E+999999999 10 -> -9.99999999E+999999999 Overflow Inexact Rounded +r0mex413 multiply 9.999E+999999999 10 -> 9.99999999E+999999999 Overflow Inexact Rounded + Modified: python/branches/py3k/Lib/test/decimaltestdata/samequantum.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/samequantum.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/samequantum.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- samequantum.decTest -- check quantums match -- --- Copyright (c) IBM Corporation, 2001, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 2001, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -64,8 +64,44 @@ samq048 samequantum -0E-17 -0.0E-16 -> 1 samq049 samequantum -0E-17 -0.0E-17 -> 0 --- specials & combinations +-- Nmax, Nmin, Ntiny +samq051 samequantum 9.99999999E+999 9.99999999E+999 -> 1 +samq052 samequantum 1E-999 1E-999 -> 1 +samq053 samequantum 1.00000000E-999 1.00000000E-999 -> 1 +samq054 samequantum 1E-1007 1E-1007 -> 1 +samq055 samequantum 9.99999999E+999 9.99999999E+999 -> 1 +samq056 samequantum 1E-999 1E-999 -> 1 +samq057 samequantum 1.00000000E-999 1.00000000E-999 -> 1 +samq058 samequantum 1E-1007 1E-1007 -> 1 + +samq061 samequantum -1E-1007 -1E-1007 -> 1 +samq062 samequantum -1.00000000E-999 -1.00000000E-999 -> 1 +samq063 samequantum -1E-999 -1E-999 -> 1 +samq064 samequantum -9.99999999E+999 -9.99999999E+999 -> 1 +samq065 samequantum -1E-1007 -1E-1007 -> 1 +samq066 samequantum -1.00000000E-999 -1.00000000E-999 -> 1 +samq067 samequantum -1E-999 -1E-999 -> 1 +samq068 samequantum -9.99999999E+999 -9.99999999E+999 -> 1 + +samq071 samequantum -4E-1007 -1E-1007 -> 1 +samq072 samequantum -4.00000000E-999 -1.00004000E-999 -> 1 +samq073 samequantum -4E-999 -1E-999 -> 1 +samq074 samequantum -4.99999999E+999 -9.99949999E+999 -> 1 +samq075 samequantum -4E-1007 -1E-1007 -> 1 +samq076 samequantum -4.00000000E-999 -1.00400000E-999 -> 1 +samq077 samequantum -4E-999 -1E-999 -> 1 +samq078 samequantum -4.99999999E+999 -9.94999999E+999 -> 1 + +samq081 samequantum -4E-1006 -1E-1007 -> 0 +samq082 samequantum -4.00000000E-999 -1.00004000E-996 -> 0 +samq083 samequantum -4E-996 -1E-999 -> 0 +samq084 samequantum -4.99999999E+999 -9.99949999E+996 -> 0 +samq085 samequantum -4E-1006 -1E-1007 -> 0 +samq086 samequantum -4.00000000E-999 -1.00400000E-996 -> 0 +samq087 samequantum -4E-996 -1E-999 -> 0 +samq088 samequantum -4.99999999E+999 -9.94999999E+996 -> 0 +-- specials & combinations samq0110 samequantum -Inf -Inf -> 1 samq0111 samequantum -Inf Inf -> 1 samq0112 samequantum -Inf NaN -> 0 Modified: python/branches/py3k/Lib/test/decimaltestdata/squareroot.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/squareroot.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/squareroot.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- squareroot.decTest -- decimal square root -- --- Copyright (c) IBM Corporation, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 2003, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -102,6 +102,8 @@ sqtx075 squareroot -100.00 -> NaN Invalid_operation sqtx076 squareroot -1.1000E+3 -> NaN Invalid_operation sqtx077 squareroot -1.10000E+3 -> NaN Invalid_operation +sqtx078 squareroot 1.000 -> 1.00 +sqtx079 squareroot 1.0000 -> 1.00 -- famous squares sqtx080 squareroot 1 -> 1 @@ -2926,19 +2928,26 @@ precision: 11 -- Etiny=-19 sqtx804 squareroot 1E-19 -> 3.162277660E-10 Underflow Subnormal Inexact Rounded -sqtx805 squareroot 10E-19 -> 1.0E-9 +sqtx805 squareroot 10E-19 -> 1.0E-9 -- exact precision: 12 -- Etiny=-20 sqtx806 squareroot 10E-20 -> 3.1622776602E-10 Underflow Subnormal Inexact Rounded -sqtx807 squareroot 1E-20 -> 1E-10 Subnormal -- Exact Subnormal case +sqtx807 squareroot 1E-20 -> 1E-10 Subnormal -- exact Subnormal case precision: 13 -- Etiny=-21 sqtx808 squareroot 1E-21 -> 3.1622776602E-11 Underflow Subnormal Inexact Rounded -sqtx809 squareroot 10E-21 -> 1.0E-10 Subnormal +sqtx809 squareroot 10E-21 -> 1.0E-10 Subnormal -- exact Subnormal case precision: 14 -- Etiny=-22 sqtx810 squareroot 1E-21 -> 3.16227766017E-11 Underflow Subnormal Inexact Rounded sqtx811 squareroot 10E-22 -> 3.16227766017E-11 Underflow Subnormal Inexact Rounded -sqtx812 squareroot 1E-22 -> 1E-11 Subnormal -- Exact Subnormal case +sqtx812 squareroot 1E-22 -> 1E-11 Subnormal -- exact Subnormal case +-- Not enough digits? +precision: 16 +maxExponent: 384 +minExponent: -383 +rounding: half_even +sqtx815 squareroot 1.0000000001000000E-78 -> 1.000000000050000E-39 Inexact Rounded +-- 1 234567890123456 -- special values maxexponent: 999 @@ -2954,5 +2963,842 @@ sqtx827 squareroot -NaN654 -> -NaN654 sqtx828 squareroot NaN1 -> NaN1 +-- payload decapitate +precision: 5 +sqtx840 squareroot -sNaN1234567890 -> -NaN67890 Invalid_operation + +------------------------------------------------------------------------ +-- +-- Special thanks to Mark Dickinson for tests in the range 8000-8999. +-- +-- Extra tests for the square root function, dealing with a variety of +-- corner cases. In particular, these tests concentrate on +-- (1) cases where the input precision exceeds the context precision, and +-- (2) cases where the input exponent is outside the current context, +-- and in particular when the result is subnormal +-- +-- maxexponent and minexponent are set to 9 and -9 for most of these +-- cases; only the precision changes. The rounding also does not +-- change, because it is ignored for this operation. +maxexponent: 9 +minexponent: -9 + +-- exact results, input precision > context precision +precision: 1 +sqtx8000 squareroot 0 -> 0 +sqtx8001 squareroot 1 -> 1 +sqtx8002 squareroot 4 -> 2 +sqtx8003 squareroot 9 -> 3 +sqtx8004 squareroot 16 -> 4 +sqtx8005 squareroot 25 -> 5 +sqtx8006 squareroot 36 -> 6 +sqtx8007 squareroot 49 -> 7 +sqtx8008 squareroot 64 -> 8 +sqtx8009 squareroot 81 -> 9 +sqtx8010 squareroot 100 -> 1E+1 Rounded +sqtx8011 squareroot 121 -> 1E+1 Inexact Rounded + +precision: 2 +sqtx8012 squareroot 0 -> 0 +sqtx8013 squareroot 1 -> 1 +sqtx8014 squareroot 4 -> 2 +sqtx8015 squareroot 9 -> 3 +sqtx8016 squareroot 16 -> 4 +sqtx8017 squareroot 25 -> 5 +sqtx8018 squareroot 36 -> 6 +sqtx8019 squareroot 49 -> 7 +sqtx8020 squareroot 64 -> 8 +sqtx8021 squareroot 81 -> 9 +sqtx8022 squareroot 100 -> 10 +sqtx8023 squareroot 121 -> 11 +sqtx8024 squareroot 144 -> 12 +sqtx8025 squareroot 169 -> 13 +sqtx8026 squareroot 196 -> 14 +sqtx8027 squareroot 225 -> 15 +sqtx8028 squareroot 256 -> 16 +sqtx8029 squareroot 289 -> 17 +sqtx8030 squareroot 324 -> 18 +sqtx8031 squareroot 361 -> 19 +sqtx8032 squareroot 400 -> 20 +sqtx8033 squareroot 441 -> 21 +sqtx8034 squareroot 484 -> 22 +sqtx8035 squareroot 529 -> 23 +sqtx8036 squareroot 576 -> 24 +sqtx8037 squareroot 625 -> 25 +sqtx8038 squareroot 676 -> 26 +sqtx8039 squareroot 729 -> 27 +sqtx8040 squareroot 784 -> 28 +sqtx8041 squareroot 841 -> 29 +sqtx8042 squareroot 900 -> 30 +sqtx8043 squareroot 961 -> 31 +sqtx8044 squareroot 1024 -> 32 +sqtx8045 squareroot 1089 -> 33 +sqtx8046 squareroot 1156 -> 34 +sqtx8047 squareroot 1225 -> 35 +sqtx8048 squareroot 1296 -> 36 +sqtx8049 squareroot 1369 -> 37 +sqtx8050 squareroot 1444 -> 38 +sqtx8051 squareroot 1521 -> 39 +sqtx8052 squareroot 1600 -> 40 +sqtx8053 squareroot 1681 -> 41 +sqtx8054 squareroot 1764 -> 42 +sqtx8055 squareroot 1849 -> 43 +sqtx8056 squareroot 1936 -> 44 +sqtx8057 squareroot 2025 -> 45 +sqtx8058 squareroot 2116 -> 46 +sqtx8059 squareroot 2209 -> 47 +sqtx8060 squareroot 2304 -> 48 +sqtx8061 squareroot 2401 -> 49 +sqtx8062 squareroot 2500 -> 50 +sqtx8063 squareroot 2601 -> 51 +sqtx8064 squareroot 2704 -> 52 +sqtx8065 squareroot 2809 -> 53 +sqtx8066 squareroot 2916 -> 54 +sqtx8067 squareroot 3025 -> 55 +sqtx8068 squareroot 3136 -> 56 +sqtx8069 squareroot 3249 -> 57 +sqtx8070 squareroot 3364 -> 58 +sqtx8071 squareroot 3481 -> 59 +sqtx8072 squareroot 3600 -> 60 +sqtx8073 squareroot 3721 -> 61 +sqtx8074 squareroot 3844 -> 62 +sqtx8075 squareroot 3969 -> 63 +sqtx8076 squareroot 4096 -> 64 +sqtx8077 squareroot 4225 -> 65 +sqtx8078 squareroot 4356 -> 66 +sqtx8079 squareroot 4489 -> 67 +sqtx8080 squareroot 4624 -> 68 +sqtx8081 squareroot 4761 -> 69 +sqtx8082 squareroot 4900 -> 70 +sqtx8083 squareroot 5041 -> 71 +sqtx8084 squareroot 5184 -> 72 +sqtx8085 squareroot 5329 -> 73 +sqtx8086 squareroot 5476 -> 74 +sqtx8087 squareroot 5625 -> 75 +sqtx8088 squareroot 5776 -> 76 +sqtx8089 squareroot 5929 -> 77 +sqtx8090 squareroot 6084 -> 78 +sqtx8091 squareroot 6241 -> 79 +sqtx8092 squareroot 6400 -> 80 +sqtx8093 squareroot 6561 -> 81 +sqtx8094 squareroot 6724 -> 82 +sqtx8095 squareroot 6889 -> 83 +sqtx8096 squareroot 7056 -> 84 +sqtx8097 squareroot 7225 -> 85 +sqtx8098 squareroot 7396 -> 86 +sqtx8099 squareroot 7569 -> 87 +sqtx8100 squareroot 7744 -> 88 +sqtx8101 squareroot 7921 -> 89 +sqtx8102 squareroot 8100 -> 90 +sqtx8103 squareroot 8281 -> 91 +sqtx8104 squareroot 8464 -> 92 +sqtx8105 squareroot 8649 -> 93 +sqtx8106 squareroot 8836 -> 94 +sqtx8107 squareroot 9025 -> 95 +sqtx8108 squareroot 9216 -> 96 +sqtx8109 squareroot 9409 -> 97 +sqtx8110 squareroot 9604 -> 98 +sqtx8111 squareroot 9801 -> 99 +sqtx8112 squareroot 10000 -> 1.0E+2 Rounded +sqtx8113 squareroot 10201 -> 1.0E+2 Inexact Rounded + +precision: 3 +sqtx8114 squareroot 841 -> 29 +sqtx8115 squareroot 1600 -> 40 +sqtx8116 squareroot 2209 -> 47 +sqtx8117 squareroot 9604 -> 98 +sqtx8118 squareroot 21316 -> 146 +sqtx8119 squareroot 52441 -> 229 +sqtx8120 squareroot 68644 -> 262 +sqtx8121 squareroot 69696 -> 264 +sqtx8122 squareroot 70225 -> 265 +sqtx8123 squareroot 76729 -> 277 +sqtx8124 squareroot 130321 -> 361 +sqtx8125 squareroot 171396 -> 414 +sqtx8126 squareroot 270400 -> 520 +sqtx8127 squareroot 279841 -> 529 +sqtx8128 squareroot 407044 -> 638 +sqtx8129 squareroot 408321 -> 639 +sqtx8130 squareroot 480249 -> 693 +sqtx8131 squareroot 516961 -> 719 +sqtx8132 squareroot 692224 -> 832 +sqtx8133 squareroot 829921 -> 911 + +-- selection of random exact results +precision: 6 +sqtx8134 squareroot 2.25E-12 -> 0.0000015 +sqtx8135 squareroot 8.41E-14 -> 2.9E-7 +sqtx8136 squareroot 6.241E-15 -> 7.9E-8 +sqtx8137 squareroot 5.041E+13 -> 7.1E+6 +sqtx8138 squareroot 4761 -> 69 +sqtx8139 squareroot 1.369E+17 -> 3.7E+8 +sqtx8140 squareroot 0.00002116 -> 0.0046 +sqtx8141 squareroot 7.29E+4 -> 2.7E+2 +sqtx8142 squareroot 4.624E-13 -> 6.8E-7 +sqtx8143 squareroot 3.969E+5 -> 6.3E+2 +sqtx8144 squareroot 3.73321E-11 -> 0.00000611 +sqtx8145 squareroot 5.61001E+17 -> 7.49E+8 +sqtx8146 squareroot 2.30400E-11 -> 0.00000480 +sqtx8147 squareroot 4.30336E+17 -> 6.56E+8 +sqtx8148 squareroot 0.057121 -> 0.239 +sqtx8149 squareroot 7.225E+17 -> 8.5E+8 +sqtx8150 squareroot 3.14721E+13 -> 5.61E+6 +sqtx8151 squareroot 4.61041E+17 -> 6.79E+8 +sqtx8152 squareroot 1.39876E-15 -> 3.74E-8 +sqtx8153 squareroot 6.19369E-9 -> 0.0000787 +sqtx8154 squareroot 1.620529E-10 -> 0.00001273 +sqtx8155 squareroot 1177.1761 -> 34.31 +sqtx8156 squareroot 67043344 -> 8188 +sqtx8157 squareroot 4.84E+6 -> 2.2E+3 +sqtx8158 squareroot 1.23904E+11 -> 3.52E+5 +sqtx8159 squareroot 32604100 -> 5710 +sqtx8160 squareroot 2.9757025E-11 -> 0.000005455 +sqtx8161 squareroot 6.3760225E-9 -> 0.00007985 +sqtx8162 squareroot 4.5198729E-11 -> 0.000006723 +sqtx8163 squareroot 1.4745600E-11 -> 0.000003840 +sqtx8164 squareroot 18964283.04 -> 4354.8 +sqtx8165 squareroot 3.308895529E+13 -> 5.7523E+6 +sqtx8166 squareroot 0.0028590409 -> 0.05347 +sqtx8167 squareroot 3572.213824 -> 59.768 +sqtx8168 squareroot 4.274021376E+15 -> 6.5376E+7 +sqtx8169 squareroot 4455476.64 -> 2110.8 +sqtx8170 squareroot 38.44 -> 6.2 +sqtx8171 squareroot 68.558400 -> 8.280 +sqtx8172 squareroot 715402009 -> 26747 +sqtx8173 squareroot 93.373569 -> 9.663 +sqtx8174 squareroot 2.62144000000E+15 -> 5.12000E+7 +sqtx8175 squareroot 7.48225000000E+15 -> 8.65000E+7 +sqtx8176 squareroot 3.38724000000E-9 -> 0.0000582000 +sqtx8177 squareroot 5.64001000000E-13 -> 7.51000E-7 +sqtx8178 squareroot 5.06944000000E-15 -> 7.12000E-8 +sqtx8179 squareroot 4.95616000000E+17 -> 7.04000E+8 +sqtx8180 squareroot 0.0000242064000000 -> 0.00492000 +sqtx8181 squareroot 1.48996000000E-15 -> 3.86000E-8 +sqtx8182 squareroot 9.37024000000E+17 -> 9.68000E+8 +sqtx8183 squareroot 7128900.0000 -> 2670.00 +sqtx8184 squareroot 8.2311610000E-10 -> 0.0000286900 +sqtx8185 squareroot 482747040000 -> 694800 +sqtx8186 squareroot 4.14478440000E+17 -> 6.43800E+8 +sqtx8187 squareroot 5.10510250000E-7 -> 0.000714500 +sqtx8188 squareroot 355096.810000 -> 595.900 +sqtx8189 squareroot 14288400.0000 -> 3780.00 +sqtx8190 squareroot 3.36168040000E-15 -> 5.79800E-8 +sqtx8191 squareroot 1.70899560000E-13 -> 4.13400E-7 +sqtx8192 squareroot 0.0000378348010000 -> 0.00615100 +sqtx8193 squareroot 2.00972890000E-13 -> 4.48300E-7 +sqtx8194 squareroot 4.07222659600E-13 -> 6.38140E-7 +sqtx8195 squareroot 131486012100 -> 362610 +sqtx8196 squareroot 818192611600 -> 904540 +sqtx8197 squareroot 9.8558323600E+16 -> 3.13940E+8 +sqtx8198 squareroot 5641.06144900 -> 75.1070 +sqtx8199 squareroot 4.58789475600E+17 -> 6.77340E+8 +sqtx8200 squareroot 3.21386948100E-9 -> 0.0000566910 +sqtx8201 squareroot 3.9441960000E-8 -> 0.000198600 +sqtx8202 squareroot 242723.728900 -> 492.670 +sqtx8203 squareroot 1874.89000000 -> 43.3000 +sqtx8204 squareroot 2.56722595684E+15 -> 5.06678E+7 +sqtx8205 squareroot 3.96437714689E-17 -> 6.29633E-9 +sqtx8206 squareroot 3.80106774784E-17 -> 6.16528E-9 +sqtx8207 squareroot 1.42403588496E-13 -> 3.77364E-7 +sqtx8208 squareroot 4604.84388100 -> 67.8590 +sqtx8209 squareroot 2157100869.16 -> 46444.6 +sqtx8210 squareroot 355288570.81 -> 18849.1 +sqtx8211 squareroot 4.69775901604E-11 -> 0.00000685402 +sqtx8212 squareroot 8.22115770436E+17 -> 9.06706E+8 +sqtx8213 squareroot 7.16443744900E+15 -> 8.46430E+7 +sqtx8214 squareroot 9.48995498896E+15 -> 9.74164E+7 +sqtx8215 squareroot 0.0000419091801129 -> 0.00647373 +sqtx8216 squareroot 5862627996.84 -> 76567.8 +sqtx8217 squareroot 9369537.3409 -> 3060.97 +sqtx8218 squareroot 7.74792529729E+17 -> 8.80223E+8 +sqtx8219 squareroot 1.08626931396E+17 -> 3.29586E+8 +sqtx8220 squareroot 8.89584739684E-7 -> 0.000943178 +sqtx8221 squareroot 4.0266040896E-18 -> 2.00664E-9 +sqtx8222 squareroot 9.27669480336E-7 -> 0.000963156 +sqtx8223 squareroot 0.00225497717956 -> 0.0474866 + +-- test use of round-half-even for ties +precision: 1 +sqtx8224 squareroot 225 -> 2E+1 Inexact Rounded +sqtx8225 squareroot 625 -> 2E+1 Inexact Rounded +sqtx8226 squareroot 1225 -> 4E+1 Inexact Rounded +sqtx8227 squareroot 2025 -> 4E+1 Inexact Rounded +sqtx8228 squareroot 3025 -> 6E+1 Inexact Rounded +sqtx8229 squareroot 4225 -> 6E+1 Inexact Rounded +sqtx8230 squareroot 5625 -> 8E+1 Inexact Rounded +sqtx8231 squareroot 7225 -> 8E+1 Inexact Rounded +sqtx8232 squareroot 9025 -> 1E+2 Inexact Rounded + +precision: 2 +sqtx8233 squareroot 11025 -> 1.0E+2 Inexact Rounded +sqtx8234 squareroot 13225 -> 1.2E+2 Inexact Rounded +sqtx8235 squareroot 15625 -> 1.2E+2 Inexact Rounded +sqtx8236 squareroot 18225 -> 1.4E+2 Inexact Rounded +sqtx8237 squareroot 21025 -> 1.4E+2 Inexact Rounded +sqtx8238 squareroot 24025 -> 1.6E+2 Inexact Rounded +sqtx8239 squareroot 27225 -> 1.6E+2 Inexact Rounded +sqtx8240 squareroot 30625 -> 1.8E+2 Inexact Rounded +sqtx8241 squareroot 34225 -> 1.8E+2 Inexact Rounded +sqtx8242 squareroot 38025 -> 2.0E+2 Inexact Rounded +sqtx8243 squareroot 42025 -> 2.0E+2 Inexact Rounded +sqtx8244 squareroot 46225 -> 2.2E+2 Inexact Rounded +sqtx8245 squareroot 50625 -> 2.2E+2 Inexact Rounded +sqtx8246 squareroot 55225 -> 2.4E+2 Inexact Rounded +sqtx8247 squareroot 60025 -> 2.4E+2 Inexact Rounded +sqtx8248 squareroot 65025 -> 2.6E+2 Inexact Rounded +sqtx8249 squareroot 70225 -> 2.6E+2 Inexact Rounded +sqtx8250 squareroot 75625 -> 2.8E+2 Inexact Rounded +sqtx8251 squareroot 81225 -> 2.8E+2 Inexact Rounded +sqtx8252 squareroot 87025 -> 3.0E+2 Inexact Rounded +sqtx8253 squareroot 93025 -> 3.0E+2 Inexact Rounded +sqtx8254 squareroot 99225 -> 3.2E+2 Inexact Rounded +sqtx8255 squareroot 105625 -> 3.2E+2 Inexact Rounded +sqtx8256 squareroot 112225 -> 3.4E+2 Inexact Rounded +sqtx8257 squareroot 119025 -> 3.4E+2 Inexact Rounded +sqtx8258 squareroot 126025 -> 3.6E+2 Inexact Rounded +sqtx8259 squareroot 133225 -> 3.6E+2 Inexact Rounded +sqtx8260 squareroot 140625 -> 3.8E+2 Inexact Rounded +sqtx8261 squareroot 148225 -> 3.8E+2 Inexact Rounded +sqtx8262 squareroot 156025 -> 4.0E+2 Inexact Rounded +sqtx8263 squareroot 164025 -> 4.0E+2 Inexact Rounded +sqtx8264 squareroot 172225 -> 4.2E+2 Inexact Rounded +sqtx8265 squareroot 180625 -> 4.2E+2 Inexact Rounded +sqtx8266 squareroot 189225 -> 4.4E+2 Inexact Rounded +sqtx8267 squareroot 198025 -> 4.4E+2 Inexact Rounded +sqtx8268 squareroot 207025 -> 4.6E+2 Inexact Rounded +sqtx8269 squareroot 216225 -> 4.6E+2 Inexact Rounded +sqtx8270 squareroot 225625 -> 4.8E+2 Inexact Rounded +sqtx8271 squareroot 235225 -> 4.8E+2 Inexact Rounded +sqtx8272 squareroot 245025 -> 5.0E+2 Inexact Rounded +sqtx8273 squareroot 255025 -> 5.0E+2 Inexact Rounded +sqtx8274 squareroot 265225 -> 5.2E+2 Inexact Rounded +sqtx8275 squareroot 275625 -> 5.2E+2 Inexact Rounded +sqtx8276 squareroot 286225 -> 5.4E+2 Inexact Rounded +sqtx8277 squareroot 297025 -> 5.4E+2 Inexact Rounded +sqtx8278 squareroot 308025 -> 5.6E+2 Inexact Rounded +sqtx8279 squareroot 319225 -> 5.6E+2 Inexact Rounded +sqtx8280 squareroot 330625 -> 5.8E+2 Inexact Rounded +sqtx8281 squareroot 342225 -> 5.8E+2 Inexact Rounded +sqtx8282 squareroot 354025 -> 6.0E+2 Inexact Rounded +sqtx8283 squareroot 366025 -> 6.0E+2 Inexact Rounded +sqtx8284 squareroot 378225 -> 6.2E+2 Inexact Rounded +sqtx8285 squareroot 390625 -> 6.2E+2 Inexact Rounded +sqtx8286 squareroot 403225 -> 6.4E+2 Inexact Rounded +sqtx8287 squareroot 416025 -> 6.4E+2 Inexact Rounded +sqtx8288 squareroot 429025 -> 6.6E+2 Inexact Rounded +sqtx8289 squareroot 442225 -> 6.6E+2 Inexact Rounded +sqtx8290 squareroot 455625 -> 6.8E+2 Inexact Rounded +sqtx8291 squareroot 469225 -> 6.8E+2 Inexact Rounded +sqtx8292 squareroot 483025 -> 7.0E+2 Inexact Rounded +sqtx8293 squareroot 497025 -> 7.0E+2 Inexact Rounded +sqtx8294 squareroot 511225 -> 7.2E+2 Inexact Rounded +sqtx8295 squareroot 525625 -> 7.2E+2 Inexact Rounded +sqtx8296 squareroot 540225 -> 7.4E+2 Inexact Rounded +sqtx8297 squareroot 555025 -> 7.4E+2 Inexact Rounded +sqtx8298 squareroot 570025 -> 7.6E+2 Inexact Rounded +sqtx8299 squareroot 585225 -> 7.6E+2 Inexact Rounded +sqtx8300 squareroot 600625 -> 7.8E+2 Inexact Rounded +sqtx8301 squareroot 616225 -> 7.8E+2 Inexact Rounded +sqtx8302 squareroot 632025 -> 8.0E+2 Inexact Rounded +sqtx8303 squareroot 648025 -> 8.0E+2 Inexact Rounded +sqtx8304 squareroot 664225 -> 8.2E+2 Inexact Rounded +sqtx8305 squareroot 680625 -> 8.2E+2 Inexact Rounded +sqtx8306 squareroot 697225 -> 8.4E+2 Inexact Rounded +sqtx8307 squareroot 714025 -> 8.4E+2 Inexact Rounded +sqtx8308 squareroot 731025 -> 8.6E+2 Inexact Rounded +sqtx8309 squareroot 748225 -> 8.6E+2 Inexact Rounded +sqtx8310 squareroot 765625 -> 8.8E+2 Inexact Rounded +sqtx8311 squareroot 783225 -> 8.8E+2 Inexact Rounded +sqtx8312 squareroot 801025 -> 9.0E+2 Inexact Rounded +sqtx8313 squareroot 819025 -> 9.0E+2 Inexact Rounded +sqtx8314 squareroot 837225 -> 9.2E+2 Inexact Rounded +sqtx8315 squareroot 855625 -> 9.2E+2 Inexact Rounded +sqtx8316 squareroot 874225 -> 9.4E+2 Inexact Rounded +sqtx8317 squareroot 893025 -> 9.4E+2 Inexact Rounded +sqtx8318 squareroot 912025 -> 9.6E+2 Inexact Rounded +sqtx8319 squareroot 931225 -> 9.6E+2 Inexact Rounded +sqtx8320 squareroot 950625 -> 9.8E+2 Inexact Rounded +sqtx8321 squareroot 970225 -> 9.8E+2 Inexact Rounded +sqtx8322 squareroot 990025 -> 1.0E+3 Inexact Rounded + +precision: 6 +sqtx8323 squareroot 88975734963025 -> 9.43270E+6 Inexact Rounded +sqtx8324 squareroot 71085555000625 -> 8.43122E+6 Inexact Rounded +sqtx8325 squareroot 39994304.051025 -> 6324.10 Inexact Rounded +sqtx8326 squareroot 0.000007327172265625 -> 0.00270688 Inexact Rounded +sqtx8327 squareroot 1.0258600439025E-13 -> 3.20290E-7 Inexact Rounded +sqtx8328 squareroot 0.0034580574275625 -> 0.0588052 Inexact Rounded +sqtx8329 squareroot 7.6842317700625E-7 -> 0.000876598 Inexact Rounded +sqtx8330 squareroot 1263834495.2025 -> 35550.4 Inexact Rounded +sqtx8331 squareroot 433970666460.25 -> 658764 Inexact Rounded +sqtx8332 squareroot 4.5879286230625E-7 -> 0.000677342 Inexact Rounded +sqtx8333 squareroot 0.0029305603306225 -> 0.0541346 Inexact Rounded +sqtx8334 squareroot 70218282.733225 -> 8379.64 Inexact Rounded +sqtx8335 squareroot 11942519.082025 -> 3455.80 Inexact Rounded +sqtx8336 squareroot 0.0021230668905625 -> 0.0460768 Inexact Rounded +sqtx8337 squareroot 0.90081833411025 -> 0.949114 Inexact Rounded +sqtx8338 squareroot 5.5104120936225E-17 -> 7.42322E-9 Inexact Rounded +sqtx8339 squareroot 0.10530446854225 -> 0.324506 Inexact Rounded +sqtx8340 squareroot 8.706069866025E-14 -> 2.95060E-7 Inexact Rounded +sqtx8341 squareroot 23838.58800625 -> 154.398 Inexact Rounded +sqtx8342 squareroot 0.0013426911275625 -> 0.0366428 Inexact Rounded + +-- test use of round-half-even in underflow situations + +-- precisions 2; all cases where result is both subnormal and a tie +precision: 2 +sqtx8343 squareroot 2.5E-21 -> 0E-10 Underflow Subnormal Inexact Rounded Clamped +sqtx8344 squareroot 2.25E-20 -> 2E-10 Underflow Subnormal Inexact Rounded +sqtx8345 squareroot 6.25E-20 -> 2E-10 Underflow Subnormal Inexact Rounded +sqtx8346 squareroot 1.225E-19 -> 4E-10 Underflow Subnormal Inexact Rounded +sqtx8347 squareroot 2.025E-19 -> 4E-10 Underflow Subnormal Inexact Rounded +sqtx8348 squareroot 3.025E-19 -> 6E-10 Underflow Subnormal Inexact Rounded +sqtx8349 squareroot 4.225E-19 -> 6E-10 Underflow Subnormal Inexact Rounded +sqtx8350 squareroot 5.625E-19 -> 8E-10 Underflow Subnormal Inexact Rounded +sqtx8351 squareroot 7.225E-19 -> 8E-10 Underflow Subnormal Inexact Rounded +sqtx8352 squareroot 9.025E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded + +-- precision 3, input precision <= 5 +precision: 3 +sqtx8353 squareroot 2.5E-23 -> 0E-11 Underflow Subnormal Inexact Rounded Clamped +sqtx8354 squareroot 2.25E-22 -> 2E-11 Underflow Subnormal Inexact Rounded +sqtx8355 squareroot 6.25E-22 -> 2E-11 Underflow Subnormal Inexact Rounded +sqtx8356 squareroot 1.225E-21 -> 4E-11 Underflow Subnormal Inexact Rounded +sqtx8357 squareroot 2.025E-21 -> 4E-11 Underflow Subnormal Inexact Rounded +sqtx8358 squareroot 3.025E-21 -> 6E-11 Underflow Subnormal Inexact Rounded +sqtx8359 squareroot 4.225E-21 -> 6E-11 Underflow Subnormal Inexact Rounded +sqtx8360 squareroot 5.625E-21 -> 8E-11 Underflow Subnormal Inexact Rounded +sqtx8361 squareroot 7.225E-21 -> 8E-11 Underflow Subnormal Inexact Rounded +sqtx8362 squareroot 9.025E-21 -> 1.0E-10 Underflow Subnormal Inexact Rounded +sqtx8363 squareroot 1.1025E-20 -> 1.0E-10 Underflow Subnormal Inexact Rounded +sqtx8364 squareroot 1.3225E-20 -> 1.2E-10 Underflow Subnormal Inexact Rounded +sqtx8365 squareroot 1.5625E-20 -> 1.2E-10 Underflow Subnormal Inexact Rounded +sqtx8366 squareroot 1.8225E-20 -> 1.4E-10 Underflow Subnormal Inexact Rounded +sqtx8367 squareroot 2.1025E-20 -> 1.4E-10 Underflow Subnormal Inexact Rounded +sqtx8368 squareroot 2.4025E-20 -> 1.6E-10 Underflow Subnormal Inexact Rounded +sqtx8369 squareroot 2.7225E-20 -> 1.6E-10 Underflow Subnormal Inexact Rounded +sqtx8370 squareroot 3.0625E-20 -> 1.8E-10 Underflow Subnormal Inexact Rounded +sqtx8371 squareroot 3.4225E-20 -> 1.8E-10 Underflow Subnormal Inexact Rounded +sqtx8372 squareroot 3.8025E-20 -> 2.0E-10 Underflow Subnormal Inexact Rounded +sqtx8373 squareroot 4.2025E-20 -> 2.0E-10 Underflow Subnormal Inexact Rounded +sqtx8374 squareroot 4.6225E-20 -> 2.2E-10 Underflow Subnormal Inexact Rounded +sqtx8375 squareroot 5.0625E-20 -> 2.2E-10 Underflow Subnormal Inexact Rounded +sqtx8376 squareroot 5.5225E-20 -> 2.4E-10 Underflow Subnormal Inexact Rounded +sqtx8377 squareroot 6.0025E-20 -> 2.4E-10 Underflow Subnormal Inexact Rounded +sqtx8378 squareroot 6.5025E-20 -> 2.6E-10 Underflow Subnormal Inexact Rounded +sqtx8379 squareroot 7.0225E-20 -> 2.6E-10 Underflow Subnormal Inexact Rounded +sqtx8380 squareroot 7.5625E-20 -> 2.8E-10 Underflow Subnormal Inexact Rounded +sqtx8381 squareroot 8.1225E-20 -> 2.8E-10 Underflow Subnormal Inexact Rounded +sqtx8382 squareroot 8.7025E-20 -> 3.0E-10 Underflow Subnormal Inexact Rounded +sqtx8383 squareroot 9.3025E-20 -> 3.0E-10 Underflow Subnormal Inexact Rounded +sqtx8384 squareroot 9.9225E-20 -> 3.2E-10 Underflow Subnormal Inexact Rounded + +--precision 4, input precision <= 4 +precision: 4 +sqtx8385 squareroot 2.5E-25 -> 0E-12 Underflow Subnormal Inexact Rounded Clamped +sqtx8386 squareroot 2.25E-24 -> 2E-12 Underflow Subnormal Inexact Rounded +sqtx8387 squareroot 6.25E-24 -> 2E-12 Underflow Subnormal Inexact Rounded +sqtx8388 squareroot 1.225E-23 -> 4E-12 Underflow Subnormal Inexact Rounded +sqtx8389 squareroot 2.025E-23 -> 4E-12 Underflow Subnormal Inexact Rounded +sqtx8390 squareroot 3.025E-23 -> 6E-12 Underflow Subnormal Inexact Rounded +sqtx8391 squareroot 4.225E-23 -> 6E-12 Underflow Subnormal Inexact Rounded +sqtx8392 squareroot 5.625E-23 -> 8E-12 Underflow Subnormal Inexact Rounded +sqtx8393 squareroot 7.225E-23 -> 8E-12 Underflow Subnormal Inexact Rounded +sqtx8394 squareroot 9.025E-23 -> 1.0E-11 Underflow Subnormal Inexact Rounded + +--precision 5, input precision <= 5 +precision: 5 +sqtx8395 squareroot 2.5E-27 -> 0E-13 Underflow Subnormal Inexact Rounded Clamped +sqtx8396 squareroot 2.25E-26 -> 2E-13 Underflow Subnormal Inexact Rounded +sqtx8397 squareroot 6.25E-26 -> 2E-13 Underflow Subnormal Inexact Rounded +sqtx8398 squareroot 1.225E-25 -> 4E-13 Underflow Subnormal Inexact Rounded +sqtx8399 squareroot 2.025E-25 -> 4E-13 Underflow Subnormal Inexact Rounded +sqtx8400 squareroot 3.025E-25 -> 6E-13 Underflow Subnormal Inexact Rounded +sqtx8401 squareroot 4.225E-25 -> 6E-13 Underflow Subnormal Inexact Rounded +sqtx8402 squareroot 5.625E-25 -> 8E-13 Underflow Subnormal Inexact Rounded +sqtx8403 squareroot 7.225E-25 -> 8E-13 Underflow Subnormal Inexact Rounded +sqtx8404 squareroot 9.025E-25 -> 1.0E-12 Underflow Subnormal Inexact Rounded +sqtx8405 squareroot 1.1025E-24 -> 1.0E-12 Underflow Subnormal Inexact Rounded +sqtx8406 squareroot 1.3225E-24 -> 1.2E-12 Underflow Subnormal Inexact Rounded +sqtx8407 squareroot 1.5625E-24 -> 1.2E-12 Underflow Subnormal Inexact Rounded +sqtx8408 squareroot 1.8225E-24 -> 1.4E-12 Underflow Subnormal Inexact Rounded +sqtx8409 squareroot 2.1025E-24 -> 1.4E-12 Underflow Subnormal Inexact Rounded +sqtx8410 squareroot 2.4025E-24 -> 1.6E-12 Underflow Subnormal Inexact Rounded +sqtx8411 squareroot 2.7225E-24 -> 1.6E-12 Underflow Subnormal Inexact Rounded +sqtx8412 squareroot 3.0625E-24 -> 1.8E-12 Underflow Subnormal Inexact Rounded +sqtx8413 squareroot 3.4225E-24 -> 1.8E-12 Underflow Subnormal Inexact Rounded +sqtx8414 squareroot 3.8025E-24 -> 2.0E-12 Underflow Subnormal Inexact Rounded +sqtx8415 squareroot 4.2025E-24 -> 2.0E-12 Underflow Subnormal Inexact Rounded +sqtx8416 squareroot 4.6225E-24 -> 2.2E-12 Underflow Subnormal Inexact Rounded +sqtx8417 squareroot 5.0625E-24 -> 2.2E-12 Underflow Subnormal Inexact Rounded +sqtx8418 squareroot 5.5225E-24 -> 2.4E-12 Underflow Subnormal Inexact Rounded +sqtx8419 squareroot 6.0025E-24 -> 2.4E-12 Underflow Subnormal Inexact Rounded +sqtx8420 squareroot 6.5025E-24 -> 2.6E-12 Underflow Subnormal Inexact Rounded +sqtx8421 squareroot 7.0225E-24 -> 2.6E-12 Underflow Subnormal Inexact Rounded +sqtx8422 squareroot 7.5625E-24 -> 2.8E-12 Underflow Subnormal Inexact Rounded +sqtx8423 squareroot 8.1225E-24 -> 2.8E-12 Underflow Subnormal Inexact Rounded +sqtx8424 squareroot 8.7025E-24 -> 3.0E-12 Underflow Subnormal Inexact Rounded +sqtx8425 squareroot 9.3025E-24 -> 3.0E-12 Underflow Subnormal Inexact Rounded +sqtx8426 squareroot 9.9225E-24 -> 3.2E-12 Underflow Subnormal Inexact Rounded + +-- a random selection of values that Python2.5.1 rounds incorrectly +precision: 1 +sqtx8427 squareroot 227 -> 2E+1 Inexact Rounded +sqtx8428 squareroot 625 -> 2E+1 Inexact Rounded +sqtx8429 squareroot 1215 -> 3E+1 Inexact Rounded +sqtx8430 squareroot 2008 -> 4E+1 Inexact Rounded +sqtx8431 squareroot 2020 -> 4E+1 Inexact Rounded +sqtx8432 squareroot 2026 -> 5E+1 Inexact Rounded +sqtx8433 squareroot 2027 -> 5E+1 Inexact Rounded +sqtx8434 squareroot 2065 -> 5E+1 Inexact Rounded +sqtx8435 squareroot 2075 -> 5E+1 Inexact Rounded +sqtx8436 squareroot 2088 -> 5E+1 Inexact Rounded +sqtx8437 squareroot 3049 -> 6E+1 Inexact Rounded +sqtx8438 squareroot 3057 -> 6E+1 Inexact Rounded +sqtx8439 squareroot 3061 -> 6E+1 Inexact Rounded +sqtx8440 squareroot 3092 -> 6E+1 Inexact Rounded +sqtx8441 squareroot 4222 -> 6E+1 Inexact Rounded +sqtx8442 squareroot 5676 -> 8E+1 Inexact Rounded +sqtx8443 squareroot 5686 -> 8E+1 Inexact Rounded +sqtx8444 squareroot 7215 -> 8E+1 Inexact Rounded +sqtx8445 squareroot 9086 -> 1E+2 Inexact Rounded +sqtx8446 squareroot 9095 -> 1E+2 Inexact Rounded + +precision: 2 +sqtx8447 squareroot 1266 -> 36 Inexact Rounded +sqtx8448 squareroot 2552 -> 51 Inexact Rounded +sqtx8449 squareroot 5554 -> 75 Inexact Rounded +sqtx8450 squareroot 7832 -> 88 Inexact Rounded +sqtx8451 squareroot 13201 -> 1.1E+2 Inexact Rounded +sqtx8452 squareroot 15695 -> 1.3E+2 Inexact Rounded +sqtx8453 squareroot 18272 -> 1.4E+2 Inexact Rounded +sqtx8454 squareroot 21026 -> 1.5E+2 Inexact Rounded +sqtx8455 squareroot 24069 -> 1.6E+2 Inexact Rounded +sqtx8456 squareroot 34277 -> 1.9E+2 Inexact Rounded +sqtx8457 squareroot 46233 -> 2.2E+2 Inexact Rounded +sqtx8458 squareroot 46251 -> 2.2E+2 Inexact Rounded +sqtx8459 squareroot 46276 -> 2.2E+2 Inexact Rounded +sqtx8460 squareroot 70214 -> 2.6E+2 Inexact Rounded +sqtx8461 squareroot 81249 -> 2.9E+2 Inexact Rounded +sqtx8462 squareroot 81266 -> 2.9E+2 Inexact Rounded +sqtx8463 squareroot 93065 -> 3.1E+2 Inexact Rounded +sqtx8464 squareroot 93083 -> 3.1E+2 Inexact Rounded +sqtx8465 squareroot 99230 -> 3.2E+2 Inexact Rounded +sqtx8466 squareroot 99271 -> 3.2E+2 Inexact Rounded + +precision: 3 +sqtx8467 squareroot 11349 -> 107 Inexact Rounded +sqtx8468 squareroot 26738 -> 164 Inexact Rounded +sqtx8469 squareroot 31508 -> 178 Inexact Rounded +sqtx8470 squareroot 44734 -> 212 Inexact Rounded +sqtx8471 squareroot 44738 -> 212 Inexact Rounded +sqtx8472 squareroot 51307 -> 227 Inexact Rounded +sqtx8473 squareroot 62259 -> 250 Inexact Rounded +sqtx8474 squareroot 75901 -> 276 Inexact Rounded +sqtx8475 squareroot 76457 -> 277 Inexact Rounded +sqtx8476 squareroot 180287 -> 425 Inexact Rounded +sqtx8477 squareroot 202053 -> 450 Inexact Rounded +sqtx8478 squareroot 235747 -> 486 Inexact Rounded +sqtx8479 squareroot 256537 -> 506 Inexact Rounded +sqtx8480 squareroot 299772 -> 548 Inexact Rounded +sqtx8481 squareroot 415337 -> 644 Inexact Rounded +sqtx8482 squareroot 617067 -> 786 Inexact Rounded +sqtx8483 squareroot 628022 -> 792 Inexact Rounded +sqtx8484 squareroot 645629 -> 804 Inexact Rounded +sqtx8485 squareroot 785836 -> 886 Inexact Rounded +sqtx8486 squareroot 993066 -> 997 Inexact Rounded + +precision: 6 +sqtx8487 squareroot 14917781 -> 3862.35 Inexact Rounded +sqtx8488 squareroot 17237238 -> 4151.78 Inexact Rounded +sqtx8489 squareroot 18054463 -> 4249.05 Inexact Rounded +sqtx8490 squareroot 19990694 -> 4471.10 Inexact Rounded +sqtx8491 squareroot 29061855 -> 5390.90 Inexact Rounded +sqtx8492 squareroot 49166257 -> 7011.87 Inexact Rounded +sqtx8493 squareroot 53082086 -> 7285.75 Inexact Rounded +sqtx8494 squareroot 56787909 -> 7535.78 Inexact Rounded +sqtx8495 squareroot 81140019 -> 9007.78 Inexact Rounded +sqtx8496 squareroot 87977554 -> 9379.64 Inexact Rounded +sqtx8497 squareroot 93624683 -> 9675.98 Inexact Rounded +sqtx8498 squareroot 98732747 -> 9936.44 Inexact Rounded +sqtx8499 squareroot 99222813 -> 9961.06 Inexact Rounded +sqtx8500 squareroot 143883626 -> 11995.2 Inexact Rounded +sqtx8501 squareroot 180433301 -> 13432.5 Inexact Rounded +sqtx8502 squareroot 227034020 -> 15067.6 Inexact Rounded +sqtx8503 squareroot 283253992 -> 16830.2 Inexact Rounded +sqtx8504 squareroot 617047954 -> 24840.4 Inexact Rounded +sqtx8505 squareroot 736870094 -> 27145.4 Inexact Rounded +sqtx8506 squareroot 897322915 -> 29955.3 Inexact Rounded + +-- results close to minimum normal +precision: 1 +sqtx8507 squareroot 1E-20 -> 0E-9 Underflow Subnormal Inexact Rounded Clamped +sqtx8508 squareroot 1E-19 -> 0E-9 Underflow Subnormal Inexact Rounded Clamped +sqtx8509 squareroot 1E-18 -> 1E-9 + +precision: 2 +sqtx8510 squareroot 8.1E-19 -> 9E-10 Subnormal +sqtx8511 squareroot 8.10E-19 -> 9E-10 Subnormal Rounded +sqtx8512 squareroot 9.0E-19 -> 9E-10 Underflow Subnormal Inexact Rounded +sqtx8513 squareroot 9.02E-19 -> 9E-10 Underflow Subnormal Inexact Rounded +sqtx8514 squareroot 9.03E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8515 squareroot 9.1E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8516 squareroot 9.9E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8517 squareroot 9.91E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8518 squareroot 9.92E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8519 squareroot 9.95E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8520 squareroot 9.98E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8521 squareroot 9.99E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8522 squareroot 1E-18 -> 1E-9 +sqtx8523 squareroot 1.0E-18 -> 1.0E-9 +sqtx8524 squareroot 1.00E-18 -> 1.0E-9 +sqtx8525 squareroot 1.000E-18 -> 1.0E-9 Rounded +sqtx8526 squareroot 1.0000E-18 -> 1.0E-9 Rounded +sqtx8527 squareroot 1.01E-18 -> 1.0E-9 Inexact Rounded +sqtx8528 squareroot 1.02E-18 -> 1.0E-9 Inexact Rounded +sqtx8529 squareroot 1.1E-18 -> 1.0E-9 Inexact Rounded + +precision: 3 +sqtx8530 squareroot 8.1E-19 -> 9E-10 Subnormal +sqtx8531 squareroot 8.10E-19 -> 9.0E-10 Subnormal +sqtx8532 squareroot 8.100E-19 -> 9.0E-10 Subnormal +sqtx8533 squareroot 8.1000E-19 -> 9.0E-10 Subnormal Rounded +sqtx8534 squareroot 9.9E-19 -> 9.9E-10 Underflow Subnormal Inexact Rounded +sqtx8535 squareroot 9.91E-19 -> 1.00E-9 Underflow Subnormal Inexact Rounded +sqtx8536 squareroot 9.99E-19 -> 1.00E-9 Underflow Subnormal Inexact Rounded +sqtx8537 squareroot 9.998E-19 -> 1.00E-9 Underflow Subnormal Inexact Rounded +sqtx8538 squareroot 1E-18 -> 1E-9 +sqtx8539 squareroot 1.0E-18 -> 1.0E-9 +sqtx8540 squareroot 1.00E-18 -> 1.0E-9 +sqtx8541 squareroot 1.000E-18 -> 1.00E-9 +sqtx8542 squareroot 1.0000E-18 -> 1.00E-9 +sqtx8543 squareroot 1.00000E-18 -> 1.00E-9 Rounded +sqtx8544 squareroot 1.000000E-18 -> 1.00E-9 Rounded +sqtx8545 squareroot 1.01E-18 -> 1.00E-9 Inexact Rounded +sqtx8546 squareroot 1.02E-18 -> 1.01E-9 Inexact Rounded + +-- result exactly representable with precision p, but not necessarily +-- exactly representable as a subnormal; check the correct flags are raised +precision: 2 +sqtx8547 squareroot 1.21E-20 -> 1E-10 Underflow Subnormal Inexact Rounded +sqtx8548 squareroot 1.44E-20 -> 1E-10 Underflow Subnormal Inexact Rounded +sqtx8549 squareroot 9.61E-20 -> 3E-10 Underflow Subnormal Inexact Rounded +sqtx8550 squareroot 8.836E-19 -> 9E-10 Underflow Subnormal Inexact Rounded +sqtx8551 squareroot 9.216E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded + +precision: 3 +sqtx8552 squareroot 1.21E-22 -> 1E-11 Underflow Subnormal Inexact Rounded +sqtx8553 squareroot 1.21E-20 -> 1.1E-10 Subnormal +sqtx8554 squareroot 1.96E-22 -> 1E-11 Underflow Subnormal Inexact Rounded +sqtx8555 squareroot 1.96E-20 -> 1.4E-10 Subnormal +sqtx8556 squareroot 2.56E-22 -> 2E-11 Underflow Subnormal Inexact Rounded +sqtx8557 squareroot 4.00E-22 -> 2E-11 Subnormal Rounded +sqtx8558 squareroot 7.84E-22 -> 3E-11 Underflow Subnormal Inexact Rounded +sqtx8559 squareroot 9.801E-21 -> 1.0E-10 Underflow Subnormal Inexact Rounded +sqtx8560 squareroot 9.801E-19 -> 9.9E-10 Subnormal +sqtx8561 squareroot 1.0201E-20 -> 1.0E-10 Underflow Subnormal Inexact Rounded +sqtx8562 squareroot 1.1025E-20 -> 1.0E-10 Underflow Subnormal Inexact Rounded +sqtx8563 squareroot 1.1236E-20 -> 1.1E-10 Underflow Subnormal Inexact Rounded +sqtx8564 squareroot 1.2996E-20 -> 1.1E-10 Underflow Subnormal Inexact Rounded +sqtx8565 squareroot 1.3225E-20 -> 1.2E-10 Underflow Subnormal Inexact Rounded + +-- A selection of subnormal results prone to double rounding errors +precision: 2 +sqtx8566 squareroot 2.3E-21 -> 0E-10 Underflow Subnormal Inexact Rounded Clamped +sqtx8567 squareroot 2.4E-21 -> 0E-10 Underflow Subnormal Inexact Rounded Clamped +sqtx8568 squareroot 2.5E-21 -> 0E-10 Underflow Subnormal Inexact Rounded Clamped +sqtx8569 squareroot 2.6E-21 -> 1E-10 Underflow Subnormal Inexact Rounded +sqtx8570 squareroot 2.7E-21 -> 1E-10 Underflow Subnormal Inexact Rounded +sqtx8571 squareroot 2.8E-21 -> 1E-10 Underflow Subnormal Inexact Rounded +sqtx8572 squareroot 2.2E-20 -> 1E-10 Underflow Subnormal Inexact Rounded +sqtx8573 squareroot 2.3E-20 -> 2E-10 Underflow Subnormal Inexact Rounded +sqtx8574 squareroot 2.4E-20 -> 2E-10 Underflow Subnormal Inexact Rounded +sqtx8575 squareroot 6.2E-20 -> 2E-10 Underflow Subnormal Inexact Rounded +sqtx8576 squareroot 6.3E-20 -> 3E-10 Underflow Subnormal Inexact Rounded +sqtx8577 squareroot 6.4E-20 -> 3E-10 Underflow Subnormal Inexact Rounded +sqtx8578 squareroot 6.5E-20 -> 3E-10 Underflow Subnormal Inexact Rounded +sqtx8579 squareroot 1.2E-19 -> 3E-10 Underflow Subnormal Inexact Rounded +sqtx8580 squareroot 2.0E-19 -> 4E-10 Underflow Subnormal Inexact Rounded +sqtx8581 squareroot 4.2E-19 -> 6E-10 Underflow Subnormal Inexact Rounded +sqtx8582 squareroot 5.6E-19 -> 7E-10 Underflow Subnormal Inexact Rounded +sqtx8583 squareroot 5.7E-19 -> 8E-10 Underflow Subnormal Inexact Rounded +sqtx8584 squareroot 9.0E-19 -> 9E-10 Underflow Subnormal Inexact Rounded +sqtx8585 squareroot 9.1E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +precision: 3 +sqtx8586 squareroot 2.6E-23 -> 1E-11 Underflow Subnormal Inexact Rounded +sqtx8587 squareroot 2.22E-22 -> 1E-11 Underflow Subnormal Inexact Rounded +sqtx8588 squareroot 6.07E-22 -> 2E-11 Underflow Subnormal Inexact Rounded +sqtx8589 squareroot 6.25E-22 -> 2E-11 Underflow Subnormal Inexact Rounded +sqtx8590 squareroot 6.45E-22 -> 3E-11 Underflow Subnormal Inexact Rounded +sqtx8591 squareroot 6.50E-22 -> 3E-11 Underflow Subnormal Inexact Rounded +sqtx8592 squareroot 1.22E-21 -> 3E-11 Underflow Subnormal Inexact Rounded +sqtx8593 squareroot 1.24E-21 -> 4E-11 Underflow Subnormal Inexact Rounded +sqtx8594 squareroot 4.18E-21 -> 6E-11 Underflow Subnormal Inexact Rounded +sqtx8595 squareroot 7.19E-21 -> 8E-11 Underflow Subnormal Inexact Rounded +sqtx8596 squareroot 8.94E-21 -> 9E-11 Underflow Subnormal Inexact Rounded +sqtx8597 squareroot 1.81E-20 -> 1.3E-10 Underflow Subnormal Inexact Rounded +sqtx8598 squareroot 4.64E-20 -> 2.2E-10 Underflow Subnormal Inexact Rounded +sqtx8599 squareroot 5.06E-20 -> 2.2E-10 Underflow Subnormal Inexact Rounded +sqtx8600 squareroot 5.08E-20 -> 2.3E-10 Underflow Subnormal Inexact Rounded +sqtx8601 squareroot 7.00E-20 -> 2.6E-10 Underflow Subnormal Inexact Rounded +sqtx8602 squareroot 1.81E-19 -> 4.3E-10 Underflow Subnormal Inexact Rounded +sqtx8603 squareroot 6.64E-19 -> 8.1E-10 Underflow Subnormal Inexact Rounded +sqtx8604 squareroot 7.48E-19 -> 8.6E-10 Underflow Subnormal Inexact Rounded +sqtx8605 squareroot 9.91E-19 -> 1.00E-9 Underflow Subnormal Inexact Rounded +precision: 4 +sqtx8606 squareroot 6.24E-24 -> 2E-12 Underflow Subnormal Inexact Rounded +sqtx8607 squareroot 7.162E-23 -> 8E-12 Underflow Subnormal Inexact Rounded +sqtx8608 squareroot 7.243E-23 -> 9E-12 Underflow Subnormal Inexact Rounded +sqtx8609 squareroot 8.961E-23 -> 9E-12 Underflow Subnormal Inexact Rounded +sqtx8610 squareroot 9.029E-23 -> 1.0E-11 Underflow Subnormal Inexact Rounded +sqtx8611 squareroot 4.624E-22 -> 2.2E-11 Underflow Subnormal Inexact Rounded +sqtx8612 squareroot 5.980E-22 -> 2.4E-11 Underflow Subnormal Inexact Rounded +sqtx8613 squareroot 6.507E-22 -> 2.6E-11 Underflow Subnormal Inexact Rounded +sqtx8614 squareroot 1.483E-21 -> 3.9E-11 Underflow Subnormal Inexact Rounded +sqtx8615 squareroot 3.903E-21 -> 6.2E-11 Underflow Subnormal Inexact Rounded +sqtx8616 squareroot 8.733E-21 -> 9.3E-11 Underflow Subnormal Inexact Rounded +sqtx8617 squareroot 1.781E-20 -> 1.33E-10 Underflow Subnormal Inexact Rounded +sqtx8618 squareroot 6.426E-20 -> 2.53E-10 Underflow Subnormal Inexact Rounded +sqtx8619 squareroot 7.102E-20 -> 2.66E-10 Underflow Subnormal Inexact Rounded +sqtx8620 squareroot 7.535E-20 -> 2.74E-10 Underflow Subnormal Inexact Rounded +sqtx8621 squareroot 9.892E-20 -> 3.15E-10 Underflow Subnormal Inexact Rounded +sqtx8622 squareroot 1.612E-19 -> 4.01E-10 Underflow Subnormal Inexact Rounded +sqtx8623 squareroot 1.726E-19 -> 4.15E-10 Underflow Subnormal Inexact Rounded +sqtx8624 squareroot 1.853E-19 -> 4.30E-10 Underflow Subnormal Inexact Rounded +sqtx8625 squareroot 4.245E-19 -> 6.52E-10 Underflow Subnormal Inexact Rounded + +-- clamping and overflow for large exponents +precision: 1 +sqtx8626 squareroot 1E+18 -> 1E+9 +sqtx8627 squareroot 1E+19 -> 3E+9 Inexact Rounded +sqtx8628 squareroot 9E+19 -> 9E+9 Inexact Rounded +sqtx8629 squareroot 9.1E+19 -> Infinity Overflow Inexact Rounded +sqtx8630 squareroot 1E+20 -> Infinity Overflow Inexact Rounded + +precision: 2 +sqtx8631 squareroot 1E+18 -> 1E+9 +sqtx8632 squareroot 1.0E+18 -> 1.0E+9 +sqtx8633 squareroot 1.00E+18 -> 1.0E+9 +sqtx8634 squareroot 1.000E+18 -> 1.0E+9 Rounded +sqtx8635 squareroot 1E+20 -> Infinity Overflow Inexact Rounded +clamp: 1 +sqtx8636 squareroot 1E+18 -> 1.0E+9 Clamped +sqtx8637 squareroot 1.0E+18 -> 1.0E+9 +sqtx8638 squareroot 1E+20 -> Infinity Overflow Inexact Rounded +clamp: 0 + +precision: 6 +sqtx8639 squareroot 1E+18 -> 1E+9 +sqtx8640 squareroot 1.0000000000E+18 -> 1.00000E+9 +sqtx8641 squareroot 1.00000000000E+18 -> 1.00000E+9 Rounded +sqtx8642 squareroot 1E+20 -> Infinity Overflow Inexact Rounded +clamp: 1 +sqtx8643 squareroot 1E+8 -> 1E+4 +sqtx8644 squareroot 1E+10 -> 1.0E+5 Clamped +sqtx8645 squareroot 1.0E+10 -> 1.0E+5 +sqtx8646 squareroot 1E+12 -> 1.00E+6 Clamped +sqtx8647 squareroot 1.0E+12 -> 1.00E+6 Clamped +sqtx8648 squareroot 1.00E+12 -> 1.00E+6 Clamped +sqtx8649 squareroot 1.000E+12 -> 1.00E+6 +sqtx8650 squareroot 1E+18 -> 1.00000E+9 Clamped +sqtx8651 squareroot 1.00000000E+18 -> 1.00000E+9 Clamped +sqtx8652 squareroot 1.000000000E+18 -> 1.00000E+9 +sqtx8653 squareroot 1E+20 -> Infinity Overflow Inexact Rounded +clamp: 0 + +-- The following example causes a TypeError in Python 2.5.1 +precision: 3 +maxexponent: 9 +minexponent: -9 +sqtx8654 squareroot 10000000000 -> 1.00E+5 Rounded + +-- Additional tricky cases of underflown subnormals +rounding: half_even +precision: 5 +maxexponent: 999 +minexponent: -999 +sqtx8700 squareroot 2.8073E-2000 -> 1.675E-1000 Underflow Subnormal Inexact Rounded +sqtx8701 squareroot 2.8883E-2000 -> 1.699E-1000 Underflow Subnormal Inexact Rounded +sqtx8702 squareroot 3.1524E-2000 -> 1.775E-1000 Underflow Subnormal Inexact Rounded +sqtx8703 squareroot 3.2382E-2000 -> 1.799E-1000 Underflow Subnormal Inexact Rounded +sqtx8704 squareroot 3.5175E-2000 -> 1.875E-1000 Underflow Subnormal Inexact Rounded +sqtx8705 squareroot 3.6081E-2000 -> 1.899E-1000 Underflow Subnormal Inexact Rounded +sqtx8706 squareroot 3.9026E-2000 -> 1.975E-1000 Underflow Subnormal Inexact Rounded +sqtx8707 squareroot 3.9980E-2000 -> 1.999E-1000 Underflow Subnormal Inexact Rounded +sqtx8708 squareroot 4.3077E-2000 -> 2.075E-1000 Underflow Subnormal Inexact Rounded +sqtx8709 squareroot 4.4079E-2000 -> 2.099E-1000 Underflow Subnormal Inexact Rounded +sqtx8710 squareroot 4.7328E-2000 -> 2.175E-1000 Underflow Subnormal Inexact Rounded +sqtx8711 squareroot 4.8378E-2000 -> 2.199E-1000 Underflow Subnormal Inexact Rounded +sqtx8712 squareroot 5.1779E-2000 -> 2.275E-1000 Underflow Subnormal Inexact Rounded +sqtx8713 squareroot 5.2877E-2000 -> 2.299E-1000 Underflow Subnormal Inexact Rounded +sqtx8714 squareroot 5.6430E-2000 -> 2.375E-1000 Underflow Subnormal Inexact Rounded +sqtx8715 squareroot 5.7576E-2000 -> 2.399E-1000 Underflow Subnormal Inexact Rounded +sqtx8716 squareroot 6.1281E-2000 -> 2.475E-1000 Underflow Subnormal Inexact Rounded +sqtx8717 squareroot 6.2475E-2000 -> 2.499E-1000 Underflow Subnormal Inexact Rounded +sqtx8718 squareroot 6.6332E-2000 -> 2.575E-1000 Underflow Subnormal Inexact Rounded +sqtx8719 squareroot 6.7574E-2000 -> 2.599E-1000 Underflow Subnormal Inexact Rounded +sqtx8720 squareroot 7.1583E-2000 -> 2.675E-1000 Underflow Subnormal Inexact Rounded +sqtx8721 squareroot 7.2873E-2000 -> 2.699E-1000 Underflow Subnormal Inexact Rounded +sqtx8722 squareroot 7.7034E-2000 -> 2.775E-1000 Underflow Subnormal Inexact Rounded +sqtx8723 squareroot 7.8372E-2000 -> 2.799E-1000 Underflow Subnormal Inexact Rounded +sqtx8724 squareroot 8.2685E-2000 -> 2.875E-1000 Underflow Subnormal Inexact Rounded +sqtx8725 squareroot 8.4071E-2000 -> 2.899E-1000 Underflow Subnormal Inexact Rounded +sqtx8726 squareroot 8.8536E-2000 -> 2.975E-1000 Underflow Subnormal Inexact Rounded +sqtx8727 squareroot 8.9970E-2000 -> 2.999E-1000 Underflow Subnormal Inexact Rounded +sqtx8728 squareroot 9.4587E-2000 -> 3.075E-1000 Underflow Subnormal Inexact Rounded +sqtx8729 squareroot 9.6069E-2000 -> 3.099E-1000 Underflow Subnormal Inexact Rounded +-- (End of Mark Dickinson's testcases.) + + +-- Some additional edge cases +maxexponent: 9 +minexponent: -9 +precision: 2 +sqtx9000 squareroot 9980.01 -> 1.0E+2 Inexact Rounded +precision: 3 +sqtx9001 squareroot 9980.01 -> 99.9 +precision: 4 +sqtx9002 squareroot 9980.01 -> 99.9 + +-- Exact from over-precise +precision: 4 +sqtx9003 squareroot 11025 -> 105 +precision: 3 +sqtx9004 squareroot 11025 -> 105 +precision: 2 +sqtx9005 squareroot 11025 -> 1.0E+2 Inexact Rounded +precision: 1 +sqtx9006 squareroot 11025 -> 1E+2 Inexact Rounded + +-- Out-of-bounds zeros +precision: 4 +sqtx9010 squareroot 0E-9 -> 0.00000 +sqtx9011 squareroot 0E-10 -> 0.00000 +sqtx9012 squareroot 0E-11 -> 0.000000 +sqtx9013 squareroot 0E-12 -> 0.000000 +sqtx9014 squareroot 0E-13 -> 0E-7 +sqtx9015 squareroot 0E-14 -> 0E-7 +sqtx9020 squareroot 0E-17 -> 0E-9 +sqtx9021 squareroot 0E-20 -> 0E-10 +sqtx9022 squareroot 0E-22 -> 0E-11 +sqtx9023 squareroot 0E-24 -> 0E-12 +sqtx9024 squareroot 0E-25 -> 0E-12 Clamped +sqtx9025 squareroot 0E-26 -> 0E-12 Clamped +sqtx9026 squareroot 0E-27 -> 0E-12 Clamped +sqtx9027 squareroot 0E-28 -> 0E-12 Clamped + +sqtx9030 squareroot 0E+8 -> 0E+4 +sqtx9031 squareroot 0E+10 -> 0E+5 +sqtx9032 squareroot 0E+12 -> 0E+6 +sqtx9033 squareroot 0E+14 -> 0E+7 +sqtx9034 squareroot 0E+15 -> 0E+7 +sqtx9035 squareroot 0E+16 -> 0E+8 +sqtx9036 squareroot 0E+18 -> 0E+9 +sqtx9037 squareroot 0E+19 -> 0E+9 +sqtx9038 squareroot 0E+20 -> 0E+9 Clamped +sqtx9039 squareroot 0E+21 -> 0E+9 Clamped +sqtx9040 squareroot 0E+22 -> 0E+9 Clamped + + -- Null test -sqtx900 squareroot # -> NaN Invalid_operation +sqtx9900 squareroot # -> NaN Invalid_operation Modified: python/branches/py3k/Lib/test/decimaltestdata/subtract.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/subtract.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/subtract.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- subtract.decTest -- decimal subtraction -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -805,9 +805,9 @@ subx1015 subtract 0 0.999E-999 -> -1.00E-999 Inexact Rounded Subnormal Underflow subx1016 subtract 0 0.099E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow subx1017 subtract 0 0.009E-999 -> -1E-1001 Inexact Rounded Subnormal Underflow -subx1018 subtract 0 0.001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow -subx1019 subtract 0 0.0009E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow -subx1020 subtract 0 0.0001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow +subx1018 subtract 0 0.001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +subx1019 subtract 0 0.0009E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +subx1020 subtract 0 0.0001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped subx1030 subtract 0 -1.00E-999 -> 1.00E-999 subx1031 subtract 0 -0.1E-999 -> 1E-1000 Subnormal @@ -818,9 +818,9 @@ subx1035 subtract 0 -0.999E-999 -> 1.00E-999 Inexact Rounded Subnormal Underflow subx1036 subtract 0 -0.099E-999 -> 1.0E-1000 Inexact Rounded Subnormal Underflow subx1037 subtract 0 -0.009E-999 -> 1E-1001 Inexact Rounded Subnormal Underflow -subx1038 subtract 0 -0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -subx1039 subtract 0 -0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -subx1040 subtract 0 -0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow +subx1038 subtract 0 -0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +subx1039 subtract 0 -0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +subx1040 subtract 0 -0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped -- some non-zero subnormal subtracts -- subx1056 is a tricky case @@ -831,7 +831,7 @@ subx1053 subtract 0.100E-999 0.1E-999 -> 0E-1001 Clamped subx1054 subtract 0.01E-999 0.1E-999 -> -9E-1001 Subnormal subx1055 subtract 0.999E-999 0.1E-999 -> 9.0E-1000 Inexact Rounded Subnormal Underflow -subx1056 subtract 0.099E-999 0.1E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow +subx1056 subtract 0.099E-999 0.1E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped subx1057 subtract 0.009E-999 0.1E-999 -> -9E-1001 Inexact Rounded Subnormal Underflow subx1058 subtract 0.001E-999 0.1E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow subx1059 subtract 0.0009E-999 0.1E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow @@ -849,15 +849,25 @@ subx1105 subtract 1.52445E-80 0 -> 1.524E-80 Inexact Rounded Subnormal Underflow subx1106 subtract 1.52446E-80 0 -> 1.524E-80 Inexact Rounded Subnormal Underflow -subx1111 subtract 1.2345678E-80 1.2345671E-80 -> 0E-83 Inexact Rounded Subnormal Underflow -subx1112 subtract 1.2345678E-80 1.2345618E-80 -> 0E-83 Inexact Rounded Subnormal Underflow -subx1113 subtract 1.2345678E-80 1.2345178E-80 -> 0E-83 Inexact Rounded Subnormal Underflow -subx1114 subtract 1.2345678E-80 1.2341678E-80 -> 0E-83 Inexact Rounded Subnormal Underflow +subx1111 subtract 1.2345678E-80 1.2345671E-80 -> 0E-83 Inexact Rounded Subnormal Underflow Clamped +subx1112 subtract 1.2345678E-80 1.2345618E-80 -> 0E-83 Inexact Rounded Subnormal Underflow Clamped +subx1113 subtract 1.2345678E-80 1.2345178E-80 -> 0E-83 Inexact Rounded Subnormal Underflow Clamped +subx1114 subtract 1.2345678E-80 1.2341678E-80 -> 0E-83 Inexact Rounded Subnormal Underflow Clamped subx1115 subtract 1.2345678E-80 1.2315678E-80 -> 3E-83 Rounded Subnormal subx1116 subtract 1.2345678E-80 1.2145678E-80 -> 2.0E-82 Rounded Subnormal subx1117 subtract 1.2345678E-80 1.1345678E-80 -> 1.00E-81 Rounded Subnormal subx1118 subtract 1.2345678E-80 0.2345678E-80 -> 1.000E-80 Rounded Subnormal +precision: 34 +rounding: half_up +maxExponent: 6144 +minExponent: -6143 +-- Examples from SQL proposal (Krishna Kulkarni) +subx1125 subtract 130E-2 120E-2 -> 0.10 +subx1126 subtract 130E-2 12E-1 -> 0.10 +subx1127 subtract 130E-2 1E0 -> 0.30 +subx1128 subtract 1E2 1E4 -> -9.9E+3 + -- Null tests subx9990 subtract 10 # -> NaN Invalid_operation subx9991 subtract # 10 -> NaN Invalid_operation Modified: python/branches/py3k/Lib/test/decimaltestdata/testall.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/testall.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/testall.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- testall.decTest -- run all general decimal arithmetic testcases -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,41 +17,70 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- core tests (using Extended: 1) -------------------------------------- dectest: base + dectest: abs dectest: add +dectest: and dectest: clamp +dectest: class dectest: compare +dectest: comparesig +dectest: comparetotal +dectest: comparetotmag +dectest: copy +dectest: copyabs +dectest: copynegate +dectest: copysign dectest: divide dectest: divideint +dectest: exp +dectest: fma dectest: inexact +dectest: invert +dectest: ln +dectest: logb +dectest: log10 dectest: max +dectest: maxmag dectest: min +dectest: minmag dectest: minus dectest: multiply -dectest: normalize +dectest: nextminus +dectest: nextplus +dectest: nexttoward +dectest: or dectest: plus dectest: power +dectest: powersqrt dectest: quantize dectest: randoms +dectest: reduce -- [was called normalize] dectest: remainder dectest: remaindernear dectest: rescale -- [obsolete] +dectest: rotate dectest: rounding dectest: samequantum +dectest: scaleb +dectest: shift dectest: squareroot dectest: subtract dectest: tointegral +dectest: tointegralx dectest: trim +dectest: xor --- The next are for the Strawman 4d concrete representations -dectest: decimal32 -dectest: decimal64 -dectest: decimal128 - +-- The next are for the Strawman 4d concrete representations and +-- tests at those sizes [including dsEncode, ddEncode, and dqEncode, +-- which replace decimal32, decimal64, and decimal128] +dectest: decSingle +dectest: decDouble +dectest: decQuad -- General 31->33-digit boundary tests dectest: randombound32 Modified: python/branches/py3k/Lib/test/decimaltestdata/tointegral.decTest ============================================================================== --- python/branches/py3k/Lib/test/decimaltestdata/tointegral.decTest (original) +++ python/branches/py3k/Lib/test/decimaltestdata/tointegral.decTest Wed Sep 19 05:06:30 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- tointegral.decTest -- round decimal to integral value -- --- Copyright (c) IBM Corporation, 2001, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 2001, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- This set of tests tests the extended specification 'round-to-integral -- value' operation (from IEEE 854, later modified in 754r). @@ -174,3 +174,68 @@ intx206 tointegral 7.89E+77 -> 7.89E+77 intx207 tointegral -Inf -> -Infinity + +-- all rounding modes +rounding: half_even + +intx210 tointegral 55.5 -> 56 +intx211 tointegral 56.5 -> 56 +intx212 tointegral 57.5 -> 58 +intx213 tointegral -55.5 -> -56 +intx214 tointegral -56.5 -> -56 +intx215 tointegral -57.5 -> -58 + +rounding: half_up + +intx220 tointegral 55.5 -> 56 +intx221 tointegral 56.5 -> 57 +intx222 tointegral 57.5 -> 58 +intx223 tointegral -55.5 -> -56 +intx224 tointegral -56.5 -> -57 +intx225 tointegral -57.5 -> -58 + +rounding: half_down + +intx230 tointegral 55.5 -> 55 +intx231 tointegral 56.5 -> 56 +intx232 tointegral 57.5 -> 57 +intx233 tointegral -55.5 -> -55 +intx234 tointegral -56.5 -> -56 +intx235 tointegral -57.5 -> -57 + +rounding: up + +intx240 tointegral 55.3 -> 56 +intx241 tointegral 56.3 -> 57 +intx242 tointegral 57.3 -> 58 +intx243 tointegral -55.3 -> -56 +intx244 tointegral -56.3 -> -57 +intx245 tointegral -57.3 -> -58 + +rounding: down + +intx250 tointegral 55.7 -> 55 +intx251 tointegral 56.7 -> 56 +intx252 tointegral 57.7 -> 57 +intx253 tointegral -55.7 -> -55 +intx254 tointegral -56.7 -> -56 +intx255 tointegral -57.7 -> -57 + +rounding: ceiling + +intx260 tointegral 55.3 -> 56 +intx261 tointegral 56.3 -> 57 +intx262 tointegral 57.3 -> 58 +intx263 tointegral -55.3 -> -55 +intx264 tointegral -56.3 -> -56 +intx265 tointegral -57.3 -> -57 + +rounding: floor + +intx270 tointegral 55.7 -> 55 +intx271 tointegral 56.7 -> 56 +intx272 tointegral 57.7 -> 57 +intx273 tointegral -55.7 -> -56 +intx274 tointegral -56.7 -> -57 +intx275 tointegral -57.7 -> -58 + Modified: python/branches/py3k/Lib/test/list_tests.py ============================================================================== --- python/branches/py3k/Lib/test/list_tests.py (original) +++ python/branches/py3k/Lib/test/list_tests.py Wed Sep 19 05:06:30 2007 @@ -46,6 +46,11 @@ self.assertEqual(str(a2), "[0, 1, 2, [...], 3]") self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]") + l0 = [] + for i in range(sys.getrecursionlimit() + 100): + l0 = [l0] + self.assertRaises(RuntimeError, repr, l0) + def test_print(self): d = self.type2test(range(200)) d.append(d) Modified: python/branches/py3k/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k/Lib/test/regrtest.py (original) +++ python/branches/py3k/Lib/test/regrtest.py Wed Sep 19 05:06:30 2007 @@ -1108,7 +1108,6 @@ class _ExpectedSkips: def __init__(self): import os.path - from test import test_socket_ssl from test import test_timeout self.valid = False @@ -1120,8 +1119,13 @@ if not os.path.supports_unicode_filenames: self.expected.add('test_pep277') - if test_socket_ssl.skip_expected: - self.expected.add('test_socket_ssl') + try: + from test import test_socket_ssl + except ImportError: + pass + else: + if test_socket_ssl.skip_expected: + self.expected.add('test_socket_ssl') if test_timeout.skip_expected: self.expected.add('test_timeout') Modified: python/branches/py3k/Lib/test/test_cmd_line.py ============================================================================== --- python/branches/py3k/Lib/test/test_cmd_line.py (original) +++ python/branches/py3k/Lib/test/test_cmd_line.py Wed Sep 19 05:06:30 2007 @@ -4,7 +4,7 @@ import subprocess def _spawn_python(*args): - cmd_line = [sys.executable] + cmd_line = [sys.executable, '-E'] cmd_line.extend(args) return subprocess.Popen(cmd_line, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) @@ -24,7 +24,7 @@ return _kill_python(p) def exit_code(self, *args): - cmd_line = [sys.executable] + cmd_line = [sys.executable, '-E'] cmd_line.extend(args) return subprocess.call(cmd_line, stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -38,9 +38,6 @@ self.assertTrue(data == b'' or data.endswith(b'\n')) self.assertTrue(b'Traceback' not in data) - def test_environment(self): - self.verify_valid_flag('-E') - def test_optimize(self): self.verify_valid_flag('-O') self.verify_valid_flag('-OO') Modified: python/branches/py3k/Lib/test/test_collections.py ============================================================================== --- python/branches/py3k/Lib/test/test_collections.py (original) +++ python/branches/py3k/Lib/test/test_collections.py Wed Sep 19 05:06:30 2007 @@ -38,6 +38,13 @@ self.assertEqual(repr(p), 'Point(x=11, y=22)') self.assert_('__dict__' not in dir(p)) # verify instance has no dict self.assert_('__weakref__' not in dir(p)) + self.assertEqual(p.__fields__, ('x', 'y')) # test __fields__ attribute + self.assertEqual(p.__replace__('x', 1), (1, 22)) # test __replace__ method + + # verify that field string can have commas + Point = NamedTuple('Point', 'x, y') + p = Point(x=11, y=22) + self.assertEqual(repr(p), 'Point(x=11, y=22)') def test_tupleness(self): Point = NamedTuple('Point', 'x y') @@ -58,6 +65,12 @@ self.assertEqual(p.y, y) self.assertRaises(AttributeError, eval, 'p.z', locals()) + def test_odd_sizes(self): + Zero = NamedTuple('Zero', '') + self.assertEqual(Zero(), ()) + Dot = NamedTuple('Dot', 'd') + self.assertEqual(Dot(1), (1,)) + class TestOneTrickPonyABCs(unittest.TestCase): Modified: python/branches/py3k/Lib/test/test_decimal.py ============================================================================== --- python/branches/py3k/Lib/test/test_decimal.py (original) +++ python/branches/py3k/Lib/test/test_decimal.py Wed Sep 19 05:06:30 2007 @@ -65,9 +65,7 @@ # Slower, since it runs some things several times. EXTENDEDERRORTEST = False - #Map the test cases' error names to the actual errors - ErrorNames = {'clamped' : Clamped, 'conversion_syntax' : InvalidOperation, 'division_by_zero' : DivisionByZero, @@ -92,20 +90,62 @@ 'half_down' : ROUND_HALF_DOWN, 'half_even' : ROUND_HALF_EVEN, 'half_up' : ROUND_HALF_UP, - 'up' : ROUND_UP} + 'up' : ROUND_UP, + '05up' : ROUND_05UP} # Name adapter to be able to change the Decimal and Context # interface without changing the test files from Cowlishaw nameAdapter = {'toeng':'to_eng_string', 'tosci':'to_sci_string', 'samequantum':'same_quantum', - 'tointegral':'to_integral', + 'tointegral':'to_integral_value', + 'tointegralx':'to_integral_exact', 'remaindernear':'remainder_near', 'divideint':'divide_int', 'squareroot':'sqrt', 'apply':'_apply', + 'class':'number_class', + 'comparesig':'compare_signal', + 'comparetotal':'compare_total', + 'comparetotmag':'compare_total_mag', + 'copyabs':'copy_abs', + 'copy':'copy_decimal', + 'copynegate':'copy_negate', + 'copysign':'copy_sign', + 'and':'logical_and', + 'or':'logical_or', + 'xor':'logical_xor', + 'invert':'logical_invert', + 'maxmag':'max_mag', + 'minmag':'min_mag', + 'nextminus':'next_minus', + 'nextplus':'next_plus', + 'nexttoward':'next_toward', + 'reduce':'normalize', } +# For some operations (currently exp, ln, log10, power), the decNumber +# reference implementation imposes additional restrictions on the +# context and operands. These restrictions are not part of the +# specification; however, the effect of these restrictions does show +# up in some of the testcases. We skip testcases that violate these +# restrictions, since Decimal behaves differently from decNumber for +# these testcases so these testcases would otherwise fail. + +decNumberRestricted = ('power', 'ln', 'log10', 'exp') +DEC_MAX_MATH = 999999 +def outside_decNumber_bounds(v, context): + if (context.prec > DEC_MAX_MATH or + context.Emax > DEC_MAX_MATH or + -context.Emin > DEC_MAX_MATH): + return True + if not v._is_special and v and ( + len(v._int) > DEC_MAX_MATH or + v.adjusted() > DEC_MAX_MATH or + v.adjusted() < 1-2*DEC_MAX_MATH): + return True + return False + class DecimalTest(unittest.TestCase): """Class which tests the Decimal class against the test cases. @@ -142,10 +182,6 @@ #print line try: t = self.eval_line(line) - except InvalidOperation: - print('Error in test cases:') - print(line) - continue except DecimalException as exception: #Exception raised where there shoudn't have been one. self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line) @@ -194,7 +230,8 @@ Sides = s.split('->') L = Sides[0].strip().split() id = L[0] -# print id, + if DEBUG: + print("Test ", id, end=" ") funct = L[1].lower() valstemp = L[2:] L = Sides[1].strip().split() @@ -246,11 +283,27 @@ self.context.traps[error] = 0 v = self.context.create_decimal(v) else: - v = Decimal(v) + v = Decimal(v, self.context) vals.append(v) ans = FixQuotes(ans) + # skip tests that are related to bounds imposed in the decNumber + # reference implementation + if fname in decNumberRestricted: + if fname == 'power': + if not (vals[1]._isinteger() and + -1999999997 <= vals[1] <= 999999999): + if outside_decNumber_bounds(vals[0], self.context) or \ + outside_decNumber_bounds(vals[1], self.context): + #print "Skipping test %s" % s + return + else: + if outside_decNumber_bounds(vals[0], self.context): + #print "Skipping test %s" % s + return + + if EXTENDEDERRORTEST and fname not in ('to_sci_string', 'to_eng_string'): for error in theirexceptions: self.context.traps[error] = 1 @@ -264,6 +317,8 @@ else: self.fail("Did not raise %s in %s" % (error, s)) self.context.traps[error] = 0 + if DEBUG: + print("--", self.context) try: result = str(funct(*vals)) if fname == 'same_quantum': @@ -283,8 +338,7 @@ self.assertEqual(result, ans, 'Incorrect answer for ' + s + ' -- got ' + result) self.assertEqual(myexceptions, theirexceptions, - 'Incorrect flags set in ' + s + ' -- got ' \ - + str(myexceptions)) + 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions)) return def getexceptions(self): @@ -301,17 +355,6 @@ def change_clamp(self, clamp): self.context._clamp = clamp -# Dynamically build custom test definition for each file in the test -# directory and add the definitions to the DecimalTest class. This -# procedure insures that new files do not get skipped. -for filename in os.listdir(directory): - if '.decTest' not in filename: - continue - head, tail = filename.split('.') - tester = lambda self, f=filename: self.eval_file(directory + f) - setattr(DecimalTest, 'test_' + head, tester) - del filename, head, tail, tester - # The following classes test the behaviour of Decimal according to PEP 327 @@ -798,7 +841,7 @@ th2.start() self.finish1.wait() - self.finish1.wait() + self.finish2.wait() return if threading is None: @@ -955,8 +998,8 @@ d1 = Decimal('-25e55') b1 = Decimal('-25e55') - d2 = Decimal('33e-33') - b2 = Decimal('33e-33') + d2 = Decimal('33e+33') + b2 = Decimal('33e+33') def checkSameDec(operation, useOther=False): if useOther: @@ -987,7 +1030,6 @@ checkSameDec("__floordiv__", True) checkSameDec("__hash__") checkSameDec("__int__") - checkSameDec("__long__") checkSameDec("__mod__", True) checkSameDec("__mul__", True) checkSameDec("__neg__") @@ -1018,6 +1060,21 @@ checkSameDec("to_eng_string") checkSameDec("to_integral") + def test_subclassing(self): + # Different behaviours when subclassing Decimal + + class MyDecimal(Decimal): + pass + + d1 = MyDecimal(1) + d2 = MyDecimal(2) + d = d1 + d2 + self.assertTrue(type(d) is Decimal) + + d = d1.max(d2) + self.assertTrue(type(d) is Decimal) + + class DecimalPythonAPItests(unittest.TestCase): def test_pickle(self): @@ -1084,7 +1141,59 @@ self.assert_(new_ctx is not set_ctx, 'did not copy the context') self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context') -def test_main(arith=False, verbose=None): +class ContextFlags(unittest.TestCase): + def test_flags_irrelevant(self): + # check that the result (numeric result + flags raised) of an + # arithmetic operation doesn't depend on the current flags + + context = Context(prec=9, Emin = -999999999, Emax = 999999999, + rounding=ROUND_HALF_EVEN, traps=[], flags=[]) + + # operations that raise various flags, in the form (function, arglist) + operations = [ + (context._apply, [Decimal("100E-1000000009")]), + (context.sqrt, [Decimal(2)]), + (context.add, [Decimal("1.23456789"), Decimal("9.87654321")]), + (context.multiply, [Decimal("1.23456789"), Decimal("9.87654321")]), + (context.subtract, [Decimal("1.23456789"), Decimal("9.87654321")]), + ] + + # try various flags individually, then a whole lot at once + flagsets = [[Inexact], [Rounded], [Underflow], [Clamped], [Subnormal], + [Inexact, Rounded, Underflow, Clamped, Subnormal]] + + for fn, args in operations: + # find answer and flags raised using a clean context + context.clear_flags() + ans = fn(*args) + flags = [k for k, v in context.flags.items() if v] + + for extra_flags in flagsets: + # set flags, before calling operation + context.clear_flags() + for flag in extra_flags: + context._raise_error(flag) + new_ans = fn(*args) + + # flags that we expect to be set after the operation + expected_flags = list(flags) + for flag in extra_flags: + if flag not in expected_flags: + expected_flags.append(flag) + expected_flags.sort(key=id) + + # flags we actually got + new_flags = [k for k,v in context.flags.items() if v] + new_flags.sort(key=id) + + self.assertEqual(ans, new_ans, + "operation produces different answers depending on flags set: " + + "expected %s, got %s." % (ans, new_ans)) + self.assertEqual(new_flags, expected_flags, + "operation raises different flags depending on flags set: " + + "expected %s, got %s" % (expected_flags, new_flags)) + +def test_main(arith=False, verbose=None, todo_tests=None, debug=None): """ Execute the tests. Runs all arithmetic tests if arith is True or if the "decimal" resource @@ -1092,35 +1201,58 @@ """ init() - global TEST_ALL + global TEST_ALL, DEBUG TEST_ALL = arith or is_resource_enabled('decimal') + DEBUG = debug + + if todo_tests is None: + test_classes = [ + DecimalExplicitConstructionTest, + DecimalImplicitConstructionTest, + DecimalArithmeticOperatorsTest, + DecimalUseOfContextTest, + DecimalUsabilityTest, + DecimalPythonAPItests, + ContextAPItests, + DecimalTest, + WithStatementTest, + ContextFlags + ] + else: + test_classes = [DecimalTest] + + # Dynamically build custom test definition for each file in the test + # directory and add the definitions to the DecimalTest class. This + # procedure insures that new files do not get skipped. + for filename in os.listdir(directory): + if '.decTest' not in filename or filename.startswith("."): + continue + head, tail = filename.split('.') + if todo_tests is not None and head not in todo_tests: + continue + tester = lambda self, f=filename: self.eval_file(directory + f) + setattr(DecimalTest, 'test_' + head, tester) + del filename, head, tail, tester - test_classes = [ - DecimalExplicitConstructionTest, - DecimalImplicitConstructionTest, - DecimalArithmeticOperatorsTest, - DecimalUseOfContextTest, - DecimalUsabilityTest, - DecimalPythonAPItests, - ContextAPItests, - DecimalTest, - WithStatementTest, - ] try: run_unittest(*test_classes) - import decimal as DecimalModule - run_doctest(DecimalModule, verbose) + if todo_tests is None: + import decimal as DecimalModule + run_doctest(DecimalModule, verbose) finally: setcontext(ORIGINAL_CONTEXT) if __name__ == '__main__': - # Calling with no arguments runs all tests. - # Calling with "Skip" will skip over 90% of the arithmetic tests. - if len(sys.argv) == 1: - test_main(arith=True, verbose=True) - elif len(sys.argv) == 2: - arith = sys.argv[1].lower() != 'skip' - test_main(arith=arith, verbose=True) + import optparse + p = optparse.OptionParser("test_decimal.py [--debug] [{--skip | test1 [test2 [...]]}]") + p.add_option('--debug', '-d', action='store_true', help='shows the test number and context before each test') + p.add_option('--skip', '-s', action='store_true', help='skip over 90% of the arithmetic tests') + (opt, args) = p.parse_args() + + if opt.skip: + test_main(arith=False, verbose=True) + elif args: + test_main(arith=True, verbose=True, todo_tests=args, debug=opt.debug) else: - raise ValueError("test called with wrong arguments, use test_Decimal [Skip]") + test_main(arith=True, verbose=True) Modified: python/branches/py3k/Lib/test/test_re.py ============================================================================== --- python/branches/py3k/Lib/test/test_re.py (original) +++ python/branches/py3k/Lib/test/test_re.py Wed Sep 19 05:06:30 2007 @@ -83,6 +83,34 @@ self.assertEqual(re.sub('\r\n', '\n', 'abc\r\ndef\r\n'), 'abc\ndef\n') +# This test makes no sense until re supports bytes, and should then probably +# test for the *in*ability to mix bytes and str this way :) +# +# def test_bug_1140(self): +# # re.sub(x, y, b'') should return b'', not '', and +# # re.sub(x, y, '') should return '', not b''. +# # Also: +# # re.sub(x, y, str(x)) should return str(y), and +# # re.sub(x, y, bytes(x)) should return +# # str(y) if isinstance(y, str) else unicode(y). +# for x in 'x', u'x': +# for y in 'y', u'y': +# z = re.sub(x, y, u'') +# self.assertEqual(z, u'') +# self.assertEqual(type(z), unicode) +# # +# z = re.sub(x, y, '') +# self.assertEqual(z, '') +# self.assertEqual(type(z), str) +# # +# z = re.sub(x, y, unicode(x)) +# self.assertEqual(z, y) +# self.assertEqual(type(z), unicode) +# # +# z = re.sub(x, y, str(x)) +# self.assertEqual(z, y) +# self.assertEqual(type(z), type(y)) + def test_sub_template_numeric_escape(self): # bug 776311 and friends self.assertEqual(re.sub('x', r'\0', 'x'), '\0') Modified: python/branches/py3k/Lib/test/test_repr.py ============================================================================== --- python/branches/py3k/Lib/test/test_repr.py (original) +++ python/branches/py3k/Lib/test/test_repr.py Wed Sep 19 05:06:30 2007 @@ -188,6 +188,16 @@ x = classmethod(C.foo) self.failUnless(repr(x).startswith('> received; expected <<%s>>\n" % (data, indata.lower())) - c1.close() + print("didn't raise TypeError") + ssl.RAND_add("this is a random string", 75.0) - def testReadCert(self): + def testParseCert(self): + # note that this uses an 'unofficial' function in _ssl.c, + # provided solely for this test, to exercise the certificate + # parsing code + p = ssl._ssl._test_decode_cert(CERTFILE, False) + if test_support.verbose: + sys.stdout.write("\n" + pprint.pformat(p) + "\n") - s2 = socket.socket() + def testDERtoPEM(self): + + pem = open(SVN_PYTHON_ORG_ROOT_CERT, 'r').read() + d1 = ssl.PEM_cert_to_DER_cert(pem) + p2 = ssl.DER_cert_to_PEM_cert(d1) + d2 = ssl.PEM_cert_to_DER_cert(p2) + if (d1 != d2): + raise test_support.TestFailed("PEM-to-DER or DER-to-PEM translation failed") + + +class NetworkTests(unittest.TestCase): + + def testConnect(self): + import os + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_NONE) + s.connect(("svn.python.org", 443)) + c = s.getpeercert() + if c: + raise test_support.TestFailed("Peer cert %s shouldn't be here!") + s.close() + + # this should fail because we have no verification certs + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED) try: - s2.connect(('127.0.0.1', 10024)) - except: - handle_error("connection failure:\n") - raise test_support.TestFailed("Can't connect to test server") + s.connect(("svn.python.org", 443)) + except ssl.SSLError: + pass + finally: + s.close() + + # this should succeed because we specify the root cert + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED, + ca_certs=SVN_PYTHON_ORG_ROOT_CERT) + try: + s.connect(("svn.python.org", 443)) + except ssl.SSLError as x: + raise test_support.TestFailed("Unexpected exception %s" % x) + finally: + s.close() + + def testFetchServerCert(self): + + pem = ssl.get_server_certificate(("svn.python.org", 443)) + if not pem: + raise test_support.TestFailed("No server certificate on svn.python.org:443!") + + try: + pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=CERTFILE) + except ssl.SSLError: + #should fail + pass else: - try: - c2 = ssl.sslsocket(s2, ssl_version=ssl.PROTOCOL_TLSv1, - cert_reqs=ssl.CERT_REQUIRED, ca_certs=CERTFILE) - except: - handle_error("SSL handshake failure:\n") - raise test_support.TestFailed("Can't SSL-handshake with test server") - else: - if not c2: - raise test_support.TestFailed("Can't SSL-handshake with test server") - cert = c2.getpeercert() - if not cert: - raise test_support.TestFailed("Can't get peer certificate.") - if test_support.verbose: - sys.stdout.write(pprint.pformat(cert) + '\n') - if not cert.has_key('subject'): - raise test_support.TestFailed( - "No subject field in certificate: %s." % - pprint.pformat(cert)) - if not ('organizationName', 'Python Software Foundation') in cert['subject']: - raise test_support.TestFailed( - "Missing or invalid 'organizationName' field in certificate subject; " - "should be 'Python Software Foundation'."); - c2.close() + raise test_support.TestFailed("Got server certificate %s for svn.python.org!" % pem) + pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=SVN_PYTHON_ORG_ROOT_CERT) + if not pem: + raise test_support.TestFailed("No server certificate on svn.python.org:443!") + if test_support.verbose: + sys.stdout.write("\nVerified certificate for svn.python.org:443 is\n%s\n" % pem) -class ThreadedEchoServer(threading.Thread): - class ConnectionHandler(threading.Thread): +try: + import threading +except ImportError: + _have_threads = False +else: - def __init__(self, server, connsock): - self.server = server - self.running = False - self.sock = connsock - threading.Thread.__init__(self) - self.setDaemon(True) + _have_threads = True - def run (self): - self.running = True - try: - sslconn = ssl.sslsocket(self.sock, server_side=True, - certfile=self.server.certificate, - ssl_version=self.server.protocol, - cert_reqs=self.server.certreqs) - except: - # here, we want to stop the server, because this shouldn't - # happen in the context of our test case - handle_error("Test server failure:\n") + class ThreadedEchoServer(threading.Thread): + + class ConnectionHandler(threading.Thread): + + """A mildly complicated class, because we want it to work both + with and without the SSL wrapper around the socket connection, so + that we can test the STARTTLS functionality.""" + + def __init__(self, server, connsock): + self.server = server self.running = False - # normally, we'd just stop here, but for the test - # harness, we want to stop the server - self.server.stop() - return + self.sock = connsock + self.sock.setblocking(1) + self.sslconn = None + threading.Thread.__init__(self) + self.setDaemon(True) - while self.running: + def wrap_conn (self): try: - msg = sslconn.read() - if not msg: - # eof, so quit this handler + self.sslconn = ssl.wrap_socket(self.sock, server_side=True, + certfile=self.server.certificate, + ssl_version=self.server.protocol, + ca_certs=self.server.cacerts, + cert_reqs=self.server.certreqs) + except: + if self.server.chatty: + handle_error("\n server: bad connection attempt from " + + str(self.sock.getpeername()) + ":\n") + if not self.server.expect_bad_connects: + # here, we want to stop the server, because this shouldn't + # happen in the context of our test case self.running = False - sslconn.close() - elif msg.strip() == 'over': - sslconn.close() + # normally, we'd just stop here, but for the test + # harness, we want to stop the server self.server.stop() + return False + + else: + if self.server.certreqs == ssl.CERT_REQUIRED: + cert = self.sslconn.getpeercert() + if test_support.verbose and self.server.chatty: + sys.stdout.write(" client cert is " + pprint.pformat(cert) + "\n") + cert_binary = self.sslconn.getpeercert(True) + if test_support.verbose and self.server.chatty: + sys.stdout.write(" cert binary is " + str(len(cert_binary)) + " bytes\n") + cipher = self.sslconn.cipher() + if test_support.verbose and self.server.chatty: + sys.stdout.write(" server: connection cipher is now " + str(cipher) + "\n") + return True + + def read(self): + if self.sslconn: + return self.sslconn.read() + else: + return self.sock.recv(1024) + + def write(self, bytes): + if self.sslconn: + return self.sslconn.write(bytes) + else: + return self.sock.send(bytes) + + def close(self): + if self.sslconn: + self.sslconn.close() + else: + self.sock.close() + + def run (self): + self.running = True + if not self.server.starttls_server: + if not self.wrap_conn(): + return + while self.running: + try: + msg = self.read() + if not msg: + # eof, so quit this handler + self.running = False + self.close() + elif msg.strip() == 'over': + if test_support.verbose and self.server.connectionchatty: + sys.stdout.write(" server: client closed connection\n") + self.close() + return + elif self.server.starttls_server and msg.strip() == 'STARTTLS': + if test_support.verbose and self.server.connectionchatty: + sys.stdout.write(" server: read STARTTLS from client, sending OK...\n") + self.write("OK\n") + if not self.wrap_conn(): + return + else: + if (test_support.verbose and + self.server.connectionchatty): + ctype = (self.sslconn and "encrypted") or "unencrypted" + sys.stdout.write(" server: read %s (%s), sending back %s (%s)...\n" + % (repr(msg), ctype, repr(msg.lower()), ctype)) + self.write(msg.lower()) + except ssl.SSLError: + if self.server.chatty: + handle_error("Test server failure:\n") + self.close() self.running = False - else: - if test_support.verbose: - sys.stdout.write("\nserver: %s\n" % msg.strip().lower()) - sslconn.write(msg.lower()) - except ssl.sslerror: - handle_error("Test server failure:\n") - sslconn.close() - self.running = False - # normally, we'd just stop here, but for the test - # harness, we want to stop the server - self.server.stop() + # normally, we'd just stop here, but for the test + # harness, we want to stop the server + self.server.stop() + except: + handle_error('') + + def __init__(self, port, certificate, ssl_version=None, + certreqs=None, cacerts=None, expect_bad_connects=False, + chatty=True, connectionchatty=False, starttls_server=False): + if ssl_version is None: + ssl_version = ssl.PROTOCOL_TLSv1 + if certreqs is None: + certreqs = ssl.CERT_NONE + self.certificate = certificate + self.protocol = ssl_version + self.certreqs = certreqs + self.cacerts = cacerts + self.expect_bad_connects = expect_bad_connects + self.chatty = chatty + self.connectionchatty = connectionchatty + self.starttls_server = starttls_server + self.sock = socket.socket() + self.flag = None + if hasattr(socket, 'SO_REUSEADDR'): + self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, 'SO_REUSEPORT'): + self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + self.sock.bind(('127.0.0.1', port)) + self.active = False + threading.Thread.__init__(self) + self.setDaemon(False) + + def start (self, flag=None): + self.flag = flag + threading.Thread.start(self) + + def run (self): + self.sock.settimeout(0.5) + self.sock.listen(5) + self.active = True + if self.flag: + # signal an event + self.flag.set() + while self.active: + try: + newconn, connaddr = self.sock.accept() + if test_support.verbose and self.chatty: + sys.stdout.write(' server: new connection from ' + + str(connaddr) + '\n') + handler = self.ConnectionHandler(self, newconn) + handler.start() + except socket.timeout: + pass + except KeyboardInterrupt: + self.stop() except: - handle_error('') + if self.chatty: + handle_error("Test server failure:\n") + + def stop (self): + self.active = False + self.sock.close() + + + class AsyncoreHTTPSServer(threading.Thread): + + class HTTPSServer(HTTPServer): + + def __init__(self, server_address, RequestHandlerClass, certfile): + + HTTPServer.__init__(self, server_address, RequestHandlerClass) + # we assume the certfile contains both private key and certificate + self.certfile = certfile + self.active = False + self.allow_reuse_address = True + + def get_request (self): + # override this to wrap socket with SSL + sock, addr = self.socket.accept() + sslconn = ssl.wrap_socket(sock, server_side=True, + certfile=self.certfile) + return sslconn, addr + + # The methods overridden below this are mainly so that we + # can run it in a thread and be able to stop it from another + # You probably wouldn't need them in other uses. + + def server_activate(self): + # We want to run this in a thread for testing purposes, + # so we override this to set timeout, so that we get + # a chance to stop the server + self.socket.settimeout(0.5) + HTTPServer.server_activate(self) + + def serve_forever(self): + # We want this to run in a thread, so we use a slightly + # modified version of "forever". + self.active = True + while self.active: + try: + self.handle_request() + except socket.timeout: + pass + except KeyboardInterrupt: + self.server_close() + return + except: + sys.stdout.write(''.join(traceback.format_exception(*sys.exc_info()))); + + def server_close(self): + # Again, we want this to run in a thread, so we need to override + # close to clear the "active" flag, so that serve_forever() will + # terminate. + HTTPServer.server_close(self) + self.active = False + + class RootedHTTPRequestHandler(SimpleHTTPRequestHandler): + + # need to override translate_path to get a known root, + # instead of using os.curdir, since the test could be + # run from anywhere + + server_version = "TestHTTPS/1.0" + + root = None + + def translate_path(self, path): + """Translate a /-separated PATH to the local filename syntax. + + Components that mean special things to the local file system + (e.g. drive or directory names) are ignored. (XXX They should + probably be diagnosed.) + + """ + # abandon query parameters + path = urlparse.urlparse(path)[2] + path = os.path.normpath(urllib.unquote(path)) + words = path.split('/') + words = filter(None, words) + path = self.root + for word in words: + drive, word = os.path.splitdrive(word) + head, word = os.path.split(word) + if word in self.root: continue + path = os.path.join(path, word) + return path + + def log_message(self, format, *args): + + # we override this to suppress logging unless "verbose" + + if test_support.verbose: + sys.stdout.write(" server (%s, %d, %s):\n [%s] %s\n" % + (self.server.server_name, + self.server.server_port, + self.request.cipher(), + self.log_date_time_string(), + format%args)) + + + def __init__(self, port, certfile): + self.flag = None + self.active = False + self.RootedHTTPRequestHandler.root = os.path.split(CERTFILE)[0] + self.server = self.HTTPSServer( + ('', port), self.RootedHTTPRequestHandler, certfile) + threading.Thread.__init__(self) + self.setDaemon(True) - def __init__(self, port, certificate, ssl_version=None, - certreqs=None, cacerts=None): - if ssl_version is None: - ssl_version = ssl.PROTOCOL_TLSv1 - if certreqs is None: - certreqs = ssl.CERT_NONE - self.certificate = certificate - self.protocol = ssl_version - self.certreqs = certreqs - self.cacerts = cacerts - self.sock = socket.socket() - self.flag = None - if hasattr(socket, 'SO_REUSEADDR'): - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - if hasattr(socket, 'SO_REUSEPORT'): - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) - self.sock.bind(('127.0.0.1', port)) - self.active = False - threading.Thread.__init__(self) - self.setDaemon(False) - - def start (self, flag=None): - self.flag = flag - threading.Thread.start(self) - - def run (self): - self.sock.settimeout(0.5) - self.sock.listen(5) - self.active = True - if self.flag: - # signal an event - self.flag.set() - while self.active: + def __str__(self): + return '<%s %s:%d>' % (self.__class__.__name__, + self.server.server_name, + self.server.server_port) + + def start (self, flag=None): + self.flag = flag + threading.Thread.start(self) + + def run (self): + self.active = True + if self.flag: + self.flag.set() + self.server.serve_forever() + self.active = False + + def stop (self): + self.active = False + self.server.server_close() + + + def badCertTest (certfile): + server = ThreadedEchoServer(TESTPORT, CERTFILE, + certreqs=ssl.CERT_REQUIRED, + cacerts=CERTFILE, chatty=False) + flag = threading.Event() + server.start(flag) + # wait for it to start + flag.wait() + # try to connect + try: try: - newconn, connaddr = self.sock.accept() + s = ssl.wrap_socket(socket.socket(), + certfile=certfile, + ssl_version=ssl.PROTOCOL_TLSv1) + s.connect(('127.0.0.1', TESTPORT)) + except ssl.SSLError as x: if test_support.verbose: - sys.stdout.write('\nserver: new connection from ' + str(connaddr) + '\n') - handler = self.ConnectionHandler(self, newconn) - handler.start() - except socket.timeout: - pass - except KeyboardInterrupt: - self.stop() - except: - handle_error("Test server failure:\n") + sys.stdout.write("\nSSLError is %s\n" % x[1]) + else: + raise test_support.TestFailed( + "Use of invalid cert should have failed!") + finally: + server.stop() + server.join() + + def serverParamsTest (certfile, protocol, certreqs, cacertsfile, + client_certfile, client_protocol=None, indata="FOO\n", + chatty=True, connectionchatty=False): + + server = ThreadedEchoServer(TESTPORT, certfile, + certreqs=certreqs, + ssl_version=protocol, + cacerts=cacertsfile, + chatty=chatty, + connectionchatty=connectionchatty) + flag = threading.Event() + server.start(flag) + # wait for it to start + flag.wait() + # try to connect + if client_protocol is None: + client_protocol = protocol + try: + try: + s = ssl.wrap_socket(socket.socket(), + certfile=client_certfile, + ca_certs=cacertsfile, + cert_reqs=certreqs, + ssl_version=client_protocol) + s.connect(('127.0.0.1', TESTPORT)) + except ssl.SSLError as x: + raise test_support.TestFailed("Unexpected SSL error: " + str(x)) + except Exception as x: + raise test_support.TestFailed("Unexpected exception: " + str(x)) + else: + if connectionchatty: + if test_support.verbose: + sys.stdout.write( + " client: sending %s...\n" % (repr(indata))) + s.write(indata) + outdata = s.read() + if connectionchatty: + if test_support.verbose: + sys.stdout.write(" client: read %s\n" % repr(outdata)) + if outdata != indata.lower(): + raise test_support.TestFailed( + "bad data <<%s>> (%d) received; expected <<%s>> (%d)\n" + % (outdata[:min(len(outdata),20)], len(outdata), + indata[:min(len(indata),20)].lower(), len(indata))) + s.write("over\n") + if connectionchatty: + if test_support.verbose: + sys.stdout.write(" client: closing connection.\n") + s.close() + finally: + server.stop() + server.join() - def stop (self): - self.active = False - self.sock.close() - -CERTFILE_CONFIG_TEMPLATE = """ -# create RSA certs - Server - -[ req ] -default_bits = 1024 -encrypt_key = yes -distinguished_name = req_dn -x509_extensions = cert_type - -[ req_dn ] -countryName = Country Name (2 letter code) -countryName_default = US -countryName_min = 2 -countryName_max = 2 - -stateOrProvinceName = State or Province Name (full name) -stateOrProvinceName_default = %(state)s - -localityName = Locality Name (eg, city) -localityName_default = %(city)s - -0.organizationName = Organization Name (eg, company) -0.organizationName_default = %(organization)s - -organizationalUnitName = Organizational Unit Name (eg, section) -organizationalUnitName_default = %(unit)s - -0.commonName = Common Name (FQDN of your server) -0.commonName_default = %(common-name)s - -# To create a certificate for more than one name uncomment: -# 1.commonName = DNS alias of your server -# 2.commonName = DNS alias of your server -# ... -# See http://home.netscape.com/eng/security/ssl_2.0_certificate.html -# to see how Netscape understands commonName. - -[ cert_type ] -nsCertType = server -""" - -def create_cert_files(hostname=None): - - """This is the routine that was run to create the certificate - and private key contained in keycert.pem.""" - - import tempfile, socket, os - d = tempfile.mkdtemp() - # now create a configuration file for the CA signing cert - fqdn = hostname or socket.getfqdn() - crtfile = os.path.join(d, "cert.pem") - conffile = os.path.join(d, "ca.conf") - fp = open(conffile, "w") - fp.write(CERTFILE_CONFIG_TEMPLATE % - {'state': "Delaware", - 'city': "Wilmington", - 'organization': "Python Software Foundation", - 'unit': "SSL", - 'common-name': fqdn, - }) - fp.close() - error = os.system( - "openssl req -batch -new -x509 -days 2000 -nodes -config %s " - "-keyout \"%s\" -out \"%s\" > /dev/null < /dev/null 2>&1" % - (conffile, crtfile, crtfile)) - # now we have a self-signed server cert in crtfile - os.unlink(conffile) - if (os.WEXITSTATUS(error) or - not os.path.exists(crtfile) or os.path.getsize(crtfile) == 0): + def tryProtocolCombo (server_protocol, + client_protocol, + expectedToWork, + certsreqs=None): + + if certsreqs == None: + certsreqs = ssl.CERT_NONE + + if certsreqs == ssl.CERT_NONE: + certtype = "CERT_NONE" + elif certsreqs == ssl.CERT_OPTIONAL: + certtype = "CERT_OPTIONAL" + elif certsreqs == ssl.CERT_REQUIRED: + certtype = "CERT_REQUIRED" if test_support.verbose: - sys.stdout.write("Unable to create certificate for test, " - + "error status %d\n" % (error >> 8)) - crtfile = None - elif test_support.verbose: - sys.stdout.write(open(crtfile, 'r').read() + '\n') - return d, crtfile + formatstr = (expectedToWork and " %s->%s %s\n") or " {%s->%s} %s\n" + sys.stdout.write(formatstr % + (ssl.get_protocol_name(client_protocol), + ssl.get_protocol_name(server_protocol), + certtype)) + try: + serverParamsTest(CERTFILE, server_protocol, certsreqs, + CERTFILE, CERTFILE, client_protocol, chatty=False) + except test_support.TestFailed: + if expectedToWork: + raise + else: + if not expectedToWork: + raise test_support.TestFailed( + "Client protocol %s succeeded with server protocol %s!" + % (ssl.get_protocol_name(client_protocol), + ssl.get_protocol_name(server_protocol))) + + + class ConnectedTests(unittest.TestCase): + + def testRudeShutdown(self): + + listener_ready = threading.Event() + listener_gone = threading.Event() + + # `listener` runs in a thread. It opens a socket listening on + # PORT, and sits in an accept() until the main thread connects. + # Then it rudely closes the socket, and sets Event `listener_gone` + # to let the main thread know the socket is gone. + def listener(): + s = socket.socket() + if hasattr(socket, 'SO_REUSEADDR'): + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, 'SO_REUSEPORT'): + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + s.bind(('127.0.0.1', TESTPORT)) + s.listen(5) + listener_ready.set() + s.accept() + s = None # reclaim the socket object, which also closes it + listener_gone.set() + + def connector(): + listener_ready.wait() + s = socket.socket() + s.connect(('127.0.0.1', TESTPORT)) + listener_gone.wait() + try: + ssl_sock = ssl.wrap_socket(s) + except socket.sslerror: + pass + else: + raise test_support.TestFailed( + 'connecting to closed SSL socket should have failed') + + t = threading.Thread(target=listener) + t.start() + connector() + t.join() + + def testEcho (self): + + if test_support.verbose: + sys.stdout.write("\n") + serverParamsTest(CERTFILE, ssl.PROTOCOL_TLSv1, ssl.CERT_NONE, + CERTFILE, CERTFILE, ssl.PROTOCOL_TLSv1, + chatty=True, connectionchatty=True) + + def testReadCert(self): + + if test_support.verbose: + sys.stdout.write("\n") + s2 = socket.socket() + server = ThreadedEchoServer(TESTPORT, CERTFILE, + certreqs=ssl.CERT_NONE, + ssl_version=ssl.PROTOCOL_SSLv23, + cacerts=CERTFILE, + chatty=False) + flag = threading.Event() + server.start(flag) + # wait for it to start + flag.wait() + # try to connect + try: + try: + s = ssl.wrap_socket(socket.socket(), + certfile=CERTFILE, + ca_certs=CERTFILE, + cert_reqs=ssl.CERT_REQUIRED, + ssl_version=ssl.PROTOCOL_SSLv23) + s.connect(('127.0.0.1', TESTPORT)) + except ssl.SSLError as x: + raise test_support.TestFailed( + "Unexpected SSL error: " + str(x)) + except Exception as x: + raise test_support.TestFailed( + "Unexpected exception: " + str(x)) + else: + if not s: + raise test_support.TestFailed( + "Can't SSL-handshake with test server") + cert = s.getpeercert() + if not cert: + raise test_support.TestFailed( + "Can't get peer certificate.") + cipher = s.cipher() + if test_support.verbose: + sys.stdout.write(pprint.pformat(cert) + '\n') + sys.stdout.write("Connection cipher is " + str(cipher) + '.\n') + if not cert.has_key('subject'): + raise test_support.TestFailed( + "No subject field in certificate: %s." % + pprint.pformat(cert)) + if ((('organizationName', 'Python Software Foundation'),) + not in cert['subject']): + raise test_support.TestFailed( + "Missing or invalid 'organizationName' field in certificate subject; " + "should be 'Python Software Foundation'."); + s.close() + finally: + server.stop() + server.join() + + def testNULLcert(self): + badCertTest(os.path.join(os.path.dirname(__file__) or os.curdir, + "nullcert.pem")) + def testMalformedCert(self): + badCertTest(os.path.join(os.path.dirname(__file__) or os.curdir, + "badcert.pem")) + def testMalformedKey(self): + badCertTest(os.path.join(os.path.dirname(__file__) or os.curdir, + "badkey.pem")) + + def testProtocolSSL2(self): + if test_support.verbose: + sys.stdout.write("\n") + tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True) + tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL) + tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED) + tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True) + tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) + tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) + + def testProtocolSSL23(self): + if test_support.verbose: + sys.stdout.write("\n") + try: + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True) + except test_support.TestFailed as x: + # this fails on some older versions of OpenSSL (0.9.7l, for instance) + if test_support.verbose: + sys.stdout.write( + " SSL2 client to SSL23 server test unexpectedly failed:\n %s\n" + % str(x)) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True) + + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_OPTIONAL) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) + + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) + + def testProtocolSSL3(self): + if test_support.verbose: + sys.stdout.write("\n") + tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True) + tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) + tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) + tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False) + tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False) + tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) + + def testProtocolTLS1(self): + if test_support.verbose: + sys.stdout.write("\n") + tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True) + tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) + tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) + tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False) + tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False) + tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False) + + def testSTARTTLS (self): + + msgs = ("msg 1", "MSG 2", "STARTTLS", "MSG 3", "msg 4") + + server = ThreadedEchoServer(TESTPORT, CERTFILE, + ssl_version=ssl.PROTOCOL_TLSv1, + starttls_server=True, + chatty=True, + connectionchatty=True) + flag = threading.Event() + server.start(flag) + # wait for it to start + flag.wait() + # try to connect + wrapped = False + try: + try: + s = socket.socket() + s.setblocking(1) + s.connect(('127.0.0.1', TESTPORT)) + except Exception as x: + raise test_support.TestFailed("Unexpected exception: " + str(x)) + else: + if test_support.verbose: + sys.stdout.write("\n") + for indata in msgs: + if test_support.verbose: + sys.stdout.write( + " client: sending %s...\n" % repr(indata)) + if wrapped: + conn.write(indata) + outdata = conn.read() + else: + s.send(indata) + outdata = s.recv(1024) + if (indata == "STARTTLS" and + outdata.strip().lower().startswith("ok")): + if test_support.verbose: + sys.stdout.write( + " client: read %s from server, starting TLS...\n" + % repr(outdata)) + conn = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1) + + wrapped = True + else: + if test_support.verbose: + sys.stdout.write( + " client: read %s from server\n" % repr(outdata)) + if test_support.verbose: + sys.stdout.write(" client: closing connection.\n") + if wrapped: + conn.write("over\n") + else: + s.send("over\n") + s.close() + finally: + server.stop() + server.join() + + def testAsyncore(self): + + server = AsyncoreHTTPSServer(TESTPORT, CERTFILE) + flag = threading.Event() + server.start(flag) + # wait for it to start + flag.wait() + # try to connect + try: + if test_support.verbose: + sys.stdout.write('\n') + d1 = open(CERTFILE, 'rb').read() + d2 = '' + # now fetch the same data from the HTTPS server + url = 'https://127.0.0.1:%d/%s' % ( + TESTPORT, os.path.split(CERTFILE)[1]) + f = urllib.urlopen(url) + dlen = f.info().getheader("content-length") + if dlen and (int(dlen) > 0): + d2 = f.read(int(dlen)) + if test_support.verbose: + sys.stdout.write( + " client: read %d bytes from remote server '%s'\n" + % (len(d2), server)) + f.close() + except: + msg = ''.join(traceback.format_exception(*sys.exc_info())) + if test_support.verbose: + sys.stdout.write('\n' + msg) + raise test_support.TestFailed(msg) + else: + if not (d1 == d2): + raise test_support.TestFailed( + "Couldn't fetch data from HTTPS server") + finally: + server.stop() + server.join() + + +def findtestsocket(start, end): + def testbind(i): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + s.bind(("127.0.0.1", i)) + except: + return 0 + else: + return 1 + finally: + s.close() + + for i in range(start, end): + if testbind(i) and testbind(i+1): + return i + return 0 def test_main(verbose=False): if skip_expected: raise test_support.TestSkipped("No SSL support") - global CERTFILE + global CERTFILE, TESTPORT, SVN_PYTHON_ORG_ROOT_CERT CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") - if not CERTFILE: - sys.__stdout__.write("Skipping test_ssl ConnectedTests; " - "couldn't create a certificate.\n") + SVN_PYTHON_ORG_ROOT_CERT = os.path.join( + os.path.dirname(__file__) or os.curdir, + "https_svn_python_org_root.pem") + + if (not os.path.exists(CERTFILE) or + not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)): + raise test_support.TestFailed("Can't read certificate files!") + TESTPORT = findtestsocket(10025, 12000) + if not TESTPORT: + raise test_support.TestFailed("Can't find open port to test servers on!") tests = [BasicTests] - server = None - if CERTFILE and test_support.is_resource_enabled('network'): - server = ThreadedEchoServer(10024, CERTFILE) - flag = threading.Event() - server.start(flag) - # wait for it to start - flag.wait() - tests.append(ConnectedTests) + if test_support.is_resource_enabled('network'): + tests.append(NetworkTests) - thread_info = test_support.threading_setup() + if _have_threads: + thread_info = test_support.threading_setup() + if thread_info and test_support.is_resource_enabled('network'): + tests.append(ConnectedTests) - try: - test_support.run_unittest(*tests) - finally: - if server is not None and server.active: - server.stop() - # wait for it to stop - server.join() + test_support.run_unittest(*tests) - test_support.threading_cleanup(*thread_info) + if _have_threads: + test_support.threading_cleanup(*thread_info) if __name__ == "__main__": test_main() Modified: python/branches/py3k/Mac/Modules/cf/_CFmodule.c ============================================================================== --- python/branches/py3k/Mac/Modules/cf/_CFmodule.c (original) +++ python/branches/py3k/Mac/Modules/cf/_CFmodule.c Wed Sep 19 05:06:30 2007 @@ -1821,6 +1821,7 @@ if (!PyArg_Parse(v, "es", "ascii", &cStr)) return 0; *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII); + PyMem_Free(cStr); return 1; } if (PyUnicode_Check(v)) { Modified: python/branches/py3k/Mac/Modules/cf/cfsupport.py ============================================================================== --- python/branches/py3k/Mac/Modules/cf/cfsupport.py (original) +++ python/branches/py3k/Mac/Modules/cf/cfsupport.py Wed Sep 19 05:06:30 2007 @@ -429,6 +429,7 @@ if (!PyArg_Parse(v, "es", "ascii", &cStr)) return NULL; *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII); + PyMem_Free(cStr); return 1; } if (PyUnicode_Check(v)) { Modified: python/branches/py3k/Mac/Modules/cf/pycfbridge.c ============================================================================== --- python/branches/py3k/Mac/Modules/cf/pycfbridge.c (original) +++ python/branches/py3k/Mac/Modules/cf/pycfbridge.c Wed Sep 19 05:06:30 2007 @@ -285,6 +285,7 @@ if (!PyArg_Parse(src, "es", "ascii", &chars)) return 0; /* This error is more descriptive than the general one below */ *dst = CFStringCreateWithCString((CFAllocatorRef)NULL, chars, kCFStringEncodingASCII); + PyMem_Free(chars); return 1; } if (PyUnicode_Check(src)) { Modified: python/branches/py3k/Modules/_sre.c ============================================================================== --- python/branches/py3k/Modules/_sre.c (original) +++ python/branches/py3k/Modules/_sre.c Wed Sep 19 05:06:30 2007 @@ -1969,7 +1969,7 @@ #endif static PyObject* -join_list(PyObject* list, PyObject* pattern) +join_list(PyObject* list, PyObject* string) { /* join list elements */ @@ -1980,24 +1980,15 @@ #endif PyObject* result; - switch (PyList_GET_SIZE(list)) { - case 0: - Py_DECREF(list); - return PySequence_GetSlice(pattern, 0, 0); - case 1: - result = PyList_GET_ITEM(list, 0); - Py_INCREF(result); - Py_DECREF(list); - return result; - } - - /* two or more elements: slice out a suitable separator from the - first member, and use that to join the entire list */ - - joiner = PySequence_GetSlice(pattern, 0, 0); + joiner = PySequence_GetSlice(string, 0, 0); if (!joiner) return NULL; + if (PyList_GET_SIZE(list) == 0) { + Py_DECREF(list); + return joiner; + } + #if PY_VERSION_HEX >= 0x01060000 function = PyObject_GetAttrString(joiner, "join"); if (!function) { @@ -2433,7 +2424,7 @@ Py_DECREF(filter); /* convert list to single string (also removes list) */ - item = join_list(list, self->pattern); + item = join_list(list, string); if (!item) return NULL; Modified: python/branches/py3k/Modules/_ssl.c ============================================================================== --- python/branches/py3k/Modules/_ssl.c (original) +++ python/branches/py3k/Modules/_ssl.c Wed Sep 19 05:06:30 2007 @@ -1,14 +1,38 @@ /* SSL socket module SSL support based on patches by Brian E Gallew and Laszlo Kovacs. + Re-worked a bit by Bill Janssen to add server-side support and + certificate decoding. - This module is imported by socket.py. It should *not* be used + This module is imported by ssl.py. It should *not* be used directly. + XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE? + + XXX what about SSL_MODE_AUTO_RETRY */ #include "Python.h" +#ifdef WITH_THREAD +#include "pythread.h" +#define PySSL_BEGIN_ALLOW_THREADS { \ + PyThreadState *_save; \ + if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} +#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)}; +#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; +#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ + } + +#else /* no WITH_THREAD */ + +#define PySSL_BEGIN_ALLOW_THREADS +#define PySSL_BLOCK_THREADS +#define PySSL_UNBLOCK_THREADS +#define PySSL_END_ALLOW_THREADS + +#endif + enum py_ssl_error { /* these mirror ssl.h */ PY_SSL_ERROR_NONE, @@ -55,6 +79,7 @@ #include "openssl/rsa.h" #include "openssl/crypto.h" #include "openssl/x509.h" +#include "openssl/x509v3.h" #include "openssl/pem.h" #include "openssl/ssl.h" #include "openssl/err.h" @@ -63,6 +88,15 @@ /* SSL error object */ static PyObject *PySSLErrorObject; +#ifdef WITH_THREAD + +/* serves as a flag to see whether we've initialized the SSL thread support. */ +/* 0 means no, greater than 0 means yes */ + +static unsigned int _ssl_locks_count = 0; + +#endif /* def WITH_THREAD */ + /* SSL socket object */ #define X509_NAME_MAXLEN 256 @@ -90,8 +124,8 @@ static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args); static int check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing); -static PyObject *PySSL_peercert(PySSLObject *self); - +static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args); +static PyObject *PySSL_cipher(PySSLObject *self); #define PySSLObject_Check(v) (Py_Type(v) == &PySSL_Type) @@ -126,7 +160,7 @@ assert(ret <= 0); - if ((obj != NULL) && (obj->ssl != NULL)) { + if (obj->ssl != NULL) { err = SSL_get_error(obj->ssl, ret); switch (err) { @@ -202,6 +236,25 @@ return NULL; } +static PyObject * +_setSSLError (char *errstr, int errcode, char *filename, int lineno) { + + char buf[2048]; + PyObject *v; + + if (errstr == NULL) { + errcode = ERR_peek_last_error(); + errstr = ERR_error_string(errcode, NULL); + } + PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + v = Py_BuildValue("(is)", errcode, buf); + if (v != NULL) { + PyErr_SetObject(PySSLErrorObject, v); + Py_DECREF(v); + } + return NULL; +} + static PySSLObject * newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file, enum py_ssl_server_or_client socket_type, @@ -226,6 +279,10 @@ self->ctx = NULL; self->Socket = NULL; + /* Make sure the SSL error state is initialized */ + (void) ERR_get_state(); + ERR_clear_error(); + if ((key_file && !cert_file) || (!key_file && cert_file)) { errstr = ERRSTR("Both the key & certificate files " "must be specified"); @@ -239,16 +296,16 @@ goto fail; } - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS if (proto_version == PY_SSL_VERSION_TLS1) self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ else if (proto_version == PY_SSL_VERSION_SSL3) self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ else if (proto_version == PY_SSL_VERSION_SSL2) self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ - else + else if (proto_version == PY_SSL_VERSION_SSL23) self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if (self->ctx == NULL) { errstr = ERRSTR("Invalid SSL protocol variant specified."); @@ -261,39 +318,46 @@ "verification of other-side certificates."); goto fail; } else { - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS ret = SSL_CTX_load_verify_locations(self->ctx, cacerts_file, NULL); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if (ret != 1) { - PySSL_SetError(NULL, 0, __FILE__, __LINE__); + _setSSLError(NULL, 0, __FILE__, __LINE__); goto fail; } } } if (key_file) { - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, SSL_FILETYPE_PEM); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if (ret != 1) { - PySSL_SetError(NULL, 0, __FILE__, __LINE__); + _setSSLError(NULL, ret, __FILE__, __LINE__); goto fail; } - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS ret = SSL_CTX_use_certificate_chain_file(self->ctx, - cert_file); - Py_END_ALLOW_THREADS + cert_file); + PySSL_END_ALLOW_THREADS if (ret != 1) { - PySSL_SetError(NULL, 0, __FILE__, __LINE__); - goto fail; + /* + fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", + ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); + */ + if (ERR_peek_last_error() != 0) { + _setSSLError(NULL, ret, __FILE__, __LINE__); + goto fail; + } } - /* ssl compatibility */ - SSL_CTX_set_options(self->ctx, SSL_OP_ALL); } + /* ssl compatibility */ + SSL_CTX_set_options(self->ctx, SSL_OP_ALL); + verification_mode = SSL_VERIFY_NONE; if (certreq == PY_SSL_CERT_OPTIONAL) verification_mode = SSL_VERIFY_PEER; @@ -303,9 +367,9 @@ SSL_CTX_set_verify(self->ctx, verification_mode, NULL); /* set verify lvl */ - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS self->ssl = SSL_new(self->ctx); /* New ssl struct */ - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ /* If the socket is in non-blocking mode or timeout mode, set the BIO @@ -317,24 +381,24 @@ BIO_set_nbio(SSL_get_wbio(self->ssl), 1); } - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS if (socket_type == PY_SSL_CLIENT) SSL_set_connect_state(self->ssl); else SSL_set_accept_state(self->ssl); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS /* Actually negotiate SSL connection */ /* XXX If SSL_connect() returns 0, it's also a failure. */ sockstate = 0; do { - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS if (socket_type == PY_SSL_CLIENT) ret = SSL_connect(self->ssl); else ret = SSL_accept(self->ssl); err = SSL_get_error(self->ssl, ret); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if(PyErr_CheckSignals()) { goto fail; } @@ -367,14 +431,14 @@ } self->ssl->debug = 1; - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) { X509_NAME_oneline(X509_get_subject_name(self->peer_cert), self->server, X509_NAME_MAXLEN); X509_NAME_oneline(X509_get_issuer_name(self->peer_cert), self->issuer, X509_NAME_MAXLEN); } - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS self->Socket = Sock; Py_INCREF(self->Socket); return self; @@ -437,96 +501,313 @@ } static PyObject * +_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) { + + char namebuf[X509_NAME_MAXLEN]; + int buflen; + PyObject *name_obj; + PyObject *value_obj; + PyObject *attr; + unsigned char *valuebuf = NULL; + + buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + name_obj = PyString_FromStringAndSize(namebuf, buflen); + if (name_obj == NULL) + goto fail; + + buflen = ASN1_STRING_to_UTF8(&valuebuf, value); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + Py_DECREF(name_obj); + goto fail; + } + value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, + buflen, "strict"); + OPENSSL_free(valuebuf); + if (value_obj == NULL) { + Py_DECREF(name_obj); + goto fail; + } + attr = PyTuple_New(2); + if (attr == NULL) { + Py_DECREF(name_obj); + Py_DECREF(value_obj); + goto fail; + } + PyTuple_SET_ITEM(attr, 0, name_obj); + PyTuple_SET_ITEM(attr, 1, value_obj); + return attr; + + fail: + return NULL; +} + +static PyObject * _create_tuple_for_X509_NAME (X509_NAME *xname) { - PyObject *pt = NULL; - PyObject *entry_tuple = NULL; + PyObject *dn = NULL; /* tuple which represents the "distinguished name" */ + PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */ + PyObject *rdnt; + PyObject *attr = NULL; /* tuple to hold an attribute */ int entry_count = X509_NAME_entry_count(xname); + X509_NAME_ENTRY *entry; + ASN1_OBJECT *name; + ASN1_STRING *value; int index_counter; + int rdn_level = -1; + int retcode; - pt = PyTuple_New(entry_count); - if (pt == NULL) + dn = PyList_New(0); + if (dn == NULL) return NULL; + /* now create another tuple to hold the top-level RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; for (index_counter = 0; - index_counter < X509_NAME_entry_count(xname); + index_counter < entry_count; index_counter++) { - char namebuf[X509_NAME_MAXLEN]; - int buflen; - PyObject *name_obj; - ASN1_STRING *value; - PyObject *value_obj; - unsigned char *valuebuf = NULL; - - X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, - index_counter); - - ASN1_OBJECT *name = X509_NAME_ENTRY_get_object(entry); - buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); - if (buflen < 0) - goto fail0; - name_obj = PyString_FromStringAndSize(namebuf, buflen); - if (name_obj == NULL) - goto fail0; + entry = X509_NAME_get_entry(xname, index_counter); + /* check to see if we've gotten to a new RDN */ + if (rdn_level >= 0) { + if (rdn_level != entry->set) { + /* yes, new RDN */ + /* add old RDN to DN */ + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) + goto fail0; + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) + goto fail0; + /* create new RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; + } + } + rdn_level = entry->set; + + /* now add this attribute to the current RDN */ + name = X509_NAME_ENTRY_get_object(entry); value = X509_NAME_ENTRY_get_data(entry); - buflen = ASN1_STRING_to_UTF8(&valuebuf, value); - if (buflen < 0) { - Py_DECREF(name_obj); + attr = _create_tuple_for_attribute(name, value); + /* + fprintf(stderr, "RDN level %d, attribute %s: %s\n", + entry->set, + PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)), + PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1))); + */ + if (attr == NULL) + goto fail1; + retcode = PyList_Append(rdn, attr); + Py_DECREF(attr); + if (retcode < 0) + goto fail1; + } + /* now, there's typically a dangling RDN */ + if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) goto fail0; - } - value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); - OPENSSL_free(valuebuf); - if (value_obj == NULL) { - Py_DECREF(name_obj); + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) goto fail0; + } + + /* convert list to tuple */ + rdnt = PyList_AsTuple(dn); + Py_DECREF(dn); + if (rdnt == NULL) + return NULL; + return rdnt; + + fail1: + Py_XDECREF(rdn); + + fail0: + Py_XDECREF(dn); + return NULL; +} + +static PyObject * +_get_peer_alt_names (X509 *certificate) { + + /* this code follows the procedure outlined in + OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() + function to extract the STACK_OF(GENERAL_NAME), + then iterates through the stack to add the + names. */ + + int i, j; + PyObject *peer_alt_names = Py_None; + PyObject *v, *t; + X509_EXTENSION *ext = NULL; + GENERAL_NAMES *names = NULL; + GENERAL_NAME *name; + X509V3_EXT_METHOD *method; + BIO *biobuf = NULL; + char buf[2048]; + char *vptr; + int len; + unsigned char *p; + + if (certificate == NULL) + return peer_alt_names; + + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); + + i = 0; + while ((i = X509_get_ext_by_NID( + certificate, NID_subject_alt_name, i)) >= 0) { + + if (peer_alt_names == Py_None) { + peer_alt_names = PyList_New(0); + if (peer_alt_names == NULL) + goto fail; } - entry_tuple = PyTuple_New(2); - if (entry_tuple == NULL) { - Py_DECREF(name_obj); - Py_DECREF(value_obj); - goto fail0; + + /* now decode the altName */ + ext = X509_get_ext(certificate, i); + if(!(method = X509V3_EXT_get(ext))) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("No method for internalizing subjectAltName!")); + goto fail; + } + + p = ext->value->data; + if(method->it) + names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL, + &p, + ext->value->length, + ASN1_ITEM_ptr(method->it))); + else + names = (GENERAL_NAMES*) (method->d2i(NULL, + &p, + ext->value->length)); + + for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { + + /* get a rendering of each name in the set of names */ + + name = sk_GENERAL_NAME_value(names, j); + if (name->type == GEN_DIRNAME) { + + /* we special-case DirName as a tuple of tuples of attributes */ + + t = PyTuple_New(2); + if (t == NULL) { + goto fail; + } + + v = PyString_FromString("DirName"); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + + v = _create_tuple_for_X509_NAME (name->d.dirn); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + + } else { + + /* for everything else, we use the OpenSSL print form */ + + (void) BIO_reset(biobuf); + GENERAL_NAME_print(biobuf, name); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + vptr = strchr(buf, ':'); + if (vptr == NULL) + goto fail; + t = PyTuple_New(2); + if (t == NULL) + goto fail; + v = PyString_FromStringAndSize(buf, (vptr - buf)); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1))); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + } + + /* and add that rendering to the list */ + + if (PyList_Append(peer_alt_names, t) < 0) { + Py_DECREF(t); + goto fail; + } + Py_DECREF(t); } - PyTuple_SET_ITEM(entry_tuple, 0, name_obj); - PyTuple_SET_ITEM(entry_tuple, 1, value_obj); - PyTuple_SET_ITEM(pt, index_counter, entry_tuple); } - return pt; + BIO_free(biobuf); + if (peer_alt_names != Py_None) { + v = PyList_AsTuple(peer_alt_names); + Py_DECREF(peer_alt_names); + return v; + } else { + return peer_alt_names; + } + + + fail: + if (biobuf != NULL) + BIO_free(biobuf); + + if (peer_alt_names != Py_None) { + Py_XDECREF(peer_alt_names); + } - fail0: - Py_XDECREF(pt); return NULL; } static PyObject * -PySSL_peercert(PySSLObject *self) -{ +_decode_certificate (X509 *certificate, int verbose) { + PyObject *retval = NULL; BIO *biobuf = NULL; PyObject *peer; + PyObject *peer_alt_names = NULL; PyObject *issuer; PyObject *version; + PyObject *sn_obj; + ASN1_INTEGER *serialNumber; char buf[2048]; int len; ASN1_TIME *notBefore, *notAfter; PyObject *pnotBefore, *pnotAfter; - int verification; - - if (!self->peer_cert) - Py_RETURN_NONE; retval = PyDict_New(); if (retval == NULL) return NULL; - verification = SSL_CTX_get_verify_mode(self->ctx); - if ((verification & SSL_VERIFY_PEER) == 0) - return retval; - peer = _create_tuple_for_X509_NAME( - X509_get_subject_name(self->peer_cert)); + X509_get_subject_name(certificate)); if (peer == NULL) goto fail0; if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) { @@ -535,51 +816,98 @@ } Py_DECREF(peer); - issuer = _create_tuple_for_X509_NAME( - X509_get_issuer_name(self->peer_cert)); - if (issuer == NULL) - goto fail0; - if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { + if (verbose) { + issuer = _create_tuple_for_X509_NAME( + X509_get_issuer_name(certificate)); + if (issuer == NULL) + goto fail0; + if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { + Py_DECREF(issuer); + goto fail0; + } Py_DECREF(issuer); - goto fail0; - } - Py_DECREF(issuer); - - version = PyInt_FromLong(X509_get_version(self->peer_cert)); - if (PyDict_SetItemString(retval, "version", version) < 0) { + + version = PyInt_FromLong(X509_get_version(certificate) + 1); + if (PyDict_SetItemString(retval, "version", version) < 0) { + Py_DECREF(version); + goto fail0; + } Py_DECREF(version); - goto fail0; } - Py_DECREF(version); - + /* get a memory buffer */ biobuf = BIO_new(BIO_s_mem()); + + if (verbose) { - notBefore = X509_get_notBefore(self->peer_cert); - ASN1_TIME_print(biobuf, notBefore); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - pnotBefore = PyString_FromStringAndSize(buf, len); - if (pnotBefore == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { + (void) BIO_reset(biobuf); + serialNumber = X509_get_serialNumber(certificate); + /* should not exceed 20 octets, 160 bits, so buf is big enough */ + i2a_ASN1_INTEGER(biobuf, serialNumber); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + sn_obj = PyString_FromStringAndSize(buf, len); + if (sn_obj == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) { + Py_DECREF(sn_obj); + goto fail1; + } + Py_DECREF(sn_obj); + + (void) BIO_reset(biobuf); + notBefore = X509_get_notBefore(certificate); + ASN1_TIME_print(biobuf, notBefore); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + pnotBefore = PyString_FromStringAndSize(buf, len); + if (pnotBefore == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { + Py_DECREF(pnotBefore); + goto fail1; + } Py_DECREF(pnotBefore); - goto fail1; } - Py_DECREF(pnotBefore); (void) BIO_reset(biobuf); - notAfter = X509_get_notAfter(self->peer_cert); + notAfter = X509_get_notAfter(certificate); ASN1_TIME_print(biobuf, notAfter); len = BIO_gets(biobuf, buf, sizeof(buf)-1); - BIO_free(biobuf); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } pnotAfter = PyString_FromStringAndSize(buf, len); if (pnotAfter == NULL) - goto fail0; + goto fail1; if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) { Py_DECREF(pnotAfter); - goto fail0; + goto fail1; } Py_DECREF(pnotAfter); + + /* Now look for subjectAltName */ + + peer_alt_names = _get_peer_alt_names(certificate); + if (peer_alt_names == NULL) + goto fail1; + else if (peer_alt_names != Py_None) { + if (PyDict_SetItemString(retval, "subjectAltName", + peer_alt_names) < 0) { + Py_DECREF(peer_alt_names); + goto fail1; + } + Py_DECREF(peer_alt_names); + } + + BIO_free(biobuf); return retval; fail1: @@ -590,6 +918,141 @@ return NULL; } + +static PyObject * +PySSL_test_decode_certificate (PyObject *mod, PyObject *args) { + + PyObject *retval = NULL; + char *filename = NULL; + X509 *x=NULL; + BIO *cert; + int verbose = 1; + + if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose)) + return NULL; + + if ((cert=BIO_new(BIO_s_file())) == NULL) { + PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file"); + goto fail0; + } + + if (BIO_read_filename(cert,filename) <= 0) { + PyErr_SetString(PySSLErrorObject, "Can't open file"); + goto fail0; + } + + x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL); + if (x == NULL) { + PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file"); + goto fail0; + } + + retval = _decode_certificate(x, verbose); + + fail0: + + if (cert != NULL) BIO_free(cert); + return retval; +} + + +static PyObject * +PySSL_peercert(PySSLObject *self, PyObject *args) +{ + PyObject *retval = NULL; + int len; + int verification; + PyObject *binary_mode = Py_None; + + if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode)) + return NULL; + + if (!self->peer_cert) + Py_RETURN_NONE; + + if (PyObject_IsTrue(binary_mode)) { + /* return cert in DER-encoded format */ + + unsigned char *bytes_buf = NULL; + + bytes_buf = NULL; + len = i2d_X509(self->peer_cert, &bytes_buf); + if (len < 0) { + PySSL_SetError(self, len, __FILE__, __LINE__); + return NULL; + } + retval = PyString_FromStringAndSize((const char *) bytes_buf, len); + OPENSSL_free(bytes_buf); + return retval; + + } else { + + verification = SSL_CTX_get_verify_mode(self->ctx); + if ((verification & SSL_VERIFY_PEER) == 0) + return PyDict_New(); + else + return _decode_certificate (self->peer_cert, 0); + } +} + +PyDoc_STRVAR(PySSL_peercert_doc, +"peer_certificate([der=False]) -> certificate\n\ +\n\ +Returns the certificate for the peer. If no certificate was provided,\n\ +returns None. If a certificate was provided, but not validated, returns\n\ +an empty dictionary. Otherwise returns a dict containing information\n\ +about the peer certificate.\n\ +\n\ +If the optional argument is True, returns a DER-encoded copy of the\n\ +peer certificate, or None if no certificate was provided. This will\n\ +return the certificate even if it wasn't validated."); + +static PyObject *PySSL_cipher (PySSLObject *self) { + + PyObject *retval, *v; + SSL_CIPHER *current; + char *cipher_name; + char *cipher_protocol; + + if (self->ssl == NULL) + return Py_None; + current = SSL_get_current_cipher(self->ssl); + if (current == NULL) + return Py_None; + + retval = PyTuple_New(3); + if (retval == NULL) + return NULL; + + cipher_name = (char *) SSL_CIPHER_get_name(current); + if (cipher_name == NULL) { + PyTuple_SET_ITEM(retval, 0, Py_None); + } else { + v = PyString_FromString(cipher_name); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 0, v); + } + cipher_protocol = SSL_CIPHER_get_version(current); + if (cipher_protocol == NULL) { + PyTuple_SET_ITEM(retval, 1, Py_None); + } else { + v = PyString_FromString(cipher_protocol); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 1, v); + } + v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL)); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 2, v); + return retval; + + fail0: + Py_DECREF(retval); + return NULL; +} + static void PySSL_dealloc(PySSLObject *self) { if (self->peer_cert) /* Possible not to have one? */ @@ -636,9 +1099,9 @@ /* s->sock_timeout is in seconds, timeout in ms */ timeout = (int)(s->sock_timeout * 1000 + 0.5); - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS rc = poll(&pollfd, 1, timeout); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS goto normal_return; } @@ -657,12 +1120,12 @@ FD_SET(s->sock_fd, &fds); /* See if the socket is ready */ - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS if (writing) rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv); else rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS normal_return: /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise @@ -697,10 +1160,10 @@ } do { err = 0; - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS len = SSL_write(self->ssl, data, count); err = SSL_get_error(self->ssl, len); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if(PyErr_CheckSignals()) { return NULL; } @@ -752,9 +1215,9 @@ return NULL; /* first check if there are bytes ready to be read */ - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS count = SSL_pending(self->ssl); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if (!count) { sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); @@ -769,26 +1232,17 @@ Py_DECREF(buf); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - if (SSL_get_shutdown(self->ssl) != - SSL_RECEIVED_SHUTDOWN) - { - Py_DECREF(buf); - PyErr_SetString(PySSLErrorObject, - "Socket closed without SSL shutdown handshake"); - return NULL; - } else { - /* should contain a zero-length string */ - _PyString_Resize(&buf, 0); - return buf; - } + /* should contain a zero-length string */ + _PyString_Resize(&buf, 0); + return buf; } } do { err = 0; - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS count = SSL_read(self->ssl, PyBytes_AS_STRING(buf), len); err = SSL_get_error(self->ssl, count); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if(PyErr_CheckSignals()) { Py_DECREF(buf); return NULL; @@ -834,49 +1288,16 @@ \n\ Read up to len bytes from the SSL socket."); -static PyObject *PySSL_SSLshutdown(PySSLObject *self, PyObject *args) -{ - int err; - - /* Guard against closed socket */ - if (self->Socket->sock_fd < 0) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - err = SSL_shutdown(self->ssl); - if (err == 0) { - /* we need to call it again to finish the shutdown */ - err = SSL_shutdown(self->ssl); - } - Py_END_ALLOW_THREADS - - if (err < 0) - return PySSL_SetError(self, err, __FILE__, __LINE__); - else { - Py_INCREF(self->Socket); - return (PyObject *) (self->Socket); - } -} - -PyDoc_STRVAR(PySSL_SSLshutdown_doc, -"shutdown(s) -> socket\n\ -\n\ -Does the SSL shutdown handshake with the remote end, and returns\n\ -the underlying socket object."); - static PyMethodDef PySSLMethods[] = { {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS, - PySSL_SSLwrite_doc}, + PySSL_SSLwrite_doc}, {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS, - PySSL_SSLread_doc}, + PySSL_SSLread_doc}, {"server", (PyCFunction)PySSL_server, METH_NOARGS}, {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS}, - {"peer_certificate", (PyCFunction)PySSL_peercert, METH_NOARGS}, - {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS, - PySSL_SSLshutdown_doc}, + {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS, + PySSL_peercert_doc}, + {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS}, {NULL, NULL} }; @@ -924,7 +1345,7 @@ "RAND_add(string, entropy)\n\ \n\ Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\ -bound on the entropy contained in string."); +bound on the entropy contained in string. See RFC 1750."); static PyObject * PySSL_RAND_status(PyObject *self) @@ -961,9 +1382,9 @@ PyDoc_STRVAR(PySSL_RAND_egd_doc, "RAND_egd(path) -> bytes\n\ \n\ -Queries the entropy gather daemon (EGD) on socket path. Returns number\n\ -of bytes read. Raises ssl.sslerror if connection to EGD fails or\n\ -if it does provide enough data to seed PRNG."); +Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\ +Returns number of bytes read. Raises SSLError if connection to EGD\n\ +fails or if it does provide enough data to seed PRNG."); #endif @@ -972,6 +1393,8 @@ static PyMethodDef PySSL_methods[] = { {"sslwrap", PySSL_sslwrap, METH_VARARGS, ssl_doc}, + {"_test_decode_cert", PySSL_test_decode_certificate, + METH_VARARGS}, #ifdef HAVE_OPENSSL_RAND {"RAND_add", PySSL_RAND_add, METH_VARARGS, PySSL_RAND_add_doc}, @@ -984,6 +1407,73 @@ }; +#ifdef WITH_THREAD + +/* an implementation of OpenSSL threading operations in terms + of the Python C thread library */ + +static PyThread_type_lock *_ssl_locks = NULL; + +static unsigned long _ssl_thread_id_function (void) { + return PyThread_get_thread_ident(); +} + +static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) { + /* this function is needed to perform locking on shared data + structures. (Note that OpenSSL uses a number of global data + structures that will be implicitly shared whenever multiple threads + use OpenSSL.) Multi-threaded applications will crash at random if + it is not set. + + locking_function() must be able to handle up to CRYPTO_num_locks() + different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and + releases it otherwise. + + file and line are the file number of the function setting the + lock. They can be useful for debugging. + */ + + if ((_ssl_locks == NULL) || + (n < 0) || (n >= _ssl_locks_count)) + return; + + if (mode & CRYPTO_LOCK) { + PyThread_acquire_lock(_ssl_locks[n], 1); + } else { + PyThread_release_lock(_ssl_locks[n]); + } +} + +static int _setup_ssl_threads(void) { + + int i; + + if (_ssl_locks == NULL) { + _ssl_locks_count = CRYPTO_num_locks(); + _ssl_locks = (PyThread_type_lock *) + malloc(sizeof(PyThread_type_lock) * _ssl_locks_count); + if (_ssl_locks == NULL) + return 0; + memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count); + for (i = 0; i < _ssl_locks_count; i++) { + _ssl_locks[i] = PyThread_allocate_lock(); + if (_ssl_locks[i] == NULL) { + int j; + for (j = 0; j < i; j++) { + PyThread_free_lock(_ssl_locks[j]); + } + free(_ssl_locks); + return 0; + } + } + CRYPTO_set_locking_callback(_ssl_thread_locking_function); + CRYPTO_set_id_callback(_ssl_thread_id_function); + } + return 1; +} + +#endif /* def HAVE_THREAD */ + PyDoc_STRVAR(module_doc, "Implementation module for SSL socket operations. See the socket module\n\ for documentation."); @@ -1006,15 +1496,21 @@ /* Init OpenSSL */ SSL_load_error_strings(); +#ifdef WITH_THREAD + /* note that this will start threading if not already started */ + if (!_setup_ssl_threads()) { + return; + } +#endif SSLeay_add_ssl_algorithms(); /* Add symbols to module dict */ - PySSLErrorObject = PyErr_NewException("ssl.sslerror", + PySSLErrorObject = PyErr_NewException("ssl.SSLError", PySocketModule.error, NULL); if (PySSLErrorObject == NULL) return; - if (PyDict_SetItemString(d, "sslerror", PySSLErrorObject) != 0) + if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) return; if (PyDict_SetItemString(d, "SSLType", (PyObject *)&PySSL_Type) != 0) Modified: python/branches/py3k/Modules/bz2module.c ============================================================================== --- python/branches/py3k/Modules/bz2module.c (original) +++ python/branches/py3k/Modules/bz2module.c Wed Sep 19 05:06:30 2007 @@ -229,6 +229,7 @@ size_t increment; /* amount to increment the buffer */ PyObject *v; int bzerror; + int bytes_read; total_v_size = n > 0 ? n : 100; v = PyBytes_FromStringAndSize((char *)NULL, total_v_size); @@ -241,8 +242,10 @@ for (;;) { Py_BEGIN_ALLOW_THREADS do { - BZ2_bzRead(&bzerror, f->fp, &c, 1); + bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1); f->pos++; + if (bytes_read == 0) + break; *buf++ = c; } while (bzerror == BZ_OK && c != '\n' && buf != end); Py_END_ALLOW_THREADS Modified: python/branches/py3k/Objects/genobject.c ============================================================================== --- python/branches/py3k/Objects/genobject.c (original) +++ python/branches/py3k/Objects/genobject.c Wed Sep 19 05:06:30 2007 @@ -252,7 +252,6 @@ Py_INCREF(typ); } } - else { /* Not something you can raise. throw() fails. */ PyErr_Format(PyExc_TypeError, Modified: python/branches/py3k/Objects/listobject.c ============================================================================== --- python/branches/py3k/Objects/listobject.c (original) +++ python/branches/py3k/Objects/listobject.c Wed Sep 19 05:06:30 2007 @@ -297,7 +297,10 @@ so must refetch the list size on each iteration. */ for (i = 0; i < Py_Size(v); ++i) { int status; + if (Py_EnterRecursiveCall(" while getting the repr of a list")) + goto Done; s = PyObject_Repr(v->ob_item[i]); + Py_LeaveRecursiveCall(); if (s == NULL) goto Done; status = PyList_Append(pieces, s); Modified: python/branches/py3k/Objects/object.c ============================================================================== --- python/branches/py3k/Objects/object.c (original) +++ python/branches/py3k/Objects/object.c Wed Sep 19 05:06:30 2007 @@ -271,14 +271,18 @@ #endif clearerr(fp); /* Clear any previous error condition */ if (op == NULL) { + Py_BEGIN_ALLOW_THREADS fprintf(fp, ""); + Py_END_ALLOW_THREADS } else { if (op->ob_refcnt <= 0) /* XXX(twouters) cast refcount to long until %zd is universally available */ + Py_BEGIN_ALLOW_THREADS fprintf(fp, "", (long)op->ob_refcnt, op); + Py_END_ALLOW_THREADS else { PyObject *s; if (flags & Py_PRINT_RAW) From python-3000-checkins at python.org Wed Sep 19 05:07:56 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Wed, 19 Sep 2007 05:07:56 +0200 (CEST) Subject: [Python-3000-checkins] r58203 - python/branches/py3k Message-ID: <20070919030756.162A61E4004@bag.python.org> Author: thomas.wouters Date: Wed Sep 19 05:07:55 2007 New Revision: 58203 Modified: python/branches/py3k/ (props changed) Log: Merged revisions 58198-58202 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r58198 | thomas.wouters | 2007-09-19 01:27:30 +0200 (Wed, 19 Sep 2007) | 5 lines Properly indent two lines. (Spotted because it caused merge conflicts in the py3k branch ;) ........ r58199 | sean.reifschneider | 2007-09-19 01:34:44 +0200 (Wed, 19 Sep 2007) | 2 lines issue1172: Documentation of "done" attribute in cgi module. ........ From python-3000-checkins at python.org Wed Sep 19 23:19:29 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Wed, 19 Sep 2007 23:19:29 +0200 (CEST) Subject: [Python-3000-checkins] r58213 - in python/branches/py3k: Lib/test/test_hash.py Lib/urllib.py Objects/longobject.c Python/ceval.c Python/compile.c Message-ID: <20070919211929.4C53F1E4772@bag.python.org> Author: thomas.wouters Date: Wed Sep 19 23:19:28 2007 New Revision: 58213 Modified: python/branches/py3k/ (props changed) python/branches/py3k/Lib/test/test_hash.py python/branches/py3k/Lib/urllib.py python/branches/py3k/Objects/longobject.c python/branches/py3k/Python/ceval.c python/branches/py3k/Python/compile.c Log: Merged revisions 58203-58210 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r58204 | georg.brandl | 2007-09-19 08:37:19 +0200 (Wed, 19 Sep 2007) | 2 lines Fix #1169: remove docstrings in functions for -OO. ........ r58206 | sean.reifschneider | 2007-09-19 09:52:56 +0200 (Wed, 19 Sep 2007) | 2 lines issue1177: Ported Facundo's from urllib2 to urllib, accepting 2xx responses. ........ r58207 | facundo.batista | 2007-09-19 16:02:03 +0200 (Wed, 19 Sep 2007) | 3 lines Annotated the correction to urllib.py, issue #1177 ........ r58208 | facundo.batista | 2007-09-19 17:10:06 +0200 (Wed, 19 Sep 2007) | 7 lines Issue #1772851. Alters long.__hash__ from being *almost* completely predictable to being completely predictable. The value of hash(n) is unchanged for any n that's small enough to be representable as an int, and also unchanged for the vast majority of long integers n of reasonable size. ........ r58209 | thomas.wouters | 2007-09-19 19:27:29 +0200 (Wed, 19 Sep 2007) | 4 lines Fix obvious typo in threaded test. ........ r58210 | thomas.wouters | 2007-09-19 19:27:43 +0200 (Wed, 19 Sep 2007) | 4 lines Whitespace cleanup. ........ Modified: python/branches/py3k/Lib/test/test_hash.py ============================================================================== --- python/branches/py3k/Lib/test/test_hash.py (original) +++ python/branches/py3k/Lib/test/test_hash.py Wed Sep 19 23:19:28 2007 @@ -18,10 +18,19 @@ def test_numeric_literals(self): self.same_hash(1, 1, 1.0, 1.0+0.0j) + self.same_hash(0, 0.0, 0.0+0.0j) + self.same_hash(-1, -1.0, -1.0+0.0j) + self.same_hash(-2, -2.0, -2.0+0.0j) def test_coerced_integers(self): self.same_hash(int(1), int(1), float(1), complex(1), int('1'), float('1.0')) + self.same_hash(int(-2**31), float(-2**31)) + self.same_hash(int(1-2**31), float(1-2**31)) + self.same_hash(int(2**31-1), float(2**31-1)) + # for 64-bit platforms + self.same_hash(int(2**31), float(2**31)) + self.same_hash(int(-2**63), float(-2**63)) def test_coerced_floats(self): self.same_hash(int(1.23e300), float(1.23e300)) Modified: python/branches/py3k/Lib/urllib.py ============================================================================== --- python/branches/py3k/Lib/urllib.py (original) +++ python/branches/py3k/Lib/urllib.py Wed Sep 19 23:19:28 2007 @@ -357,7 +357,9 @@ raise IOError('http protocol error', 0, 'got a bad status line', None) - if response.status == 200: + # According to RFC 2616, "2xx" code indicates that the client's + # request was successfully received, understood, and accepted. + if not (200 <= response.status < 300): return addinfourl(response.fp, response.msg, "http:" + url) else: return self.http_error( Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Wed Sep 19 23:19:28 2007 @@ -2197,10 +2197,18 @@ i = -(i); } #define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT) + /* The following loop produces a C long x such that (unsigned long)x + is congruent to the absolute value of v modulo ULONG_MAX. The + resulting x is nonzero if and only if v is. */ while (--i >= 0) { /* Force a native long #-bits (32 or 64) circular shift */ x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK); x += v->ob_digit[i]; + /* If the addition above overflowed (thinking of x as + unsigned), we compensate by incrementing. This preserves + the value modulo ULONG_MAX. */ + if ((unsigned long)x < v->ob_digit[i]) + x++; } #undef LONG_BIT_PyLong_SHIFT x = x * sign; Modified: python/branches/py3k/Python/ceval.c ============================================================================== --- python/branches/py3k/Python/ceval.c (original) +++ python/branches/py3k/Python/ceval.c Wed Sep 19 23:19:28 2007 @@ -431,7 +431,7 @@ Py_SetRecursionLimit(int new_limit) { recursion_limit = new_limit; - _Py_CheckRecursionLimit = recursion_limit; + _Py_CheckRecursionLimit = recursion_limit; } /* the macro Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall() @@ -469,7 +469,7 @@ where); return -1; } - _Py_CheckRecursionLimit = recursion_limit; + _Py_CheckRecursionLimit = recursion_limit; return 0; } @@ -805,11 +805,11 @@ Py_MakePendingCalls() above. */ if (--_Py_Ticker < 0) { - if (*next_instr == SETUP_FINALLY) { - /* Make the last opcode before - a try: finally: block uninterruptable. */ - goto fast_next_opcode; - } + if (*next_instr == SETUP_FINALLY) { + /* Make the last opcode before + a try: finally: block uninterruptable. */ + goto fast_next_opcode; + } _Py_Ticker = _Py_CheckInterval; tstate->tick_counter++; #ifdef WITH_TSC @@ -2500,7 +2500,7 @@ } /* pop frame */ - exit_eval_frame: +exit_eval_frame: Py_LeaveRecursiveCall(); tstate->frame = f->f_back; @@ -2761,9 +2761,9 @@ return PyGen_New(f); } - retval = PyEval_EvalFrameEx(f,0); + retval = PyEval_EvalFrameEx(f,0); - fail: /* Jump here from prelude on failure */ +fail: /* Jump here from prelude on failure */ /* decref'ing the frame can cause __del__ methods to get invoked, which can call back into Python. While we're done with the @@ -2772,7 +2772,7 @@ */ assert(tstate != NULL); ++tstate->recursion_depth; - Py_DECREF(f); + Py_DECREF(f); --tstate->recursion_depth; return retval; } @@ -3186,18 +3186,18 @@ represents a jump backwards, call the trace function. */ if ((frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub)) { - int line; - PyAddrPair bounds; + int line; + PyAddrPair bounds; - line = PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, - &bounds); - if (line >= 0) { + line = PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, + &bounds); + if (line >= 0) { frame->f_lineno = line; result = call_trace(func, obj, frame, PyTrace_LINE, Py_None); - } - *instr_lb = bounds.ap_lower; - *instr_ub = bounds.ap_upper; + } + *instr_lb = bounds.ap_lower; + *instr_ub = bounds.ap_upper; } else if (frame->f_lasti <= *instr_prev) { result = call_trace(func, obj, frame, PyTrace_LINE, Py_None); @@ -3583,9 +3583,9 @@ PyObject *value = EXT_POP(*pp_stack); PyObject *key = EXT_POP(*pp_stack); if (PyDict_GetItem(kwdict, key) != NULL) { - PyErr_Format(PyExc_TypeError, - "%.200s%s got multiple values " - "for keyword argument '%.200s'", + PyErr_Format(PyExc_TypeError, + "%.200s%s got multiple values " + "for keyword argument '%.200s'", PyEval_GetFuncName(func), PyEval_GetFuncDesc(func), PyUnicode_AsString(key)); @@ -3763,7 +3763,7 @@ PCALL(PCALL_OTHER); #endif result = PyObject_Call(func, callargs, kwdict); - ext_call_fail: +ext_call_fail: Py_XDECREF(callargs); Py_XDECREF(kwdict); Py_XDECREF(stararg); Modified: python/branches/py3k/Python/compile.c ============================================================================== --- python/branches/py3k/Python/compile.c (original) +++ python/branches/py3k/Python/compile.c Wed Sep 19 23:19:28 2007 @@ -1428,7 +1428,7 @@ st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0); docstring = compiler_isdocstring(st); - if (docstring) + if (docstring && Py_OptimizeFlag < 2) first_const = st->v.Expr.value->v.Str.s; if (compiler_add_o(c, c->u->u_consts, first_const) < 0) { compiler_exit_scope(c); From python-3000-checkins at python.org Wed Sep 19 23:56:33 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Wed, 19 Sep 2007 23:56:33 +0200 (CEST) Subject: [Python-3000-checkins] r58214 - python/branches/py3k/Python/ceval.c Message-ID: <20070919215633.6BECF1E4008@bag.python.org> Author: thomas.wouters Date: Wed Sep 19 23:56:32 2007 New Revision: 58214 Modified: python/branches/py3k/Python/ceval.c Log: Whitespace cleanup. Modified: python/branches/py3k/Python/ceval.c ============================================================================== --- python/branches/py3k/Python/ceval.c (original) +++ python/branches/py3k/Python/ceval.c Wed Sep 19 23:56:32 2007 @@ -1467,8 +1467,8 @@ case RAISE_VARARGS: v = w = NULL; switch (oparg) { - case 2: - v = POP(); /* cause */ + case 2: + v = POP(); /* cause */ case 1: w = POP(); /* exc */ case 0: /* Fallthrough */ @@ -2876,7 +2876,7 @@ tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; - PyException_SetTraceback(value, tb); + PyException_SetTraceback(value, tb); Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); @@ -2927,7 +2927,7 @@ static enum why_code do_raise(PyObject *exc, PyObject *cause) { - PyObject *type = NULL, *value = NULL, *tb = NULL; + PyObject *type = NULL, *value = NULL, *tb = NULL; if (exc == NULL) { /* Reraise */ @@ -2935,16 +2935,16 @@ type = tstate->exc_type; value = tstate->exc_value; tb = tstate->exc_traceback; - if (type == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "No active exception to reraise"); - return WHY_EXCEPTION; - } - Py_XINCREF(type); + if (type == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "No active exception to reraise"); + return WHY_EXCEPTION; + } + Py_XINCREF(type); Py_XINCREF(value); Py_XINCREF(tb); - PyErr_Restore(type, value, tb); - return WHY_RERAISE; + PyErr_Restore(type, value, tb); + return WHY_RERAISE; } /* We support the following forms of raise: @@ -2953,11 +2953,11 @@ raise */ if (PyExceptionClass_Check(exc)) { - type = exc; - value = PyObject_CallObject(exc, NULL); + type = exc; + value = PyObject_CallObject(exc, NULL); if (value == NULL) - goto raise_error; - } + goto raise_error; + } else if (PyExceptionInstance_Check(exc)) { value = exc; type = PyExceptionInstance_Class(exc); @@ -2966,31 +2966,32 @@ else { /* Not something you can raise. You get an exception anyway, just not what you specified :-) */ - Py_DECREF(exc); + Py_DECREF(exc); PyErr_SetString(PyExc_TypeError, - "exceptions must derive from BaseException"); + "exceptions must derive from BaseException"); goto raise_error; } - tb = PyException_GetTraceback(value); - if (cause) { - PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto raise_error; - Py_DECREF(cause); - } - else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - } - else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from BaseException"); - goto raise_error; - } - PyException_SetCause(value, fixed_cause); - } + tb = PyException_GetTraceback(value); + if (cause) { + PyObject *fixed_cause; + if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto raise_error; + Py_DECREF(cause); + } + else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + } + else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto raise_error; + } + PyException_SetCause(value, fixed_cause); + } PyErr_Restore(type, value, tb); return WHY_EXCEPTION; @@ -3675,7 +3676,7 @@ PCALL(PCALL_OTHER); #endif result = PyObject_Call(func, callargs, kwdict); - call_fail: +call_fail: Py_XDECREF(callargs); Py_XDECREF(kwdict); return result; From python-3000-checkins at python.org Thu Sep 20 04:58:35 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Thu, 20 Sep 2007 04:58:35 +0200 (CEST) Subject: [Python-3000-checkins] r58215 - in python/branches/py3k-importlib: Modules/getpath.c NEWS Message-ID: <20070920025835.3969F1E44A7@bag.python.org> Author: brett.cannon Date: Thu Sep 20 04:58:34 2007 New Revision: 58215 Added: python/branches/py3k-importlib/NEWS (contents, props changed) Modified: python/branches/py3k-importlib/Modules/getpath.c Log: Use _importlib.py over os.py as landmark when searching for the stdlib. Modified: python/branches/py3k-importlib/Modules/getpath.c ============================================================================== --- python/branches/py3k-importlib/Modules/getpath.c (original) +++ python/branches/py3k-importlib/Modules/getpath.c Thu Sep 20 04:58:34 2007 @@ -51,7 +51,7 @@ * Modules/Setup. If the landmark is found, we're done. * * For the remaining steps, the prefix landmark will always be - * lib/python$VERSION/os.py and the exec_prefix will always be + * lib/python$VERSION/_importlib.py and the exec_prefix will always be * lib/python$VERSION/lib-dynload, where $VERSION is Python's version * number as supplied by the Makefile. Note that this means that no more * build directory checking is performed; if the first step did not find @@ -122,7 +122,7 @@ #endif #ifndef LANDMARK -#define LANDMARK "os.py" +#define LANDMARK "_importlib.py" #endif static char prefix[MAXPATHLEN+1]; Added: python/branches/py3k-importlib/NEWS ============================================================================== --- (empty file) +++ python/branches/py3k-importlib/NEWS Thu Sep 20 04:58:34 2007 @@ -0,0 +1,2 @@ +* Have Modules/getpath.c use _importlib.py instead of os.py when searching for + Python's stdlib directory. From python-3000-checkins at python.org Thu Sep 20 20:22:41 2007 From: python-3000-checkins at python.org (thomas.wouters) Date: Thu, 20 Sep 2007 20:22:41 +0200 (CEST) Subject: [Python-3000-checkins] r58222 - in python/branches/py3k: Doc/library/collections.rst Doc/library/decimal.rst Doc/library/stdtypes.rst Doc/tutorial/inputoutput.rst Lib/cgi.py Lib/decimal.py Lib/test/test_decimal.py Python/ceval.c Message-ID: <20070920182241.5A91B1E4008@bag.python.org> Author: thomas.wouters Date: Thu Sep 20 20:22:40 2007 New Revision: 58222 Modified: python/branches/py3k/ (props changed) python/branches/py3k/Doc/library/collections.rst python/branches/py3k/Doc/library/decimal.rst python/branches/py3k/Doc/library/stdtypes.rst python/branches/py3k/Doc/tutorial/inputoutput.rst python/branches/py3k/Lib/cgi.py python/branches/py3k/Lib/decimal.py python/branches/py3k/Lib/test/test_decimal.py python/branches/py3k/Python/ceval.c Log: Merged revisions 58211-58220 via svnmerge from svn+ssh://pythondev at svn.python.org/python/trunk ........ r58211 | facundo.batista | 2007-09-19 19:53:25 +0200 (Wed, 19 Sep 2007) | 4 lines Issue #1772851. Optimization of __hash__ to behave better for big big numbers. ........ r58216 | raymond.hettinger | 2007-09-20 05:03:43 +0200 (Thu, 20 Sep 2007) | 1 line Fit nits ........ r58217 | georg.brandl | 2007-09-20 10:44:59 +0200 (Thu, 20 Sep 2007) | 2 lines alternate -> alternative. ........ r58218 | georg.brandl | 2007-09-20 18:06:07 +0200 (Thu, 20 Sep 2007) | 2 lines Patch #1541463: optimize performance of cgi.FieldStorage operations. ........ r58219 | georg.brandl | 2007-09-20 18:45:27 +0200 (Thu, 20 Sep 2007) | 2 lines #1176: document that string methods don't take keyword args. ........ r58220 | thomas.wouters | 2007-09-20 19:35:10 +0200 (Thu, 20 Sep 2007) | 4 lines Try harder to stay within the 79-column limit. There's still two places that go (way) over, but those are harder to fix without suffering in readability. ........ Modified: python/branches/py3k/Doc/library/collections.rst ============================================================================== --- python/branches/py3k/Doc/library/collections.rst (original) +++ python/branches/py3k/Doc/library/collections.rst Thu Sep 20 20:22:40 2007 @@ -395,8 +395,8 @@ .. _named-tuple-factory: -:func:`NamedTuple` factory function ------------------------------------ +:func:`NamedTuple` Factory Function for Tuples with Named Fields +---------------------------------------------------------------- Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and @@ -411,12 +411,12 @@ method which lists the tuple contents in a ``name=value`` format. The *fieldnames* are specified in a single string with each fieldname separated by - a space and/or comma. Any valid Python identifier may be used for a field name. + a space and/or comma. Any valid Python identifier may be used for a fieldname. - If *verbose* is true, the *NamedTuple* call will print the class definition. + If *verbose* is true, will print the class definition. *NamedTuple* instances do not have per-instance dictionaries, so they are - lightweight, requiring no more memory than regular tuples. + lightweight and require no more memory than regular tuples. Example:: @@ -467,7 +467,9 @@ .. method:: somenamedtuple.replace(field, value) - Return a new instance of the named tuple replacing the named *field* with a new *value*:: + Return a new instance of the named tuple replacing the named *field* with a new *value*: + +:: >>> p = Point(x=11, y=22) >>> p.__replace__('x', 33) @@ -480,7 +482,9 @@ Return a tuple of strings listing the field names. This is useful for introspection, for converting a named tuple instance to a dictionary, and for combining named tuple - types to create new named tuple types:: + types to create new named tuple types: + +:: >>> p.__fields__ # view the field names ('x', 'y') Modified: python/branches/py3k/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k/Doc/library/decimal.rst (original) +++ python/branches/py3k/Doc/library/decimal.rst Thu Sep 20 20:22:40 2007 @@ -977,7 +977,7 @@ The usual approach to working with decimals is to create :class:`Decimal` instances and then apply arithmetic operations which take place within the -current context for the active thread. An alternate approach is to use context +current context for the active thread. An alternative approach is to use context methods for calculating within a specific context. The methods are similar to those for the :class:`Decimal` class and are only briefly recounted here. Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Thu Sep 20 20:22:40 2007 @@ -657,10 +657,13 @@ .. index:: pair: string; methods -String objects support the methods listed below. In addition, Python's strings -support the sequence type methods described in the :ref:`typesseq` section. To -output formatted strings, see the :ref:`string-formatting` section. Also, see -the :mod:`re` module for string functions based on regular expressions. +String objects support the methods listed below. Note that none of these +methods take keyword arguments. + +In addition, Python's strings support the sequence type methods described in +the :ref:`typesseq` section. To output formatted strings, see the +:ref:`string-formatting` section. Also, see the :mod:`re` module for string +functions based on regular expressions. .. method:: str.capitalize() Modified: python/branches/py3k/Doc/tutorial/inputoutput.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/inputoutput.rst (original) +++ python/branches/py3k/Doc/tutorial/inputoutput.rst Thu Sep 20 20:22:40 2007 @@ -252,7 +252,7 @@ >>> f.readlines() ['This is the first line of the file.\n', 'Second line of the file\n'] -An alternate approach to reading lines is to loop over the file object. This is +An alternative approach to reading lines is to loop over the file object. This is memory efficient, fast, and leads to simpler code:: >>> for line in f: Modified: python/branches/py3k/Lib/cgi.py ============================================================================== --- python/branches/py3k/Lib/cgi.py (original) +++ python/branches/py3k/Lib/cgi.py Thu Sep 20 20:22:40 2007 @@ -604,23 +604,21 @@ """Dictionary style keys() method.""" if self.list is None: raise TypeError("not indexable") - keys = [] - for item in self.list: - if item.name not in keys: keys.append(item.name) - return keys + return list(set(item.name for item in self.list)) def __contains__(self, key): """Dictionary style __contains__ method.""" if self.list is None: raise TypeError("not indexable") - for item in self.list: - if item.name == key: return True - return False + return any(item.name == key for item in self.list) def __len__(self): """Dictionary style len(x) support.""" return len(self.keys()) + def __nonzero__(self): + return bool(self.list) + def read_urlencoded(self): """Internal: read data in query string format.""" qs = self.fp.read(self.length) Modified: python/branches/py3k/Lib/decimal.py ============================================================================== --- python/branches/py3k/Lib/decimal.py (original) +++ python/branches/py3k/Lib/decimal.py Thu Sep 20 20:22:40 2007 @@ -786,10 +786,17 @@ if self._isnan(): raise TypeError('Cannot hash a NaN value.') return hash(str(self)) - i = int(self) - if self == Decimal(i): - return hash(i) - assert self.__bool__() # '-0' handled by integer case + if not self: + return 0 + if self._isinteger(): + op = _WorkRep(self.to_integral_value()) + # to make computation feasible for Decimals with large + # exponent, we use the fact that hash(n) == hash(m) for + # any two nonzero integers n and m such that (i) n and m + # have the same sign, and (ii) n is congruent to m modulo + # 2**64-1. So we can replace hash((-1)**s*c*10**e) with + # hash((-1)**s*c*pow(10, e, 2**64-1). + return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1)) return hash(str(self.normalize())) def as_tuple(self): Modified: python/branches/py3k/Lib/test/test_decimal.py ============================================================================== --- python/branches/py3k/Lib/test/test_decimal.py (original) +++ python/branches/py3k/Lib/test/test_decimal.py Thu Sep 20 20:22:40 2007 @@ -901,6 +901,38 @@ def test_hash_method(self): #just that it's hashable hash(Decimal(23)) + + test_values = [Decimal(sign*(2**m + n)) + for m in [0, 14, 15, 16, 17, 30, 31, + 32, 33, 62, 63, 64, 65, 66] + for n in range(-10, 10) + for sign in [-1, 1]] + test_values.extend([ + Decimal("-0"), # zeros + Decimal("0.00"), + Decimal("-0.000"), + Decimal("0E10"), + Decimal("-0E12"), + Decimal("10.0"), # negative exponent + Decimal("-23.00000"), + Decimal("1230E100"), # positive exponent + Decimal("-4.5678E50"), + # a value for which hash(n) != hash(n % (2**64-1)) + # in Python pre-2.6 + Decimal(2**64 + 2**32 - 1), + # selection of values which fail with the old (before + # version 2.6) long.__hash__ + Decimal("1.634E100"), + Decimal("90.697E100"), + Decimal("188.83E100"), + Decimal("1652.9E100"), + Decimal("56531E100"), + ]) + + # check that hash(d) == hash(int(d)) for integral values + for value in test_values: + self.assertEqual(hash(value), hash(int(value))) + #the same hash that to an int self.assertEqual(hash(Decimal(23)), hash(23)) self.assertRaises(TypeError, hash, Decimal('NaN')) Modified: python/branches/py3k/Python/ceval.c ============================================================================== --- python/branches/py3k/Python/ceval.c (original) +++ python/branches/py3k/Python/ceval.c Thu Sep 20 20:22:40 2007 @@ -28,8 +28,9 @@ typedef unsigned long long uint64; #if defined(__ppc__) /* <- Don't know if this is the correct symbol; this - section should work for GCC on any PowerPC platform, - irrespective of OS. POWER? Who knows :-) */ + section should work for GCC on any PowerPC + platform, irrespective of OS. + POWER? Who knows :-) */ #define READ_TIMESTAMP(var) ppc_getcounter(&var) @@ -93,7 +94,8 @@ static PyObject * fast_function(PyObject *, PyObject ***, int, int, int); static PyObject * do_call(PyObject *, PyObject ***, int, int); static PyObject * ext_do_call(PyObject *, PyObject ***, int, int, int); -static PyObject * update_keyword_args(PyObject *, int, PyObject ***,PyObject *); +static PyObject * update_keyword_args(PyObject *, int, PyObject ***, + PyObject *); static PyObject * update_star_args(int, int, PyObject *, PyObject ***); static PyObject * load_args(PyObject ***, int); #define CALL_FLAG_VAR 1 @@ -509,7 +511,8 @@ PyObject * PyEval_EvalFrame(PyFrameObject *f) { /* This is for backward compatibility with extension modules that - used this API; core interpreter code should call PyEval_EvalFrameEx() */ + used this API; core interpreter code should call + PyEval_EvalFrameEx() */ return PyEval_EvalFrameEx(f, 0); } @@ -519,7 +522,7 @@ #ifdef DXPAIRS int lastopcode = 0; #endif - register PyObject **stack_pointer; /* Next free slot in value stack */ + register PyObject **stack_pointer; /* Next free slot in value stack */ register unsigned char *next_instr; register int opcode; /* Current opcode */ register int oparg; /* Current opcode argument, if any */ @@ -610,10 +613,10 @@ #define JUMPBY(x) (next_instr += (x)) /* OpCode prediction macros - Some opcodes tend to come in pairs thus making it possible to predict - the second code when the first is run. For example, COMPARE_OP is often - followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, those opcodes are often - followed by a POP_TOP. + Some opcodes tend to come in pairs thus making it possible to + predict the second code when the first is run. For example, + COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, + those opcodes are often followed by a POP_TOP. Verifying the prediction costs a single high-speed test of register variable against a constant. If the pairing was good, then the @@ -660,11 +663,13 @@ #define PUSH(v) { (void)(BASIC_PUSH(v), \ lltrace && prtrace(TOP(), "push")); \ assert(STACK_LEVEL() <= co->co_stacksize); } -#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), BASIC_POP()) +#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \ + BASIC_POP()) #define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \ lltrace && prtrace(TOP(), "stackadj")); \ assert(STACK_LEVEL() <= co->co_stacksize); } -#define EXT_POP(STACK_POINTER) (lltrace && prtrace((STACK_POINTER)[-1], "ext_pop"), *--(STACK_POINTER)) +#define EXT_POP(STACK_POINTER) (lltrace && prtrace((STACK_POINTER)[-1], \ + "ext_pop"), *--(STACK_POINTER)) #else #define PUSH(v) BASIC_PUSH(v) #define POP() BASIC_POP() @@ -1568,7 +1573,8 @@ if ((x = f->f_locals) != NULL) { if ((err = PyObject_DelItem(x, w)) != 0) format_exc_check_arg(PyExc_NameError, - NAME_ERROR_MSG ,w); + NAME_ERROR_MSG, + w); break; } PyErr_Format(PyExc_SystemError, @@ -1579,8 +1585,10 @@ PREDICTED_WITH_ARG(UNPACK_SEQUENCE); case UNPACK_SEQUENCE: v = POP(); - if (PyTuple_CheckExact(v) && PyTuple_GET_SIZE(v) == oparg) { - PyObject **items = ((PyTupleObject *)v)->ob_item; + if (PyTuple_CheckExact(v) && + PyTuple_GET_SIZE(v) == oparg) { + PyObject **items = \ + ((PyTupleObject *)v)->ob_item; while (oparg--) { w = items[oparg]; Py_INCREF(w); @@ -1588,15 +1596,17 @@ } Py_DECREF(v); continue; - } else if (PyList_CheckExact(v) && PyList_GET_SIZE(v) == oparg) { - PyObject **items = ((PyListObject *)v)->ob_item; + } else if (PyList_CheckExact(v) && + PyList_GET_SIZE(v) == oparg) { + PyObject **items = \ + ((PyListObject *)v)->ob_item; while (oparg--) { w = items[oparg]; Py_INCREF(w); PUSH(w); } } else if (unpack_iterable(v, oparg, -1, - stack_pointer + oparg)) { + stack_pointer + oparg)) { stack_pointer += oparg; } else { /* unpack_iterable() raised an exception */ @@ -1669,7 +1679,8 @@ else { x = PyObject_GetItem(v, w); if (x == NULL && PyErr_Occurred()) { - if (!PyErr_ExceptionMatches(PyExc_KeyError)) + if (!PyErr_ExceptionMatches( + PyExc_KeyError)) break; PyErr_Clear(); } @@ -1681,7 +1692,7 @@ if (x == NULL) { format_exc_check_arg( PyExc_NameError, - NAME_ERROR_MSG ,w); + NAME_ERROR_MSG, w); break; } } @@ -1782,13 +1793,10 @@ UNBOUNDLOCAL_ERROR_MSG, v); } else { - v = PyTuple_GET_ITEM( - co->co_freevars, - oparg - PyTuple_GET_SIZE(co->co_cellvars)); - format_exc_check_arg( - PyExc_NameError, - UNBOUNDFREE_ERROR_MSG, - v); + v = PyTuple_GET_ITEM(co->co_freevars, oparg - + PyTuple_GET_SIZE(co->co_cellvars)); + format_exc_check_arg(PyExc_NameError, + UNBOUNDFREE_ERROR_MSG, v); } break; @@ -2046,7 +2054,8 @@ continue; } if (PyErr_Occurred()) { - if (!PyErr_ExceptionMatches(PyExc_StopIteration)) + if (!PyErr_ExceptionMatches( + PyExc_StopIteration)) break; PyErr_Clear(); } @@ -2072,9 +2081,10 @@ case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: - /* NOTE: If you add any new block-setup opcodes that are - not try/except/finally handlers, you may need to - update the PyGen_NeedsFinalizing() function. */ + /* NOTE: If you add any new block-setup opcodes that + are not try/except/finally handlers, you may need + to update the PyGen_NeedsFinalizing() function. + */ PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, STACK_LEVEL()); @@ -3968,8 +3978,9 @@ if (v->ob_refcnt == 2) { /* In the common case, there are 2 references to the value * stored in 'variable' when the += is performed: one on the - * value stack (in 'v') and one still stored in the 'variable'. - * We try to delete the variable now to reduce the refcnt to 1. + * value stack (in 'v') and one still stored in the + * 'variable'. We try to delete the variable now to reduce + * the refcnt to 1. */ switch (*next_instr) { case STORE_FAST: @@ -3982,7 +3993,8 @@ } case STORE_DEREF: { - PyObject **freevars = f->f_localsplus + f->f_code->co_nlocals; + PyObject **freevars = (f->f_localsplus + + f->f_code->co_nlocals); PyObject *c = freevars[PEEKARG()]; if (PyCell_GET(c) == v) PyCell_Set(c, NULL); @@ -4010,10 +4022,10 @@ */ if (_PyString_Resize(&v, new_len) != 0) { /* XXX if _PyString_Resize() fails, 'v' has been - * deallocated so it cannot be put back into 'variable'. - * The MemoryError is raised when there is no value in - * 'variable', which might (very remotely) be a cause - * of incompatibilities. + * deallocated so it cannot be put back into + * 'variable'. The MemoryError is raised when there + * is no value in 'variable', which might (very + * remotely) be a cause of incompatibilities. */ return NULL; } From python-3000-checkins at python.org Fri Sep 21 03:17:15 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 21 Sep 2007 03:17:15 +0200 (CEST) Subject: [Python-3000-checkins] r58223 - in python/branches/py3k-importlib: Doc/c-api/concrete.rst Doc/library/cgi.rst Doc/library/collections.rst Doc/library/decimal.rst Doc/library/fileinput.rst Doc/library/functions.rst Doc/library/hashlib.rst Doc/library/operator.rst Doc/library/os.rst Doc/library/simplexmlrpcserver.rst Doc/library/ssl.rst Doc/library/stdtypes.rst Doc/library/undoc.rst Doc/reference/index.rst Doc/reference/simple_stmts.rst Doc/tutorial/inputoutput.rst Doc/whatsnew/2.5.rst Doc/whatsnew/2.6.rst Lib/cgi.py Lib/collections.py Lib/ctypes/test/test_cfuncs.py Lib/ctypes/test/test_functions.py Lib/ctypes/util.py Lib/decimal.py Lib/distutils/command/build_scripts.py Lib/httplib.py Lib/imaplib.py Lib/platform.py Lib/poplib.py Lib/repr.py Lib/smtplib.py Lib/socket.py Lib/ssl.py Lib/test/badcert.pem Lib/test/badkey.pem Lib/test/decimaltestdata/abs.decTest Lib/test/decimaltestdata/add.decTest Lib/test/decimaltestdata/and.decTest Lib/test/decimaltestdata/base.decTest Lib/test/decimaltestdata/clamp.decTest Lib/test/decimaltestdata/class.decTest Lib/test/decimaltestdata/compare.decTest Lib/test/decimaltestdata/comparetotal.decTest Lib/test/decimaltestdata/comparetotmag.decTest Lib/test/decimaltestdata/copy.decTest Lib/test/decimaltestdata/copyabs.decTest Lib/test/decimaltestdata/copynegate.decTest Lib/test/decimaltestdata/copysign.decTest Lib/test/decimaltestdata/ddAbs.decTest Lib/test/decimaltestdata/ddAdd.decTest Lib/test/decimaltestdata/ddAnd.decTest Lib/test/decimaltestdata/ddBase.decTest Lib/test/decimaltestdata/ddCanonical.decTest Lib/test/decimaltestdata/ddClass.decTest Lib/test/decimaltestdata/ddCompare.decTest Lib/test/decimaltestdata/ddCompareSig.decTest Lib/test/decimaltestdata/ddCompareTotal.decTest Lib/test/decimaltestdata/ddCompareTotalMag.decTest Lib/test/decimaltestdata/ddCopy.decTest Lib/test/decimaltestdata/ddCopyAbs.decTest Lib/test/decimaltestdata/ddCopyNegate.decTest Lib/test/decimaltestdata/ddCopySign.decTest Lib/test/decimaltestdata/ddDivide.decTest Lib/test/decimaltestdata/ddDivideInt.decTest Lib/test/decimaltestdata/ddEncode.decTest Lib/test/decimaltestdata/ddFMA.decTest Lib/test/decimaltestdata/ddInvert.decTest Lib/test/decimaltestdata/ddLogB.decTest Lib/test/decimaltestdata/ddMax.decTest Lib/test/decimaltestdata/ddMaxMag.decTest Lib/test/decimaltestdata/ddMin.decTest Lib/test/decimaltestdata/ddMinMag.decTest Lib/test/decimaltestdata/ddMinus.decTest Lib/test/decimaltestdata/ddMultiply.decTest Lib/test/decimaltestdata/ddNextMinus.decTest Lib/test/decimaltestdata/ddNextPlus.decTest Lib/test/decimaltestdata/ddNextToward.decTest Lib/test/decimaltestdata/ddOr.decTest Lib/test/decimaltestdata/ddPlus.decTest Lib/test/decimaltestdata/ddQuantize.decTest Lib/test/decimaltestdata/ddReduce.decTest Lib/test/decimaltestdata/ddRemainder.decTest Lib/test/decimaltestdata/ddRemainderNear.decTest Lib/test/decimaltestdata/ddRotate.decTest Lib/test/decimaltestdata/ddSameQuantum.decTest Lib/test/decimaltestdata/ddScaleB.decTest Lib/test/decimaltestdata/ddShift.decTest Lib/test/decimaltestdata/ddSubtract.decTest Lib/test/decimaltestdata/ddToIntegral.decTest Lib/test/decimaltestdata/ddXor.decTest Lib/test/decimaltestdata/decDouble.decTest Lib/test/decimaltestdata/decQuad.decTest Lib/test/decimaltestdata/decSingle.decTest Lib/test/decimaltestdata/decimal128.decTest Lib/test/decimaltestdata/decimal32.decTest Lib/test/decimaltestdata/decimal64.decTest Lib/test/decimaltestdata/divide.decTest Lib/test/decimaltestdata/divideint.decTest Lib/test/decimaltestdata/dqAbs.decTest Lib/test/decimaltestdata/dqAdd.decTest Lib/test/decimaltestdata/dqAnd.decTest Lib/test/decimaltestdata/dqBase.decTest Lib/test/decimaltestdata/dqCanonical.decTest Lib/test/decimaltestdata/dqClass.decTest Lib/test/decimaltestdata/dqCompare.decTest Lib/test/decimaltestdata/dqCompareSig.decTest Lib/test/decimaltestdata/dqCompareTotal.decTest Lib/test/decimaltestdata/dqCompareTotalMag.decTest Lib/test/decimaltestdata/dqCopy.decTest Lib/test/decimaltestdata/dqCopyAbs.decTest Lib/test/decimaltestdata/dqCopyNegate.decTest Lib/test/decimaltestdata/dqCopySign.decTest Lib/test/decimaltestdata/dqDivide.decTest Lib/test/decimaltestdata/dqDivideInt.decTest Lib/test/decimaltestdata/dqEncode.decTest Lib/test/decimaltestdata/dqFMA.decTest Lib/test/decimaltestdata/dqInvert.decTest Lib/test/decimaltestdata/dqLogB.decTest Lib/test/decimaltestdata/dqMax.decTest Lib/test/decimaltestdata/dqMaxMag.decTest Lib/test/decimaltestdata/dqMin.decTest Lib/test/decimaltestdata/dqMinMag.decTest Lib/test/decimaltestdata/dqMinus.decTest Lib/test/decimaltestdata/dqMultiply.decTest Lib/test/decimaltestdata/dqNextMinus.decTest Lib/test/decimaltestdata/dqNextPlus.decTest Lib/test/decimaltestdata/dqNextToward.decTest Lib/test/decimaltestdata/dqOr.decTest Lib/test/decimaltestdata/dqPlus.decTest Lib/test/decimaltestdata/dqQuantize.decTest Lib/test/decimaltestdata/dqReduce.decTest Lib/test/decimaltestdata/dqRemainder.decTest Lib/test/decimaltestdata/dqRemainderNear.decTest Lib/test/decimaltestdata/dqRotate.decTest Lib/test/decimaltestdata/dqSameQuantum.decTest Lib/test/decimaltestdata/dqScaleB.decTest Lib/test/decimaltestdata/dqShift.decTest Lib/test/decimaltestdata/dqSubtract.decTest Lib/test/decimaltestdata/dqToIntegral.decTest Lib/test/decimaltestdata/dqXor.decTest Lib/test/decimaltestdata/dsBase.decTest Lib/test/decimaltestdata/dsEncode.decTest Lib/test/decimaltestdata/exp.decTest Lib/test/decimaltestdata/extra.decTest Lib/test/decimaltestdata/fma.decTest Lib/test/decimaltestdata/inexact.decTest Lib/test/decimaltestdata/invert.decTest Lib/test/decimaltestdata/ln.decTest Lib/test/decimaltestdata/log10.decTest Lib/test/decimaltestdata/logb.decTest Lib/test/decimaltestdata/max.decTest Lib/test/decimaltestdata/maxmag.decTest Lib/test/decimaltestdata/min.decTest Lib/test/decimaltestdata/minmag.decTest Lib/test/decimaltestdata/minus.decTest Lib/test/decimaltestdata/multiply.decTest Lib/test/decimaltestdata/nextminus.decTest Lib/test/decimaltestdata/nextplus.decTest Lib/test/decimaltestdata/nexttoward.decTest Lib/test/decimaltestdata/normalize.decTest Lib/test/decimaltestdata/or.decTest Lib/test/decimaltestdata/plus.decTest Lib/test/decimaltestdata/power.decTest Lib/test/decimaltestdata/powersqrt.decTest Lib/test/decimaltestdata/quantize.decTest Lib/test/decimaltestdata/randomBound32.decTest Lib/test/decimaltestdata/randoms.decTest Lib/test/decimaltestdata/reduce.decTest Lib/test/decimaltestdata/remainder.decTest Lib/test/decimaltestdata/remainderNear.decTest Lib/test/decimaltestdata/rescale.decTest Lib/test/decimaltestdata/rotate.decTest Lib/test/decimaltestdata/rounding.decTest Lib/test/decimaltestdata/samequantum.decTest Lib/test/decimaltestdata/scaleb.decTest Lib/test/decimaltestdata/shift.decTest Lib/test/decimaltestdata/squareroot.decTest Lib/test/decimaltestdata/subtract.decTest Lib/test/decimaltestdata/testall.decTest Lib/test/decimaltestdata/tointegral.decTest Lib/test/decimaltestdata/tointegralx.decTest Lib/test/decimaltestdata/xor.decTest Lib/test/https_svn_python_org_root.pem Lib/test/list_tests.py Lib/test/nullcert.pem Lib/test/regrtest.py Lib/test/test_cmd_line.py Lib/test/test_collections.py Lib/test/test_decimal.py Lib/test/test_hash.py Lib/test/test_re.py Lib/test/test_repr.py Lib/test/test_socket_ssl.py Lib/test/test_ssl.py Lib/urllib.py Mac/Modules/cf/_CFmodule.c Mac/Modules/cf/cfsupport.py Mac/Modules/cf/pycfbridge.c Modules/_sre.c Modules/_ssl.c Modules/bz2module.c Objects/dictobject.c Objects/genobject.c Objects/listobject.c Objects/longobject.c Objects/object.c Objects/unicodeobject.c Python/ceval.c Python/compile.c Message-ID: <20070921011715.65CF71E400A@bag.python.org> Author: brett.cannon Date: Fri Sep 21 03:17:09 2007 New Revision: 58223 Added: python/branches/py3k-importlib/Lib/test/badcert.pem - copied unchanged from r58222, python/branches/py3k/Lib/test/badcert.pem python/branches/py3k-importlib/Lib/test/badkey.pem - copied unchanged from r58222, python/branches/py3k/Lib/test/badkey.pem python/branches/py3k-importlib/Lib/test/decimaltestdata/and.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/and.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/class.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/class.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/comparetotal.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/comparetotal.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/comparetotmag.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/comparetotmag.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/copy.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/copy.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/copyabs.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/copyabs.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/copynegate.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/copynegate.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/copysign.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/copysign.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddAbs.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddAbs.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddAdd.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddAdd.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddAnd.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddAnd.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddBase.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddBase.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddCanonical.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddCanonical.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddClass.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddClass.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddCompare.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddCompare.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddCompareSig.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddCompareSig.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddCompareTotal.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddCompareTotal.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddCompareTotalMag.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddCompareTotalMag.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddCopy.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddCopy.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddCopyAbs.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddCopyAbs.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddCopyNegate.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddCopyNegate.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddCopySign.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddCopySign.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddDivide.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddDivide.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddDivideInt.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddDivideInt.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddEncode.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddEncode.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddFMA.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddFMA.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddInvert.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddInvert.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddLogB.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddLogB.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddMax.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddMax.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddMaxMag.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddMaxMag.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddMin.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddMin.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddMinMag.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddMinMag.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddMinus.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddMinus.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddMultiply.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddMultiply.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddNextMinus.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddNextMinus.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddNextPlus.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddNextPlus.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddNextToward.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddNextToward.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddOr.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddOr.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddPlus.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddPlus.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddQuantize.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddQuantize.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddReduce.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddReduce.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddRemainder.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddRemainder.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddRemainderNear.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddRemainderNear.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddRotate.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddRotate.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddSameQuantum.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddSameQuantum.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddScaleB.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddScaleB.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddShift.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddShift.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddSubtract.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddSubtract.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddToIntegral.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddToIntegral.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ddXor.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ddXor.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/decDouble.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/decDouble.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/decQuad.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/decQuad.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/decSingle.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/decSingle.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqAbs.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqAbs.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqAdd.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqAdd.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqAnd.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqAnd.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqBase.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqBase.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqCanonical.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqCanonical.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqClass.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqClass.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqCompare.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqCompare.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqCompareSig.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqCompareSig.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqCompareTotal.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqCompareTotal.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqCompareTotalMag.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqCompareTotalMag.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqCopy.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqCopy.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqCopyAbs.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqCopyAbs.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqCopyNegate.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqCopyNegate.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqCopySign.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqCopySign.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqDivide.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqDivide.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqDivideInt.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqDivideInt.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqEncode.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqEncode.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqFMA.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqFMA.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqInvert.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqInvert.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqLogB.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqLogB.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqMax.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqMax.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqMaxMag.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqMaxMag.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqMin.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqMin.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqMinMag.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqMinMag.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqMinus.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqMinus.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqMultiply.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqMultiply.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqNextMinus.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqNextMinus.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqNextPlus.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqNextPlus.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqNextToward.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqNextToward.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqOr.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqOr.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqPlus.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqPlus.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqQuantize.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqQuantize.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqReduce.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqReduce.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqRemainder.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqRemainder.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqRemainderNear.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqRemainderNear.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqRotate.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqRotate.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqSameQuantum.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqSameQuantum.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqScaleB.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqScaleB.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqShift.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqShift.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqSubtract.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqSubtract.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqToIntegral.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqToIntegral.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dqXor.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dqXor.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dsBase.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dsBase.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/dsEncode.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/dsEncode.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/exp.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/exp.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/extra.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/extra.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/fma.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/fma.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/invert.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/invert.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/ln.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/ln.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/log10.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/log10.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/logb.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/logb.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/maxmag.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/maxmag.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/minmag.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/minmag.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/nextminus.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/nextminus.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/nextplus.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/nextplus.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/nexttoward.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/nexttoward.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/or.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/or.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/powersqrt.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/powersqrt.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/reduce.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/reduce.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/rotate.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/rotate.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/scaleb.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/scaleb.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/shift.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/shift.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/tointegralx.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/tointegralx.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/xor.decTest - copied unchanged from r58222, python/branches/py3k/Lib/test/decimaltestdata/xor.decTest python/branches/py3k-importlib/Lib/test/https_svn_python_org_root.pem - copied unchanged from r58222, python/branches/py3k/Lib/test/https_svn_python_org_root.pem python/branches/py3k-importlib/Lib/test/nullcert.pem - copied unchanged from r58222, python/branches/py3k/Lib/test/nullcert.pem Removed: python/branches/py3k-importlib/Lib/test/decimaltestdata/decimal128.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/decimal32.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/decimal64.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/normalize.decTest Modified: python/branches/py3k-importlib/ (props changed) python/branches/py3k-importlib/Doc/c-api/concrete.rst python/branches/py3k-importlib/Doc/library/cgi.rst python/branches/py3k-importlib/Doc/library/collections.rst python/branches/py3k-importlib/Doc/library/decimal.rst python/branches/py3k-importlib/Doc/library/fileinput.rst python/branches/py3k-importlib/Doc/library/functions.rst python/branches/py3k-importlib/Doc/library/hashlib.rst python/branches/py3k-importlib/Doc/library/operator.rst python/branches/py3k-importlib/Doc/library/os.rst python/branches/py3k-importlib/Doc/library/simplexmlrpcserver.rst python/branches/py3k-importlib/Doc/library/ssl.rst python/branches/py3k-importlib/Doc/library/stdtypes.rst python/branches/py3k-importlib/Doc/library/undoc.rst python/branches/py3k-importlib/Doc/reference/index.rst python/branches/py3k-importlib/Doc/reference/simple_stmts.rst python/branches/py3k-importlib/Doc/tutorial/inputoutput.rst python/branches/py3k-importlib/Doc/whatsnew/2.5.rst python/branches/py3k-importlib/Doc/whatsnew/2.6.rst python/branches/py3k-importlib/Lib/cgi.py python/branches/py3k-importlib/Lib/collections.py python/branches/py3k-importlib/Lib/ctypes/test/test_cfuncs.py python/branches/py3k-importlib/Lib/ctypes/test/test_functions.py python/branches/py3k-importlib/Lib/ctypes/util.py python/branches/py3k-importlib/Lib/decimal.py python/branches/py3k-importlib/Lib/distutils/command/build_scripts.py python/branches/py3k-importlib/Lib/httplib.py python/branches/py3k-importlib/Lib/imaplib.py python/branches/py3k-importlib/Lib/platform.py python/branches/py3k-importlib/Lib/poplib.py python/branches/py3k-importlib/Lib/repr.py python/branches/py3k-importlib/Lib/smtplib.py python/branches/py3k-importlib/Lib/socket.py python/branches/py3k-importlib/Lib/ssl.py python/branches/py3k-importlib/Lib/test/decimaltestdata/abs.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/add.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/base.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/clamp.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/compare.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/divide.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/divideint.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/inexact.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/max.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/min.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/minus.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/multiply.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/plus.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/power.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/quantize.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/randomBound32.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/randoms.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/remainder.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/remainderNear.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/rescale.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/rounding.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/samequantum.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/squareroot.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/subtract.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/testall.decTest python/branches/py3k-importlib/Lib/test/decimaltestdata/tointegral.decTest python/branches/py3k-importlib/Lib/test/list_tests.py python/branches/py3k-importlib/Lib/test/regrtest.py python/branches/py3k-importlib/Lib/test/test_cmd_line.py python/branches/py3k-importlib/Lib/test/test_collections.py python/branches/py3k-importlib/Lib/test/test_decimal.py python/branches/py3k-importlib/Lib/test/test_hash.py python/branches/py3k-importlib/Lib/test/test_re.py python/branches/py3k-importlib/Lib/test/test_repr.py python/branches/py3k-importlib/Lib/test/test_socket_ssl.py python/branches/py3k-importlib/Lib/test/test_ssl.py python/branches/py3k-importlib/Lib/urllib.py python/branches/py3k-importlib/Mac/Modules/cf/_CFmodule.c python/branches/py3k-importlib/Mac/Modules/cf/cfsupport.py python/branches/py3k-importlib/Mac/Modules/cf/pycfbridge.c python/branches/py3k-importlib/Modules/_sre.c python/branches/py3k-importlib/Modules/_ssl.c python/branches/py3k-importlib/Modules/bz2module.c python/branches/py3k-importlib/Objects/dictobject.c python/branches/py3k-importlib/Objects/genobject.c python/branches/py3k-importlib/Objects/listobject.c python/branches/py3k-importlib/Objects/longobject.c python/branches/py3k-importlib/Objects/object.c python/branches/py3k-importlib/Objects/unicodeobject.c python/branches/py3k-importlib/Python/ceval.c python/branches/py3k-importlib/Python/compile.c Log: Merged revisions 58188-58222 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k Modified: python/branches/py3k-importlib/Doc/c-api/concrete.rst ============================================================================== --- python/branches/py3k-importlib/Doc/c-api/concrete.rst (original) +++ python/branches/py3k-importlib/Doc/c-api/concrete.rst Fri Sep 21 03:17:09 2007 @@ -1953,12 +1953,12 @@ ``PyTuple_Pack(2, a, b)`` is equivalent to ``Py_BuildValue("(OO)", a, b)``. -.. cfunction:: int PyTuple_Size(PyObject *p) +.. cfunction:: Py_ssize_t PyTuple_Size(PyObject *p) Take a pointer to a tuple object, and return the size of that tuple. -.. cfunction:: int PyTuple_GET_SIZE(PyObject *p) +.. cfunction:: Py_ssize_t PyTuple_GET_SIZE(PyObject *p) Return the size of the tuple *p*, which must be non-*NULL* and point to a tuple; no error checking is performed. @@ -2458,7 +2458,7 @@ immediately after file object creation. -.. cfunction:: int PyFile_Encoding(PyFileObject *p, char *enc) +.. cfunction:: int PyFile_SetEncoding(PyFileObject *p, const char *enc) Set the file's encoding for Unicode output to *enc*. Return 1 on success and 0 on failure. @@ -3371,7 +3371,7 @@ or :class:`frozenset` or instances of their subtypes. -.. cfunction:: int PySet_Size(PyObject *anyset) +.. cfunction:: Py_ssize_t PySet_Size(PyObject *anyset) .. index:: builtin: len @@ -3380,7 +3380,7 @@ :class:`set`, :class:`frozenset`, or an instance of a subtype. -.. cfunction:: int PySet_GET_SIZE(PyObject *anyset) +.. cfunction:: Py_ssize_t PySet_GET_SIZE(PyObject *anyset) Macro form of :cfunc:`PySet_Size` without error checking. Modified: python/branches/py3k-importlib/Doc/library/cgi.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/cgi.rst (original) +++ python/branches/py3k-importlib/Doc/library/cgi.rst Fri Sep 21 03:17:09 2007 @@ -147,6 +147,11 @@ if not line: break linecount = linecount + 1 +If an error is encountered when obtaining the contents of an uploaded file +(for example, when the user interrupts the form submission by clicking on +a Back or Cancel button) the :attr:`done` attribute of the object for the +field will be set to the value -1. + The file upload draft standard entertains the possibility of uploading multiple files from one field (using a recursive :mimetype:`multipart/\*` encoding). When this occurs, the item will be a dictionary-like :class:`FieldStorage` item. Modified: python/branches/py3k-importlib/Doc/library/collections.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/collections.rst (original) +++ python/branches/py3k-importlib/Doc/library/collections.rst Fri Sep 21 03:17:09 2007 @@ -395,11 +395,14 @@ .. _named-tuple-factory: -:func:`NamedTuple` datatype factory function --------------------------------------------- +:func:`NamedTuple` Factory Function for Tuples with Named Fields +---------------------------------------------------------------- +Named tuples assign meaning to each position in a tuple and allow for more readable, +self-documenting code. They can be used wherever regular tuples are used, and +they add the ability to access fields by name instead of position index. -.. function:: NamedTuple(typename, fieldnames) +.. function:: NamedTuple(typename, fieldnames, [verbose]) Returns a new tuple subclass named *typename*. The new subclass is used to create tuple-like objects that have fields accessable by attribute lookup as @@ -407,43 +410,92 @@ helpful docstring (with typename and fieldnames) and a helpful :meth:`__repr__` method which lists the tuple contents in a ``name=value`` format. - The *fieldnames* are specified in a single string and are separated by spaces. - Any valid Python identifier may be used for a field name. + The *fieldnames* are specified in a single string with each fieldname separated by + a space and/or comma. Any valid Python identifier may be used for a fieldname. - Example:: + If *verbose* is true, will print the class definition. - >>> Point = NamedTuple('Point', 'x y') - >>> Point.__doc__ # docstring for the new datatype - 'Point(x, y)' - >>> p = Point(11, y=22) # instantiate with positional or keyword arguments - >>> p[0] + p[1] # works just like the tuple (11, 22) - 33 - >>> x, y = p # unpacks just like a tuple - >>> x, y - (11, 22) - >>> p.x + p.y # fields also accessable by name - 33 - >>> p # readable __repr__ with name=value style - Point(x=11, y=22) - - The use cases are the same as those for tuples. The named factories assign - meaning to each tuple position and allow for more readable, self-documenting - code. Named tuples can also be used to assign field names to tuples returned - by the :mod:`csv` or :mod:`sqlite3` modules. For example:: - - from itertools import starmap - import csv - EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade') - for record in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))): - print(record) - - To cast an individual record stored as :class:`list`, :class:`tuple`, or some - other iterable type, use the star-operator [#]_ to unpack the values:: - - >>> Color = NamedTuple('Color', 'name code') - >>> m = dict(red=1, green=2, blue=3) - >>> print(Color(*m.popitem())) - Color(name='blue', code=3) + *NamedTuple* instances do not have per-instance dictionaries, so they are + lightweight and require no more memory than regular tuples. + +Example:: + + >>> Point = NamedTuple('Point', 'x y', True) + class Point(tuple): + 'Point(x, y)' + __slots__ = () + __fields__ = ('x', 'y') + def __new__(cls, x, y): + return tuple.__new__(cls, (x, y)) + def __repr__(self): + return 'Point(x=%r, y=%r)' % self + def __replace__(self, field, value): + 'Return a new Point object replacing one field with a new value' + return Point(**dict(zip(('x', 'y'), self) + [(field, value)])) + x = property(itemgetter(0)) + y = property(itemgetter(1)) + + >>> p = Point(11, y=22) # instantiate with positional or keyword arguments + >>> p[0] + p[1] # indexable like the regular tuple (11, 22) + 33 + >>> x, y = p # unpack like a regular tuple + >>> x, y + (11, 22) + >>> p.x + p.y # fields also accessable by name + 33 + >>> p # readable __repr__ with a name=value style + Point(x=11, y=22) + +Named tuples are especially useful for assigning field names to result tuples returned +by the :mod:`csv` or :mod:`sqlite3` modules:: + + from itertools import starmap + import csv + EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade') + for record in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))): + print(emp.name, emp.title) + +When casting a single record to a *NamedTuple*, use the star-operator [#]_ to unpack +the values:: + + >>> t = [11, 22] + >>> Point(*t) # the star-operator unpacks any iterable object + Point(x=11, y=22) + +In addition to the methods inherited from tuples, named tuples support +an additonal method and an informational read-only attribute. + +.. method:: somenamedtuple.replace(field, value) + + Return a new instance of the named tuple replacing the named *field* with a new *value*: + +:: + + >>> p = Point(x=11, y=22) + >>> p.__replace__('x', 33) + Point(x=33, y=22) + + >>> for recordnum, record in inventory: + ... inventory[recordnum] = record.replace('total', record.price * record.quantity) + +.. attribute:: somenamedtuple.__fields__ + + Return a tuple of strings listing the field names. This is useful for introspection, + for converting a named tuple instance to a dictionary, and for combining named tuple + types to create new named tuple types: + +:: + + >>> p.__fields__ # view the field names + ('x', 'y') + >>> dict(zip(p.__fields__, p)) # convert to a dictionary + {'y': 22, 'x': 11} + + >>> Color = NamedTuple('Color', 'red green blue') + >>> pixel_fields = ' '.join(Point.__fields__ + Color.__fields__) # combine fields + >>> Pixel = NamedTuple('Pixel', pixel_fields) + >>> Pixel(11, 22, 128, 255, 0) + Pixel(x=11, y=22, red=128, green=255, blue=0)' .. rubric:: Footnotes Modified: python/branches/py3k-importlib/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/decimal.rst (original) +++ python/branches/py3k-importlib/Doc/library/decimal.rst Fri Sep 21 03:17:09 2007 @@ -14,7 +14,7 @@ The :mod:`decimal` module provides support for decimal floating point -arithmetic. It offers several advantages over the :class:`float()` datatype: +arithmetic. It offers several advantages over the :class:`float` datatype: * Decimal numbers can be represented exactly. In contrast, numbers like :const:`1.1` do not have an exact representation in binary floating point. End @@ -22,7 +22,7 @@ :const:`1.1000000000000001` as it does with binary floating point. * The exactness carries over into arithmetic. In decimal floating point, ``0.1 - + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, result + + 0.1 + 0.1 - 0.3`` is exactly equal to zero. In binary floating point, the result is :const:`5.5511151231257827e-017`. While near to zero, the differences prevent reliable equality testing and differences can accumulate. For this reason, decimal would be preferred in accounting applications which have strict @@ -36,7 +36,7 @@ 1.20`` gives :const:`1.5600`. * Unlike hardware based binary floating point, the decimal module has a user - settable precision (defaulting to 28 places) which can be as large as needed for + alterable precision (defaulting to 28 places) which can be as large as needed for a given problem:: >>> getcontext().prec = 6 @@ -56,7 +56,7 @@ A decimal number is immutable. It has a sign, coefficient digits, and an exponent. To preserve significance, the coefficient digits do not truncate -trailing zeroes. Decimals also include special values such as +trailing zeros. Decimals also include special values such as :const:`Infinity`, :const:`-Infinity`, and :const:`NaN`. The standard also differentiates :const:`-0` from :const:`+0`. @@ -65,7 +65,7 @@ enablers which determine whether signals are treated as exceptions. Rounding options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`, :const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`, -:const:`ROUND_HALF_UP`, and :const:`ROUND_UP`. +:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`. Signals are groups of exceptional conditions arising during the course of computation. Depending on the needs of the application, signals may be ignored, @@ -82,11 +82,11 @@ .. seealso:: - IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic - Specification `_. + * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic + Specification `_. - IEEE standard 854-1987, `Unofficial IEEE 854 Text - `_. + * IEEE standard 854-1987, `Unofficial IEEE 854 Text + `_. .. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -123,6 +123,8 @@ Decimal("3.14") >>> Decimal(str(2.0 ** 0.5)) Decimal("1.41421356237") + >>> Decimal(2) ** Decimal("0.5") + Decimal("1.414213562373095048801688724") >>> Decimal("NaN") Decimal("NaN") >>> Decimal("-Infinity") @@ -172,6 +174,17 @@ >>> c % a Decimal("0.77") +And some mathematic functions are also available to Decimal:: + + >>> Decimal(2).sqrt() + Decimal("1.414213562373095048801688724") + >>> Decimal(1).exp() + Decimal("2.718281828459045235360287471") + >>> Decimal("10").ln() + Decimal("2.302585092994045684017991455") + >>> Decimal("10").log10() + Decimal("1") + The :meth:`quantize` method rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of places:: @@ -285,7 +298,7 @@ The *context* precision does not affect how many digits are stored. That is determined exclusively by the number of digits in *value*. For example, - ``Decimal("3.00000")`` records all five zeroes even if the context precision is + ``Decimal("3.00000")`` records all five zeros even if the context precision is only three. The purpose of the *context* argument is determining what to do if *value* is a @@ -295,7 +308,7 @@ Once constructed, :class:`Decimal` objects are immutable. -Decimal floating point objects share many properties with the other builtin +Decimal floating point objects share many properties with the other built-in numeric types such as :class:`float` and :class:`int`. All of the usual math operations and special methods apply. Likewise, decimal objects can be copied, pickled, printed, used as dictionary keys, used as set elements, compared, @@ -315,50 +328,363 @@ .. method:: Decimal.as_tuple() - Returns a tuple representation of the number: ``(sign, digittuple, exponent)``. + Return a tuple representation of the number: ``(sign, digit_tuple, exponent)``. + +.. method:: Decimal.canonical() + + Return the canonical encoding of the argument. Currently, the + encoding of a :class:`Decimal` instance is always canonical, so + this operation returns its argument unchanged. + + .. versionadded:: 2.6 .. method:: Decimal.compare(other[, context]) - Compares like :meth:`__cmp__` but returns a decimal instance:: + Compare the values of two Decimal instances. This operation + behaves in the same way as the usual comparison method + :meth:`__cmp__`, except that :meth:`compare` returns a Decimal + instance rather than an integer, and if either operand is a NaN + then the result is a NaN:: a or b is a NaN ==> Decimal("NaN") a < b ==> Decimal("-1") a == b ==> Decimal("0") a > b ==> Decimal("1") +.. method:: Decimal.compare_signal(other[, context]) + + This operation is identical to the :meth:`compare` method, except + that all NaNs signal. That is, if neither operand is a signaling + NaN then any quiet NaN operand is treated as though it were a + signaling NaN. + + .. versionadded:: 2.6 + +.. method:: Decimal.compare_total(other) + + Compare two operands using their abstract representation rather + than their numerical value. Similar to the :meth:`compare` method, + but the result gives a total ordering on :class:`Decimal` + instances. Two :class:`Decimal` instances with the same numeric + value but different representations compare unequal in this + ordering:: + + >>> Decimal("12.0").compare_total(Decimal("12")) + Decimal("-1") + + Quiet and signaling NaNs are also included in the total ordering. + The result of this function is ``Decimal("0")`` if both operands + have the same representation, ``Decimal("-1")`` if the first + operand is lower in the total order than the second, and + ``Decimal("1")`` if the first operand is higher in the total order + than the second operand. See the specification for details of the + total order. + + .. versionadded:: 2.6 + +.. method:: Decimal.compare_total_mag(other) + + Compare two operands using their abstract representation rather + than their value as in :meth:`compare_total`, but ignoring the sign + of each operand. ``x.compare_total_mag(y)`` is equivalent to + ``x.copy_abs().compare_total(y.copy_abs())``. + + .. versionadded:: 2.6 + +.. method:: Decimal.copy_abs() + + Return the absolute value of the argument. This operation is + unaffected by the context and is quiet: no flags are changed and no + rounding is performed. + + .. versionadded:: 2.6 + +.. method:: Decimal.copy_negate() + + Return the negation of the argument. This operation is unaffected + by the context and is quiet: no flags are changed and no rounding + is performed. + + .. versionadded:: 2.6 + +.. method:: Decimal.copy_sign(other) + + Return a copy of the first operand with the sign set to be the + same as the sign of the second operand. For example:: + + >>> Decimal("2.3").copy_sign(Decimal("-1.5")) + Decimal("-2.3") + + This operation is unaffected by the context and is quiet: no flags + are changed and no rounding is performed. + + .. versionadded:: 2.6 + +.. method:: Decimal.exp([context]) + + Return the value of the (natural) exponential function ``e**x`` at the + given number. The result is correctly rounded using the + :const:`ROUND_HALF_EVEN` rounding mode. + + >>> Decimal(1).exp() + Decimal("2.718281828459045235360287471") + >>> Decimal(321).exp() + Decimal("2.561702493119680037517373933E+139") + + .. versionadded:: 2.6 + +.. method:: Decimal.fma(other, third[, context]) + + Fused multiply-add. Return self*other+third with no rounding of + the intermediate product self*other. + + >>> Decimal(2).fma(3, 5) + Decimal("11") + + .. versionadded:: 2.6 + +.. method:: Decimal.is_canonical() + + Return :const:`True` if the argument is canonical and + :const:`False` otherwise. Currently, a :class:`Decimal` instance + is always canonical, so this operation always returns + :const:`True`. + + .. versionadded:: 2.6 + +.. method:: is_finite() + + Return :const:`True` if the argument is a finite number, and + :const:`False` if the argument is an infinity or a NaN. + + .. versionadded:: 2.6 + +.. method:: is_infinite() + + Return :const:`True` if the argument is either positive or + negative infinity and :const:`False` otherwise. + + .. versionadded:: 2.6 + +.. method:: is_nan() + + Return :const:`True` if the argument is a (quiet or signaling) + NaN and :const:`False` otherwise. + + .. versionadded:: 2.6 + +.. method:: is_normal() + + Return :const:`True` if the argument is a *normal* finite number. + Return :const:`False` if the argument is zero, subnormal, infinite + or a NaN. + + .. versionadded:: 2.6 + +.. method:: is_qnan() + + Return :const:`True` if the argument is a quiet NaN, and + :const:`False` otherwise. + + .. versionadded:: 2.6 + +.. method:: is_signed() + + Return :const:`True` if the argument has a negative sign and + :const:`False` otherwise. Note that zeros and NaNs can both carry + signs. + + .. versionadded:: 2.6 + +.. method:: is_snan() + + Return :const:`True` if the argument is a signaling NaN and + :const:`False` otherwise. + + .. versionadded:: 2.6 + +.. method:: is_subnormal() + + Return :const:`True` if the argument is subnormal, and + :const:`False` otherwise. + + .. versionadded:: 2.6 + +.. method:: is_zero() + + Return :const:`True` if the argument is a (positive or negative) + zero and :const:`False` otherwise. + + .. versionadded:: 2.6 + +.. method:: Decimal.ln([context]) + + Return the natural (base e) logarithm of the operand. The result + is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding + mode. + + .. versionadded:: 2.6 + +.. method:: Decimal.log10([context]) + + Return the base ten logarithm of the operand. The result is + correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode. + + .. versionadded:: 2.6 + +.. method: Decimal.logb([context]) + + For a nonzero number, return the adjusted exponent of its operand + as a :class:`Decimal` instance. If the operand is a zero then + ``Decimal("-Infinity")`` is returned and the + :const:`DivisionByZero` flag is raised. If the operand is an + infinity then ``Decimal("Infinity")`` is returned. + + .. versionadded:: 2.6 + +.. method:: Decimal.logical_and(other[, context]) + + :meth:`logical_and` is a logical operation which takes two + *logical operands* (see :ref:`logical_operands_label`). The result + is the digit-wise ``and`` of the two operands. + + .. versionadded:: 2.6 + +.. method:: Decimal.logical_invert(other[, context]) + + :meth:`logical_invert` is a logical operation. The argument must + be a *logical operand* (see :ref:`logical_operands_label`). The + result is the digit-wise inversion of the operand. + + .. versionadded:: 2.6 + +.. method:: Decimal.logical_or(other[, context]) + + :meth:`logical_or` is a logical operation which takes two *logical + operands* (see :ref:`logical_operands_label`). The result is the + digit-wise ``or`` of the two operands. + + .. versionadded:: 2.6 + +.. method:: Decimal.logical_xor(other[, context]) + + :meth:`logical_xor` is a logical operation which takes two + *logical operands* (see :ref:`logical_operands_label`). The result + is the digit-wise exclusive or of the two operands. + + .. versionadded:: 2.6 .. method:: Decimal.max(other[, context]) Like ``max(self, other)`` except that the context rounding rule is applied - before returning and that :const:`NaN` values are either signalled or ignored + before returning and that :const:`NaN` values are either signaled or ignored (depending on the context and whether they are signaling or quiet). +.. method:: Decimal.max_mag(other[, context]) + + Similar to the :meth:`max` method, but the comparison is done using + the absolute values of the operands. + + .. versionadded:: 2.6 .. method:: Decimal.min(other[, context]) Like ``min(self, other)`` except that the context rounding rule is applied - before returning and that :const:`NaN` values are either signalled or ignored + before returning and that :const:`NaN` values are either signaled or ignored (depending on the context and whether they are signaling or quiet). +.. method:: Decimal.min_mag(other[, context]) + + Similar to the :meth:`min` method, but the comparison is done using + the absolute values of the operands. + + .. versionadded:: 2.6 + +.. method:: Decimal.next_minus([context]) + + Return the largest number representable in the given context (or + in the current thread's context if no context is given) that is smaller + than the given operand. + + .. versionadded:: 2.6 + +.. method:: Decimal.next_plus([context]) + + Return the smallest number representable in the given context (or + in the current thread's context if no context is given) that is + larger than the given operand. + + .. versionadded:: 2.6 + +.. method:: Decimal.next_toward(other[, context]) + + If the two operands are unequal, return the number closest to the + first operand in the direction of the second operand. If both + operands are numerically equal, return a copy of the first operand + with the sign set to be the same as the sign of the second operand. + + .. versionadded:: 2.6 .. method:: Decimal.normalize([context]) - Normalize the number by stripping the rightmost trailing zeroes and converting + Normalize the number by stripping the rightmost trailing zeros and converting any result equal to :const:`Decimal("0")` to :const:`Decimal("0e0")`. Used for producing canonical values for members of an equivalence class. For example, ``Decimal("32.100")`` and ``Decimal("0.321000e+2")`` both normalize to the equivalent value ``Decimal("32.1")``. +.. method:: Decimal.number_class([context]) + + Return a string describing the *class* of the operand. The + returned value is one of the following ten strings. + + * ``"-Infinity"``, indicating that the operand is negative infinity. + * ``"-Normal"``, indicating that the operand is a negative normal number. + * ``"-Subnormal"``, indicating that the operand is negative and subnormal. + * ``"-Zero"``, indicating that the operand is a negative zero. + * ``"+Zero"``, indicating that the operand is a positive zero. + * ``"+Subnormal"``, indicating that the operand is positive and subnormal. + * ``"+Normal"``, indicating that the operand is a positive normal number. + * ``"+Infinity"``, indicating that the operand is positive infinity. + * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number). + * ``"sNaN"``, indicating that the operand is a signaling NaN. -.. method:: Decimal.quantize(exp [, rounding[, context[, watchexp]]]) + .. versionadded:: 2.6 - Quantize makes the exponent the same as *exp*. Searches for a rounding method - in *rounding*, then in *context*, and then in the current context. +.. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]]) - If *watchexp* is set (default), then an error is returned whenever the resulting - exponent is greater than :attr:`Emax` or less than :attr:`Etiny`. + Returns a value equal to the first operand after rounding and + having the exponent of the second operand. + >>> Decimal("1.41421356").quantize(Decimal("1.000")) + Decimal("1.414") + + Unlike other operations, if the length of the coefficient after the + quantize operation would be greater than precision, then an + :const:`InvalidOperation` is signaled. This guarantees that, unless + there is an error condition, the quantized exponent is always equal + to that of the right-hand operand. + + Also unlike other operations, quantize never signals Underflow, + even if the result is subnormal and inexact. + + If the exponent of the second operand is larger than that of the + first then rounding may be necessary. In this case, the rounding + mode is determined by the ``rounding`` argument if given, else by + the given ``context`` argument; if neither argument is given the + rounding mode of the current thread's context is used. + + If watchexp is set (default), then an error is returned whenever + the resulting exponent is greater than Emax or less than Etiny. + +.. method:: Decimal.radix() + + Return ``Decimal(10)``, the radix (base) in which the + :class:`Decimal` class does all its arithmetic. Included for + compatibility with the specification. + + .. versionadded:: 2.6 .. method:: Decimal.remainder_near(other[, context]) @@ -368,16 +694,49 @@ If both are equally close, the one chosen will have the same sign as *self*. +.. method:: Decimal.rotate(other[, context]) + + Return the result of rotating the digits of the first operand by + an amount specified by the second operand. The second operand + must be an integer in the range -precision through precision. The + absolute value of the second operand gives the number of places to + rotate. If the second operand is positive then rotation is to the + left; otherwise rotation is to the right. The coefficient of the + first operand is padded on the left with zeros to length precision + if necessary. The sign and exponent of the first operand are + unchanged. + + .. versionadded:: 2.6 .. method:: Decimal.same_quantum(other[, context]) Test whether self and other have the same exponent or whether both are :const:`NaN`. +.. method:: Decimal.scaleb(other[, context]) + + Return the first operand with exponent adjusted by the second. + Equivalently, return the first operand multiplied by ``10**other``. + The second operand must be an integer. + + .. versionadded:: 2.6 + +.. method:: Decimal.shift(other[, context]) + + Return the result of shifting the digits of the first operand by + an amount specified by the second operand. The second operand must + be an integer in the range -precision through precision. The + absolute value of the second operand gives the number of places to + shift. If the second operand is positive then the shift is to the + left; otherwise the shift is to the right. Digits shifted into the + coefficient are zeros. The sign and exponent of the first operand + are unchanged. + + .. versionadded:: 2.6 .. method:: Decimal.sqrt([context]) - Return the square root to full precision. + Return the square root of the argument to full precision. .. method:: Decimal.to_eng_string([context]) @@ -388,13 +747,53 @@ to 3 digits left of the decimal place. For example, converts ``Decimal('123E+1')`` to ``Decimal("1.23E+3")`` - .. method:: Decimal.to_integral([rounding[, context]]) + Identical to the :meth:`to_integral_value` method. The ``to_integral`` + name has been kept for compatibility with older versions. + +.. method:: Decimal.to_integral_exact([rounding[, context]]) + + Round the argument to the nearest integer, signaling + :const:`Inexact` or :const:`Rounded` as appropriate if rounding + occurs. The rounding mode is determined by the ``rounding`` + parameter if given, else by the given ``context``. If neither + parameter is given then the rounding mode of the current context is + used. + + .. versionadded:: 2.6 + +.. method:: Decimal.to_integral_value([rounding[, context]]) + Rounds to the nearest integer without signaling :const:`Inexact` or :const:`Rounded`. If given, applies *rounding*; otherwise, uses the rounding method in either the supplied *context* or the current context. + .. versionchanged:: 2.6 + renamed from ``to_integral`` to ``to_integral_value``. The old name + remains valid for compatibility. + +.. method:: Decimal.trim() + + Returns its argument with *insignificant* trailing zeros removed. + Here, a trailing zero is considered insignificant either if it + follows the decimal point, or if the exponent of the argument (that + is, the last element of the :meth:`as_tuple` representation) is + positive. + + .. versionadded:: 2.6 + +.. _logical_operands_label: + +Logical operands +^^^^^^^^^^^^^^^^ + +The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`, +and :meth:`logical_xor` methods expect their arguments to be *logical +operands*. A *logical operand* is a :class:`Decimal` instance whose +exponent and sign are both zero, and whose digits are all either +:const:`0` or :const:`1`. + .. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -509,6 +908,8 @@ * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer), * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or * :const:`ROUND_UP` (away from zero). + * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero + would have been 0 or 5; otherwise towards zero) The *traps* and *flags* fields list any signals to be set. Generally, new contexts should only set traps and leave the flags clear. @@ -520,9 +921,16 @@ :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`. -The :class:`Context` class defines several general purpose methods as well as a -large number of methods for doing arithmetic directly in a given context. + .. versionchanged:: 2.6 + The :const:`ROUND_05UP` rounding mode was added. +The :class:`Context` class defines several general purpose methods as +well as a large number of methods for doing arithmetic directly in a +given context. In addition, for each of the :class:`Decimal` methods +described above (with the exception of the :meth:`adjusted` and +:meth:`as_tuple` methods) there is a corresponding :class:`Context` +method. For example, ``C.exp(x)`` is equivalent to +``x.exp(context=C)``. .. method:: Context.clear_flags() @@ -533,6 +941,9 @@ Return a duplicate of the context. +.. method:: Context.copy_decimal(num) + + Return a copy of the Decimal instance num. .. method:: Context.create_decimal(num) @@ -566,7 +977,7 @@ The usual approach to working with decimals is to create :class:`Decimal` instances and then apply arithmetic operations which take place within the -current context for the active thread. An alternate approach is to use context +current context for the active thread. An alternative approach is to use context methods for calculating within a specific context. The methods are similar to those for the :class:`Decimal` class and are only briefly recounted here. @@ -581,42 +992,19 @@ Return the sum of *x* and *y*. -.. method:: Context.compare(x, y) - - Compares values numerically. - - Like :meth:`__cmp__` but returns a decimal instance:: - - a or b is a NaN ==> Decimal("NaN") - a < b ==> Decimal("-1") - a == b ==> Decimal("0") - a > b ==> Decimal("1") - - .. method:: Context.divide(x, y) Return *x* divided by *y*. -.. method:: Context.divmod(x, y) - - Divides two numbers and returns the integer part of the result. - - -.. method:: Context.max(x, y) - - Compare two values numerically and return the maximum. - - If they are numerically equal then the left-hand operand is chosen as the - result. +.. method:: Context.divide_int(x, y) + Return *x* divided by *y*, truncated to an integer. -.. method:: Context.min(x, y) - Compare two values numerically and return the minimum. +.. method:: Context.divmod(x, y) - If they are numerically equal then the left-hand operand is chosen as the - result. + Divides two numbers and returns the integer part of the result. .. method:: Context.minus(x) @@ -629,14 +1017,6 @@ Return the product of *x* and *y*. -.. method:: Context.normalize(x) - - Normalize reduces an operand to its simplest form. - - Essentially a :meth:`plus` operation with all trailing zeros removed from the - result. - - .. method:: Context.plus(x) Plus corresponds to the unary prefix plus operator in Python. This operation @@ -646,33 +1026,31 @@ .. method:: Context.power(x, y[, modulo]) - Return ``x ** y`` to the *modulo* if given. - - The right-hand operand must be a whole number whose integer part (after any - exponent has been applied) has no more than 9 digits and whose fractional part - (if any) is all zeros before any rounding. The operand may be positive, - negative, or zero; if negative, the absolute value of the power is used, and the - left-hand operand is inverted (divided into 1) before use. - - If the increased precision needed for the intermediate calculations exceeds the - capabilities of the implementation then an :const:`InvalidOperation` condition - is signaled. + Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if + given. - If, when raising to a negative power, an underflow occurs during the division - into 1, the operation is not halted at that point but continues. - - -.. method:: Context.quantize(x, y) - - Returns a value equal to *x* after rounding and having the exponent of *y*. - - Unlike other operations, if the length of the coefficient after the quantize - operation would be greater than precision, then an :const:`InvalidOperation` is - signaled. This guarantees that, unless there is an error condition, the - quantized exponent is always equal to that of the right-hand operand. - - Also unlike other operations, quantize never signals Underflow, even if the - result is subnormal and inexact. + With two arguments, compute ``x**y``. If ``x`` is negative then + ``y`` must be integral. The result will be inexact unless ``y`` is + integral and the result is finite and can be expressed exactly in + 'precision' digits. The result should always be correctly rounded, + using the rounding mode of the current thread's context. + + With three arguments, compute ``(x**y) % modulo``. For the three + argument form, the following restrictions on the arguments hold: + + - all three arguments must be integral + - ``y`` must be nonnegative + - at least one of ``x`` or ``y`` must be nonzero + - ``modulo`` must be nonzero and have at most 'precision' digits + + The result of ``Context.power(x, y, modulo)`` is identical to + the result that would be obtained by computing ``(x**y) % + modulo`` with unbounded precision, but is computed more + efficiently. It is always exact. + + .. versionchanged:: 2.6 + ``y`` may now be nonintegral in ``x**y``. + Stricter requirements for the three-argument version. .. method:: Context.remainder(x, y) @@ -682,47 +1060,10 @@ The sign of the result, if non-zero, is the same as that of the original dividend. - -.. method:: Context.remainder_near(x, y) - - Computed the modulo as either a positive or negative value depending on which is - closest to zero. For instance, ``Decimal(10).remainder_near(6)`` returns - ``Decimal("-2")`` which is closer to zero than ``Decimal("4")``. - - If both are equally close, the one chosen will have the same sign as *self*. - - -.. method:: Context.same_quantum(x, y) - - Test whether *x* and *y* have the same exponent or whether both are - :const:`NaN`. - - -.. method:: Context.sqrt(x) - - Return the square root of *x* to full precision. - - .. method:: Context.subtract(x, y) Return the difference between *x* and *y*. - -.. method:: Context.to_eng_string() - - Convert to engineering-type string. - - Engineering notation has an exponent which is a multiple of 3, so there are up - to 3 digits left of the decimal place. For example, converts - ``Decimal('123E+1')`` to ``Decimal("1.23E+3")`` - - -.. method:: Context.to_integral(x) - - Rounds to the nearest integer without signaling :const:`Inexact` or - :const:`Rounded`. - - .. method:: Context.to_sci_string(x) Converts a number to a string using scientific notation. @@ -755,7 +1096,7 @@ Typically, clamping occurs when an exponent falls outside the context's :attr:`Emin` and :attr:`Emax` limits. If possible, the exponent is reduced to - fit by adding zeroes to the coefficient. + fit by adding zeros to the coefficient. .. class:: DecimalException @@ -908,7 +1249,7 @@ The number system for the :mod:`decimal` module provides special values including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`, -and two zeroes, :const:`+0` and :const:`-0`. +and two zeros, :const:`+0` and :const:`-0`. Infinities can be constructed directly with: ``Decimal('Infinity')``. Also, they can arise from dividing by zero when the :exc:`DivisionByZero` signal is Modified: python/branches/py3k-importlib/Doc/library/fileinput.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/fileinput.rst (original) +++ python/branches/py3k-importlib/Doc/library/fileinput.rst Fri Sep 21 03:17:09 2007 @@ -7,8 +7,9 @@ .. sectionauthor:: Fred L. Drake, Jr. -This module implements a helper class and functions to quickly write a loop over -standard input or a list of files. +This module implements a helper class and functions to quickly write a +loop over standard input or a list of files. If you just want to read or +write one file see :func:`open`. The typical use is:: Modified: python/branches/py3k-importlib/Doc/library/functions.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/functions.rst (original) +++ python/branches/py3k-importlib/Doc/library/functions.rst Fri Sep 21 03:17:09 2007 @@ -746,7 +746,8 @@ Python enforces that the mode, after stripping ``'U'``, begins with ``'r'``, ``'w'`` or ``'a'``. - See also the :mod:`fileinput` module. + See also the :mod:`fileinput` module, the :mod:`os` module, and the + :mod:`os.path` module. .. function:: ord(c) Modified: python/branches/py3k-importlib/Doc/library/hashlib.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/hashlib.rst (original) +++ python/branches/py3k-importlib/Doc/library/hashlib.rst Fri Sep 21 03:17:09 2007 @@ -36,7 +36,7 @@ Feeding string objects is to :meth:`update` is not supported, as hashes work on bytes, not on characters. -.. index:: single: OpenSSL +.. index:: single: OpenSSL; (use in module hashlib) Constructors for hash algorithms that are always present in this module are :func:`md5`, :func:`sha1`, :func:`sha224`, :func:`sha256`, :func:`sha384`, and Modified: python/branches/py3k-importlib/Doc/library/operator.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/operator.rst (original) +++ python/branches/py3k-importlib/Doc/library/operator.rst Fri Sep 21 03:17:09 2007 @@ -47,18 +47,18 @@ truth tests, identity tests, and boolean operations: -.. function:: not_(o) - __not__(o) +.. function:: not_(obj) + __not__(obj) - Return the outcome of :keyword:`not` *o*. (Note that there is no + Return the outcome of :keyword:`not` *obj*. (Note that there is no :meth:`__not__` method for object instances; only the interpreter core defines this operation. The result is affected by the :meth:`__bool__` and :meth:`__len__` methods.) -.. function:: truth(o) +.. function:: truth(obj) - Return :const:`True` if *o* is true, and :const:`False` otherwise. This is + Return :const:`True` if *obj* is true, and :const:`False` otherwise. This is equivalent to using the :class:`bool` constructor. @@ -75,10 +75,10 @@ The mathematical and bitwise operations are the most numerous: -.. function:: abs(o) - __abs__(o) +.. function:: abs(obj) + __abs__(obj) - Return the absolute value of *o*. + Return the absolute value of *obj*. .. function:: add(a, b) @@ -106,12 +106,12 @@ Return ``a // b``. -.. function:: inv(o) - invert(o) - __inv__(o) - __invert__(o) +.. function:: inv(obj) + invert(obj) + __inv__(obj) + __invert__(obj) - Return the bitwise inverse of the number *o*. This is equivalent to ``~o``. + Return the bitwise inverse of the number *obj*. This is equivalent to ``~obj``. .. function:: lshift(a, b) @@ -132,10 +132,10 @@ Return ``a * b``, for *a* and *b* numbers. -.. function:: neg(o) - __neg__(o) +.. function:: neg(obj) + __neg__(obj) - Return *o* negated. + Return *obj* negated. .. function:: or_(a, b) @@ -144,10 +144,10 @@ Return the bitwise or of *a* and *b*. -.. function:: pos(o) - __pos__(o) +.. function:: pos(obj) + __pos__(obj) - Return *o* positive. + Return *obj* positive. .. function:: pow(a, b) @@ -373,24 +373,30 @@ ... pass ... >>> import operator - >>> o = C() - >>> operator.isMappingType(o) + >>> obj = C() + >>> operator.isMappingType(obj) True +.. note:: + + Python 3 is expected to introduce abstract base classes for + collection types, so it should be possible to write, for example, + ``isinstance(obj, collections.Mapping)`` and ``isinstance(obj, + collections.Sequence)``. -.. function:: isCallable(o) +.. function:: isCallable(obj) .. deprecated:: 2.0 Use the :func:`callable` built-in function instead. - Returns true if the object *o* can be called like a function, otherwise it + Returns true if the object *obj* can be called like a function, otherwise it returns false. True is returned for functions, bound and unbound methods, class objects, and instance objects which support the :meth:`__call__` method. -.. function:: isMappingType(o) +.. function:: isMappingType(obj) - Returns true if the object *o* supports the mapping interface. This is true for + Returns true if the object *obj* supports the mapping interface. This is true for dictionaries and all instance objects defining :meth:`__getitem__`. .. warning:: @@ -400,9 +406,9 @@ useful than it otherwise might be. -.. function:: isNumberType(o) +.. function:: isNumberType(obj) - Returns true if the object *o* represents a number. This is true for all + Returns true if the object *obj* represents a number. This is true for all numeric types implemented in C. .. warning:: @@ -412,9 +418,9 @@ useful than it otherwise might be. -.. function:: isSequenceType(o) +.. function:: isSequenceType(obj) - Returns true if the object *o* supports the sequence protocol. This returns true + Returns true if the object *obj* supports the sequence protocol. This returns true for all objects which define sequence methods in C, and for all instance objects defining :meth:`__getitem__`. @@ -484,7 +490,7 @@ +-----------------------+-------------------------+---------------------------------+ | Concatenation | ``seq1 + seq2`` | ``concat(seq1, seq2)`` | +-----------------------+-------------------------+---------------------------------+ -| Containment Test | ``o in seq`` | ``contains(seq, o)`` | +| Containment Test | ``obj in seq`` | ``contains(seq, obj)`` | +-----------------------+-------------------------+---------------------------------+ | Division | ``a / b`` | ``div(a, b)`` (without | | | | ``__future__.division``) | @@ -508,11 +514,11 @@ +-----------------------+-------------------------+---------------------------------+ | Identity | ``a is not b`` | ``is_not(a, b)`` | +-----------------------+-------------------------+---------------------------------+ -| Indexed Assignment | ``o[k] = v`` | ``setitem(o, k, v)`` | +| Indexed Assignment | ``obj[k] = v`` | ``setitem(obj, k, v)`` | +-----------------------+-------------------------+---------------------------------+ -| Indexed Deletion | ``del o[k]`` | ``delitem(o, k)`` | +| Indexed Deletion | ``del obj[k]`` | ``delitem(obj, k)`` | +-----------------------+-------------------------+---------------------------------+ -| Indexing | ``o[k]`` | ``getitem(o, k)`` | +| Indexing | ``obj[k]`` | ``getitem(obj, k)`` | +-----------------------+-------------------------+---------------------------------+ | Left Shift | ``a << b`` | ``lshift(a, b)`` | +-----------------------+-------------------------+---------------------------------+ @@ -534,11 +540,11 @@ +-----------------------+-------------------------+---------------------------------+ | Slicing | ``seq[i:j]`` | ``getslice(seq, i, j)`` | +-----------------------+-------------------------+---------------------------------+ -| String Formatting | ``s % o`` | ``mod(s, o)`` | +| String Formatting | ``s % obj`` | ``mod(s, obj)`` | +-----------------------+-------------------------+---------------------------------+ | Subtraction | ``a - b`` | ``sub(a, b)`` | +-----------------------+-------------------------+---------------------------------+ -| Truth Test | ``o`` | ``truth(o)`` | +| Truth Test | ``obj`` | ``truth(obj)`` | +-----------------------+-------------------------+---------------------------------+ | Ordering | ``a < b`` | ``lt(a, b)`` | +-----------------------+-------------------------+---------------------------------+ Modified: python/branches/py3k-importlib/Doc/library/os.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/os.rst (original) +++ python/branches/py3k-importlib/Doc/library/os.rst Fri Sep 21 03:17:09 2007 @@ -8,9 +8,10 @@ This module provides a more portable way of using operating system dependent functionality than importing a operating system dependent built-in module like -:mod:`posix` or :mod:`nt`. (If you just want to read or write a file see -:func:`open`, and if you want to manipulate paths, see the :mod:`os.path` -module.) +:mod:`posix` or :mod:`nt`. If you just want to read or write a file see +:func:`open`, if you want to manipulate paths, see the :mod:`os.path` +module, and if you want to read all the lines in all the files on the +command line see the :mod:`fileinput` module. This module searches for an operating system dependent built-in module like :mod:`mac` or :mod:`posix` and exports the same functions and data as found Modified: python/branches/py3k-importlib/Doc/library/simplexmlrpcserver.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/simplexmlrpcserver.rst (original) +++ python/branches/py3k-importlib/Doc/library/simplexmlrpcserver.rst Fri Sep 21 03:17:09 2007 @@ -142,7 +142,7 @@ import xmlrpclib - s = xmlrpclib.Server('http://localhost:8000') + s = xmlrpclib.ServerProxy('http://localhost:8000') print(s.pow(2,3)) # Returns 2**3 = 8 print(s.add(2,3)) # Returns 5 print(s.div(5,2)) # Returns 5//2 = 2 Modified: python/branches/py3k-importlib/Doc/library/ssl.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/ssl.rst (original) +++ python/branches/py3k-importlib/Doc/library/ssl.rst Fri Sep 21 03:17:09 2007 @@ -9,6 +9,10 @@ .. sectionauthor:: Bill Janssen +.. index:: single: OpenSSL; (use in module ssl) + +.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer + This module provides access to Transport Layer Security (often known as "Secure Sockets Layer") encryption and peer authentication facilities for network sockets, both client-side and server-side. @@ -19,18 +23,125 @@ .. note:: Some behavior may be platform dependent, since calls are made to the operating - system socket APIs. + system socket APIs. The installed version of OpenSSL may also cause + variations in behavior. This section documents the objects and functions in the ``ssl`` module; for more general information about TLS, SSL, and certificates, the -reader is referred to the documents in the :ref:`ssl-references` section. +reader is referred to the documents in the "See Also" section at +the bottom. -This module defines a class, :class:`ssl.sslsocket`, which is -derived from the :class:`socket.socket` type, and supports additional +This module provides a class, :class:`ssl.SSLSocket`, which is +derived from the :class:`socket.socket` type, and provides +a socket-like wrapper that also encrypts and decrypts the data +going over the socket with SSL. It supports additional :meth:`read` and :meth:`write` methods, along with a method, :meth:`getpeercert`, -to retrieve the certificate of the other side of the connection. +to retrieve the certificate of the other side of the connection, and +a method, :meth:`cipher`, to retrieve the cipher being used for the +secure connection. + +Functions, Constants, and Exceptions +------------------------------------ + +.. exception:: SSLError + + Raised to signal an error from the underlying SSL implementation. This + signifies some problem in the higher-level + encryption and authentication layer that's superimposed on the underlying + network connection. This error is a subtype of :exc:`socket.error`, which + in turn is a subtype of :exc:`IOError`. + +.. function:: wrap_socket (sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None) + + Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance of :class:`ssl.SSLSocket`, a subtype + of :class:`socket.socket`, which wraps the underlying socket in an SSL context. + For client-side sockets, the context construction is lazy; if the underlying socket isn't + connected yet, the context construction will be performed after :meth:`connect` is called + on the socket. For server-side sockets, if the socket has no remote peer, it is assumed + to be a listening socket, and the server-side SSL wrapping is automatically performed + on client connections accepted via the :meth:`accept` method. :func:`wrap_socket` may + raise :exc:`SSLError`. + + The ``keyfile`` and ``certfile`` parameters specify optional files which contain a certificate + to be used to identify the local side of the connection. See the discussion of :ref:`ssl-certificates` + for more information on how the certificate is stored in the ``certfile``. + + Often the private key is stored + in the same file as the certificate; in this case, only the ``certfile`` parameter need be + passed. If the private key is stored in a separate file, both parameters must be used. + If the private key is stored in the ``certfile``, it should come before the first certificate + in the certificate chain:: + + -----BEGIN RSA PRIVATE KEY----- + ... (private key in base64 encoding) ... + -----END RSA PRIVATE KEY----- + -----BEGIN CERTIFICATE----- + ... (certificate in base64 PEM encoding) ... + -----END CERTIFICATE----- + + The parameter ``server_side`` is a boolean which identifies whether server-side or client-side + behavior is desired from this socket. -This module defines the following functions, exceptions, and constants: + The parameter ``cert_reqs`` specifies whether a certificate is + required from the other side of the connection, and whether it will + be validated if provided. It must be one of the three values + :const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required, + but validated if provided), or :const:`CERT_REQUIRED` (required and + validated). If the value of this parameter is not :const:`CERT_NONE`, then + the ``ca_certs`` parameter must point to a file of CA certificates. + + The ``ca_certs`` file contains a set of concatenated "certification authority" certificates, + which are used to validate certificates passed from the other end of the connection. + See the discussion of :ref:`ssl-certificates` for more information about how to arrange + the certificates in this file. + + The parameter ``ssl_version`` specifies which version of the SSL protocol to use. + Typically, the server chooses a particular protocol version, and the client + must adapt to the server's choice. Most of the versions are not interoperable + with the other versions. If not specified, for client-side operation, the + default SSL version is SSLv3; for server-side operation, SSLv23. These + version selections provide the most compatibility with other versions. + + Here's a table showing which versions in a client (down the side) + can connect to which versions in a server (along the top): + + .. table:: + + ======================== ========= ========= ========== ========= + *client* / **server** **SSLv2** **SSLv3** **SSLv23** **TLSv1** + *SSLv2* yes no yes* no + *SSLv3* yes yes yes no + *SSLv23* yes no yes no + *TLSv1* no no yes yes + ======================== ========= ========= ========== ========= + + `*` In some older versions of OpenSSL (for instance, 0.9.7l on OS X 10.4), + an SSLv2 client could not connect to an SSLv23 server. + +.. function:: RAND_status() + + Returns True if the SSL pseudo-random number generator has been + seeded with 'enough' randomness, and False otherwise. You can use + :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness + of the pseudo-random number generator. + +.. function:: RAND_egd(path) + + If you are running an entropy-gathering daemon (EGD) somewhere, and ``path`` + is the pathname of a socket connection open to it, this will read + 256 bytes of randomness from the socket, and add it to the SSL pseudo-random number generator + to increase the security of generated secret keys. This is typically only + necessary on systems without better sources of randomness. + + See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for + sources of entropy-gathering daemons. + +.. function:: RAND_add(bytes, entropy) + + Mixes the given ``bytes`` into the SSL pseudo-random number generator. + The parameter ``entropy`` (a float) is a lower bound on the entropy + contained in string (so you can always use :const:`0.0`). + See :rfc:`1750` for more information on sources of entropy. .. function:: cert_time_to_seconds(timestring) @@ -48,12 +159,27 @@ 'Wed May 9 00:00:00 2007' >>> -.. exception:: sslerror +.. function:: get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None) - Raised to signal an error from the underlying SSL implementation. This - signifies some problem in the higher-level - encryption and authentication layer that's superimposed on the underlying - network connection. + Given the address ``addr`` of an SSL-protected server, as a + (*hostname*, *port-number*) pair, fetches the server's certificate, + and returns it as a PEM-encoded string. If ``ssl_version`` is + specified, uses that version of the SSL protocol to attempt to + connect to the server. If ``ca_certs`` is specified, it should be + a file containing a list of root certificates, the same format as + used for the same parameter in :func:`wrap_socket`. The call will + attempt to validate the server certificate against that set of root + certificates, and will fail if the validation attempt fails. + +.. function:: DER_cert_to_PEM_cert (DER_cert_bytes) + + Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded + string version of the same certificate. + +.. function:: PEM_cert_to_DER_cert (PEM_cert_string) + + Given a certificate as an ASCII PEM string, returns a DER-encoded + sequence of bytes for that same certificate. .. data:: CERT_NONE @@ -84,13 +210,16 @@ .. data:: PROTOCOL_SSLv23 - Selects SSL version 2 or 3 as the channel encryption protocol. This is a setting to use for maximum compatibility - with the other end of an SSL connection, but it may cause the specific ciphers chosen for the encryption to be - of fairly low quality. + Selects SSL version 2 or 3 as the channel encryption protocol. + This is a setting to use with servers for maximum compatibility + with the other end of an SSL connection, but it may cause the + specific ciphers chosen for the encryption to be of fairly low + quality. .. data:: PROTOCOL_SSLv3 Selects SSL version 3 as the channel encryption protocol. + For clients, this is the maximally compatible SSL variant. .. data:: PROTOCOL_TLSv1 @@ -99,6 +228,69 @@ protection, if both sides can speak it. +SSLSocket Objects +----------------- + +.. method:: SSLSocket.read([nbytes=1024]) + + Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them. + +.. method:: SSLSocket.write(data) + + Writes the ``data`` to the other side of the connection, using the + SSL channel to encrypt. Returns the number of bytes written. + +.. method:: SSLSocket.getpeercert(binary_form=False) + + If there is no certificate for the peer on the other end of the + connection, returns ``None``. + + If the the parameter ``binary_form`` is :const:`False`, and a + certificate was received from the peer, this method returns a + :class:`dict` instance. If the certificate was not validated, the + dict is empty. If the certificate was validated, it returns a dict + with the keys ``subject`` (the principal for which the certificate + was issued), and ``notAfter`` (the time after which the certificate + should not be trusted). The certificate was already validated, so + the ``notBefore`` and ``issuer`` fields are not returned. If a + certificate contains an instance of the *Subject Alternative Name* + extension (see :rfc:`3280`), there will also be a + ``subjectAltName`` key in the dictionary. + + The "subject" field is a tuple containing the sequence of relative + distinguished names (RDNs) given in the certificate's data + structure for the principal, and each RDN is a sequence of + name-value pairs:: + + {'notAfter': 'Feb 16 16:54:50 2013 GMT', + 'subject': ((('countryName', u'US'),), + (('stateOrProvinceName', u'Delaware'),), + (('localityName', u'Wilmington'),), + (('organizationName', u'Python Software Foundation'),), + (('organizationalUnitName', u'SSL'),), + (('commonName', u'somemachine.python.org'),))} + + If the ``binary_form`` parameter is :const:`True`, and a + certificate was provided, this method returns the DER-encoded form + of the entire certificate as a sequence of bytes, or :const:`None` if the + peer did not provide a certificate. This return + value is independent of validation; if validation was required + (:const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`), it will have + been validated, but if :const:`CERT_NONE` was used to establish the + connection, the certificate, if present, will not have been validated. + +.. method:: SSLSocket.cipher() + + Returns a three-value tuple containing the name of the cipher being + used, the version of the SSL protocol that defines its use, and the + number of secret bits being used. If no connection has been + established, returns ``None``. + + +.. index:: single: certificates + +.. index:: single: X509 certificate + .. _ssl-certificates: Certificates @@ -127,8 +319,12 @@ side of a network connection can also be required to produce a certificate, and that certificate can be validated to the satisfaction of the client or server that requires such validation. -The connection can be set to fail automatically if such -validation is not achieved. +The connection attempt can be set to raise an exception if +the validation fails. Validation is done +automatically, by the underlying OpenSSL framework; the +application need not concern itself with its mechanics. +But the application does usually need to provide +sets of certificates to allow this process to take place. Python uses files to contain certificates. They should be formatted as "PEM" (see :rfc:`1422`), which is a base-64 encoded form wrapped @@ -167,108 +363,55 @@ chains for each issuer you are willing to trust. Again, this file just contains these chains concatenated together. For validation, Python will use the first chain it finds in the file which matches. -Some "standard" root certificates are available at -http://www.thawte.com/roots/ (for Thawte roots) and -http://www.verisign.com/support/roots.html (for Verisign roots). -See also :rfc:`4158` for more discussion of the way in which +Some "standard" root certificates are available from various certification +authorities: +`CACert.org `_, +`Thawte `_, +`Verisign `_, +`Positive SSL `_ (used by python.org), +`Equifax and GeoTrust `_. + +In general, if you are using +SSL3 or TLS1, you don't need to put the full chain in your "CA certs" file; +you only need the root certificates, and the remote peer is supposed to +furnish the other certificates necessary to chain from its certificate to +a root certificate. +See :rfc:`4158` for more discussion of the way in which certification chains can be built. - -sslsocket Objects ------------------ - -.. class:: sslsocket(sock [, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_SSLv23, ca_certs=None]) - - Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance of a subtype - of :class:`socket.socket` which wraps the underlying socket in an SSL context. - For client-side sockets, the context construction is lazy; if the underlying socket isn't - connected yet, the context construction will be performed after :meth:`connect` is called - on the socket. - - The ``keyfile`` and ``certfile`` parameters specify optional files which contain a certificate - to be used to identify the local side of the connection. See the above discussion of :ref:`ssl-certificates` - for more information on how the certificate is stored in the ``certfile``. - - Often the private key is stored - in the same file as the certificate; in this case, only the ``certfile`` parameter need be - passed. If the private key is stored in a separate file, both parameters must be used. - If the private key is stored in the ``certfile``, it should come before the first certificate - in the certificate chain:: - - -----BEGIN RSA PRIVATE KEY----- - ... (private key in base64 encoding) ... - -----END RSA PRIVATE KEY----- - -----BEGIN CERTIFICATE----- - ... (certificate in base64 PEM encoding) ... - -----END CERTIFICATE----- - - The parameter ``server_side`` is a boolean which identifies whether server-side or client-side - behavior is desired from this socket. - - The parameter ``cert_reqs`` specifies whether a certificate is - required from the other side of the connection, and whether it will - be validated if provided. It must be one of the three values - :const:`CERT_NONE` (certificates ignored), :const:`CERT_OPTIONAL` (not required, - but validated if provided), or :const:`CERT_REQUIRED` (required and - validated). If the value of this parameter is not :const:`CERT_NONE`, then - the ``ca_certs`` parameter must point to a file of CA certificates. - - The parameter ``ssl_version`` specifies which version of the SSL protocol to use. Typically, - the server specifies this, and a client connecting to it must use the same protocol. An - SSL server using :const:`PROTOCOL_SSLv23` can understand a client connecting via SSL2, SSL3, or TLS1, - but a client using :const:`PROTOCOL_SSLv23` can only connect to an SSL2 server. - - The ``ca_certs`` file contains a set of concatenated "certification authority" certificates, - which are used to validate certificates passed from the other end of the connection. - See the above discussion of :ref:`ssl-certificates` for more information about how to arrange - the certificates in this file. - -.. method:: sslsocket.read([nbytes]) - - Reads up to ``nbytes`` bytes from the SSL-encrypted channel and returns them. - -.. method:: sslsocket.write(data) - - Writes the ``data`` to the other side of the connection, using the SSL channel to encrypt. Returns the number - of bytes written. - -.. method:: sslsocket.getpeercert() - - If there is no certificate for the peer on the other end of the connection, returns ``None``. - If a certificate was received from the peer, but not validated, returns an empty ``dict`` instance. - If a certificate was received and validated, returns a ``dict`` instance with the fields - ``subject`` (the principal for which the certificate was issued), ``issuer`` (the signer of - the certificate), ``notBefore`` (the time before which the certificate should not be trusted), - and ``notAfter`` (the time after which the certificate should not be trusted) filled in. - - The "subject" and "issuer" fields are tuples containing the name-value fields - given in the certificate's data structure for each principal:: - - {'issuer': (('countryName', u'US'), - ('stateOrProvinceName', u'Delaware'), - ('localityName', u'Wilmington'), - ('organizationName', u'Python Software Foundation'), - ('organizationalUnitName', u'SSL'), - ('commonName', u'somemachine.python.org')), - 'notAfter': 'Feb 16 16:54:50 2013 GMT', - 'notBefore': 'Aug 27 16:54:50 2007 GMT', - 'subject': (('countryName', u'US'), - ('stateOrProvinceName', u'Delaware'), - ('localityName', u'Wilmington'), - ('organizationName', u'Python Software Foundation'), - ('organizationalUnitName', u'SSL'), - ('commonName', u'somemachine.python.org')), - 'version': 2} - - This certificate is said to be *self-signed*, because the subject - and issuer are the same entity. The *version* field refers to the X509 version - that's used for the certificate. - -.. method:: sslsocket.ssl_shutdown() - - Closes the SSL context (if any) over the socket, but leaves the socket connection - open for further use, if both sides are willing. This is different from :meth:`socket.socket.shutdown`, - which will close the connection, but leave the local socket available for further use. +If you are going to create a server that provides SSL-encrypted +connection services, you will need to acquire a certificate for that +service. There are many ways of acquiring appropriate certificates, +such as buying one from a certification authority. Another common +practice is to generate a self-signed certificate. The simplest +way to do this is with the OpenSSL package, using something like +the following:: + + % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem + Generating a 1024 bit RSA private key + .......++++++ + .............................++++++ + writing new private key to 'cert.pem' + ----- + You are about to be asked to enter information that will be incorporated + into your certificate request. + What you are about to enter is what is called a Distinguished Name or a DN. + There are quite a few fields but you can leave some blank + For some fields there will be a default value, + If you enter '.', the field will be left blank. + ----- + Country Name (2 letter code) [AU]:US + State or Province Name (full name) [Some-State]:MyState + Locality Name (eg, city) []:Some City + Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc. + Organizational Unit Name (eg, section) []:My Group + Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com + Email Address []:ops at myserver.mygroup.myorganization.com + % + +The disadvantage of a self-signed certificate is that it is its +own root certificate, and no one else will have it in their cache +of known (and trusted) root certificates. Examples @@ -295,12 +438,17 @@ import socket, ssl, pprint s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - ssl_sock = ssl.sslsocket(s, ca_certs="/etc/ca_certs_file", cert_reqs=ssl.CERT_REQUIRED) + + # require a certificate from the server + ssl_sock = ssl.wrap_socket(s, + ca_certs="/etc/ca_certs_file", + cert_reqs=ssl.CERT_REQUIRED) ssl_sock.connect(('www.verisign.com', 443)) print(repr(ssl_sock.getpeername())) pprint.pprint(ssl_sock.getpeercert()) + print(pprint.pformat(ssl_sock.getpeercert())) # Set a simple HTTP request -- use httplib in actual code. ssl_sock.write("""GET / HTTP/1.0\r @@ -310,35 +458,29 @@ # read all the data returned by the server. data = ssl_sock.read() - # note that closing the sslsocket will also close the underlying socket + # note that closing the SSLSocket will also close the underlying socket ssl_sock.close() -As of September 4, 2007, the certificate printed by this program +As of September 6, 2007, the certificate printed by this program looked like this:: - {'issuer': (('countryName', u'US'), - ('organizationName', u'VeriSign, Inc.'), - ('organizationalUnitName', u'VeriSign Trust Network'), - ('organizationalUnitName', - u'Terms of use at https://www.verisign.com/rpa (c)06'), - ('commonName', - u'VeriSign Class 3 Extended Validation SSL SGC CA')), - 'notAfter': 'May 8 23:59:59 2009 GMT', - 'notBefore': 'May 9 00:00:00 2007 GMT', - 'subject': (('serialNumber', u'2497886'), - ('1.3.6.1.4.1.311.60.2.1.3', u'US'), - ('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'), - ('countryName', u'US'), - ('postalCode', u'94043'), - ('stateOrProvinceName', u'California'), - ('localityName', u'Mountain View'), - ('streetAddress', u'487 East Middlefield Road'), - ('organizationName', u'VeriSign, Inc.'), - ('organizationalUnitName', u'Production Security Services'), - ('organizationalUnitName', - u'Terms of use at www.verisign.com/rpa (c)06'), - ('commonName', u'www.verisign.com')), - 'version': 2} + {'notAfter': 'May 8 23:59:59 2009 GMT', + 'subject': ((('serialNumber', u'2497886'),), + (('1.3.6.1.4.1.311.60.2.1.3', u'US'),), + (('1.3.6.1.4.1.311.60.2.1.2', u'Delaware'),), + (('countryName', u'US'),), + (('postalCode', u'94043'),), + (('stateOrProvinceName', u'California'),), + (('localityName', u'Mountain View'),), + (('streetAddress', u'487 East Middlefield Road'),), + (('organizationName', u'VeriSign, Inc.'),), + (('organizationalUnitName', + u'Production Security Services'),), + (('organizationalUnitName', + u'Terms of use at www.verisign.com/rpa (c)06'),), + (('commonName', u'www.verisign.com'),))} + +which is a fairly poorly-formed ``subject`` field. Server-side operation ^^^^^^^^^^^^^^^^^^^^^ @@ -354,12 +496,15 @@ bindsocket.listen(5) When one did, you'd call :meth:`accept` on the socket to get the new socket from the other -end, and use :func:`sslsocket` to create a server-side SSL context for it:: +end, and use :func:`wrap_socket` to create a server-side SSL context for it:: while True: newsocket, fromaddr = bindsocket.accept() - connstream = ssl.sslsocket(newsocket, server_side=True, certfile="mycertfile", - keyfile="mykeyfile", ssl_protocol=ssl.PROTOCOL_TLSv1) + connstream = ssl.wrap_socket(newsocket, + server_side=True, + certfile="mycertfile", + keyfile="mykeyfile", + ssl_protocol=ssl.PROTOCOL_TLSv1) deal_with_client(connstream) Then you'd read data from the ``connstream`` and do something with it till you are finished with the client (or the client is finished with you):: @@ -370,7 +515,8 @@ # null data means the client is finished with us while data: if not do_something(connstream, data): - # we'll assume do_something returns False when we're finished with client + # we'll assume do_something returns False + # when we're finished with client break data = connstream.read() # finished with client @@ -379,16 +525,19 @@ And go back to listening for new client connections. -.. _ssl-references: +.. seealso:: -References ----------- + Class :class:`socket.socket` + Documentation of underlying :mod:`socket` class -Class :class:`socket.socket` - Documentation of underlying :mod:`socket` class + `Introducing SSL and Certificates using OpenSSL `_ + Frederick J. Hirsch -`Introducing SSL and Certificates using OpenSSL `_, by Frederick J. Hirsch + `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management `_ + Steve Kent -`Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management`, :rfc:`1422`, by Steve Kent + `RFC 1750: Randomness Recommendations for Security `_ + D. Eastlake et. al. -`Internet X.509 Public Key Infrastructure Certificate and CRL Profile`, :rfc:`3280`, Housley et. al. + `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile `_ + Housley et. al. Modified: python/branches/py3k-importlib/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/stdtypes.rst (original) +++ python/branches/py3k-importlib/Doc/library/stdtypes.rst Fri Sep 21 03:17:09 2007 @@ -657,10 +657,13 @@ .. index:: pair: string; methods -String objects support the methods listed below. In addition, Python's strings -support the sequence type methods described in the :ref:`typesseq` section. To -output formatted strings, see the :ref:`string-formatting` section. Also, see -the :mod:`re` module for string functions based on regular expressions. +String objects support the methods listed below. Note that none of these +methods take keyword arguments. + +In addition, Python's strings support the sequence type methods described in +the :ref:`typesseq` section. To output formatted strings, see the +:ref:`string-formatting` section. Also, see the :mod:`re` module for string +functions based on regular expressions. .. method:: str.capitalize() Modified: python/branches/py3k-importlib/Doc/library/undoc.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/undoc.rst (original) +++ python/branches/py3k-importlib/Doc/library/undoc.rst Fri Sep 21 03:17:09 2007 @@ -19,9 +19,6 @@ Some of these are very old and/or not very robust; marked with "hmm." -:mod:`bdb` - --- A generic Python debugger base class (used by pdb). - :mod:`ihooks` --- Import hook support (for :mod:`rexec`; may become obsolete). Modified: python/branches/py3k-importlib/Doc/reference/index.rst ============================================================================== --- python/branches/py3k-importlib/Doc/reference/index.rst (original) +++ python/branches/py3k-importlib/Doc/reference/index.rst Fri Sep 21 03:17:09 2007 @@ -17,7 +17,7 @@ interfaces available to C/C++ programmers in detail. .. toctree:: - :maxdepth: 2 + :maxdepth: 3 introduction.rst lexical_analysis.rst Modified: python/branches/py3k-importlib/Doc/reference/simple_stmts.rst ============================================================================== --- python/branches/py3k-importlib/Doc/reference/simple_stmts.rst (original) +++ python/branches/py3k-importlib/Doc/reference/simple_stmts.rst Fri Sep 21 03:17:09 2007 @@ -62,47 +62,6 @@ standard output on a line by itself (except if the result is ``None``, so that procedure calls do not cause any output.) - -.. _assert: - -Assert statements -================= - -.. index:: - statement: assert - pair: debugging; assertions - single: __debug__ - exception: AssertionError - -Assert statements are a convenient way to insert debugging assertions into a -program: - -.. productionlist:: - assert_stmt: "assert" `expression` ["," `expression`] - -The simple form, ``assert expression``, is equivalent to :: - - if __debug__: - if not expression: raise AssertionError - -The extended form, ``assert expression1, expression2``, is equivalent to :: - - if __debug__: - if not expression1: raise AssertionError(expression2) - -These equivalences assume that :data:`__debug__` and :exc:`AssertionError` refer -to the built-in variables with those names. In the current implementation, the -built-in variable :data:`__debug__` is ``True`` under normal circumstances, -``False`` when optimization is requested (command line option ``-O``). The -current code generator emits no code for an assert statement when optimization -is requested at compile time. Note that it is unnecessary to include the source -code for the expression that failed in the error message; it will be displayed -as part of the stack trace. - -Assignments to :data:`__debug__` are illegal. The value for the built-in -variable is determined when the interpreter starts. - - .. _assignment: Assignment statements @@ -308,6 +267,48 @@ a.x += 1 # writes a.x as 4 leaving A.x as 3 +.. _assert: + +The :keyword:`assert` statement +=============================== + +.. index:: + statement: assert + pair: debugging; assertions + +Assert statements are a convenient way to insert debugging assertions into a +program: + +.. productionlist:: + assert_stmt: "assert" `expression` ["," `expression`] + +The simple form, ``assert expression``, is equivalent to :: + + if __debug__: + if not expression: raise AssertionError + +The extended form, ``assert expression1, expression2``, is equivalent to :: + + if __debug__: + if not expression1: raise AssertionError, expression2 + +.. index:: + single: __debug__ + exception: AssertionError + +These equivalences assume that ``__debug__`` and :exc:`AssertionError` refer to +the built-in variables with those names. In the current implementation, the +built-in variable ``__debug__`` is ``True`` under normal circumstances, +``False`` when optimization is requested (command line option -O). The current +code generator emits no code for an assert statement when optimization is +requested at compile time. Note that it is unnecessary to include the source +code for the expression that failed in the error message; it will be displayed +as part of the stack trace. + +Assignments to ``__debug__`` are illegal. The value for the built-in variable +is determined when the interpreter starts. + + .. _pass: The :keyword:`pass` statement Modified: python/branches/py3k-importlib/Doc/tutorial/inputoutput.rst ============================================================================== --- python/branches/py3k-importlib/Doc/tutorial/inputoutput.rst (original) +++ python/branches/py3k-importlib/Doc/tutorial/inputoutput.rst Fri Sep 21 03:17:09 2007 @@ -252,7 +252,7 @@ >>> f.readlines() ['This is the first line of the file.\n', 'Second line of the file\n'] -An alternate approach to reading lines is to loop over the file object. This is +An alternative approach to reading lines is to loop over the file object. This is memory efficient, fast, and leads to simpler code:: >>> for line in f: Modified: python/branches/py3k-importlib/Doc/whatsnew/2.5.rst ============================================================================== --- python/branches/py3k-importlib/Doc/whatsnew/2.5.rst (original) +++ python/branches/py3k-importlib/Doc/whatsnew/2.5.rst Fri Sep 21 03:17:09 2007 @@ -637,7 +637,7 @@ print v.sqrt() -.. _context-managers: +.. _new-25-context-managers: Writing Context Managers ------------------------ Modified: python/branches/py3k-importlib/Doc/whatsnew/2.6.rst ============================================================================== --- python/branches/py3k-importlib/Doc/whatsnew/2.6.rst (original) +++ python/branches/py3k-importlib/Doc/whatsnew/2.6.rst Fri Sep 21 03:17:09 2007 @@ -2,6 +2,9 @@ What's New in Python 2.6 **************************** +.. % XXX mention switch to reST for documentation +.. % XXX mention switch to Roundup for bug tracking + :Author: A.M. Kuchling :Release: |release| :Date: |today| @@ -67,12 +70,367 @@ .. % sets module deprecated .. % ====================================================================== +Python 3.0 +================ + +.. % XXX add general comment about Python 3.0 features in 2.6 + +.. % XXX mention -3 switch + +A new command-line switch, :option:`-3`, enables warnings +about features that will be removed in Python 3.0. You can run code +with this switch to see how much work will be necessary to port +code to 3.0. + +.. seealso:: + + The 3xxx series of PEPs, which describes the development process for + Python 3.0 and various features that have been accepted, rejected, + or are still under consideration. + +PEP 343: The 'with' statement +============================= + +The previous version, Python 2.5, added the ':keyword:`with`' +statement an optional feature, to be enabled by a ``from __future__ +import generators`` directive. In 2.6 the statement no longer need to +be specially enabled; this means that :keyword:`with` is now always a +keyword. The rest of this section is a copy of the corresponding +section from "What's New in Python 2.5" document; if you read +it back when Python 2.5 came out, you can skip the rest of this +section. + +The ':keyword:`with`' statement clarifies code that previously would use +``try...finally`` blocks to ensure that clean-up code is executed. In this +section, I'll discuss the statement as it will commonly be used. In the next +section, I'll examine the implementation details and show how to write objects +for use with this statement. + +The ':keyword:`with`' statement is a new control-flow structure whose basic +structure is:: + + with expression [as variable]: + with-block + +The expression is evaluated, and it should result in an object that supports the +context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__` +methods. + +The object's :meth:`__enter__` is called before *with-block* is executed and +therefore can run set-up code. It also may return a value that is bound to the +name *variable*, if given. (Note carefully that *variable* is *not* assigned +the result of *expression*.) + +After execution of the *with-block* is finished, the object's :meth:`__exit__` +method is called, even if the block raised an exception, and can therefore run +clean-up code. + +Some standard Python objects now support the context management protocol and can +be used with the ':keyword:`with`' statement. File objects are one example:: + + with open('/etc/passwd', 'r') as f: + for line in f: + print line + ... more processing code ... + +After this statement has executed, the file object in *f* will have been +automatically closed, even if the :keyword:`for` loop raised an exception part- +way through the block. + +.. note:: + + In this case, *f* is the same object created by :func:`open`, because + :meth:`file.__enter__` returns *self*. + +The :mod:`threading` module's locks and condition variables also support the +':keyword:`with`' statement:: + + lock = threading.Lock() + with lock: + # Critical section of code + ... + +The lock is acquired before the block is executed and always released once the +block is complete. + +The new :func:`localcontext` function in the :mod:`decimal` module makes it easy +to save and restore the current decimal context, which encapsulates the desired +precision and rounding characteristics for computations:: + + from decimal import Decimal, Context, localcontext + + # Displays with default precision of 28 digits + v = Decimal('578') + print v.sqrt() + + with localcontext(Context(prec=16)): + # All code in this block uses a precision of 16 digits. + # The original context is restored on exiting the block. + print v.sqrt() + + +.. _new-26-context-managers: + +Writing Context Managers +------------------------ + +Under the hood, the ':keyword:`with`' statement is fairly complicated. Most +people will only use ':keyword:`with`' in company with existing objects and +don't need to know these details, so you can skip the rest of this section if +you like. Authors of new objects will need to understand the details of the +underlying implementation and should keep reading. + +A high-level explanation of the context management protocol is: + +* The expression is evaluated and should result in an object called a "context + manager". The context manager must have :meth:`__enter__` and :meth:`__exit__` + methods. + +* The context manager's :meth:`__enter__` method is called. The value returned + is assigned to *VAR*. If no ``'as VAR'`` clause is present, the value is simply + discarded. + +* The code in *BLOCK* is executed. + +* If *BLOCK* raises an exception, the :meth:`__exit__(type, value, traceback)` + is called with the exception details, the same values returned by + :func:`sys.exc_info`. The method's return value controls whether the exception + is re-raised: any false value re-raises the exception, and ``True`` will result + in suppressing it. You'll only rarely want to suppress the exception, because + if you do the author of the code containing the ':keyword:`with`' statement will + never realize anything went wrong. + +* If *BLOCK* didn't raise an exception, the :meth:`__exit__` method is still + called, but *type*, *value*, and *traceback* are all ``None``. + +Let's think through an example. I won't present detailed code but will only +sketch the methods necessary for a database that supports transactions. + +(For people unfamiliar with database terminology: a set of changes to the +database are grouped into a transaction. Transactions can be either committed, +meaning that all the changes are written into the database, or rolled back, +meaning that the changes are all discarded and the database is unchanged. See +any database textbook for more information.) + +Let's assume there's an object representing a database connection. Our goal will +be to let the user write code like this:: + + db_connection = DatabaseConnection() + with db_connection as cursor: + cursor.execute('insert into ...') + cursor.execute('delete from ...') + # ... more operations ... + +The transaction should be committed if the code in the block runs flawlessly or +rolled back if there's an exception. Here's the basic interface for +:class:`DatabaseConnection` that I'll assume:: + + class DatabaseConnection: + # Database interface + def cursor (self): + "Returns a cursor object and starts a new transaction" + def commit (self): + "Commits current transaction" + def rollback (self): + "Rolls back current transaction" + +The :meth:`__enter__` method is pretty easy, having only to start a new +transaction. For this application the resulting cursor object would be a useful +result, so the method will return it. The user can then add ``as cursor`` to +their ':keyword:`with`' statement to bind the cursor to a variable name. :: + + class DatabaseConnection: + ... + def __enter__ (self): + # Code to start a new transaction + cursor = self.cursor() + return cursor + +The :meth:`__exit__` method is the most complicated because it's where most of +the work has to be done. The method has to check if an exception occurred. If +there was no exception, the transaction is committed. The transaction is rolled +back if there was an exception. + +In the code below, execution will just fall off the end of the function, +returning the default value of ``None``. ``None`` is false, so the exception +will be re-raised automatically. If you wished, you could be more explicit and +add a :keyword:`return` statement at the marked location. :: + + class DatabaseConnection: + ... + def __exit__ (self, type, value, tb): + if tb is None: + # No exception, so commit + self.commit() + else: + # Exception occurred, so rollback. + self.rollback() + # return False + + +.. _module-contextlib: + +The contextlib module +--------------------- + +The new :mod:`contextlib` module provides some functions and a decorator that +are useful for writing objects for use with the ':keyword:`with`' statement. + +The decorator is called :func:`contextmanager`, and lets you write a single +generator function instead of defining a new class. The generator should yield +exactly one value. The code up to the :keyword:`yield` will be executed as the +:meth:`__enter__` method, and the value yielded will be the method's return +value that will get bound to the variable in the ':keyword:`with`' statement's +:keyword:`as` clause, if any. The code after the :keyword:`yield` will be +executed in the :meth:`__exit__` method. Any exception raised in the block will +be raised by the :keyword:`yield` statement. + +Our database example from the previous section could be written using this +decorator as:: + + from contextlib import contextmanager + + @contextmanager + def db_transaction (connection): + cursor = connection.cursor() + try: + yield cursor + except: + connection.rollback() + raise + else: + connection.commit() + + db = DatabaseConnection() + with db_transaction(db) as cursor: + ... + +The :mod:`contextlib` module also has a :func:`nested(mgr1, mgr2, ...)` function +that combines a number of context managers so you don't need to write nested +':keyword:`with`' statements. In this example, the single ':keyword:`with`' +statement both starts a database transaction and acquires a thread lock:: + + lock = threading.Lock() + with nested (db_transaction(db), lock) as (cursor, locked): + ... + +Finally, the :func:`closing(object)` function returns *object* so that it can be +bound to a variable, and calls ``object.close`` at the end of the block. :: + + import urllib, sys + from contextlib import closing + + with closing(urllib.urlopen('http://www.yahoo.com')) as f: + for line in f: + sys.stdout.write(line) + + +.. seealso:: + + :pep:`343` - The "with" statement + PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland, + Guido van Rossum, and Neal Norwitz. The PEP shows the code generated for a + ':keyword:`with`' statement, which can be helpful in learning how the statement + works. + + The documentation for the :mod:`contextlib` module. + +.. % ====================================================================== + +.. _pep-3110: + +PEP 3110: Exception-Handling Changes +===================================================== + +One error that Python programmers occasionally make +is the following:: + + try: + ... + except TypeError, ValueError: + ... + +The author is probably trying to catch both +:exc:`TypeError` and :exc:`ValueError` exceptions, but this code +actually does something different: it will catch +:exc:`TypeError` and bind the resulting exception object +to the local name ``"ValueError"``. The correct code +would have specified a tuple:: + + try: + ... + except (TypeError, ValueError): + ... + +This error is possible because the use of the comma here is ambiguous: +does it indicate two different nodes in the parse tree, or a single +node that's a tuple. + +Python 3.0 changes the syntax to make this unambiguous by replacing +the comma with the word "as". To catch an exception and store the +exception object in the variable ``exc``, you must write:: + + try: + ... + except TypeError as exc: + ... + +Python 3.0 will only support the use of "as", and therefore interprets +the first example as catching two different exceptions. Python 2.6 +supports both the comma and "as", so existing code will continue to +work. + +.. seealso:: + + :pep:`3110` - Catching Exceptions in Python 3000 + PEP written and implemented by Collin Winter. + +.. % ====================================================================== + +.. _pep-3119: + +PEP 3119: Abstract Base Classes +===================================================== + +XXX + +.. seealso:: + + :pep:`3119` - Introducing Abstract Base Classes + PEP written by Guido van Rossum and Talin. + Implemented by XXX. + Backported to 2.6 by Benjamin Aranguren (with Alex Martelli). Other Language Changes ====================== Here are all of the changes that Python 2.6 makes to the core Python language. +* Changes to the :class:`Exception` interface + as dictated by :pep:`352` continue to be made. For 2.6, + the :attr:`message` attribute is being deprecated in favor of the + :attr:`args` attribute. + +* When calling a function using the ``**`` syntax to provide keyword + arguments, you are no longer required to use a Python dictionary; + any mapping will now work:: + + >>> def f(**kw): + ... print sorted(kw) + ... + >>> ud=UserDict.UserDict() + >>> ud['a'] = 1 + >>> ud['b'] = 'string' + >>> f(**ud) + ['a', 'b'] + + .. % Patch 1686487 + +* The :func:`compile` built-in function now accepts keyword arguments + as well as positional parameters. (Contributed by XXX.) + + .. % Patch 1444529 + * The :func:`complex` constructor now accepts strings containing parenthesized complex numbers, letting ``complex(repr(cmplx))`` will now round-trip values. For example, ``complex('(3+4j)')`` @@ -87,6 +445,15 @@ .. % Patch 1193128 +* The built-in :func:`dir` function now checks for a :meth:`__dir__` + method on the objects it receives. This method must return a list + of strings containing the names of valid attributes for the object, + and lets the object control the value that :func:`dir` produces. + Objects that have :meth:`__getattr__` or :meth:`__getattribute__` + methods. + + .. % Patch 1591665 + * An obscure change: when you use the the :func:`locals` function inside a :keyword:`class` statement, the resulting dictionary no longer returns free variables. (Free variables, in this case, are variables referred to in the @@ -160,6 +527,11 @@ (Contributed by Raymond Hettinger.) +* An optional ``timeout`` parameter was added to the + :class:`httplib.HTTPConnection` and :class:`HTTPSConnection` + class constructors, specifying a timeout measured in seconds. + (Added by Facundo Batista.) + * A new function in the :mod:`itertools` module: ``izip_longest(iter1, iter2, ...[, fillvalue])`` makes tuples from each of the elements; if some of the iterables are shorter than others, the missing values are set to *fillvalue*. @@ -176,6 +548,15 @@ .. % Patch #1490190 +* The :func:`os.walk` function now has a "followlinks" parameter. If + set to True, it will follow symlinks pointing to directories and + visit the directory's contents. For backward compatibility, the + parameter's default value is false. Note that the function can fall + into an infinite recursion if there's a symlink that points to a + parent directory. + + .. % Patch 1273829 + * In the :mod:`os.path` module, the :func:`splitext` function has been changed to not split on leading period characters. This produces better results when operating on Unix's dot-files. @@ -191,6 +572,12 @@ .. % Patch 1339796 + On Windows, :func:`os.path.expandvars` will now expand environment variables + in the form "%var%", and "~user" will be expanded into the + user's home directory path. (Contributed by XXX.) + + .. % Patch 957650 + * New functions in the :mod:`posix` module: :func:`chflags` and :func:`lchflags` are wrappers for the corresponding system calls (where they're available). Constants for the flag values are defined in the :mod:`stat` module; some @@ -217,13 +604,78 @@ .. % Patch #957003 +* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) and + POSIX.1-1988 (ustar) format tarfiles, in addition to the GNU tar + format that was already supported. The default format + is GNU tar; specify the ``format`` parameter to open a file + using a different format:: + + tar = tarfile.open("output.tar", "w", format=tarfile.PAX_FORMAT) + + The new ``errors`` parameter lets you specify an error handling + scheme for character conversions: the three standard ways Python can + handle errors ``'strict'``, ``'ignore'``, ``'replace'`` , or the + special value ``'utf-8'``, which replaces bad characters with their + UTF-8 representation. Character conversions occur because the PAX + format supports Unicode filenames, defaulting to UTF-8 encoding. + + The :meth:`TarFile.add` method now accepts a ``exclude`` argument that's + a function that can be used to exclude certain filenames from + an archive. + The function must take a filename and return true if the file + should be excluded or false if it should be archived. + The function is applied to both the name initially passed to :meth:`add` + and to the names of files in recursively-added directories. + + (All changes contributed by Lars Gust?bel). + * An optional ``timeout`` parameter was added to the :class:`telnetlib.Telnet` class constructor, specifying a timeout measured in seconds. (Added by Facundo Batista.) -* The :mod:`test.test_support` module now contains a :func:`EnvironmentVarGuard` +* The :class:`tempfile.NamedTemporaryFile` class usually deletes + the temporary file it created when the file is closed. This + behaviour can now be changed by passing ``delete=False`` to the + constructor. (Contributed by Damien Miller.) + + .. % Patch #1537850 + +* The :mod:`test.test_support` module now contains a + :func:`EnvironmentVarGuard` context manager that supports temporarily changing environment variables and - automatically restores them to their old values. (Contributed by Brett Cannon.) + automatically restores them to their old values. + + Another context manager, :class:`TransientResource`, can surround calls + to resources that may or may not be available; it will catch and + ignore a specified list of exceptions. For example, + a network test may ignore certain failures when connecting to an + external web site:: + + with test_support.TransientResource(IOError, errno=errno.ETIMEDOUT): + f = urllib.urlopen('https://sf.net') + ... + + (Contributed by Brett Cannon.) + +* The :mod:`textwrap` module can now preserve existing whitespace + at the beginnings and ends of the newly-created lines + by specifying ``drop_whitespace=False`` + as an argument:: + + >>> S = """This sentence has a bunch of extra whitespace.""" + >>> print textwrap.fill(S, width=15) + This sentence + has a bunch + of extra + whitespace. + >>> print textwrap.fill(S, drop_whitespace=False, width=15) + This sentence + has a bunch + of extra + whitespace. + >>> + + .. % Patch #1581073 * The :mod:`timeit` module now accepts callables as well as strings for the statement being timed and for the setup code. @@ -235,6 +687,20 @@ .. % Patch #1533909 +* An optional ``timeout`` parameter was added to the + :func:`urllib.urlopen` function and the + :class:`urllib.ftpwrapper` class constructor, as well as the + :func:`urllib2.urlopen` function. The parameter specifies a timeout + measured in seconds. For example:: + + >>> u = urllib2.urlopen("http://slow.example.com", timeout=3) + Traceback (most recent call last): + ... + urllib2.URLError: + >>> + + (Added by Facundo Batista.) + .. % ====================================================================== .. % whole new modules get described in \subsections here Modified: python/branches/py3k-importlib/Lib/cgi.py ============================================================================== --- python/branches/py3k-importlib/Lib/cgi.py (original) +++ python/branches/py3k-importlib/Lib/cgi.py Fri Sep 21 03:17:09 2007 @@ -604,23 +604,21 @@ """Dictionary style keys() method.""" if self.list is None: raise TypeError("not indexable") - keys = [] - for item in self.list: - if item.name not in keys: keys.append(item.name) - return keys + return list(set(item.name for item in self.list)) def __contains__(self, key): """Dictionary style __contains__ method.""" if self.list is None: raise TypeError("not indexable") - for item in self.list: - if item.name == key: return True - return False + return any(item.name == key for item in self.list) def __len__(self): """Dictionary style len(x) support.""" return len(self.keys()) + def __nonzero__(self): + return bool(self.list) + def read_urlencoded(self): """Internal: read data in query string format.""" qs = self.fp.read(self.length) Modified: python/branches/py3k-importlib/Lib/collections.py ============================================================================== --- python/branches/py3k-importlib/Lib/collections.py (original) +++ python/branches/py3k-importlib/Lib/collections.py Fri Sep 21 03:17:09 2007 @@ -11,40 +11,50 @@ __all__ += _abcoll.__all__ -def NamedTuple(typename, s): +def NamedTuple(typename, s, verbose=False): """Returns a new subclass of tuple with named fields. >>> Point = NamedTuple('Point', 'x y') - >>> Point.__doc__ # docstring for the new class + >>> Point.__doc__ # docstring for the new class 'Point(x, y)' - >>> p = Point(11, y=22) # instantiate with positional args or keywords - >>> p[0] + p[1] # works just like the tuple (11, 22) + >>> p = Point(11, y=22) # instantiate with positional args or keywords + >>> p[0] + p[1] # works just like the tuple (11, 22) 33 - >>> x, y = p # unpacks just like a tuple + >>> x, y = p # unpacks just like a tuple >>> x, y (11, 22) - >>> p.x + p.y # fields also accessable by name + >>> p.x + p.y # fields also accessable by name 33 - >>> p # readable __repr__ with name=value style + >>> p # readable __repr__ with name=value style Point(x=11, y=22) + >>> p.__replace__('x', 100) # __replace__() is like str.replace() but targets a named field + Point(x=100, y=22) + >>> d = dict(zip(p.__fields__, p)) # use __fields__ to make a dictionary + >>> d['x'] + 11 """ - field_names = s.split() - if not ''.join([typename] + field_names).replace('_', '').isalnum(): + field_names = tuple(s.replace(',', ' ').split()) # names separated by spaces and/or commas + if not ''.join((typename,) + field_names).replace('_', '').isalnum(): raise ValueError('Type names and field names can only contain alphanumeric characters and underscores') - argtxt = ', '.join(field_names) + argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes reprtxt = ', '.join('%s=%%r' % name for name in field_names) template = '''class %(typename)s(tuple): '%(typename)s(%(argtxt)s)' __slots__ = () + __fields__ = %(field_names)r def __new__(cls, %(argtxt)s): - return tuple.__new__(cls, (%(argtxt)s,)) + return tuple.__new__(cls, (%(argtxt)s)) def __repr__(self): return '%(typename)s(%(reprtxt)s)' %% self - ''' % locals() + def __replace__(self, field, value): + 'Return a new %(typename)s object replacing one field with a new value' + return %(typename)s(**dict(list(zip(%(field_names)r, self)) + [(field, value)])) \n''' % locals() for i, name in enumerate(field_names): - template += '\n %s = property(itemgetter(%d))\n' % (name, i) + template += ' %s = property(itemgetter(%d))\n' % (name, i) + if verbose: + print(template) m = dict(itemgetter=_itemgetter) exec(template, m) result = m[typename] @@ -57,9 +67,9 @@ if __name__ == '__main__': - # verify that instances are pickable + # verify that instances can be pickled from pickle import loads, dumps - Point = NamedTuple('Point', 'x y') + Point = NamedTuple('Point', 'x, y', True) p = Point(x=10, y=20) assert p == loads(dumps(p)) Modified: python/branches/py3k-importlib/Lib/ctypes/test/test_cfuncs.py ============================================================================== --- python/branches/py3k-importlib/Lib/ctypes/test/test_cfuncs.py (original) +++ python/branches/py3k-importlib/Lib/ctypes/test/test_cfuncs.py Fri Sep 21 03:17:09 2007 @@ -158,17 +158,17 @@ self.failUnlessEqual(self._dll.tf_bd(0, 42.), 14.) self.failUnlessEqual(self.S(), 42) - def test_longdouble(self): - self._dll.tf_D.restype = c_longdouble - self._dll.tf_D.argtypes = (c_longdouble,) - self.failUnlessEqual(self._dll.tf_D(42.), 14.) - self.failUnlessEqual(self.S(), 42) - - def test_longdouble_plus(self): - self._dll.tf_bD.restype = c_longdouble - self._dll.tf_bD.argtypes = (c_byte, c_longdouble) - self.failUnlessEqual(self._dll.tf_bD(0, 42.), 14.) - self.failUnlessEqual(self.S(), 42) +## def test_longdouble(self): +## self._dll.tf_D.restype = c_longdouble +## self._dll.tf_D.argtypes = (c_longdouble,) +## self.failUnlessEqual(self._dll.tf_D(42.), 14.) +## self.failUnlessEqual(self.S(), 42) + +## def test_longdouble_plus(self): +## self._dll.tf_bD.restype = c_longdouble +## self._dll.tf_bD.argtypes = (c_byte, c_longdouble) +## self.failUnlessEqual(self._dll.tf_bD(0, 42.), 14.) +## self.failUnlessEqual(self.S(), 42) def test_callwithresult(self): def process_result(result): Modified: python/branches/py3k-importlib/Lib/ctypes/test/test_functions.py ============================================================================== --- python/branches/py3k-importlib/Lib/ctypes/test/test_functions.py (original) +++ python/branches/py3k-importlib/Lib/ctypes/test/test_functions.py Fri Sep 21 03:17:09 2007 @@ -143,17 +143,17 @@ self.failUnlessEqual(result, -21) self.failUnlessEqual(type(result), float) - def test_longdoubleresult(self): - f = dll._testfunc_D_bhilfD - f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_longdouble] - f.restype = c_longdouble - result = f(1, 2, 3, 4, 5.0, 6.0) - self.failUnlessEqual(result, 21) - self.failUnlessEqual(type(result), float) - - result = f(-1, -2, -3, -4, -5.0, -6.0) - self.failUnlessEqual(result, -21) - self.failUnlessEqual(type(result), float) +## def test_longdoubleresult(self): +## f = dll._testfunc_D_bhilfD +## f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_longdouble] +## f.restype = c_longdouble +## result = f(1, 2, 3, 4, 5.0, 6.0) +## self.failUnlessEqual(result, 21) +## self.failUnlessEqual(type(result), float) + +## result = f(-1, -2, -3, -4, -5.0, -6.0) +## self.failUnlessEqual(result, -21) +## self.failUnlessEqual(type(result), float) def test_longlongresult(self): try: Modified: python/branches/py3k-importlib/Lib/ctypes/util.py ============================================================================== --- python/branches/py3k-importlib/Lib/ctypes/util.py (original) +++ python/branches/py3k-importlib/Lib/ctypes/util.py Fri Sep 21 03:17:09 2007 @@ -63,15 +63,27 @@ return None return res.group(0) - def _get_soname(f): - # assuming GNU binutils / ELF - if not f: - return None - cmd = "objdump -p -j .dynamic 2>/dev/null " + f - res = re.search(r'\sSONAME\s+([^\s]+)', os.popen(cmd).read()) - if not res: - return None - return res.group(1) + + if sys.platform == "sunos5": + # use /usr/ccs/bin/dump on solaris + def _get_soname(f): + if not f: + return None + cmd = "/usr/ccs/bin/dump -Lpv 2>/dev/null " + f + res = re.search(r'\[.*\]\sSONAME\s+([^\s]+)', os.popen(cmd).read()) + if not res: + return None + return res.group(1) + else: + def _get_soname(f): + # assuming GNU binutils / ELF + if not f: + return None + cmd = "objdump -p -j .dynamic 2>/dev/null " + f + res = re.search(r'\sSONAME\s+([^\s]+)', os.popen(cmd).read()) + if not res: + return None + return res.group(1) if (sys.platform.startswith("freebsd") or sys.platform.startswith("openbsd") Modified: python/branches/py3k-importlib/Lib/decimal.py ============================================================================== --- python/branches/py3k-importlib/Lib/decimal.py (original) +++ python/branches/py3k-importlib/Lib/decimal.py Fri Sep 21 03:17:09 2007 @@ -128,7 +128,7 @@ # Constants for use in setting up contexts 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING', - 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', + 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP', # Functions for manipulating contexts 'setcontext', 'getcontext', 'localcontext' @@ -144,6 +144,7 @@ ROUND_FLOOR = 'ROUND_FLOOR' ROUND_UP = 'ROUND_UP' ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' +ROUND_05UP = 'ROUND_05UP' # Rounding decision (not part of the public API) NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY @@ -204,13 +205,22 @@ x ** (non-integer) x ** (+-)INF An operand is invalid + + The result of the operation after these is a quiet positive NaN, + except when the cause is a signaling NaN, in which case the result is + also a quiet NaN, but with the original sign, and an optional + diagnostic information. """ def handle(self, context, *args): if args: if args[0] == 1: # sNaN, must drop 's' but keep diagnostics - return Decimal( (args[1]._sign, args[1]._int, 'n') ) + ans = Decimal((args[1]._sign, args[1]._int, 'n')) + return ans._fix_nan(context) + elif args[0] == 2: + return Decimal( (args[1], args[2], 'n') ) return NaN + class ConversionSyntax(InvalidOperation): """Trying to convert badly formed string. @@ -218,9 +228,8 @@ converted to a number and it does not conform to the numeric string syntax. The result is [0,qNaN]. """ - def handle(self, context, *args): - return (0, (0,), 'n') # Passed to something which uses a tuple. + return NaN class DivisionByZero(DecimalException, ZeroDivisionError): """Division by 0. @@ -235,9 +244,7 @@ -0, for power. """ - def handle(self, context, sign, double = None, *args): - if double is not None: - return (Infsign[sign],)*2 + def handle(self, context, sign, *args): return Infsign[sign] class DivisionImpossible(InvalidOperation): @@ -249,7 +256,7 @@ """ def handle(self, context, *args): - return (NaN, NaN) + return NaN class DivisionUndefined(InvalidOperation, ZeroDivisionError): """Undefined result of division. @@ -259,9 +266,7 @@ the dividend is also zero. The result is [0,qNaN]. """ - def handle(self, context, tup=None, *args): - if tup is not None: - return (NaN, NaN) # for 0 %0, 0 // 0 + def handle(self, context, *args): return NaN class Inexact(DecimalException): @@ -340,7 +345,7 @@ def handle(self, context, sign, *args): if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, - ROUND_HALF_DOWN, ROUND_UP): + ROUND_HALF_DOWN, ROUND_UP): return Infsign[sign] if sign == 0: if context.rounding == ROUND_CEILING: @@ -520,7 +525,7 @@ Decimal("3.14") >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) Decimal("3.14") - >>> Decimal(314) # int or long + >>> Decimal(314) # int Decimal("314") >>> Decimal(Decimal(314)) # another decimal instance Decimal("314") @@ -545,7 +550,7 @@ return self # From an integer - if isinstance(value, (int,int)): + if isinstance(value, int): if value >= 0: self._sign = 0 else: @@ -561,8 +566,8 @@ if value[0] not in (0,1): raise ValueError('Invalid sign') for digit in value[1]: - if not isinstance(digit, (int,int)) or digit < 0: - raise ValueError("The second value in the tuple must be" + if not isinstance(digit, int) or digit < 0: + raise ValueError("The second value in the tuple must be " "composed of non negative integer elements.") self._sign = value[0] self._int = tuple(value[1]) @@ -596,10 +601,6 @@ if _isnan(value): sig, sign, diag = _isnan(value) self._is_special = True - if len(diag) > context.prec: # Diagnostic info too long - self._sign, self._int, self._exp = \ - context._raise_error(ConversionSyntax) - return self if sig == 1: self._exp = 'n' # qNaN else: # sig == 2 @@ -611,9 +612,8 @@ self._sign, self._int, self._exp = _string2exact(value) except ValueError: self._is_special = True - self._sign, self._int, self._exp = \ - context._raise_error(ConversionSyntax, - "Invalid literal for Decimal: %r" % value) + return context._raise_error(ConversionSyntax, + "Invalid literal for Decimal: %r" % value) return self raise TypeError("Cannot convert %r to Decimal" % value) @@ -622,7 +622,7 @@ """Returns whether the number is not actually one. 0 if a number - 1 if NaN + 1 if NaN (it could be a normal quiet NaN or a phantom one) 2 if sNaN """ if self._is_special: @@ -646,7 +646,7 @@ return 1 return 0 - def _check_nans(self, other = None, context=None): + def _check_nans(self, other=None, context=None): """Returns whether the number is not actually one. if self, other are sNaN, signal @@ -673,9 +673,9 @@ return context._raise_error(InvalidOperation, 'sNaN', 1, other) if self_is_nan: - return self + return self._fix_nan(context) - return other + return other._fix_nan(context) return 0 def __bool__(self): @@ -688,21 +688,28 @@ return True return sum(self._int) != 0 - def __cmp__(self, other, context=None): + def __cmp__(self, other): other = _convert_other(other) if other is NotImplemented: - return other + # Never return NotImplemented + return 1 if self._is_special or other._is_special: - ans = self._check_nans(other, context) - if ans: + # check for nans, without raising on a signaling nan + if self._isnan() or other._isnan(): return 1 # Comparison involving NaN's always reports self > other # INF = INF return cmp(self._isinfinity(), other._isinfinity()) - if not self and not other: - return 0 # If both 0, sign comparison isn't certain. + # check for zeros; note that cmp(0, -0) should return 0 + if not self: + if not other: + return 0 + else: + return -((-1)**other._sign) + if not other: + return (-1)**self._sign # If different signs, neg one is less if other._sign < self._sign: @@ -712,35 +719,15 @@ self_adjusted = self.adjusted() other_adjusted = other.adjusted() - if self_adjusted == other_adjusted and \ - self._int + (0,)*(self._exp - other._exp) == \ - other._int + (0,)*(other._exp - self._exp): - return 0 # equal, except in precision. ([0]*(-x) = []) - elif self_adjusted > other_adjusted and self._int[0] != 0: + if self_adjusted == other_adjusted: + self_padded = self._int + (0,)*(self._exp - other._exp) + other_padded = other._int + (0,)*(other._exp - self._exp) + return cmp(self_padded, other_padded) * (-1)**self._sign + elif self_adjusted > other_adjusted: return (-1)**self._sign - elif self_adjusted < other_adjusted and other._int[0] != 0: + else: # self_adjusted < other_adjusted return -((-1)**self._sign) - # Need to round, so make sure we have a valid context - if context is None: - context = getcontext() - - context = context._shallow_copy() - rounding = context._set_rounding(ROUND_UP) # round away from 0 - - flags = context._ignore_all_flags() - res = self.__sub__(other, context=context) - - context._regard_flags(*flags) - - context.rounding = rounding - - if not res: - return 0 - elif res._sign: - return -1 - return 1 - def __eq__(self, other): if not isinstance(other, (Decimal, int)): return NotImplemented @@ -780,9 +767,7 @@ NaN => one is NaN Like __cmp__, but returns Decimal instances. """ - other = _convert_other(other) - if other is NotImplemented: - return other + other = _convert_other(other, raiseit=True) # Compare(NaN, NaN) = NaN if (self._is_special or other and other._is_special): @@ -790,7 +775,7 @@ if ans: return ans - return Decimal(self.__cmp__(other, context)) + return Decimal(self.__cmp__(other)) def __hash__(self): """x.__hash__() <==> hash(x)""" @@ -801,10 +786,17 @@ if self._isnan(): raise TypeError('Cannot hash a NaN value.') return hash(str(self)) - i = int(self) - if self == Decimal(i): - return hash(i) - assert self.__bool__() # '-0' handled by integer case + if not self: + return 0 + if self._isinteger(): + op = _WorkRep(self.to_integral_value()) + # to make computation feasible for Decimals with large + # exponent, we use the fact that hash(n) == hash(m) for + # any two nonzero integers n and m such that (i) n and m + # have the same sign, and (ii) n is congruent to m modulo + # 2**64-1. So we can replace hash((-1)**s*c*10**e) with + # hash((-1)**s*c*pow(10, e, 2**64-1). + return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1)) return hash(str(self.normalize())) def as_tuple(self): @@ -819,7 +811,7 @@ # Invariant: eval(repr(d)) == d return 'Decimal("%s")' % str(self) - def __str__(self, eng = 0, context=None): + def __str__(self, eng=False, context=None): """Return string representation of the number in scientific notation. Captures all of the information in the underlying representation. @@ -909,7 +901,7 @@ Same rules for when in exponential and when as a value as in __str__. """ - return self.__str__(eng=1, context=context) + return self.__str__(eng=True, context=context) def __neg__(self, context=None): """Returns a copy with the sign switched. @@ -923,17 +915,15 @@ if not self: # -Decimal('0') is Decimal('0'), not Decimal('-0') - sign = 0 - elif self._sign: - sign = 0 + ans = self.copy_sign(Dec_0) else: - sign = 1 + ans = self.copy_negate() if context is None: context = getcontext() if context._rounding_decision == ALWAYS_ROUND: - return Decimal((sign, self._int, self._exp))._fix(context) - return Decimal( (sign, self._int, self._exp)) + return ans._fix(context) + return ans def __pos__(self, context=None): """Returns a copy, unless it is a sNaN. @@ -945,19 +935,16 @@ if ans: return ans - sign = self._sign if not self: # + (-0) = 0 - sign = 0 + ans = self.copy_sign(Dec_0) + else: + ans = Decimal(self) if context is None: context = getcontext() - if context._rounding_decision == ALWAYS_ROUND: - ans = self._fix(context) - else: - ans = Decimal(self) - ans._sign = sign + return ans._fix(context) return ans def __abs__(self, round=1, context=None): @@ -1020,16 +1007,19 @@ sign = min(self._sign, other._sign) if negativezero: sign = 1 - return Decimal( (sign, (0,), exp)) + ans = Decimal( (sign, (0,), exp)) + if shouldround: + ans = ans._fix(context) + return ans if not self: exp = max(exp, other._exp - context.prec-1) - ans = other._rescale(exp, watchexp=0, context=context) + ans = other._rescale(exp, context.rounding) if shouldround: ans = ans._fix(context) return ans if not other: exp = max(exp, self._exp - context.prec-1) - ans = self._rescale(exp, watchexp=0, context=context) + ans = self._rescale(exp, context.rounding) if shouldround: ans = ans._fix(context) return ans @@ -1042,10 +1032,10 @@ if op1.sign != op2.sign: # Equal and opposite if op1.int == op2.int: - if exp < context.Etiny(): - exp = context.Etiny() - context._raise_error(Clamped) - return Decimal((negativezero, (0,), exp)) + ans = Decimal((negativezero, (0,), exp)) + if shouldround: + ans = ans._fix(context) + return ans if op1.int < op2.int: op1, op2 = op2, op1 # OK, now abs(op1) > abs(op2) @@ -1076,7 +1066,7 @@ __radd__ = __add__ def __sub__(self, other, context=None): - """Return self + (-other)""" + """Return self - other""" other = _convert_other(other) if other is NotImplemented: return other @@ -1086,41 +1076,28 @@ if ans: return ans - # -Decimal(0) = Decimal(0), which we don't want since - # (-0 - 0 = -0 + (-0) = -0, but -0 + 0 = 0.) - # so we change the sign directly to a copy - tmp = Decimal(other) - tmp._sign = 1-tmp._sign - - return self.__add__(tmp, context=context) + # self - other is computed as self + other.copy_negate() + return self.__add__(other.copy_negate(), context=context) def __rsub__(self, other, context=None): - """Return other + (-self)""" + """Return other - self""" other = _convert_other(other) if other is NotImplemented: return other - tmp = Decimal(self) - tmp._sign = 1 - tmp._sign - return other.__add__(tmp, context=context) + return other.__sub__(self, context=context) - def _increment(self, round=1, context=None): + def _increment(self): """Special case of add, adding 1eExponent Since it is common, (rounding, for example) this adds (sign)*one E self._exp to the number more efficiently than add. + Assumes that self is nonspecial. + For example: Decimal('5.624e10')._increment() == Decimal('5.625e10') """ - if self._is_special: - ans = self._check_nans(context=context) - if ans: - return ans - - # Must be infinite, and incrementing makes no difference - return Decimal(self) - L = list(self._int) L[-1] += 1 spot = len(L)-1 @@ -1131,13 +1108,7 @@ break L[spot-1] += 1 spot -= 1 - ans = Decimal((self._sign, L, self._exp)) - - if context is None: - context = getcontext() - if round and context._rounding_decision == ALWAYS_ROUND: - ans = ans._fix(context) - return ans + return Decimal((self._sign, L, self._exp)) def __mul__(self, other, context=None): """Return self * other. @@ -1205,25 +1176,9 @@ def __truediv__(self, other, context=None): """Return self / other.""" - return self._divide(other, context=context) - - def _divide(self, other, divmod = 0, context=None): - """Return a / b, to context.prec precision. - - divmod: - 0 => true division - 1 => (a //b, a%b) - 2 => a //b - 3 => a%b - - Actually, if divmod is 2 or 3 a tuple is returned, but errors for - computing the other value are not raised. - """ other = _convert_other(other) if other is NotImplemented: - if divmod in (0, 1): - return NotImplemented - return (NotImplemented, NotImplemented) + return NotImplemented if context is None: context = getcontext() @@ -1233,144 +1188,84 @@ if self._is_special or other._is_special: ans = self._check_nans(other, context) if ans: - if divmod: - return (ans, ans) return ans if self._isinfinity() and other._isinfinity(): - if divmod: - return (context._raise_error(InvalidOperation, - '(+-)INF // (+-)INF'), - context._raise_error(InvalidOperation, - '(+-)INF % (+-)INF')) return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF') if self._isinfinity(): - if divmod == 1: - return (Infsign[sign], - context._raise_error(InvalidOperation, 'INF % x')) - elif divmod == 2: - return (Infsign[sign], NaN) - elif divmod == 3: - return (Infsign[sign], - context._raise_error(InvalidOperation, 'INF % x')) return Infsign[sign] if other._isinfinity(): - if divmod: - return (Decimal((sign, (0,), 0)), Decimal(self)) context._raise_error(Clamped, 'Division by infinity') return Decimal((sign, (0,), context.Etiny())) # Special cases for zeroes - if not self and not other: - if divmod: - return context._raise_error(DivisionUndefined, '0 / 0', 1) - return context._raise_error(DivisionUndefined, '0 / 0') - - if not self: - if divmod: - otherside = Decimal(self) - otherside._exp = min(self._exp, other._exp) - return (Decimal((sign, (0,), 0)), otherside) - exp = self._exp - other._exp - if exp < context.Etiny(): - exp = context.Etiny() - context._raise_error(Clamped, '0e-x / y') - if exp > context.Emax: - exp = context.Emax - context._raise_error(Clamped, '0e+x / y') - return Decimal( (sign, (0,), exp) ) - if not other: - if divmod: - return context._raise_error(DivisionByZero, 'divmod(x,0)', - sign, 1) + if not self: + return context._raise_error(DivisionUndefined, '0 / 0') return context._raise_error(DivisionByZero, 'x / 0', sign) - # OK, so neither = 0, INF or NaN - shouldround = context._rounding_decision == ALWAYS_ROUND - - # If we're dividing into ints, and self < other, stop. - # self.__abs__(0) does not round. - if divmod and (self.__abs__(0, context) < other.__abs__(0, context)): - - if divmod == 1 or divmod == 3: - exp = min(self._exp, other._exp) - ans2 = self._rescale(exp, context=context, watchexp=0) - if shouldround: - ans2 = ans2._fix(context) - return (Decimal( (sign, (0,), 0) ), - ans2) - - elif divmod == 2: - # Don't round the mod part, if we don't need it. - return (Decimal( (sign, (0,), 0) ), Decimal(self)) - - op1 = _WorkRep(self) - op2 = _WorkRep(other) - op1, op2, adjust = _adjust_coefficients(op1, op2) - res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) ) - if divmod and res.exp > context.prec + 1: - return context._raise_error(DivisionImpossible) - - prec_limit = 10 ** context.prec - while 1: - while op2.int <= op1.int: - res.int += 1 - op1.int -= op2.int - if res.exp == 0 and divmod: - if res.int >= prec_limit and shouldround: - return context._raise_error(DivisionImpossible) - otherside = Decimal(op1) - frozen = context._ignore_all_flags() - - exp = min(self._exp, other._exp) - otherside = otherside._rescale(exp, context=context, watchexp=0) - context._regard_flags(*frozen) - if shouldround: - otherside = otherside._fix(context) - return (Decimal(res), otherside) - - if op1.int == 0 and adjust >= 0 and not divmod: - break - if res.int >= prec_limit and shouldround: - if divmod: - return context._raise_error(DivisionImpossible) - shouldround=1 - # Really, the answer is a bit higher, so adding a one to - # the end will make sure the rounding is right. - if op1.int != 0: - res.int *= 10 - res.int += 1 - res.exp -= 1 - - break - res.int *= 10 - res.exp -= 1 - adjust += 1 - op1.int *= 10 - op1.exp -= 1 - - if res.exp == 0 and divmod and op2.int > op1.int: - # Solves an error in precision. Same as a previous block. - - if res.int >= prec_limit and shouldround: - return context._raise_error(DivisionImpossible) - otherside = Decimal(op1) - frozen = context._ignore_all_flags() + if not self: + exp = self._exp - other._exp + coeff = 0 + else: + # OK, so neither = 0, INF or NaN + shift = len(other._int) - len(self._int) + context.prec + 1 + exp = self._exp - other._exp - shift + op1 = _WorkRep(self) + op2 = _WorkRep(other) + if shift >= 0: + coeff, remainder = divmod(op1.int * 10**shift, op2.int) + else: + coeff, remainder = divmod(op1.int, op2.int * 10**-shift) + if remainder: + # result is not exact; adjust to ensure correct rounding + if coeff % 5 == 0: + coeff += 1 + else: + # result is exact; get as close to ideal exponent as possible + ideal_exp = self._exp - other._exp + while exp < ideal_exp and coeff % 10 == 0: + coeff //= 10 + exp += 1 - exp = min(self._exp, other._exp) - otherside = otherside._rescale(exp, context=context) + ans = Decimal((sign, list(map(int, str(coeff))), exp)) + return ans._fix(context) - context._regard_flags(*frozen) + def _divide(self, other, context): + """Return (self // other, self % other), to context.prec precision. - return (Decimal(res), otherside) + Assumes that neither self nor other is a NaN, that self is not + infinite and that other is nonzero. + """ + sign = self._sign ^ other._sign + if other._isinfinity(): + ideal_exp = self._exp + else: + ideal_exp = min(self._exp, other._exp) - ans = Decimal(res) - if shouldround: - ans = ans._fix(context) - return ans + expdiff = self.adjusted() - other.adjusted() + if not self or other._isinfinity() or expdiff <= -2: + return (Decimal((sign, (0,), 0)), + self._rescale(ideal_exp, context.rounding)) + if expdiff <= context.prec: + op1 = _WorkRep(self) + op2 = _WorkRep(other) + if op1.exp >= op2.exp: + op1.int *= 10**(op1.exp - op2.exp) + else: + op2.int *= 10**(op2.exp - op1.exp) + q, r = divmod(op1.int, op2.int) + if q < 10**context.prec: + return (Decimal((sign, list(map(int, str(q))), 0)), + Decimal((self._sign, list(map(int, str(r))), + ideal_exp))) + + # Here the quotient is too large to be representable + ans = context._raise_error(DivisionImpossible, + 'quotient too large in //, % or divmod') + return ans, ans def __rtruediv__(self, other, context=None): """Swaps self/other and returns __truediv__.""" @@ -1381,9 +1276,40 @@ def __divmod__(self, other, context=None): """ - (self // other, self % other) + Return (self // other, self % other) """ - return self._divide(other, 1, context) + other = _convert_other(other) + if other is NotImplemented: + return other + + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return (ans, ans) + + sign = self._sign ^ other._sign + if self._isinfinity(): + if other._isinfinity(): + ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') + return ans, ans + else: + return (Infsign[sign], + context._raise_error(InvalidOperation, 'INF % x')) + + if not other: + if not self: + ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') + return ans, ans + else: + return (context._raise_error(DivisionByZero, 'x // 0', sign), + context._raise_error(InvalidOperation, 'x % 0')) + + quotient, remainder = self._divide(other, context) + if context._rounding_decision == ALWAYS_ROUND: + remainder = remainder._fix(context) + return quotient, remainder def __rdivmod__(self, other, context=None): """Swaps self/other and returns __divmod__.""" @@ -1400,15 +1326,25 @@ if other is NotImplemented: return other - if self._is_special or other._is_special: - ans = self._check_nans(other, context) - if ans: - return ans + if context is None: + context = getcontext() - if self and not other: - return context._raise_error(InvalidOperation, 'x % 0') + ans = self._check_nans(other, context) + if ans: + return ans + + if self._isinfinity(): + return context._raise_error(InvalidOperation, 'INF % x') + elif not other: + if self: + return context._raise_error(InvalidOperation, 'x % 0') + else: + return context._raise_error(DivisionUndefined, '0 % 0') - return self._divide(other, 3, context)[1] + remainder = self._divide(other, context)[1] + if context._rounding_decision == ALWAYS_ROUND: + remainder = remainder._fix(context) + return remainder def __rmod__(self, other, context=None): """Swaps self/other and returns __mod__.""" @@ -1421,85 +1357,104 @@ """ Remainder nearest to 0- abs(remainder-near) <= other/2 """ - other = _convert_other(other) - if other is NotImplemented: - return other - - if self._is_special or other._is_special: - ans = self._check_nans(other, context) - if ans: - return ans - if self and not other: - return context._raise_error(InvalidOperation, 'x % 0') - if context is None: context = getcontext() - # If DivisionImpossible causes an error, do not leave Rounded/Inexact - # ignored in the calling function. - context = context._shallow_copy() - flags = context._ignore_flags(Rounded, Inexact) - # Keep DivisionImpossible flags - (side, r) = self.__divmod__(other, context=context) - - if r._isnan(): - context._regard_flags(*flags) - return r - - context = context._shallow_copy() - rounding = context._set_rounding_decision(NEVER_ROUND) - if other._sign: - comparison = other.__truediv__(Decimal(-2), context=context) - else: - comparison = other.__truediv__(Decimal(2), context=context) + other = _convert_other(other, raiseit=True) - context._set_rounding_decision(rounding) - context._regard_flags(*flags) + ans = self._check_nans(other, context) + if ans: + return ans - s1, s2 = r._sign, comparison._sign - r._sign, comparison._sign = 0, 0 + # self == +/-infinity -> InvalidOperation + if self._isinfinity(): + return context._raise_error(InvalidOperation, + 'remainder_near(infinity, x)') - if r < comparison: - r._sign, comparison._sign = s1, s2 - # Get flags now - self.__divmod__(other, context=context) - return r._fix(context) - r._sign, comparison._sign = s1, s2 + # other == 0 -> either InvalidOperation or DivisionUndefined + if not other: + if self: + return context._raise_error(InvalidOperation, + 'remainder_near(x, 0)') + else: + return context._raise_error(DivisionUndefined, + 'remainder_near(0, 0)') - rounding = context._set_rounding_decision(NEVER_ROUND) + # other = +/-infinity -> remainder = self + if other._isinfinity(): + ans = Decimal(self) + return ans._fix(context) - (side, r) = self.__divmod__(other, context=context) - context._set_rounding_decision(rounding) - if r._isnan(): - return r + # self = 0 -> remainder = self, with ideal exponent + ideal_exponent = min(self._exp, other._exp) + if not self: + ans = Decimal((self._sign, (0,), ideal_exponent)) + return ans._fix(context) - decrease = not side._iseven() - rounding = context._set_rounding_decision(NEVER_ROUND) - side = side.__abs__(context=context) - context._set_rounding_decision(rounding) + # catch most cases of large or small quotient + expdiff = self.adjusted() - other.adjusted() + if expdiff >= context.prec + 1: + # expdiff >= prec+1 => abs(self/other) > 10**prec + return context._raise_error(DivisionImpossible) + if expdiff <= -2: + # expdiff <= -2 => abs(self/other) < 0.1 + ans = self._rescale(ideal_exponent, context.rounding) + return ans._fix(context) - s1, s2 = r._sign, comparison._sign - r._sign, comparison._sign = 0, 0 - if r > comparison or decrease and r == comparison: - r._sign, comparison._sign = s1, s2 - context.prec += 1 - numbsquant = len(side.__add__(Decimal(1), context=context)._int) - if numbsquant >= context.prec: - context.prec -= 1 - return context._raise_error(DivisionImpossible)[1] - context.prec -= 1 - if self._sign == other._sign: - r = r.__sub__(other, context=context) - else: - r = r.__add__(other, context=context) + # adjust both arguments to have the same exponent, then divide + op1 = _WorkRep(self) + op2 = _WorkRep(other) + if op1.exp >= op2.exp: + op1.int *= 10**(op1.exp - op2.exp) else: - r._sign, comparison._sign = s1, s2 + op2.int *= 10**(op2.exp - op1.exp) + q, r = divmod(op1.int, op2.int) + # remainder is r*10**ideal_exponent; other is +/-op2.int * + # 10**ideal_exponent. Apply correction to ensure that + # abs(remainder) <= abs(other)/2 + if 2*r + (q&1) > op2.int: + r -= op2.int + q += 1 + + if q >= 10**context.prec: + return context._raise_error(DivisionImpossible) - return r._fix(context) + # result has same sign as self unless r is negative + sign = self._sign + if r < 0: + sign = 1-sign + r = -r + + ans = Decimal((sign, list(map(int, str(r))), ideal_exponent)) + return ans._fix(context) def __floordiv__(self, other, context=None): """self // other""" - return self._divide(other, 2, context)[0] + other = _convert_other(other) + if other is NotImplemented: + return other + + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return ans + + if self._isinfinity(): + if other._isinfinity(): + return context._raise_error(InvalidOperation, 'INF // INF') + else: + return Infsign[self._sign ^ other._sign] + + if not other: + if self: + return context._raise_error(DivisionByZero, 'x // 0', + self._sign ^ other._sign) + else: + return context._raise_error(DivisionUndefined, '0 // 0') + + return self._divide(other, context)[0] def __rfloordiv__(self, other, context=None): """Swaps self/other and returns __floordiv__.""" @@ -1519,22 +1474,27 @@ context = getcontext() return context._raise_error(InvalidContext) elif self._isinfinity(): - raise OverflowError("Cannot convert infinity to long") + raise OverflowError("Cannot convert infinity to int") + s = (-1)**self._sign if self._exp >= 0: - s = ''.join(map(str, self._int)) + '0'*self._exp + return s*int(''.join(map(str, self._int)))*10**self._exp else: - s = ''.join(map(str, self._int))[:self._exp] - if s == '': - s = '0' - sign = '-'*self._sign - return int(sign + s) - - def __long__(self): - """Converts to a long. + return s*int(''.join(map(str, self._int))[:self._exp] or '0') - Equivalent to long(int(self)) - """ - return int(self.__int__()) + def _fix_nan(self, context): + """Decapitate the payload of a NaN to fit the context""" + payload = self._int + + # maximum length of payload is precision if _clamp=0, + # precision-1 if _clamp=1. + max_payload_len = context.prec - context._clamp + if len(payload) > max_payload_len: + pos = len(payload)-max_payload_len + while pos < len(payload) and payload[pos] == 0: + pos += 1 + payload = payload[pos:] + return Decimal((self._sign, payload, self._exp)) + return Decimal(self) def _fix(self, context): """Round if it is necessary to keep self within prec precision. @@ -1545,303 +1505,649 @@ self - Decimal instance context - context used. """ - if self._is_special: - return self + if context is None: context = getcontext() - prec = context.prec - ans = self._fixexponents(context) - if len(ans._int) > prec: - ans = ans._round(prec, context=context) - ans = ans._fixexponents(context) - return ans - def _fixexponents(self, context): - """Fix the exponents and return a copy with the exponent in bounds. - Only call if known to not be a special value. - """ - folddown = context._clamp - Emin = context.Emin - ans = self - ans_adjusted = ans.adjusted() - if ans_adjusted < Emin: - Etiny = context.Etiny() - if ans._exp < Etiny: - if not ans: - ans = Decimal(self) - ans._exp = Etiny - context._raise_error(Clamped) - return ans - ans = ans._rescale(Etiny, context=context) - # It isn't zero, and exp < Emin => subnormal - context._raise_error(Subnormal) - if context.flags[Inexact]: - context._raise_error(Underflow) + if self._is_special: + if self._isnan(): + # decapitate payload if necessary + return self._fix_nan(context) else: - if ans: - # Only raise subnormal if non-zero. - context._raise_error(Subnormal) - else: - Etop = context.Etop() - if folddown and ans._exp > Etop: + # self is +/-Infinity; return unaltered + return Decimal(self) + + # if self is zero then exponent should be between Etiny and + # Emax if _clamp==0, and between Etiny and Etop if _clamp==1. + Etiny = context.Etiny() + Etop = context.Etop() + if not self: + exp_max = [context.Emax, Etop][context._clamp] + new_exp = min(max(self._exp, Etiny), exp_max) + if new_exp != self._exp: context._raise_error(Clamped) - ans = ans._rescale(Etop, context=context) + return Decimal((self._sign, (0,), new_exp)) else: - Emax = context.Emax - if ans_adjusted > Emax: - if not ans: - ans = Decimal(self) - ans._exp = Emax - context._raise_error(Clamped) - return ans - context._raise_error(Inexact) - context._raise_error(Rounded) - c = context._raise_error(Overflow, 'above Emax', ans._sign) - return c - return ans - - def _round(self, prec=None, rounding=None, context=None): - """Returns a rounded version of self. - - You can specify the precision or rounding method. Otherwise, the - context determines it. - """ - - if self._is_special: - ans = self._check_nans(context=context) - if ans: - return ans - - if self._isinfinity(): return Decimal(self) - if context is None: - context = getcontext() - - if rounding is None: - rounding = context.rounding - if prec is None: - prec = context.prec - - if not self: - if prec <= 0: - dig = (0,) - exp = len(self._int) - prec + self._exp - else: - dig = (0,) * prec - exp = len(self._int) + self._exp - prec - ans = Decimal((self._sign, dig, exp)) + # exp_min is the smallest allowable exponent of the result, + # equal to max(self.adjusted()-context.prec+1, Etiny) + exp_min = len(self._int) + self._exp - context.prec + if exp_min > Etop: + # overflow: exp_min > Etop iff self.adjusted() > Emax + context._raise_error(Inexact) context._raise_error(Rounded) - return ans + return context._raise_error(Overflow, 'above Emax', self._sign) + self_is_subnormal = exp_min < Etiny + if self_is_subnormal: + context._raise_error(Subnormal) + exp_min = Etiny - if prec == 0: - temp = Decimal(self) - temp._int = (0,)+temp._int - prec = 1 - elif prec < 0: - exp = self._exp + len(self._int) - prec - 1 - temp = Decimal( (self._sign, (0, 1), exp)) - prec = 1 - else: - temp = Decimal(self) - - numdigits = len(temp._int) - if prec == numdigits: - return temp - - # See if we need to extend precision - expdiff = prec - numdigits - if expdiff > 0: - tmp = list(temp._int) - tmp.extend([0] * expdiff) - ans = Decimal( (temp._sign, tmp, temp._exp - expdiff)) - return ans - - # OK, but maybe all the lost digits are 0. - lostdigits = self._int[expdiff:] - if lostdigits == (0,) * len(lostdigits): - ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff)) - # Rounded, but not Inexact + # round if self has too many digits + if self._exp < exp_min: context._raise_error(Rounded) + ans = self._rescale(exp_min, context.rounding) + if ans != self: + context._raise_error(Inexact) + if self_is_subnormal: + context._raise_error(Underflow) + if not ans: + # raise Clamped on underflow to 0 + context._raise_error(Clamped) + elif len(ans._int) == context.prec+1: + # we get here only if rescaling rounds the + # cofficient up to exactly 10**context.prec + if ans._exp < Etop: + ans = Decimal((ans._sign, ans._int[:-1], ans._exp+1)) + else: + # Inexact and Rounded have already been raised + ans = context._raise_error(Overflow, 'above Emax', + self._sign) return ans - # Okay, let's round and lose data - - this_function = getattr(temp, self._pick_rounding_function[rounding]) - # Now we've got the rounding function - - if prec != context.prec: - context = context._shallow_copy() - context.prec = prec - ans = this_function(prec, expdiff, context) - context._raise_error(Rounded) - context._raise_error(Inexact, 'Changed in rounding') + # fold down if _clamp == 1 and self has too few digits + if context._clamp == 1 and self._exp > Etop: + context._raise_error(Clamped) + self_padded = self._int + (0,)*(self._exp - Etop) + return Decimal((self._sign, self_padded, Etop)) - return ans + # here self was representable to begin with; return unchanged + return Decimal(self) _pick_rounding_function = {} - def _round_down(self, prec, expdiff, context): - """Also known as round-towards-0, truncate.""" - return Decimal( (self._sign, self._int[:prec], self._exp - expdiff) ) + # for each of the rounding functions below: + # self is a finite, nonzero Decimal + # prec is an integer satisfying 0 <= prec < len(self._int) + # the rounded result will have exponent self._exp + len(self._int) - prec; - def _round_half_up(self, prec, expdiff, context, tmp = None): - """Rounds 5 up (away from 0)""" + def _round_down(self, prec): + """Also known as round-towards-0, truncate.""" + newexp = self._exp + len(self._int) - prec + return Decimal((self._sign, self._int[:prec] or (0,), newexp)) - if tmp is None: - tmp = Decimal( (self._sign,self._int[:prec], self._exp - expdiff)) - if self._int[prec] >= 5: - tmp = tmp._increment(round=0, context=context) - if len(tmp._int) > prec: - return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1)) + def _round_up(self, prec): + """Rounds away from 0.""" + newexp = self._exp + len(self._int) - prec + tmp = Decimal((self._sign, self._int[:prec] or (0,), newexp)) + for digit in self._int[prec:]: + if digit != 0: + return tmp._increment() return tmp - def _round_half_even(self, prec, expdiff, context): - """Round 5 to even, rest to nearest.""" + def _round_half_up(self, prec): + """Rounds 5 up (away from 0)""" + if self._int[prec] >= 5: + return self._round_up(prec) + else: + return self._round_down(prec) - tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff)) - half = (self._int[prec] == 5) - if half: + def _round_half_down(self, prec): + """Round 5 down""" + if self._int[prec] == 5: for digit in self._int[prec+1:]: if digit != 0: - half = 0 break - if half: - if self._int[prec-1] & 1 == 0: - return tmp - return self._round_half_up(prec, expdiff, context, tmp) + else: + return self._round_down(prec) + return self._round_half_up(prec) - def _round_half_down(self, prec, expdiff, context): - """Round 5 down""" + def _round_half_even(self, prec): + """Round 5 to even, rest to nearest.""" + if prec and self._int[prec-1] & 1: + return self._round_half_up(prec) + else: + return self._round_half_down(prec) - tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff)) - half = (self._int[prec] == 5) - if half: - for digit in self._int[prec+1:]: - if digit != 0: - half = 0 - break - if half: - return tmp - return self._round_half_up(prec, expdiff, context, tmp) + def _round_ceiling(self, prec): + """Rounds up (not away from 0 if negative.)""" + if self._sign: + return self._round_down(prec) + else: + return self._round_up(prec) - def _round_up(self, prec, expdiff, context): - """Rounds away from 0.""" - tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff) ) - for digit in self._int[prec:]: - if digit != 0: - tmp = tmp._increment(round=1, context=context) - if len(tmp._int) > prec: - return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1)) - else: - return tmp - return tmp - - def _round_ceiling(self, prec, expdiff, context): - """Rounds up (not away from 0 if negative.)""" - if self._sign: - return self._round_down(prec, expdiff, context) - else: - return self._round_up(prec, expdiff, context) - - def _round_floor(self, prec, expdiff, context): + def _round_floor(self, prec): """Rounds down (not towards 0 if negative)""" if not self._sign: - return self._round_down(prec, expdiff, context) + return self._round_down(prec) + else: + return self._round_up(prec) + + def _round_05up(self, prec): + """Round down unless digit prec-1 is 0 or 5.""" + if prec == 0 or self._int[prec-1] in (0, 5): + return self._round_up(prec) else: - return self._round_up(prec, expdiff, context) + return self._round_down(prec) - def __pow__(self, n, modulo = None, context=None): - """Return self ** n (mod modulo) + def fma(self, other, third, context=None): + """Fused multiply-add. - If modulo is None (default), don't take it mod modulo. + Returns self*other+third with no rounding of the intermediate + product self*other. + + self and other are multiplied together, with no rounding of + the result. The third operand is then added to the result, + and a single final rounding is performed. """ - n = _convert_other(n) - if n is NotImplemented: - return n + + other = _convert_other(other, raiseit=True) + third = _convert_other(third, raiseit=True) if context is None: context = getcontext() - if self._is_special or n._is_special or n.adjusted() > 8: - # Because the spot << doesn't work with really big exponents - if n._isinfinity() or n.adjusted() > 8: - return context._raise_error(InvalidOperation, 'x ** INF') + # do self*other in fresh context with no traps and no rounding + mul_context = Context(traps=[], flags=[], + _rounding_decision=NEVER_ROUND) + product = self.__mul__(other, mul_context) + + if mul_context.flags[InvalidOperation]: + # reraise in current context + return context._raise_error(InvalidOperation, + 'invalid multiplication in fma', + 1, product) - ans = self._check_nans(n, context) - if ans: - return ans + ans = product.__add__(third, context) + return ans + + def _power_modulo(self, other, modulo, context=None): + """Three argument version of __pow__""" + + # if can't convert other and modulo to Decimal, raise + # TypeError; there's no point returning NotImplemented (no + # equivalent of __rpow__ for three argument pow) + other = _convert_other(other, raiseit=True) + modulo = _convert_other(modulo, raiseit=True) + + if context is None: + context = getcontext() + + # deal with NaNs: if there are any sNaNs then first one wins, + # (i.e. behaviour for NaNs is identical to that of fma) + self_is_nan = self._isnan() + other_is_nan = other._isnan() + modulo_is_nan = modulo._isnan() + if self_is_nan or other_is_nan or modulo_is_nan: + if self_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + 1, self) + if other_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + 1, other) + if modulo_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + 1, modulo) + if self_is_nan: + return self._fix_nan(context) + if other_is_nan: + return other._fix_nan(context) + return modulo._fix_nan(context) + + # check inputs: we apply same restrictions as Python's pow() + if not (self._isinteger() and + other._isinteger() and + modulo._isinteger()): + return context._raise_error(InvalidOperation, + 'pow() 3rd argument not allowed ' + 'unless all arguments are integers') + if other < 0: + return context._raise_error(InvalidOperation, + 'pow() 2nd argument cannot be ' + 'negative when 3rd argument specified') + if not modulo: + return context._raise_error(InvalidOperation, + 'pow() 3rd argument cannot be 0') + + # additional restriction for decimal: the modulus must be less + # than 10**prec in absolute value + if modulo.adjusted() >= context.prec: + return context._raise_error(InvalidOperation, + 'insufficient precision: pow() 3rd ' + 'argument must not have more than ' + 'precision digits') + + # define 0**0 == NaN, for consistency with two-argument pow + # (even though it hurts!) + if not other and not self: + return context._raise_error(InvalidOperation, + 'at least one of pow() 1st argument ' + 'and 2nd argument must be nonzero ;' + '0**0 is not defined') + + # compute sign of result + if other._iseven(): + sign = 0 + else: + sign = self._sign + + # convert modulo to a Python integer, and self and other to + # Decimal integers (i.e. force their exponents to be >= 0) + modulo = abs(int(modulo)) + base = _WorkRep(self.to_integral_value()) + exponent = _WorkRep(other.to_integral_value()) + + # compute result using integer pow() + base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo + for i in range(exponent.exp): + base = pow(base, 10, modulo) + base = pow(base, exponent.int, modulo) + + return Decimal((sign, list(map(int, str(base))), 0)) + + def _power_exact(self, other, p): + """Attempt to compute self**other exactly. + + Given Decimals self and other and an integer p, attempt to + compute an exact result for the power self**other, with p + digits of precision. Return None if self**other is not + exactly representable in p digits. + + Assumes that elimination of special cases has already been + performed: self and other must both be nonspecial; self must + be positive and not numerically equal to 1; other must be + nonzero. For efficiency, other._exp should not be too large, + so that 10**abs(other._exp) is a feasible calculation.""" + + # In the comments below, we write x for the value of self and + # y for the value of other. Write x = xc*10**xe and y = + # yc*10**ye. + + # The main purpose of this method is to identify the *failure* + # of x**y to be exactly representable with as little effort as + # possible. So we look for cheap and easy tests that + # eliminate the possibility of x**y being exact. Only if all + # these tests are passed do we go on to actually compute x**y. + + # Here's the main idea. First normalize both x and y. We + # express y as a rational m/n, with m and n relatively prime + # and n>0. Then for x**y to be exactly representable (at + # *any* precision), xc must be the nth power of a positive + # integer and xe must be divisible by n. If m is negative + # then additionally xc must be a power of either 2 or 5, hence + # a power of 2**n or 5**n. + # + # There's a limit to how small |y| can be: if y=m/n as above + # then: + # + # (1) if xc != 1 then for the result to be representable we + # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So + # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <= + # 2**(1/|y|), hence xc**|y| < 2 and the result is not + # representable. + # + # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if + # |y| < 1/|xe| then the result is not representable. + # + # Note that since x is not equal to 1, at least one of (1) and + # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) < + # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye. + # + # There's also a limit to how large y can be, at least if it's + # positive: the normalized result will have coefficient xc**y, + # so if it's representable then xc**y < 10**p, and y < + # p/log10(xc). Hence if y*log10(xc) >= p then the result is + # not exactly representable. + + # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye, + # so |y| < 1/xe and the result is not representable. + # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y| + # < 1/nbits(xc). + + x = _WorkRep(self) + xc, xe = x.int, x.exp + while xc % 10 == 0: + xc //= 10 + xe += 1 + + y = _WorkRep(other) + yc, ye = y.int, y.exp + while yc % 10 == 0: + yc //= 10 + ye += 1 + + # case where xc == 1: result is 10**(xe*y), with xe*y + # required to be an integer + if xc == 1: + if ye >= 0: + exponent = xe*yc*10**ye + else: + exponent, remainder = divmod(xe*yc, 10**-ye) + if remainder: + return None + if y.sign == 1: + exponent = -exponent + # if other is a nonnegative integer, use ideal exponent + if other._isinteger() and other._sign == 0: + ideal_exponent = self._exp*int(other) + zeros = min(exponent-ideal_exponent, p-1) + else: + zeros = 0 + return Decimal((0, (1,) + (0,)*zeros, exponent-zeros)) + + # case where y is negative: xc must be either a power + # of 2 or a power of 5. + if y.sign == 1: + last_digit = xc % 10 + if last_digit in (2,4,6,8): + # quick test for power of 2 + if xc & -xc != xc: + return None + # now xc is a power of 2; e is its exponent + e = _nbits(xc)-1 + # find e*y and xe*y; both must be integers + if ye >= 0: + y_as_int = yc*10**ye + e = e*y_as_int + xe = xe*y_as_int + else: + ten_pow = 10**-ye + e, remainder = divmod(e*yc, ten_pow) + if remainder: + return None + xe, remainder = divmod(xe*yc, ten_pow) + if remainder: + return None + + if e*65 >= p*93: # 93/65 > log(10)/log(5) + return None + xc = 5**e + + elif last_digit == 5: + # e >= log_5(xc) if xc is a power of 5; we have + # equality all the way up to xc=5**2658 + e = _nbits(xc)*28//65 + xc, remainder = divmod(5**e, xc) + if remainder: + return None + while xc % 5 == 0: + xc //= 5 + e -= 1 + if ye >= 0: + y_as_integer = yc*10**ye + e = e*y_as_integer + xe = xe*y_as_integer + else: + ten_pow = 10**-ye + e, remainder = divmod(e*yc, ten_pow) + if remainder: + return None + xe, remainder = divmod(xe*yc, ten_pow) + if remainder: + return None + if e*3 >= p*10: # 10/3 > log(10)/log(2) + return None + xc = 2**e + else: + return None + + if xc >= 10**p: + return None + xe = -e-xe + return Decimal((0, list(map(int, str(xc))), xe)) + + # now y is positive; find m and n such that y = m/n + if ye >= 0: + m, n = yc*10**ye, 1 + else: + if xe != 0 and len(str(abs(yc*xe))) <= -ye: + return None + xc_bits = _nbits(xc) + if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye: + return None + m, n = yc, 10**(-ye) + while m % 2 == n % 2 == 0: + m //= 2 + n //= 2 + while m % 5 == n % 5 == 0: + m //= 5 + n //= 5 + + # compute nth root of xc*10**xe + if n > 1: + # if 1 < xc < 2**n then xc isn't an nth power + if xc != 1 and xc_bits <= n: + return None + + xe, rem = divmod(xe, n) + if rem != 0: + return None + + # compute nth root of xc using Newton's method + a = 1 << -(-_nbits(xc)//n) # initial estimate + while True: + q, r = divmod(xc, a**(n-1)) + if a <= q: + break + else: + a = (a*(n-1) + q)//n + if not (a == q and r == 0): + return None + xc = a + + # now xc*10**xe is the nth root of the original xc*10**xe + # compute mth power of xc*10**xe + + # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m > + # 10**p and the result is not representable. + if xc > 1 and m > p*100//_log10_lb(xc): + return None + xc = xc**m + xe *= m + if xc > 10**p: + return None + + # by this point the result *is* exactly representable + # adjust the exponent to get as close as possible to the ideal + # exponent, if necessary + str_xc = str(xc) + if other._isinteger() and other._sign == 0: + ideal_exponent = self._exp*int(other) + zeros = min(xe-ideal_exponent, p-len(str_xc)) + else: + zeros = 0 + return Decimal((0, list(map(int, str_xc))+[0,]*zeros, xe-zeros)) - if not n._isinteger(): - return context._raise_error(InvalidOperation, 'x ** (non-integer)') + def __pow__(self, other, modulo=None, context=None): + """Return self ** other [ % modulo]. - if not self and not n: - return context._raise_error(InvalidOperation, '0 ** 0') + With two arguments, compute self**other. + + With three arguments, compute (self**other) % modulo. For the + three argument form, the following restrictions on the + arguments hold: + + - all three arguments must be integral + - other must be nonnegative + - either self or other (or both) must be nonzero + - modulo must be nonzero and must have at most p digits, + where p is the context precision. + + If any of these restrictions is violated the InvalidOperation + flag is raised. + + The result of pow(self, other, modulo) is identical to the + result that would be obtained by computing (self**other) % + modulo with unbounded precision, but is computed more + efficiently. It is always exact. + """ + + if modulo is not None: + return self._power_modulo(other, modulo, context) + + other = _convert_other(other) + if other is NotImplemented: + return other + + if context is None: + context = getcontext() + + # either argument is a NaN => result is NaN + ans = self._check_nans(other, context) + if ans: + return ans - if not n: - return Decimal(1) + # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity) + if not other: + if not self: + return context._raise_error(InvalidOperation, '0 ** 0') + else: + return Dec_p1 - if self == Decimal(1): - return Decimal(1) + # result has sign 1 iff self._sign is 1 and other is an odd integer + result_sign = 0 + if self._sign == 1: + if other._isinteger(): + if not other._iseven(): + result_sign = 1 + else: + # -ve**noninteger = NaN + # (-0)**noninteger = 0**noninteger + if self: + return context._raise_error(InvalidOperation, + 'x ** y with x negative and y not an integer') + # negate self, without doing any unwanted rounding + self = Decimal((0, self._int, self._exp)) - sign = self._sign and not n._iseven() - n = int(n) + # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity + if not self: + if other._sign == 0: + return Decimal((result_sign, (0,), 0)) + else: + return Infsign[result_sign] + # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0 if self._isinfinity(): - if modulo: - return context._raise_error(InvalidOperation, 'INF % x') - if n > 0: - return Infsign[sign] - return Decimal( (sign, (0,), 0) ) + if other._sign == 0: + return Infsign[result_sign] + else: + return Decimal((result_sign, (0,), 0)) - # With ludicrously large exponent, just raise an overflow - # and return inf. - if not modulo and n > 0 and \ - (self._exp + len(self._int) - 1) * n > context.Emax and self: + # 1**other = 1, but the choice of exponent and the flags + # depend on the exponent of self, and on whether other is a + # positive integer, a negative integer, or neither + if self == Dec_p1: + if other._isinteger(): + # exp = max(self._exp*max(int(other), 0), + # 1-context.prec) but evaluating int(other) directly + # is dangerous until we know other is small (other + # could be 1e999999999) + if other._sign == 1: + multiplier = 0 + elif other > context.prec: + multiplier = context.prec + else: + multiplier = int(other) - tmp = Decimal('inf') - tmp._sign = sign - context._raise_error(Rounded) - context._raise_error(Inexact) - context._raise_error(Overflow, 'Big power', sign) - return tmp + exp = self._exp * multiplier + if exp < 1-context.prec: + exp = 1-context.prec + context._raise_error(Rounded) + else: + context._raise_error(Inexact) + context._raise_error(Rounded) + exp = 1-context.prec + + return Decimal((result_sign, (1,)+(0,)*-exp, exp)) + + # compute adjusted exponent of self + self_adj = self.adjusted() + + # self ** infinity is infinity if self > 1, 0 if self < 1 + # self ** -infinity is infinity if self < 1, 0 if self > 1 + if other._isinfinity(): + if (other._sign == 0) == (self_adj < 0): + return Decimal((result_sign, (0,), 0)) + else: + return Infsign[result_sign] - elength = len(str(abs(n))) - firstprec = context.prec + # from here on, the result always goes through the call + # to _fix at the end of this function. + ans = None + + # crude test to catch cases of extreme overflow/underflow. If + # log10(self)*other >= 10**bound and bound >= len(str(Emax)) + # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence + # self**other >= 10**(Emax+1), so overflow occurs. The test + # for underflow is similar. + bound = self._log10_exp_bound() + other.adjusted() + if (self_adj >= 0) == (other._sign == 0): + # self > 1 and other +ve, or self < 1 and other -ve + # possibility of overflow + if bound >= len(str(context.Emax)): + ans = Decimal((result_sign, (1,), context.Emax+1)) + else: + # self > 1 and other -ve, or self < 1 and other +ve + # possibility of underflow to 0 + Etiny = context.Etiny() + if bound >= len(str(-Etiny)): + ans = Decimal((result_sign, (1,), Etiny-1)) - if not modulo and firstprec + elength + 1 > DefaultContext.Emax: - return context._raise_error(Overflow, 'Too much precision.', sign) + # try for an exact result with precision +1 + if ans is None: + ans = self._power_exact(other, context.prec + 1) + if ans is not None and result_sign == 1: + ans = Decimal((1, ans._int, ans._exp)) + + # usual case: inexact result, x**y computed directly as exp(y*log(x)) + if ans is None: + p = context.prec + x = _WorkRep(self) + xc, xe = x.int, x.exp + y = _WorkRep(other) + yc, ye = y.int, y.exp + if y.sign == 1: + yc = -yc + + # compute correctly rounded result: start with precision +3, + # then increase precision until result is unambiguously roundable + extra = 3 + while True: + coeff, exp = _dpower(xc, xe, yc, ye, p+extra) + if coeff % (5*10**(len(str(coeff))-p-1)): + break + extra += 3 - mul = Decimal(self) - val = Decimal(1) - context = context._shallow_copy() - context.prec = firstprec + elength + 1 - if n < 0: - # n is a long now, not Decimal instance - n = -n - mul = Decimal(1).__truediv__(mul, context=context) - - spot = 1 - while spot <= n: - spot <<= 1 - - spot >>= 1 - # spot is the highest power of 2 less than n - while spot: - val = val.__mul__(val, context=context) - if val._isinfinity(): - val = Infsign[sign] - break - if spot & n: - val = val.__mul__(mul, context=context) - if modulo is not None: - val = val.__mod__(modulo, context=context) - spot >>= 1 - context.prec = firstprec + ans = Decimal((result_sign, list(map(int, str(coeff))), exp)) - if context._rounding_decision == ALWAYS_ROUND: - return val._fix(context) - return val + # the specification says that for non-integer other we need to + # raise Inexact, even when the result is actually exact. In + # the same way, we need to raise Underflow here if the result + # is subnormal. (The call to _fix will take care of raising + # Rounded and Subnormal, as usual.) + if not other._isinteger(): + context._raise_error(Inexact) + # pad with zeros up to length context.prec+1 if necessary + if len(ans._int) <= context.prec: + expdiff = context.prec+1 - len(ans._int) + ans = Decimal((ans._sign, ans._int+(0,)*expdiff, ans._exp-expdiff)) + if ans.adjusted() < context.Emin: + context._raise_error(Underflow) + + # unlike exp, ln and log10, the power function respects the + # rounding mode; no need to use ROUND_HALF_EVEN here + ans = ans._fix(context) + return ans def __rpow__(self, other, context=None): """Swaps self/other and returns __pow__.""" @@ -1853,6 +2159,9 @@ def normalize(self, context=None): """Normalize- strip trailing 0s, change anything equal to 0 to 0e0""" + if context is None: + context = getcontext() + if self._is_special: ans = self._check_nans(context=context) if ans: @@ -1864,19 +2173,26 @@ if not dup: return Decimal( (dup._sign, (0,), 0) ) + exp_max = [context.Emax, context.Etop()][context._clamp] end = len(dup._int) exp = dup._exp - while dup._int[end-1] == 0: + while dup._int[end-1] == 0 and exp < exp_max: exp += 1 end -= 1 return Decimal( (dup._sign, dup._int[:end], exp) ) - - def quantize(self, exp, rounding=None, context=None, watchexp=1): + def quantize(self, exp, rounding=None, context=None, watchexp=True): """Quantize self so its exponent is the same as that of exp. Similar to self._rescale(exp._exp) but with error checking. """ + exp = _convert_other(exp, raiseit=True) + + if context is None: + context = getcontext() + if rounding is None: + rounding = context.rounding + if self._is_special or exp._is_special: ans = self._check_nans(exp, context) if ans: @@ -1884,12 +2200,56 @@ if exp._isinfinity() or self._isinfinity(): if exp._isinfinity() and self._isinfinity(): - return self # if both are inf, it is OK - if context is None: - context = getcontext() + return Decimal(self) # if both are inf, it is OK return context._raise_error(InvalidOperation, 'quantize with one INF') - return self._rescale(exp._exp, rounding, context, watchexp) + + # if we're not watching exponents, do a simple rescale + if not watchexp: + ans = self._rescale(exp._exp, rounding) + # raise Inexact and Rounded where appropriate + if ans._exp > self._exp: + context._raise_error(Rounded) + if ans != self: + context._raise_error(Inexact) + return ans + + # exp._exp should be between Etiny and Emax + if not (context.Etiny() <= exp._exp <= context.Emax): + return context._raise_error(InvalidOperation, + 'target exponent out of bounds in quantize') + + if not self: + ans = Decimal((self._sign, (0,), exp._exp)) + return ans._fix(context) + + self_adjusted = self.adjusted() + if self_adjusted > context.Emax: + return context._raise_error(InvalidOperation, + 'exponent of quantize result too large for current context') + if self_adjusted - exp._exp + 1 > context.prec: + return context._raise_error(InvalidOperation, + 'quantize result has too many digits for current context') + + ans = self._rescale(exp._exp, rounding) + if ans.adjusted() > context.Emax: + return context._raise_error(InvalidOperation, + 'exponent of quantize result too large for current context') + if len(ans._int) > context.prec: + return context._raise_error(InvalidOperation, + 'quantize result has too many digits for current context') + + # raise appropriate flags + if ans._exp > self._exp: + context._raise_error(Rounded) + if ans != self: + context._raise_error(Inexact) + if ans and ans.adjusted() < context.Emin: + context._raise_error(Subnormal) + + # call to fix takes care of any necessary folddown + ans = ans._fix(context) + return ans def same_quantum(self, other): """Test whether self and other have the same exponent. @@ -1903,83 +2263,85 @@ return self._isinfinity() and other._isinfinity() and True return self._exp == other._exp - def _rescale(self, exp, rounding=None, context=None, watchexp=1): - """Rescales so that the exponent is exp. + def _rescale(self, exp, rounding): + """Rescale self so that the exponent is exp, either by padding with zeros + or by truncating digits, using the given rounding mode. + + Specials are returned without change. This operation is + quiet: it raises no flags, and uses no information from the + context. exp = exp to scale to (an integer) - rounding = rounding version - watchexp: if set (default) an error is returned if exp is greater - than Emax or less than Etiny. + rounding = rounding mode """ - if context is None: - context = getcontext() - if self._is_special: - if self._isinfinity(): - return context._raise_error(InvalidOperation, 'rescale with an INF') - - ans = self._check_nans(context=context) - if ans: - return ans - - if watchexp and (context.Emax < exp or context.Etiny() > exp): - return context._raise_error(InvalidOperation, 'rescale(a, INF)') - + return Decimal(self) if not self: - ans = Decimal(self) - ans._int = (0,) - ans._exp = exp - return ans - - diff = self._exp - exp - digits = len(self._int) + diff - - if watchexp and digits > context.prec: - return context._raise_error(InvalidOperation, 'Rescale > prec') - - tmp = Decimal(self) - tmp._int = (0,) + tmp._int - digits += 1 + return Decimal((self._sign, (0,), exp)) + if self._exp >= exp: + # pad answer with zeros if necessary + return Decimal((self._sign, self._int + (0,)*(self._exp - exp), exp)) + + # too many digits; round and lose data. If self.adjusted() < + # exp-1, replace self by 10**(exp-1) before rounding + digits = len(self._int) + self._exp - exp if digits < 0: - tmp._exp = -digits + tmp._exp - tmp._int = (0,1) - digits = 1 - tmp = tmp._round(digits, rounding, context=context) - - if tmp._int[0] == 0 and len(tmp._int) > 1: - tmp._int = tmp._int[1:] - tmp._exp = exp - - tmp_adjusted = tmp.adjusted() - if tmp and tmp_adjusted < context.Emin: - context._raise_error(Subnormal) - elif tmp and tmp_adjusted > context.Emax: - return context._raise_error(InvalidOperation, 'rescale(a, INF)') - return tmp + self = Decimal((self._sign, (1,), exp-1)) + digits = 0 + this_function = getattr(self, self._pick_rounding_function[rounding]) + return this_function(digits) + + def to_integral_exact(self, rounding=None, context=None): + """Rounds to a nearby integer. + + If no rounding mode is specified, take the rounding mode from + the context. This method raises the Rounded and Inexact flags + when appropriate. - def to_integral(self, rounding=None, context=None): - """Rounds to the nearest integer, without raising inexact, rounded.""" + See also: to_integral_value, which does exactly the same as + this method except that it doesn't raise Inexact or Rounded. + """ if self._is_special: ans = self._check_nans(context=context) if ans: return ans - return self + return Decimal(self) if self._exp >= 0: - return self + return Decimal(self) + if not self: + return Decimal((self._sign, (0,), 0)) if context is None: context = getcontext() - flags = context._ignore_flags(Rounded, Inexact) - ans = self._rescale(0, rounding, context=context) - context._regard_flags(flags) + if rounding is None: + rounding = context.rounding + context._raise_error(Rounded) + ans = self._rescale(0, rounding) + if ans != self: + context._raise_error(Inexact) return ans - def sqrt(self, context=None): - """Return the square root of self. + def to_integral_value(self, rounding=None, context=None): + """Rounds to the nearest integer, without raising inexact, rounded.""" + if context is None: + context = getcontext() + if rounding is None: + rounding = context.rounding + if self._is_special: + ans = self._check_nans(context=context) + if ans: + return ans + return Decimal(self) + if self._exp >= 0: + return Decimal(self) + else: + return self._rescale(0, rounding) - Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn)) - Should quadratically approach the right answer. - """ + # the method name changed, but we provide also the old one, for compatibility + to_integral = to_integral_value + + def sqrt(self, context=None): + """Return the square root of self.""" if self._is_special: ans = self._check_nans(context=context) if ans: @@ -1989,16 +2351,9 @@ return Decimal(self) if not self: - # exponent = self._exp / 2, using round_down. - # if self._exp < 0: - # exp = (self._exp+1) // 2 - # else: - exp = (self._exp) // 2 - if self._sign == 1: - # sqrt(-0) = -0 - return Decimal( (1, (0,), exp)) - else: - return Decimal( (0, (0,), exp)) + # exponent = self._exp // 2. sqrt(-0) = -0 + ans = Decimal((self._sign, (0,), self._exp // 2)) + return ans._fix(context) if context is None: context = getcontext() @@ -2006,104 +2361,94 @@ if self._sign == 1: return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0') - tmp = Decimal(self) - - expadd = tmp._exp // 2 - if tmp._exp & 1: - tmp._int += (0,) - tmp._exp = 0 + # At this point self represents a positive number. Let p be + # the desired precision and express self in the form c*100**e + # with c a positive real number and e an integer, c and e + # being chosen so that 100**(p-1) <= c < 100**p. Then the + # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1) + # <= sqrt(c) < 10**p, so the closest representable Decimal at + # precision p is n*10**e where n = round_half_even(sqrt(c)), + # the closest integer to sqrt(c) with the even integer chosen + # in the case of a tie. + # + # To ensure correct rounding in all cases, we use the + # following trick: we compute the square root to an extra + # place (precision p+1 instead of precision p), rounding down. + # Then, if the result is inexact and its last digit is 0 or 5, + # we increase the last digit to 1 or 6 respectively; if it's + # exact we leave the last digit alone. Now the final round to + # p places (or fewer in the case of underflow) will round + # correctly and raise the appropriate flags. + + # use an extra digit of precision + prec = context.prec+1 + + # write argument in the form c*100**e where e = self._exp//2 + # is the 'ideal' exponent, to be used if the square root is + # exactly representable. l is the number of 'digits' of c in + # base 100, so that 100**(l-1) <= c < 100**l. + op = _WorkRep(self) + e = op.exp >> 1 + if op.exp & 1: + c = op.int * 10 + l = (len(self._int) >> 1) + 1 else: - tmp._exp = 0 - - context = context._shallow_copy() - flags = context._ignore_all_flags() - firstprec = context.prec - context.prec = 3 - if tmp.adjusted() & 1 == 0: - ans = Decimal( (0, (8,1,9), tmp.adjusted() - 2) ) - ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)), - context=context), context=context) - ans._exp -= 1 + tmp.adjusted() // 2 - else: - ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) ) - ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)), - context=context), context=context) - ans._exp -= 1 + tmp.adjusted() // 2 - - # ans is now a linear approximation. - Emax, Emin = context.Emax, context.Emin - context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin + c = op.int + l = len(self._int)+1 >> 1 - half = Decimal('0.5') - - maxp = firstprec + 2 - rounding = context._set_rounding(ROUND_HALF_EVEN) - while 1: - context.prec = min(2*context.prec - 2, maxp) - ans = half.__mul__(ans.__add__(tmp.__truediv__(ans, context=context), - context=context), context=context) - if context.prec == maxp: + # rescale so that c has exactly prec base 100 'digits' + shift = prec-l + if shift >= 0: + c *= 100**shift + exact = True + else: + c, remainder = divmod(c, 100**-shift) + exact = not remainder + e -= shift + + # find n = floor(sqrt(c)) using Newton's method + n = 10**prec + while True: + q = c//n + if n <= q: break + else: + n = n + q >> 1 + exact = exact and n*n == c - # Round to the answer's precision-- the only error can be 1 ulp. - context.prec = firstprec - prevexp = ans.adjusted() - ans = ans._round(context=context) - - # Now, check if the other last digits are better. - context.prec = firstprec + 1 - # In case we rounded up another digit and we should actually go lower. - if prevexp != ans.adjusted(): - ans._int += (0,) - ans._exp -= 1 - - - lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context) - context._set_rounding(ROUND_UP) - if lower.__mul__(lower, context=context) > (tmp): - ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context) - + if exact: + # result is exact; rescale to use ideal exponent e + if shift >= 0: + # assert n % 10**shift == 0 + n //= 10**shift + else: + n *= 10**-shift + e += shift else: - upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context) - context._set_rounding(ROUND_DOWN) - if upper.__mul__(upper, context=context) < tmp: - ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context) + # result is not exact; fix last digit as described above + if n % 5 == 0: + n += 1 - ans._exp += expadd + ans = Decimal((0, list(map(int, str(n))), e)) - context.prec = firstprec - context.rounding = rounding + # round, and fit to current context + context = context._shallow_copy() + rounding = context._set_rounding(ROUND_HALF_EVEN) ans = ans._fix(context) + context.rounding = rounding - rounding = context._set_rounding_decision(NEVER_ROUND) - if not ans.__mul__(ans, context=context) == self: - # Only rounded/inexact if here. - context._regard_flags(flags) - context._raise_error(Rounded) - context._raise_error(Inexact) - else: - # Exact answer, so let's set the exponent right. - # if self._exp < 0: - # exp = (self._exp +1)// 2 - # else: - exp = self._exp // 2 - context.prec += ans._exp - exp - ans = ans._rescale(exp, context=context) - context.prec = firstprec - context._regard_flags(flags) - context.Emax, context.Emin = Emax, Emin - - return ans._fix(context) + return ans def max(self, other, context=None): """Returns the larger value. - like max(self, other) except if one is not a number, returns + Like max(self, other) except if one is not a number, returns NaN (and signals if one is sNaN). Also rounds. """ - other = _convert_other(other) - if other is NotImplemented: - return other + other = _convert_other(other, raiseit=True) + + if context is None: + context = getcontext() if self._is_special or other._is_special: # If one operand is a quiet NaN and the other is number, then the @@ -2112,12 +2457,11 @@ on = other._isnan() if sn or on: if on == 1 and sn != 2: - return self + return self._fix_nan(context) if sn == 1 and on != 2: - return other + return other._fix_nan(context) return self._check_nans(other, context) - ans = self c = self.__cmp__(other) if c == 0: # If both operands are finite and equal in numerical value @@ -2127,19 +2471,14 @@ # positive sign and min returns the operand with the negative sign # # If the signs are the same then the exponent is used to select - # the result. - if self._sign != other._sign: - if self._sign: - ans = other - elif self._exp < other._exp and not self._sign: - ans = other - elif self._exp > other._exp and self._sign: - ans = other - elif c == -1: + # the result. This is exactly the ordering used in compare_total. + c = self.compare_total(other) + + if c == -1: ans = other + else: + ans = self - if context is None: - context = getcontext() if context._rounding_decision == ALWAYS_ROUND: return ans._fix(context) return ans @@ -2150,9 +2489,10 @@ Like min(self, other) except if one is not a number, returns NaN (and signals if one is sNaN). Also rounds. """ - other = _convert_other(other) - if other is NotImplemented: - return other + other = _convert_other(other, raiseit=True) + + if context is None: + context = getcontext() if self._is_special or other._is_special: # If one operand is a quiet NaN and the other is number, then the @@ -2161,49 +2501,37 @@ on = other._isnan() if sn or on: if on == 1 and sn != 2: - return self + return self._fix_nan(context) if sn == 1 and on != 2: - return other + return other._fix_nan(context) return self._check_nans(other, context) - ans = self c = self.__cmp__(other) if c == 0: - # If both operands are finite and equal in numerical value - # then an ordering is applied: - # - # If the signs differ then max returns the operand with the - # positive sign and min returns the operand with the negative sign - # - # If the signs are the same then the exponent is used to select - # the result. - if self._sign != other._sign: - if other._sign: - ans = other - elif self._exp > other._exp and not self._sign: - ans = other - elif self._exp < other._exp and self._sign: - ans = other - elif c == 1: + c = self.compare_total(other) + + if c == -1: + ans = self + else: ans = other - if context is None: - context = getcontext() if context._rounding_decision == ALWAYS_ROUND: return ans._fix(context) return ans def _isinteger(self): """Returns whether self is an integer""" + if self._is_special: + return False if self._exp >= 0: return True rest = self._int[self._exp:] return rest == (0,)*len(rest) def _iseven(self): - """Returns 1 if self is even. Assumes self is an integer.""" - if self._exp > 0: - return 1 + """Returns True if self is even. Assumes self is an integer.""" + if not self or self._exp > 0: + return True return self._int[-1+self._exp] & 1 == 0 def adjusted(self): @@ -2214,6 +2542,875 @@ except TypeError: return 0 + def canonical(self, context=None): + """Returns the same Decimal object. + + As we do not have different encodings for the same number, the + received object already is in its canonical form. + """ + return self + + def compare_signal(self, other, context=None): + """Compares self to the other operand numerically. + + It's pretty much like compare(), but all NaNs signal, with signaling + NaNs taking precedence over quiet NaNs. + """ + if context is None: + context = getcontext() + + self_is_nan = self._isnan() + other_is_nan = other._isnan() + if self_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + 1, self) + if other_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + 1, other) + if self_is_nan: + return context._raise_error(InvalidOperation, 'NaN in compare_signal', + 1, self) + if other_is_nan: + return context._raise_error(InvalidOperation, 'NaN in compare_signal', + 1, other) + return self.compare(other, context=context) + + def compare_total(self, other): + """Compares self to other using the abstract representations. + + This is not like the standard compare, which use their numerical + value. Note that a total ordering is defined for all possible abstract + representations. + """ + # if one is negative and the other is positive, it's easy + if self._sign and not other._sign: + return Dec_n1 + if not self._sign and other._sign: + return Dec_p1 + sign = self._sign + + # let's handle both NaN types + self_nan = self._isnan() + other_nan = other._isnan() + if self_nan or other_nan: + if self_nan == other_nan: + if self._int < other._int: + if sign: + return Dec_p1 + else: + return Dec_n1 + if self._int > other._int: + if sign: + return Dec_n1 + else: + return Dec_p1 + return Dec_0 + + if sign: + if self_nan == 1: + return Dec_n1 + if other_nan == 1: + return Dec_p1 + if self_nan == 2: + return Dec_n1 + if other_nan == 2: + return Dec_p1 + else: + if self_nan == 1: + return Dec_p1 + if other_nan == 1: + return Dec_n1 + if self_nan == 2: + return Dec_p1 + if other_nan == 2: + return Dec_n1 + + if self < other: + return Dec_n1 + if self > other: + return Dec_p1 + + if self._exp < other._exp: + if sign: + return Dec_p1 + else: + return Dec_n1 + if self._exp > other._exp: + if sign: + return Dec_n1 + else: + return Dec_p1 + return Dec_0 + + + def compare_total_mag(self, other): + """Compares self to other using abstract repr., ignoring sign. + + Like compare_total, but with operand's sign ignored and assumed to be 0. + """ + s = self.copy_abs() + o = other.copy_abs() + return s.compare_total(o) + + def copy_abs(self): + """Returns a copy with the sign set to 0. """ + return Decimal((0, self._int, self._exp)) + + def copy_negate(self): + """Returns a copy with the sign inverted.""" + if self._sign: + return Decimal((0, self._int, self._exp)) + else: + return Decimal((1, self._int, self._exp)) + + def copy_sign(self, other): + """Returns self with the sign of other.""" + return Decimal((other._sign, self._int, self._exp)) + + def exp(self, context=None): + """Returns e ** self.""" + + if context is None: + context = getcontext() + + # exp(NaN) = NaN + ans = self._check_nans(context=context) + if ans: + return ans + + # exp(-Infinity) = 0 + if self._isinfinity() == -1: + return Dec_0 + + # exp(0) = 1 + if not self: + return Dec_p1 + + # exp(Infinity) = Infinity + if self._isinfinity() == 1: + return Decimal(self) + + # the result is now guaranteed to be inexact (the true + # mathematical result is transcendental). There's no need to + # raise Rounded and Inexact here---they'll always be raised as + # a result of the call to _fix. + p = context.prec + adj = self.adjusted() + + # we only need to do any computation for quite a small range + # of adjusted exponents---for example, -29 <= adj <= 10 for + # the default context. For smaller exponent the result is + # indistinguishable from 1 at the given precision, while for + # larger exponent the result either overflows or underflows. + if self._sign == 0 and adj > len(str((context.Emax+1)*3)): + # overflow + ans = Decimal((0, (1,), context.Emax+1)) + elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)): + # underflow to 0 + ans = Decimal((0, (1,), context.Etiny()-1)) + elif self._sign == 0 and adj < -p: + # p+1 digits; final round will raise correct flags + ans = Decimal((0, (1,) + (0,)*(p-1) + (1,), -p)) + elif self._sign == 1 and adj < -p-1: + # p+1 digits; final round will raise correct flags + ans = Decimal((0, (9,)*(p+1), -p-1)) + # general case + else: + op = _WorkRep(self) + c, e = op.int, op.exp + if op.sign == 1: + c = -c + + # compute correctly rounded result: increase precision by + # 3 digits at a time until we get an unambiguously + # roundable result + extra = 3 + while True: + coeff, exp = _dexp(c, e, p+extra) + if coeff % (5*10**(len(str(coeff))-p-1)): + break + extra += 3 + + ans = Decimal((0, list(map(int, str(coeff))), exp)) + + # at this stage, ans should round correctly with *any* + # rounding mode, not just with ROUND_HALF_EVEN + context = context._shallow_copy() + rounding = context._set_rounding(ROUND_HALF_EVEN) + ans = ans._fix(context) + context.rounding = rounding + + return ans + + def is_canonical(self): + """Returns 1 if self is canonical; otherwise returns 0.""" + return Dec_p1 + + def is_finite(self): + """Returns 1 if self is finite, otherwise returns 0. + + For it to be finite, it must be neither infinite nor a NaN. + """ + if self._is_special: + return Dec_0 + else: + return Dec_p1 + + def is_infinite(self): + """Returns 1 if self is an Infinite, otherwise returns 0.""" + if self._isinfinity(): + return Dec_p1 + else: + return Dec_0 + + def is_nan(self): + """Returns 1 if self is qNaN or sNaN, otherwise returns 0.""" + if self._isnan(): + return Dec_p1 + else: + return Dec_0 + + def is_normal(self, context=None): + """Returns 1 if self is a normal number, otherwise returns 0.""" + if self._is_special: + return Dec_0 + if not self: + return Dec_0 + if context is None: + context = getcontext() + if context.Emin <= self.adjusted() <= context.Emax: + return Dec_p1 + else: + return Dec_0 + + def is_qnan(self): + """Returns 1 if self is a quiet NaN, otherwise returns 0.""" + if self._isnan() == 1: + return Dec_p1 + else: + return Dec_0 + + def is_signed(self): + """Returns 1 if self is negative, otherwise returns 0.""" + return Decimal(self._sign) + + def is_snan(self): + """Returns 1 if self is a signaling NaN, otherwise returns 0.""" + if self._isnan() == 2: + return Dec_p1 + else: + return Dec_0 + + def is_subnormal(self, context=None): + """Returns 1 if self is subnormal, otherwise returns 0.""" + if self._is_special: + return Dec_0 + if not self: + return Dec_0 + if context is None: + context = getcontext() + + r = self._exp + len(self._int) + if r <= context.Emin: + return Dec_p1 + return Dec_0 + + def is_zero(self): + """Returns 1 if self is a zero, otherwise returns 0.""" + if self: + return Dec_0 + else: + return Dec_p1 + + def _ln_exp_bound(self): + """Compute a lower bound for the adjusted exponent of self.ln(). + In other words, compute r such that self.ln() >= 10**r. Assumes + that self is finite and positive and that self != 1. + """ + + # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1 + adj = self._exp + len(self._int) - 1 + if adj >= 1: + # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10) + return len(str(adj*23//10)) - 1 + if adj <= -2: + # argument <= 0.1 + return len(str((-1-adj)*23//10)) - 1 + op = _WorkRep(self) + c, e = op.int, op.exp + if adj == 0: + # 1 < self < 10 + num = str(c-10**-e) + den = str(c) + return len(num) - len(den) - (num < den) + # adj == -1, 0.1 <= self < 1 + return e + len(str(10**-e - c)) - 1 + + + def ln(self, context=None): + """Returns the natural (base e) logarithm of self.""" + + if context is None: + context = getcontext() + + # ln(NaN) = NaN + ans = self._check_nans(context=context) + if ans: + return ans + + # ln(0.0) == -Infinity + if not self: + return negInf + + # ln(Infinity) = Infinity + if self._isinfinity() == 1: + return Inf + + # ln(1.0) == 0.0 + if self == Dec_p1: + return Dec_0 + + # ln(negative) raises InvalidOperation + if self._sign == 1: + return context._raise_error(InvalidOperation, + 'ln of a negative value') + + # result is irrational, so necessarily inexact + op = _WorkRep(self) + c, e = op.int, op.exp + p = context.prec + + # correctly rounded result: repeatedly increase precision by 3 + # until we get an unambiguously roundable result + places = p - self._ln_exp_bound() + 2 # at least p+3 places + while True: + coeff = _dlog(c, e, places) + # assert len(str(abs(coeff)))-p >= 1 + if coeff % (5*10**(len(str(abs(coeff)))-p-1)): + break + places += 3 + ans = Decimal((int(coeff<0), list(map(int, str(abs(coeff)))), -places)) + + context = context._shallow_copy() + rounding = context._set_rounding(ROUND_HALF_EVEN) + ans = ans._fix(context) + context.rounding = rounding + return ans + + def _log10_exp_bound(self): + """Compute a lower bound for the adjusted exponent of self.log10(). + In other words, find r such that self.log10() >= 10**r. + Assumes that self is finite and positive and that self != 1. + """ + + # For x >= 10 or x < 0.1 we only need a bound on the integer + # part of log10(self), and this comes directly from the + # exponent of x. For 0.1 <= x <= 10 we use the inequalities + # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| > + # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0 + + adj = self._exp + len(self._int) - 1 + if adj >= 1: + # self >= 10 + return len(str(adj))-1 + if adj <= -2: + # self < 0.1 + return len(str(-1-adj))-1 + op = _WorkRep(self) + c, e = op.int, op.exp + if adj == 0: + # 1 < self < 10 + num = str(c-10**-e) + den = str(231*c) + return len(num) - len(den) - (num < den) + 2 + # adj == -1, 0.1 <= self < 1 + num = str(10**-e-c) + return len(num) + e - (num < "231") - 1 + + def log10(self, context=None): + """Returns the base 10 logarithm of self.""" + + if context is None: + context = getcontext() + + # log10(NaN) = NaN + ans = self._check_nans(context=context) + if ans: + return ans + + # log10(0.0) == -Infinity + if not self: + return negInf + + # log10(Infinity) = Infinity + if self._isinfinity() == 1: + return Inf + + # log10(negative or -Infinity) raises InvalidOperation + if self._sign == 1: + return context._raise_error(InvalidOperation, + 'log10 of a negative value') + + # log10(10**n) = n + if self._int[0] == 1 and self._int[1:] == (0,)*(len(self._int) - 1): + # answer may need rounding + ans = Decimal(self._exp + len(self._int) - 1) + else: + # result is irrational, so necessarily inexact + op = _WorkRep(self) + c, e = op.int, op.exp + p = context.prec + + # correctly rounded result: repeatedly increase precision + # until result is unambiguously roundable + places = p-self._log10_exp_bound()+2 + while True: + coeff = _dlog10(c, e, places) + # assert len(str(abs(coeff)))-p >= 1 + if coeff % (5*10**(len(str(abs(coeff)))-p-1)): + break + places += 3 + ans = Decimal((int(coeff<0), list(map(int, str(abs(coeff)))), + -places)) + + context = context._shallow_copy() + rounding = context._set_rounding(ROUND_HALF_EVEN) + ans = ans._fix(context) + context.rounding = rounding + return ans + + def logb(self, context=None): + """ Returns the exponent of the magnitude of self's MSD. + + The result is the integer which is the exponent of the magnitude + of the most significant digit of self (as though it were truncated + to a single digit while maintaining the value of that digit and + without limiting the resulting exponent). + """ + # logb(NaN) = NaN + ans = self._check_nans(context=context) + if ans: + return ans + + if context is None: + context = getcontext() + + # logb(+/-Inf) = +Inf + if self._isinfinity(): + return Inf + + # logb(0) = -Inf, DivisionByZero + if not self: + return context._raise_error(DivisionByZero, 'logb(0)', 1) + + # otherwise, simply return the adjusted exponent of self, as a + # Decimal. Note that no attempt is made to fit the result + # into the current context. + return Decimal(self.adjusted()) + + def _islogical(self): + """Return True if self is a logical operand. + + For being logical, it must be a finite numbers with a sign of 0, + an exponent of 0, and a coefficient whose digits must all be + either 0 or 1. + """ + if self._sign != 0 or self._exp != 0: + return False + for dig in self._int: + if dig not in (0, 1): + return False + return True + + def _fill_logical(self, context, opa, opb): + dif = context.prec - len(opa) + if dif > 0: + opa = (0,)*dif + opa + elif dif < 0: + opa = opa[-context.prec:] + dif = context.prec - len(opb) + if dif > 0: + opb = (0,)*dif + opb + elif dif < 0: + opb = opb[-context.prec:] + return opa, opb + + def logical_and(self, other, context=None): + """Applies an 'and' operation between self and other's digits.""" + if context is None: + context = getcontext() + if not self._islogical() or not other._islogical(): + return context._raise_error(InvalidOperation) + + # fill to context.prec + (opa, opb) = self._fill_logical(context, self._int, other._int) + + # make the operation, and clean starting zeroes + result = [a&b for a,b in zip(opa,opb)] + for i,d in enumerate(result): + if d == 1: + break + result = tuple(result[i:]) + + # if empty, we must have at least a zero + if not result: + result = (0,) + return Decimal((0, result, 0)) + + def logical_invert(self, context=None): + """Invert all its digits.""" + if context is None: + context = getcontext() + return self.logical_xor(Decimal((0,(1,)*context.prec,0)), context) + + def logical_or(self, other, context=None): + """Applies an 'or' operation between self and other's digits.""" + if context is None: + context = getcontext() + if not self._islogical() or not other._islogical(): + return context._raise_error(InvalidOperation) + + # fill to context.prec + (opa, opb) = self._fill_logical(context, self._int, other._int) + + # make the operation, and clean starting zeroes + result = [a|b for a,b in zip(opa,opb)] + for i,d in enumerate(result): + if d == 1: + break + result = tuple(result[i:]) + + # if empty, we must have at least a zero + if not result: + result = (0,) + return Decimal((0, result, 0)) + + def logical_xor(self, other, context=None): + """Applies an 'xor' operation between self and other's digits.""" + if context is None: + context = getcontext() + if not self._islogical() or not other._islogical(): + return context._raise_error(InvalidOperation) + + # fill to context.prec + (opa, opb) = self._fill_logical(context, self._int, other._int) + + # make the operation, and clean starting zeroes + result = [a^b for a,b in zip(opa,opb)] + for i,d in enumerate(result): + if d == 1: + break + result = tuple(result[i:]) + + # if empty, we must have at least a zero + if not result: + result = (0,) + return Decimal((0, result, 0)) + + def max_mag(self, other, context=None): + """Compares the values numerically with their sign ignored.""" + other = _convert_other(other, raiseit=True) + + if context is None: + context = getcontext() + + if self._is_special or other._is_special: + # If one operand is a quiet NaN and the other is number, then the + # number is always returned + sn = self._isnan() + on = other._isnan() + if sn or on: + if on == 1 and sn != 2: + return self._fix_nan(context) + if sn == 1 and on != 2: + return other._fix_nan(context) + return self._check_nans(other, context) + + c = self.copy_abs().__cmp__(other.copy_abs()) + if c == 0: + c = self.compare_total(other) + + if c == -1: + ans = other + else: + ans = self + + if context._rounding_decision == ALWAYS_ROUND: + return ans._fix(context) + return ans + + def min_mag(self, other, context=None): + """Compares the values numerically with their sign ignored.""" + other = _convert_other(other, raiseit=True) + + if context is None: + context = getcontext() + + if self._is_special or other._is_special: + # If one operand is a quiet NaN and the other is number, then the + # number is always returned + sn = self._isnan() + on = other._isnan() + if sn or on: + if on == 1 and sn != 2: + return self._fix_nan(context) + if sn == 1 and on != 2: + return other._fix_nan(context) + return self._check_nans(other, context) + + c = self.copy_abs().__cmp__(other.copy_abs()) + if c == 0: + c = self.compare_total(other) + + if c == -1: + ans = self + else: + ans = other + + if context._rounding_decision == ALWAYS_ROUND: + return ans._fix(context) + return ans + + def next_minus(self, context=None): + """Returns the largest representable number smaller than itself.""" + if context is None: + context = getcontext() + + ans = self._check_nans(context=context) + if ans: + return ans + + if self._isinfinity() == -1: + return negInf + if self._isinfinity() == 1: + return Decimal((0, (9,)*context.prec, context.Etop())) + + context = context.copy() + context._set_rounding(ROUND_FLOOR) + context._ignore_all_flags() + new_self = self._fix(context) + if new_self != self: + return new_self + return self.__sub__(Decimal((0, (1,), context.Etiny()-1)), context) + + def next_plus(self, context=None): + """Returns the smallest representable number larger than itself.""" + if context is None: + context = getcontext() + + ans = self._check_nans(context=context) + if ans: + return ans + + if self._isinfinity() == 1: + return Inf + if self._isinfinity() == -1: + return Decimal((1, (9,)*context.prec, context.Etop())) + + context = context.copy() + context._set_rounding(ROUND_CEILING) + context._ignore_all_flags() + new_self = self._fix(context) + if new_self != self: + return new_self + return self.__add__(Decimal((0, (1,), context.Etiny()-1)), context) + + def next_toward(self, other, context=None): + """Returns the number closest to self, in the direction towards other. + + The result is the closest representable number to self + (excluding self) that is in the direction towards other, + unless both have the same value. If the two operands are + numerically equal, then the result is a copy of self with the + sign set to be the same as the sign of other. + """ + other = _convert_other(other, raiseit=True) + + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return ans + + comparison = self.__cmp__(other) + if comparison == 0: + return Decimal((other._sign, self._int, self._exp)) + + if comparison == -1: + ans = self.next_plus(context) + else: # comparison == 1 + ans = self.next_minus(context) + + # decide which flags to raise using value of ans + if ans._isinfinity(): + context._raise_error(Overflow, + 'Infinite result from next_toward', + ans._sign) + context._raise_error(Rounded) + context._raise_error(Inexact) + elif ans.adjusted() < context.Emin: + context._raise_error(Underflow) + context._raise_error(Subnormal) + context._raise_error(Rounded) + context._raise_error(Inexact) + # if precision == 1 then we don't raise Clamped for a + # result 0E-Etiny. + if not ans: + context._raise_error(Clamped) + + return ans + + def number_class(self, context=None): + """Returns an indication of the class of self. + + The class is one of the following strings: + -sNaN + -NaN + -Infinity + -Normal + -Subnormal + -Zero + +Zero + +Subnormal + +Normal + +Infinity + """ + if self.is_snan(): + return "sNaN" + if self.is_qnan(): + return "NaN" + inf = self._isinfinity() + if inf == 1: + return "+Infinity" + if inf == -1: + return "-Infinity" + if self.is_zero(): + if self._sign: + return "-Zero" + else: + return "+Zero" + if context is None: + context = getcontext() + if self.is_subnormal(context=context): + if self._sign: + return "-Subnormal" + else: + return "+Subnormal" + # just a normal, regular, boring number, :) + if self._sign: + return "-Normal" + else: + return "+Normal" + + def radix(self): + """Just returns 10, as this is Decimal, :)""" + return Decimal(10) + + def rotate(self, other, context=None): + """Returns a rotated copy of self, value-of-other times.""" + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return ans + + if other._exp != 0: + return context._raise_error(InvalidOperation) + if not (-context.prec <= int(other) <= context.prec): + return context._raise_error(InvalidOperation) + + if self._isinfinity(): + return Decimal(self) + + # get values, pad if necessary + torot = int(other) + rotdig = self._int + topad = context.prec - len(rotdig) + if topad: + rotdig = ((0,)*topad) + rotdig + + # let's rotate! + rotated = rotdig[torot:] + rotdig[:torot] + + # clean starting zeroes + for i,d in enumerate(rotated): + if d != 0: + break + rotated = rotated[i:] + + return Decimal((self._sign, rotated, self._exp)) + + + def scaleb (self, other, context=None): + """Returns self operand after adding the second value to its exp.""" + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return ans + + if other._exp != 0: + return context._raise_error(InvalidOperation) + liminf = -2 * (context.Emax + context.prec) + limsup = 2 * (context.Emax + context.prec) + if not (liminf <= int(other) <= limsup): + return context._raise_error(InvalidOperation) + + if self._isinfinity(): + return Decimal(self) + + d = Decimal((self._sign, self._int, self._exp + int(other))) + d = d._fix(context) + return d + + def shift(self, other, context=None): + """Returns a shifted copy of self, value-of-other times.""" + if context is None: + context = getcontext() + + ans = self._check_nans(other, context) + if ans: + return ans + + if other._exp != 0: + return context._raise_error(InvalidOperation) + if not (-context.prec <= int(other) <= context.prec): + return context._raise_error(InvalidOperation) + + if self._isinfinity(): + return Decimal(self) + + # get values, pad if necessary + torot = int(other) + if not torot: + return Decimal(self) + rotdig = self._int + topad = context.prec - len(rotdig) + if topad: + rotdig = ((0,)*topad) + rotdig + + # let's shift! + if torot < 0: + rotated = rotdig[:torot] + else: + rotated = (rotdig + ((0,) * torot)) + rotated = rotated[-context.prec:] + + # clean starting zeroes + if rotated: + for i,d in enumerate(rotated): + if d != 0: + break + rotated = rotated[i:] + else: + rotated = (0,) + + return Decimal((self._sign, rotated, self._exp)) + + # Support for pickling, copy, and deepcopy def __reduce__(self): return (self.__class__, (str(self),)) @@ -2426,6 +3623,9 @@ def create_decimal(self, num='0'): """Creates a new Decimal instance but using self as context.""" d = Decimal(num, context=self) + if d._isnan() and len(d._int) > self.prec - self._clamp: + return self._raise_error(ConversionSyntax, + "diagnostic info too long in NaN") return d._fix(self) # Methods @@ -2460,6 +3660,17 @@ def _apply(self, a): return str(a._fix(self)) + def canonical(self, a): + """Returns the same Decimal object. + + As we do not have different encodings for the same number, the + received object already is in its canonical form. + + >>> ExtendedContext.canonical(Decimal('2.50')) + Decimal("2.50") + """ + return a.canonical(context=self) + def compare(self, a, b): """Compares values numerically. @@ -2489,6 +3700,110 @@ """ return a.compare(b, context=self) + def compare_signal(self, a, b): + """Compares the values of the two operands numerically. + + It's pretty much like compare(), but all NaNs signal, with signaling + NaNs taking precedence over quiet NaNs. + + >>> c = ExtendedContext + >>> c.compare_signal(Decimal('2.1'), Decimal('3')) + Decimal("-1") + >>> c.compare_signal(Decimal('2.1'), Decimal('2.1')) + Decimal("0") + >>> c.flags[InvalidOperation] = 0 + >>> print(c.flags[InvalidOperation]) + 0 + >>> c.compare_signal(Decimal('NaN'), Decimal('2.1')) + Decimal("NaN") + >>> print(c.flags[InvalidOperation]) + 1 + >>> c.flags[InvalidOperation] = 0 + >>> print(c.flags[InvalidOperation]) + 0 + >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1')) + Decimal("NaN") + >>> print(c.flags[InvalidOperation]) + 1 + """ + return a.compare_signal(b, context=self) + + def compare_total(self, a, b): + """Compares two operands using their abstract representation. + + This is not like the standard compare, which use their numerical + value. Note that a total ordering is defined for all possible abstract + representations. + + >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) + Decimal("-1") + >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) + Decimal("-1") + >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) + Decimal("-1") + >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) + Decimal("0") + >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) + Decimal("1") + >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) + Decimal("-1") + """ + return a.compare_total(b) + + def compare_total_mag(self, a, b): + """Compares two operands using their abstract representation ignoring sign. + + Like compare_total, but with operand's sign ignored and assumed to be 0. + """ + return a.compare_total_mag(b) + + def copy_abs(self, a): + """Returns a copy of the operand with the sign set to 0. + + >>> ExtendedContext.copy_abs(Decimal('2.1')) + Decimal("2.1") + >>> ExtendedContext.copy_abs(Decimal('-100')) + Decimal("100") + """ + return a.copy_abs() + + def copy_decimal(self, a): + """Returns a copy of the decimal objet. + + >>> ExtendedContext.copy_decimal(Decimal('2.1')) + Decimal("2.1") + >>> ExtendedContext.copy_decimal(Decimal('-1.00')) + Decimal("-1.00") + """ + return Decimal(a) + + def copy_negate(self, a): + """Returns a copy of the operand with the sign inverted. + + >>> ExtendedContext.copy_negate(Decimal('101.5')) + Decimal("-101.5") + >>> ExtendedContext.copy_negate(Decimal('-101.5')) + Decimal("101.5") + """ + return a.copy_negate() + + def copy_sign(self, a, b): + """Copies the second operand's sign to the first one. + + In detail, it returns a copy of the first operand with the sign + equal to the sign of the second operand. + + >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33')) + Decimal("1.50") + >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33')) + Decimal("1.50") + >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33')) + Decimal("-1.50") + >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33')) + Decimal("-1.50") + """ + return a.copy_sign(b) + def divide(self, a, b): """Decimal division in a specified context. @@ -2530,6 +3845,316 @@ def divmod(self, a, b): return a.__divmod__(b, context=self) + def exp(self, a): + """Returns e ** a. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.exp(Decimal('-Infinity')) + Decimal("0") + >>> c.exp(Decimal('-1')) + Decimal("0.367879441") + >>> c.exp(Decimal('0')) + Decimal("1") + >>> c.exp(Decimal('1')) + Decimal("2.71828183") + >>> c.exp(Decimal('0.693147181')) + Decimal("2.00000000") + >>> c.exp(Decimal('+Infinity')) + Decimal("Infinity") + """ + return a.exp(context=self) + + def fma(self, a, b, c): + """Returns a multiplied by b, plus c. + + The first two operands are multiplied together, using multiply, + the third operand is then added to the result of that + multiplication, using add, all with only one final rounding. + + >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7')) + Decimal("22") + >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7')) + Decimal("-8") + >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578')) + Decimal("1.38435736E+12") + """ + return a.fma(b, c, context=self) + + def is_canonical(self, a): + """Returns 1 if the operand is canonical; otherwise returns 0. + + >>> ExtendedContext.is_canonical(Decimal('2.50')) + Decimal("1") + """ + return Dec_p1 + + def is_finite(self, a): + """Returns 1 if the operand is finite, otherwise returns 0. + + For it to be finite, it must be neither infinite nor a NaN. + + >>> ExtendedContext.is_finite(Decimal('2.50')) + Decimal("1") + >>> ExtendedContext.is_finite(Decimal('-0.3')) + Decimal("1") + >>> ExtendedContext.is_finite(Decimal('0')) + Decimal("1") + >>> ExtendedContext.is_finite(Decimal('Inf')) + Decimal("0") + >>> ExtendedContext.is_finite(Decimal('NaN')) + Decimal("0") + """ + return a.is_finite() + + def is_infinite(self, a): + """Returns 1 if the operand is an Infinite, otherwise returns 0. + + >>> ExtendedContext.is_infinite(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.is_infinite(Decimal('-Inf')) + Decimal("1") + >>> ExtendedContext.is_infinite(Decimal('NaN')) + Decimal("0") + """ + return a.is_infinite() + + def is_nan(self, a): + """Returns 1 if the operand is qNaN or sNaN, otherwise returns 0. + + >>> ExtendedContext.is_nan(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.is_nan(Decimal('NaN')) + Decimal("1") + >>> ExtendedContext.is_nan(Decimal('-sNaN')) + Decimal("1") + """ + return a.is_nan() + + def is_normal(self, a): + """Returns 1 if the operand is a normal number, otherwise returns 0. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.is_normal(Decimal('2.50')) + Decimal("1") + >>> c.is_normal(Decimal('0.1E-999')) + Decimal("0") + >>> c.is_normal(Decimal('0.00')) + Decimal("0") + >>> c.is_normal(Decimal('-Inf')) + Decimal("0") + >>> c.is_normal(Decimal('NaN')) + Decimal("0") + """ + return a.is_normal(context=self) + + def is_qnan(self, a): + """Returns 1 if the operand is a quiet NaN, otherwise returns 0. + + >>> ExtendedContext.is_qnan(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.is_qnan(Decimal('NaN')) + Decimal("1") + >>> ExtendedContext.is_qnan(Decimal('sNaN')) + Decimal("0") + """ + return a.is_qnan() + + def is_signed(self, a): + """Returns 1 if the operand is negative, otherwise returns 0. + + >>> ExtendedContext.is_signed(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.is_signed(Decimal('-12')) + Decimal("1") + >>> ExtendedContext.is_signed(Decimal('-0')) + Decimal("1") + """ + return a.is_signed() + + def is_snan(self, a): + """Returns 1 if the operand is a signaling NaN, otherwise returns 0. + + >>> ExtendedContext.is_snan(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.is_snan(Decimal('NaN')) + Decimal("0") + >>> ExtendedContext.is_snan(Decimal('sNaN')) + Decimal("1") + """ + return a.is_snan() + + def is_subnormal(self, a): + """Returns 1 if the operand is subnormal, otherwise returns 0. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.is_subnormal(Decimal('2.50')) + Decimal("0") + >>> c.is_subnormal(Decimal('0.1E-999')) + Decimal("1") + >>> c.is_subnormal(Decimal('0.00')) + Decimal("0") + >>> c.is_subnormal(Decimal('-Inf')) + Decimal("0") + >>> c.is_subnormal(Decimal('NaN')) + Decimal("0") + """ + return a.is_subnormal(context=self) + + def is_zero(self, a): + """Returns 1 if the operand is a zero, otherwise returns 0. + + >>> ExtendedContext.is_zero(Decimal('0')) + Decimal("1") + >>> ExtendedContext.is_zero(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.is_zero(Decimal('-0E+2')) + Decimal("1") + """ + return a.is_zero() + + def ln(self, a): + """Returns the natural (base e) logarithm of the operand. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.ln(Decimal('0')) + Decimal("-Infinity") + >>> c.ln(Decimal('1.000')) + Decimal("0") + >>> c.ln(Decimal('2.71828183')) + Decimal("1.00000000") + >>> c.ln(Decimal('10')) + Decimal("2.30258509") + >>> c.ln(Decimal('+Infinity')) + Decimal("Infinity") + """ + return a.ln(context=self) + + def log10(self, a): + """Returns the base 10 logarithm of the operand. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.log10(Decimal('0')) + Decimal("-Infinity") + >>> c.log10(Decimal('0.001')) + Decimal("-3") + >>> c.log10(Decimal('1.000')) + Decimal("0") + >>> c.log10(Decimal('2')) + Decimal("0.301029996") + >>> c.log10(Decimal('10')) + Decimal("1") + >>> c.log10(Decimal('70')) + Decimal("1.84509804") + >>> c.log10(Decimal('+Infinity')) + Decimal("Infinity") + """ + return a.log10(context=self) + + def logb(self, a): + """ Returns the exponent of the magnitude of the operand's MSD. + + The result is the integer which is the exponent of the magnitude + of the most significant digit of the operand (as though the + operand were truncated to a single digit while maintaining the + value of that digit and without limiting the resulting exponent). + + >>> ExtendedContext.logb(Decimal('250')) + Decimal("2") + >>> ExtendedContext.logb(Decimal('2.50')) + Decimal("0") + >>> ExtendedContext.logb(Decimal('0.03')) + Decimal("-2") + >>> ExtendedContext.logb(Decimal('0')) + Decimal("-Infinity") + """ + return a.logb(context=self) + + def logical_and(self, a, b): + """Applies the logical operation 'and' between each operand's digits. + + The operands must be both logical numbers. + + >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0')) + Decimal("0") + >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1')) + Decimal("0") + >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0')) + Decimal("0") + >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1')) + Decimal("1") + >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010')) + Decimal("1000") + >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10')) + Decimal("10") + """ + return a.logical_and(b, context=self) + + def logical_invert(self, a): + """Invert all the digits in the operand. + + The operand must be a logical number. + + >>> ExtendedContext.logical_invert(Decimal('0')) + Decimal("111111111") + >>> ExtendedContext.logical_invert(Decimal('1')) + Decimal("111111110") + >>> ExtendedContext.logical_invert(Decimal('111111111')) + Decimal("0") + >>> ExtendedContext.logical_invert(Decimal('101010101')) + Decimal("10101010") + """ + return a.logical_invert(context=self) + + def logical_or(self, a, b): + """Applies the logical operation 'or' between each operand's digits. + + The operands must be both logical numbers. + + >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0')) + Decimal("0") + >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1')) + Decimal("1") + >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0')) + Decimal("1") + >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1')) + Decimal("1") + >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010')) + Decimal("1110") + >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10')) + Decimal("1110") + """ + return a.logical_or(b, context=self) + + def logical_xor(self, a, b): + """Applies the logical operation 'xor' between each operand's digits. + + The operands must be both logical numbers. + + >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0')) + Decimal("0") + >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1')) + Decimal("1") + >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0')) + Decimal("1") + >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1')) + Decimal("0") + >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010')) + Decimal("110") + >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10')) + Decimal("1101") + """ + return a.logical_xor(b, context=self) + def max(self, a,b): """max compares two values numerically and returns the maximum. @@ -2550,6 +4175,10 @@ """ return a.max(b, context=self) + def max_mag(self, a, b): + """Compares the values numerically with their sign ignored.""" + return a.max_mag(b, context=self) + def min(self, a,b): """min compares two values numerically and returns the minimum. @@ -2570,6 +4199,10 @@ """ return a.min(b, context=self) + def min_mag(self, a, b): + """Compares the values numerically with their sign ignored.""" + return a.min_mag(b, context=self) + def minus(self, a): """Minus corresponds to unary prefix minus in Python. @@ -2605,6 +4238,68 @@ """ return a.__mul__(b, context=self) + def next_minus(self, a): + """Returns the largest representable number smaller than a. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> ExtendedContext.next_minus(Decimal('1')) + Decimal("0.999999999") + >>> c.next_minus(Decimal('1E-1007')) + Decimal("0E-1007") + >>> ExtendedContext.next_minus(Decimal('-1.00000003')) + Decimal("-1.00000004") + >>> c.next_minus(Decimal('Infinity')) + Decimal("9.99999999E+999") + """ + return a.next_minus(context=self) + + def next_plus(self, a): + """Returns the smallest representable number larger than a. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> ExtendedContext.next_plus(Decimal('1')) + Decimal("1.00000001") + >>> c.next_plus(Decimal('-1E-1007')) + Decimal("-0E-1007") + >>> ExtendedContext.next_plus(Decimal('-1.00000003')) + Decimal("-1.00000002") + >>> c.next_plus(Decimal('-Infinity')) + Decimal("-9.99999999E+999") + """ + return a.next_plus(context=self) + + def next_toward(self, a, b): + """Returns the number closest to a, in direction towards b. + + The result is the closest representable number from the first + operand (but not the first operand) that is in the direction + towards the second operand, unless the operands have the same + value. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.next_toward(Decimal('1'), Decimal('2')) + Decimal("1.00000001") + >>> c.next_toward(Decimal('-1E-1007'), Decimal('1')) + Decimal("-0E-1007") + >>> c.next_toward(Decimal('-1.00000003'), Decimal('0')) + Decimal("-1.00000002") + >>> c.next_toward(Decimal('1'), Decimal('0')) + Decimal("0.999999999") + >>> c.next_toward(Decimal('1E-1007'), Decimal('-100')) + Decimal("0E-1007") + >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10')) + Decimal("-1.00000004") + >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000')) + Decimal("-0.00") + """ + return a.next_toward(b, context=self) + def normalize(self, a): """normalize reduces an operand to its simplest form. @@ -2626,6 +4321,53 @@ """ return a.normalize(context=self) + def number_class(self, a): + """Returns an indication of the class of the operand. + + The class is one of the following strings: + -sNaN + -NaN + -Infinity + -Normal + -Subnormal + -Zero + +Zero + +Subnormal + +Normal + +Infinity + + >>> c = Context(ExtendedContext) + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.number_class(Decimal('Infinity')) + '+Infinity' + >>> c.number_class(Decimal('1E-10')) + '+Normal' + >>> c.number_class(Decimal('2.50')) + '+Normal' + >>> c.number_class(Decimal('0.1E-999')) + '+Subnormal' + >>> c.number_class(Decimal('0')) + '+Zero' + >>> c.number_class(Decimal('-0')) + '-Zero' + >>> c.number_class(Decimal('-0.1E-999')) + '-Subnormal' + >>> c.number_class(Decimal('-1E-10')) + '-Normal' + >>> c.number_class(Decimal('-2.50')) + '-Normal' + >>> c.number_class(Decimal('-Infinity')) + '-Infinity' + >>> c.number_class(Decimal('NaN')) + 'NaN' + >>> c.number_class(Decimal('-NaN')) + 'NaN' + >>> c.number_class(Decimal('sNaN')) + 'sNaN' + """ + return a.number_class(context=self) + def plus(self, a): """Plus corresponds to unary prefix plus in Python. @@ -2643,49 +4385,69 @@ def power(self, a, b, modulo=None): """Raises a to the power of b, to modulo if given. - The right-hand operand must be a whole number whose integer part (after - any exponent has been applied) has no more than 9 digits and whose - fractional part (if any) is all zeros before any rounding. The operand - may be positive, negative, or zero; if negative, the absolute value of - the power is used, and the left-hand operand is inverted (divided into - 1) before use. - - If the increased precision needed for the intermediate calculations - exceeds the capabilities of the implementation then an Invalid - operation condition is raised. - - If, when raising to a negative power, an underflow occurs during the - division into 1, the operation is not halted at that point but - continues. - - >>> ExtendedContext.power(Decimal('2'), Decimal('3')) + With two arguments, compute a**b. If a is negative then b + must be integral. The result will be inexact unless b is + integral and the result is finite and can be expressed exactly + in 'precision' digits. + + With three arguments, compute (a**b) % modulo. For the + three argument form, the following restrictions on the + arguments hold: + + - all three arguments must be integral + - b must be nonnegative + - at least one of a or b must be nonzero + - modulo must be nonzero and have at most 'precision' digits + + The result of pow(a, b, modulo) is identical to the result + that would be obtained by computing (a**b) % modulo with + unbounded precision, but is computed more efficiently. It is + always exact. + + >>> c = ExtendedContext.copy() + >>> c.Emin = -999 + >>> c.Emax = 999 + >>> c.power(Decimal('2'), Decimal('3')) Decimal("8") - >>> ExtendedContext.power(Decimal('2'), Decimal('-3')) + >>> c.power(Decimal('-2'), Decimal('3')) + Decimal("-8") + >>> c.power(Decimal('2'), Decimal('-3')) Decimal("0.125") - >>> ExtendedContext.power(Decimal('1.7'), Decimal('8')) + >>> c.power(Decimal('1.7'), Decimal('8')) Decimal("69.7575744") - >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-2')) + >>> c.power(Decimal('10'), Decimal('0.301029996')) + Decimal("2.00000000") + >>> c.power(Decimal('Infinity'), Decimal('-1')) Decimal("0") - >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-1')) - Decimal("0") - >>> ExtendedContext.power(Decimal('Infinity'), Decimal('0')) + >>> c.power(Decimal('Infinity'), Decimal('0')) Decimal("1") - >>> ExtendedContext.power(Decimal('Infinity'), Decimal('1')) - Decimal("Infinity") - >>> ExtendedContext.power(Decimal('Infinity'), Decimal('2')) + >>> c.power(Decimal('Infinity'), Decimal('1')) Decimal("Infinity") - >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-2')) - Decimal("0") - >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-1')) + >>> c.power(Decimal('-Infinity'), Decimal('-1')) Decimal("-0") - >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('0')) + >>> c.power(Decimal('-Infinity'), Decimal('0')) Decimal("1") - >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('1')) + >>> c.power(Decimal('-Infinity'), Decimal('1')) Decimal("-Infinity") - >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('2')) + >>> c.power(Decimal('-Infinity'), Decimal('2')) Decimal("Infinity") - >>> ExtendedContext.power(Decimal('0'), Decimal('0')) + >>> c.power(Decimal('0'), Decimal('0')) Decimal("NaN") + + >>> c.power(Decimal('3'), Decimal('7'), Decimal('16')) + Decimal("11") + >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16')) + Decimal("-11") + >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16')) + Decimal("1") + >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16')) + Decimal("11") + >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789')) + Decimal("11729830") + >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729')) + Decimal("-0") + >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537')) + Decimal("1") """ return a.__pow__(b, modulo, context=self) @@ -2740,6 +4502,14 @@ """ return a.quantize(b, context=self) + def radix(self): + """Just returns 10, as this is Decimal, :) + + >>> ExtendedContext.radix() + Decimal("10") + """ + return Decimal(10) + def remainder(self, a, b): """Returns the remainder from integer division. @@ -2794,6 +4564,28 @@ """ return a.remainder_near(b, context=self) + def rotate(self, a, b): + """Returns a rotated copy of a, b times. + + The coefficient of the result is a rotated copy of the digits in + the coefficient of the first operand. The number of places of + rotation is taken from the absolute value of the second operand, + with the rotation being to the left if the second operand is + positive or to the right otherwise. + + >>> ExtendedContext.rotate(Decimal('34'), Decimal('8')) + Decimal("400000003") + >>> ExtendedContext.rotate(Decimal('12'), Decimal('9')) + Decimal("12") + >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2')) + Decimal("891234567") + >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0')) + Decimal("123456789") + >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2')) + Decimal("345678912") + """ + return a.rotate(b, context=self) + def same_quantum(self, a, b): """Returns True if the two operands have the same exponent. @@ -2811,6 +4603,41 @@ """ return a.same_quantum(b) + def scaleb (self, a, b): + """Returns the first operand after adding the second value its exp. + + >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2')) + Decimal("0.0750") + >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0')) + Decimal("7.50") + >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3')) + Decimal("7.50E+3") + """ + return a.scaleb (b, context=self) + + def shift(self, a, b): + """Returns a shifted copy of a, b times. + + The coefficient of the result is a shifted copy of the digits + in the coefficient of the first operand. The number of places + to shift is taken from the absolute value of the second operand, + with the shift being to the left if the second operand is + positive or to the right otherwise. Digits shifted into the + coefficient are zeros. + + >>> ExtendedContext.shift(Decimal('34'), Decimal('8')) + Decimal("400000000") + >>> ExtendedContext.shift(Decimal('12'), Decimal('9')) + Decimal("0") + >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2')) + Decimal("1234567") + >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0')) + Decimal("123456789") + >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2')) + Decimal("345678900") + """ + return a.shift(b, context=self) + def sqrt(self, a): """Square root of a non-negative number to context precision. @@ -2866,7 +4693,36 @@ """ return a.__str__(context=self) - def to_integral(self, a): + def to_integral_exact(self, a): + """Rounds to an integer. + + When the operand has a negative exponent, the result is the same + as using the quantize() operation using the given operand as the + left-hand-operand, 1E+0 as the right-hand-operand, and the precision + of the operand as the precision setting; Inexact and Rounded flags + are allowed in this operation. The rounding mode is taken from the + context. + + >>> ExtendedContext.to_integral_exact(Decimal('2.1')) + Decimal("2") + >>> ExtendedContext.to_integral_exact(Decimal('100')) + Decimal("100") + >>> ExtendedContext.to_integral_exact(Decimal('100.0')) + Decimal("100") + >>> ExtendedContext.to_integral_exact(Decimal('101.5')) + Decimal("102") + >>> ExtendedContext.to_integral_exact(Decimal('-101.5')) + Decimal("-102") + >>> ExtendedContext.to_integral_exact(Decimal('10E+5')) + Decimal("1.0E+6") + >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77')) + Decimal("7.89E+77") + >>> ExtendedContext.to_integral_exact(Decimal('-Inf')) + Decimal("-Infinity") + """ + return a.to_integral_exact(context=self) + + def to_integral_value(self, a): """Rounds to an integer. When the operand has a negative exponent, the result is the same @@ -2875,29 +4731,32 @@ of the operand as the precision setting, except that no flags will be set. The rounding mode is taken from the context. - >>> ExtendedContext.to_integral(Decimal('2.1')) + >>> ExtendedContext.to_integral_value(Decimal('2.1')) Decimal("2") - >>> ExtendedContext.to_integral(Decimal('100')) + >>> ExtendedContext.to_integral_value(Decimal('100')) Decimal("100") - >>> ExtendedContext.to_integral(Decimal('100.0')) + >>> ExtendedContext.to_integral_value(Decimal('100.0')) Decimal("100") - >>> ExtendedContext.to_integral(Decimal('101.5')) + >>> ExtendedContext.to_integral_value(Decimal('101.5')) Decimal("102") - >>> ExtendedContext.to_integral(Decimal('-101.5')) + >>> ExtendedContext.to_integral_value(Decimal('-101.5')) Decimal("-102") - >>> ExtendedContext.to_integral(Decimal('10E+5')) + >>> ExtendedContext.to_integral_value(Decimal('10E+5')) Decimal("1.0E+6") - >>> ExtendedContext.to_integral(Decimal('7.89E+77')) + >>> ExtendedContext.to_integral_value(Decimal('7.89E+77')) Decimal("7.89E+77") - >>> ExtendedContext.to_integral(Decimal('-Inf')) + >>> ExtendedContext.to_integral_value(Decimal('-Inf')) Decimal("-Infinity") """ - return a.to_integral(context=self) + return a.to_integral_value(context=self) + + # the method name changed, but we provide also the old one, for compatibility + to_integral = to_integral_value class _WorkRep(object): __slots__ = ('sign','int','exp') # sign: 0 or 1 - # int: int or long + # int: int # exp: None, int, or string def __init__(self, value=None): @@ -2930,66 +4789,338 @@ Done during addition. """ - # Yes, the exponent is a long, but the difference between exponents - # must be an int-- otherwise you'd get a big memory problem. - numdigits = int(op1.exp - op2.exp) - if numdigits < 0: - numdigits = -numdigits + if op1.exp < op2.exp: tmp = op2 other = op1 else: tmp = op1 other = op2 - - if shouldround and numdigits > prec + 1: - # Big difference in exponents - check the adjusted exponents + # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1). + # Then adding 10**exp to tmp has the same effect (after rounding) + # as adding any positive quantity smaller than 10**exp; similarly + # for subtraction. So if other is smaller than 10**exp we replace + # it with 10**exp. This avoids tmp.exp - other.exp getting too large. + if shouldround: tmp_len = len(str(tmp.int)) other_len = len(str(other.int)) - if numdigits > (other_len + prec + 1 - tmp_len): - # If the difference in adjusted exps is > prec+1, we know - # other is insignificant, so might as well put a 1 after the - # precision (since this is only for addition). Also stops - # use of massive longs. - - extend = prec + 2 - tmp_len - if extend <= 0: - extend = 1 - tmp.int *= 10 ** extend - tmp.exp -= extend + exp = tmp.exp + min(-1, tmp_len - prec - 2) + if other_len + other.exp - 1 < exp: other.int = 1 - other.exp = tmp.exp - return op1, op2 + other.exp = exp - tmp.int *= 10 ** numdigits - tmp.exp -= numdigits + tmp.int *= 10 ** (tmp.exp - other.exp) + tmp.exp = other.exp return op1, op2 -def _adjust_coefficients(op1, op2): - """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int. +##### Integer arithmetic functions used by ln, log10, exp and __pow__ ##### + +# This function from Tim Peters was taken from here: +# http://mail.python.org/pipermail/python-list/1999-July/007758.html +# The correction being in the function definition is for speed, and +# the whole function is not resolved with math.log because of avoiding +# the use of floats. +def _nbits(n, correction = { + '0': 4, '1': 3, '2': 2, '3': 2, + '4': 1, '5': 1, '6': 1, '7': 1, + '8': 0, '9': 0, 'a': 0, 'b': 0, + 'c': 0, 'd': 0, 'e': 0, 'f': 0}): + """Number of bits in binary representation of the positive integer n, + or 0 if n == 0. + """ + if n < 0: + raise ValueError("The argument to _nbits should be nonnegative.") + hex_n = "%x" % n + return 4*len(hex_n) - correction[hex_n[0]] + +def _sqrt_nearest(n, a): + """Closest integer to the square root of the positive integer n. a is + an initial approximation to the square root. Any positive integer + will do for a, but the closer a is to the square root of n the + faster convergence will be. + + """ + if n <= 0 or a <= 0: + raise ValueError("Both arguments to _sqrt_nearest should be positive.") + + b=0 + while a != b: + b, a = a, a--n//a>>1 + return a + +def _rshift_nearest(x, shift): + """Given an integer x and a nonnegative integer shift, return closest + integer to x / 2**shift; use round-to-even in case of a tie. + + """ + b, q = 1 << shift, x >> shift + return q + (2*(x & (b-1)) + (q&1) > b) + +def _div_nearest(a, b): + """Closest integer to a/b, a and b positive integers; rounds to even + in the case of a tie. - Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp. + """ + q, r = divmod(a, b) + return q + (2*r + (q&1) > b) + +def _ilog(x, M, L = 8): + """Integer approximation to M*log(x/M), with absolute error boundable + in terms only of x/M. + + Given positive integers x and M, return an integer approximation to + M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference + between the approximation and the exact result is at most 22. For + L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In + both cases these are upper bounds on the error; it will usually be + much smaller.""" + + # The basic algorithm is the following: let log1p be the function + # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use + # the reduction + # + # log1p(y) = 2*log1p(y/(1+sqrt(1+y))) + # + # repeatedly until the argument to log1p is small (< 2**-L in + # absolute value). For small y we can use the Taylor series + # expansion + # + # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T + # + # truncating at T such that y**T is small enough. The whole + # computation is carried out in a form of fixed-point arithmetic, + # with a real number z being represented by an integer + # approximation to z*M. To avoid loss of precision, the y below + # is actually an integer approximation to 2**R*y*M, where R is the + # number of reductions performed so far. + + y = x-M + # argument reduction; R = number of reductions performed + R = 0 + while (R <= L and abs(y) << L-R >= M or + R > L and abs(y) >> R-L >= M): + y = _div_nearest((M*y) << 1, + M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M)) + R += 1 + + # Taylor series with T terms + T = -int(-10*len(str(M))//(3*L)) + yshift = _rshift_nearest(y, R) + w = _div_nearest(M, T) + for k in range(T-1, 0, -1): + w = _div_nearest(M, k) - _div_nearest(yshift*w, M) + + return _div_nearest(w*y, M) + +def _dlog10(c, e, p): + """Given integers c, e and p with c > 0, p >= 0, compute an integer + approximation to 10**p * log10(c*10**e), with an absolute error of + at most 1. Assumes that c*10**e is not exactly 1.""" + + # increase precision by 2; compensate for this by dividing + # final result by 100 + p += 2 + + # write c*10**e as d*10**f with either: + # f >= 0 and 1 <= d <= 10, or + # f <= 0 and 0.1 <= d <= 1. + # Thus for c*10**e close to 1, f = 0 + l = len(str(c)) + f = e+l - (e+l >= 1) + + if p > 0: + M = 10**p + k = e+p-f + if k >= 0: + c *= 10**k + else: + c = _div_nearest(c, 10**-k) + + log_d = _ilog(c, M) # error < 5 + 22 = 27 + log_10 = _ilog(10*M, M) # error < 15 + log_d = _div_nearest(log_d*M, log_10) + log_tenpower = f*M # exact + else: + log_d = 0 # error < 2.31 + log_tenpower = div_nearest(f, 10**-p) # error < 0.5 + + return _div_nearest(log_tenpower+log_d, 100) + +def _dlog(c, e, p): + """Given integers c, e and p with c > 0, compute an integer + approximation to 10**p * log(c*10**e), with an absolute error of + at most 1. Assumes that c*10**e is not exactly 1.""" + + # Increase precision by 2. The precision increase is compensated + # for at the end with a division by 100. + p += 2 + + # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10, + # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e) + # as 10**p * log(d) + 10**p*f * log(10). + l = len(str(c)) + f = e+l - (e+l >= 1) + + # compute approximation to 10**p*log(d), with error < 27 + if p > 0: + k = e+p-f + if k >= 0: + c *= 10**k + else: + c = _div_nearest(c, 10**-k) # error of <= 0.5 in c + + # _ilog magnifies existing error in c by a factor of at most 10 + log_d = _ilog(c, 10**p) # error < 5 + 22 = 27 + else: + # p <= 0: just approximate the whole thing by 0; error < 2.31 + log_d = 0 + + # compute approximation to 10**p*f*log(10), with error < 17 + if f: + sign_f = [-1, 1][f > 0] + if p >= 0: + M = 10**p * abs(f) + else: + M = _div_nearest(abs(f), 10**-p) # M = 10**p*|f|, error <= 0.5 + + if M: + f_log_ten = sign_f*_ilog(10*M, M) # M*log(10), error <= 1.2 + 15 < 17 + else: + f_log_ten = 0 + else: + f_log_ten = 0 + + # error in sum < 17+27 = 44; error after division < 0.44 + 0.5 < 1 + return _div_nearest(f_log_ten + log_d, 100) - Used on _WorkRep instances during division. +def _iexp(x, M, L=8): + """Given integers x and M, M > 0, such that x/M is small in absolute + value, compute an integer approximation to M*exp(x/M). For 0 <= + x/M <= 2.4, the absolute error in the result is bounded by 60 (and + is usually much smaller).""" + + # Algorithm: to compute exp(z) for a real number z, first divide z + # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then + # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor + # series + # + # expm1(x) = x + x**2/2! + x**3/3! + ... + # + # Now use the identity + # + # expm1(2x) = expm1(x)*(expm1(x)+2) + # + # R times to compute the sequence expm1(z/2**R), + # expm1(z/2**(R-1)), ... , exp(z/2), exp(z). + + # Find R such that x/2**R/M <= 2**-L + R = _nbits((x< M + T = -int(-10*len(str(M))//(3*L)) + y = _div_nearest(x, T) + Mshift = M<= 0: + cshift = c*10**shift + else: + cshift = c//10**-shift + quot, rem = divmod(cshift, log10) + + # reduce remainder back to original precision + rem = _div_nearest(rem, 10**extra) + + # error in result of _iexp < 120; error after division < 0.62 + return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3 + +def _dpower(xc, xe, yc, ye, p): + """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and + y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that: + + 10**(p-1) <= c <= 10**p, and + (c-1)*10**e < x**y < (c+1)*10**e + + in other words, c*10**e is an approximation to x**y with p digits + of precision, and with an error in c of at most 1. (This is + almost, but not quite, the same as the error being < 1ulp: when c + == 10**(p-1) we can only guarantee error < 10ulp.) + + We assume that: x is positive and not equal to 1, and y is nonzero. """ - adjust = 0 - # If op1 is smaller, make it larger - while op2.int > op1.int: - op1.int *= 10 - op1.exp -= 1 - adjust += 1 - - # If op2 is too small, make it larger - while op1.int >= (10 * op2.int): - op2.int *= 10 - op2.exp -= 1 - adjust -= 1 - return op1, op2, adjust + # Find b such that 10**(b-1) <= |y| <= 10**b + b = len(str(abs(yc))) + ye + + # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point + lxc = _dlog(xc, xe, p+b+1) + + # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1) + shift = ye-b + if shift >= 0: + pc = lxc*yc*10**shift + else: + pc = _div_nearest(lxc*yc, 10**-shift) + + if pc == 0: + # we prefer a result that isn't exactly 1; this makes it + # easier to compute a correctly rounded result in __pow__ + if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1: + coeff, exp = 10**(p-1)+1, 1-p + else: + coeff, exp = 10**p-1, -p + else: + coeff, exp = _dexp(pc, -(p+1), p+1) + coeff = _div_nearest(coeff, 10) + exp += 1 + + return coeff, exp + +def _log10_lb(c, correction = { + '1': 100, '2': 70, '3': 53, '4': 40, '5': 31, + '6': 23, '7': 16, '8': 10, '9': 5}): + """Compute a lower bound for 100*log10(c) for a positive integer c.""" + if c <= 0: + raise ValueError("The argument to _log10_lb should be nonnegative.") + str_c = str(c) + return 100*len(str_c) - correction[str_c[0]] ##### Helper Functions #################################################### -def _convert_other(other): +def _convert_other(other, raiseit=False): """Convert other to Decimal. Verifies that it's ok to use in an implicit construction. @@ -2998,6 +5129,8 @@ return other if isinstance(other, int): return Decimal(other) + if raiseit: + raise TypeError("Unable to convert %s to Decimal" % other) return NotImplemented _infinity_map = { @@ -3085,12 +5218,16 @@ # Reusable defaults Inf = Decimal('Inf') negInf = Decimal('-Inf') +NaN = Decimal('NaN') +Dec_0 = Decimal(0) +Dec_p1 = Decimal(1) +Dec_n1 = Decimal(-1) +Dec_p2 = Decimal(2) +Dec_n2 = Decimal(-2) # Infsign[sign] is infinity w/ that sign Infsign = (Inf, negInf) -NaN = Decimal('NaN') - ##### crud for parsing strings ############################################# import re Modified: python/branches/py3k-importlib/Lib/distutils/command/build_scripts.py ============================================================================== --- python/branches/py3k-importlib/Lib/distutils/command/build_scripts.py (original) +++ python/branches/py3k-importlib/Lib/distutils/command/build_scripts.py Fri Sep 21 03:17:09 2007 @@ -102,7 +102,8 @@ outf.write("#!%s%s\n" % (os.path.join( sysconfig.get_config_var("BINDIR"), - "python" + sysconfig.get_config_var("EXE")), + "python" + sysconfig.get_config_var("VERSION") + + sysconfig.get_config_var("EXE")), post_interp)) outf.writelines(f.readlines()) outf.close() Modified: python/branches/py3k-importlib/Lib/httplib.py ============================================================================== --- python/branches/py3k-importlib/Lib/httplib.py (original) +++ python/branches/py3k-importlib/Lib/httplib.py Fri Sep 21 03:17:09 2007 @@ -985,12 +985,12 @@ "Connect to a host on a given (SSL) port." sock = socket.create_connection((self.host, self.port), self.timeout) - self.sock = ssl.sslsocket(sock, self.key_file, self.cert_file) + self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file) def FakeSocket (sock, sslobj): warnings.warn("FakeSocket is deprecated, and won't be in 3.x. " + - "Use the result of ssl.sslsocket directly instead.", + "Use the result of ssl.wrap_socket() directly instead.", DeprecationWarning, stacklevel=2) return sslobj Modified: python/branches/py3k-importlib/Lib/imaplib.py ============================================================================== --- python/branches/py3k-importlib/Lib/imaplib.py (original) +++ python/branches/py3k-importlib/Lib/imaplib.py Fri Sep 21 03:17:09 2007 @@ -1147,7 +1147,7 @@ self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, port)) - self.sslobj = ssl.sslsocket(self.sock, self.keyfile, self.certfile) + self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile) def read(self, size): @@ -1199,7 +1199,7 @@ def ssl(self): """Return SSLObject instance used to communicate with the IMAP4 server. - ssl = ssl.sslsocket(.socket) + ssl = ssl.wrap_socket(.socket) """ return self.sslobj Modified: python/branches/py3k-importlib/Lib/platform.py ============================================================================== --- python/branches/py3k-importlib/Lib/platform.py (original) +++ python/branches/py3k-importlib/Lib/platform.py Fri Sep 21 03:17:09 2007 @@ -1142,6 +1142,12 @@ machine = '' if processor == 'unknown': processor = '' + + # normalize name + if system == 'Microsoft' and release == 'Windows': + system = 'Windows' + release = 'Vista' + _uname_cache = system,node,release,version,machine,processor return _uname_cache Modified: python/branches/py3k-importlib/Lib/poplib.py ============================================================================== --- python/branches/py3k-importlib/Lib/poplib.py (original) +++ python/branches/py3k-importlib/Lib/poplib.py Fri Sep 21 03:17:09 2007 @@ -348,7 +348,7 @@ if not self.sock: raise socket.error(msg) self.file = self.sock.makefile('rb') - self.sslobj = ssl.sslsocket(self.sock, self.keyfile, self.certfile) + self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile) self._debugging = 0 self.welcome = self._getresp() Modified: python/branches/py3k-importlib/Lib/repr.py ============================================================================== --- python/branches/py3k-importlib/Lib/repr.py (original) +++ python/branches/py3k-importlib/Lib/repr.py Fri Sep 21 03:17:09 2007 @@ -1,4 +1,4 @@ -"""Redo the `...` (representation) but with limits on most sizes.""" +"""Redo the builtin repr() (representation) but with limits on most sizes.""" __all__ = ["Repr","repr"] @@ -57,11 +57,11 @@ return self._repr_iterable(x, level, header, '])', self.maxarray) def repr_set(self, x, level): - x = sorted(x) + x = _possibly_sorted(x) return self._repr_iterable(x, level, 'set([', '])', self.maxset) def repr_frozenset(self, x, level): - x = sorted(x) + x = _possibly_sorted(x) return self._repr_iterable(x, level, 'frozenset([', '])', self.maxfrozenset) @@ -75,7 +75,7 @@ newlevel = level - 1 repr1 = self.repr1 pieces = [] - for key in islice(sorted(x), self.maxdict): + for key in islice(_possibly_sorted(x), self.maxdict): keyrepr = repr1(key, newlevel) valrepr = repr1(x[key], newlevel) pieces.append('%s: %s' % (keyrepr, valrepr)) @@ -105,7 +105,7 @@ s = __builtin__.repr(x) # Bugs in x.__repr__() can cause arbitrary # exceptions -- then make up something - except: + except Exception: return '<%s instance at %x>' % (x.__class__.__name__, id(x)) if len(s) > self.maxother: i = max(0, (self.maxother-3)//2) @@ -113,5 +113,15 @@ s = s[:i] + '...' + s[len(s)-j:] return s + +def _possibly_sorted(x): + # Since not all sequences of items can be sorted and comparison + # functions may raise arbitrary exceptions, return an unsorted + # sequence in that case. + try: + return sorted(x) + except Exception: + return list(x) + aRepr = Repr() repr = aRepr.repr Modified: python/branches/py3k-importlib/Lib/smtplib.py ============================================================================== --- python/branches/py3k-importlib/Lib/smtplib.py (original) +++ python/branches/py3k-importlib/Lib/smtplib.py Fri Sep 21 03:17:09 2007 @@ -588,7 +588,7 @@ if resp == 220: if not _have_ssl: raise RuntimeError("No SSL support included in this Python") - self.sock = ssl.sslsocket(self.sock, keyfile, certfile) + self.sock = ssl.wrap_socket(self.sock, keyfile, certfile) self.file = SSLFakeFile(self.sock) return (resp, reply) @@ -721,7 +721,7 @@ def _get_socket(self, host, port, timeout): if self.debuglevel > 0: print('connect:', (host, port), file=stderr) self.sock = socket.create_connection((host, port), timeout) - self.sock = ssl.sslsocket(self.sock, self.keyfile, self.certfile) + self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile) self.file = SSLFakeFile(self.sock) __all__.append("SMTP_SSL") Modified: python/branches/py3k-importlib/Lib/socket.py ============================================================================== --- python/branches/py3k-importlib/Lib/socket.py (original) +++ python/branches/py3k-importlib/Lib/socket.py Fri Sep 21 03:17:09 2007 @@ -56,13 +56,13 @@ def ssl(sock, keyfile=None, certfile=None): # we do an internal import here because the ssl # module imports the socket module - warnings.warn("socket.ssl() is deprecated. Use ssl.sslsocket() instead.", + warnings.warn("socket.ssl() is deprecated. Use ssl.wrap_socket() instead.", DeprecationWarning, stacklevel=2) return _realssl.sslwrap_simple(sock, keyfile, certfile) # we need to import the same constants we used to... + from _ssl import SSLError as sslerror from _ssl import \ - sslerror, \ RAND_add, \ RAND_egd, \ RAND_status, \ Modified: python/branches/py3k-importlib/Lib/ssl.py ============================================================================== --- python/branches/py3k-importlib/Lib/ssl.py (original) +++ python/branches/py3k-importlib/Lib/ssl.py Fri Sep 21 03:17:09 2007 @@ -8,11 +8,11 @@ Object types: - sslsocket -- subtype of socket.socket which does SSL over the socket + SSLSocket -- subtype of socket.socket which does SSL over the socket Exceptions: - sslerror -- exception raised for I/O errors + SSLError -- exception raised for I/O errors Functions: @@ -57,12 +57,14 @@ PROTOCOL_TLSv1 """ -import os, sys +import os, sys, textwrap import _ssl # if we can't import it, let the error propagate -from _ssl import sslerror + +from _ssl import SSLError from _ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED from _ssl import PROTOCOL_SSLv2, PROTOCOL_SSLv3, PROTOCOL_SSLv23, PROTOCOL_TLSv1 +from _ssl import RAND_status, RAND_egd, RAND_add from _ssl import \ SSL_ERROR_ZERO_RETURN, \ SSL_ERROR_WANT_READ, \ @@ -76,9 +78,9 @@ from socket import socket from socket import getnameinfo as _getnameinfo +import base64 # for DER-to-PEM translation - -class sslsocket (socket): +class SSLSocket (socket): """This class implements a subtype of socket.socket that wraps the underlying OS socket in an SSL context when necessary, and @@ -121,14 +123,21 @@ return self._sslobj.write(data) - def getpeercert(self): + def getpeercert(self, binary_form=False): """Returns a formatted version of the data in the certificate provided by the other end of the SSL channel. Return None if no certificate was provided, {} if a certificate was provided, but not validated.""" - return self._sslobj.peer_certificate() + return self._sslobj.peer_certificate(binary_form) + + def cipher (self): + + if not self._sslobj: + return None + else: + return self._sslobj.cipher() def send (self, data, flags=0): if self._sslobj: @@ -174,21 +183,12 @@ else: return socket.recv_from(self, addr, buflen, flags) - def ssl_shutdown(self): - - """Shuts down the SSL channel over this socket (if active), - without closing the socket connection.""" - - if self._sslobj: - self._sslobj.shutdown() - self._sslobj = None - def shutdown(self, how): - self.ssl_shutdown() + self._sslobj = None socket.shutdown(self, how) def close(self): - self.ssl_shutdown() + self._sslobj = None socket.close(self) def connect(self, addr): @@ -199,7 +199,7 @@ # Here we assume that the socket is client-side, and not # connected at the time of the call. We connect it, then wrap it. if self._sslobj: - raise ValueError("attempt to connect already-connected sslsocket!") + raise ValueError("attempt to connect already-connected SSLSocket!") socket.connect(self, addr) self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile, self.cert_reqs, self.ssl_version, @@ -212,11 +212,261 @@ SSL channel, and the address of the remote client.""" newsock, addr = socket.accept(self) - return (sslsocket(newsock, True, self.keyfile, self.certfile, - self.cert_reqs, self.ssl_version, - self.ca_certs), addr) + return (SSLSocket(newsock, True, self.keyfile, self.certfile, + self.cert_reqs, self.ssl_version, + self.ca_certs), addr) + def makefile(self, mode='r', bufsize=-1): + + """Ouch. Need to make and return a file-like object that + works with the SSL connection.""" + + if self._sslobj: + return SSLFileStream(self._sslobj, mode, bufsize) + else: + return socket.makefile(self, mode, bufsize) + + +class SSLFileStream: + + """A class to simulate a file stream on top of a socket. + Most of this is just lifted from the socket module, and + adjusted to work with an SSL stream instead of a socket.""" + + + default_bufsize = 8192 + name = "" + + __slots__ = ["mode", "bufsize", "softspace", + # "closed" is a property, see below + "_sslobj", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf", + "_close", "_fileno"] + + def __init__(self, sslobj, mode='rb', bufsize=-1, close=False): + self._sslobj = sslobj + self.mode = mode # Not actually used in this version + if bufsize < 0: + bufsize = self.default_bufsize + self.bufsize = bufsize + self.softspace = False + if bufsize == 0: + self._rbufsize = 1 + elif bufsize == 1: + self._rbufsize = self.default_bufsize + else: + self._rbufsize = bufsize + self._wbufsize = bufsize + self._rbuf = "" # A string + self._wbuf = [] # A list of strings + self._close = close + self._fileno = -1 + + def _getclosed(self): + return self._sslobj is None + closed = property(_getclosed, doc="True if the file is closed") + + def fileno(self): + return self._fileno + + def close(self): + try: + if self._sslobj: + self.flush() + finally: + if self._close and self._sslobj: + self._sslobj.close() + self._sslobj = None + + def __del__(self): + try: + self.close() + except: + # close() may fail if __init__ didn't complete + pass + + def flush(self): + if self._wbuf: + buffer = "".join(self._wbuf) + self._wbuf = [] + count = 0 + while (count < len(buffer)): + written = self._sslobj.write(buffer) + count += written + buffer = buffer[written:] + + def write(self, data): + data = str(data) # XXX Should really reject non-string non-buffers + if not data: + return + self._wbuf.append(data) + if (self._wbufsize == 0 or + self._wbufsize == 1 and '\n' in data or + self._get_wbuf_len() >= self._wbufsize): + self.flush() + + def writelines(self, list): + # XXX We could do better here for very long lists + # XXX Should really reject non-string non-buffers + self._wbuf.extend(filter(None, map(str, list))) + if (self._wbufsize <= 1 or + self._get_wbuf_len() >= self._wbufsize): + self.flush() + + def _get_wbuf_len(self): + buf_len = 0 + for x in self._wbuf: + buf_len += len(x) + return buf_len + + def read(self, size=-1): + data = self._rbuf + if size < 0: + # Read until EOF + buffers = [] + if data: + buffers.append(data) + self._rbuf = "" + if self._rbufsize <= 1: + recv_size = self.default_bufsize + else: + recv_size = self._rbufsize + while True: + data = self._sslobj.read(recv_size) + if not data: + break + buffers.append(data) + return "".join(buffers) + else: + # Read until size bytes or EOF seen, whichever comes first + buf_len = len(data) + if buf_len >= size: + self._rbuf = data[size:] + return data[:size] + buffers = [] + if data: + buffers.append(data) + self._rbuf = "" + while True: + left = size - buf_len + recv_size = max(self._rbufsize, left) + data = self._sslobj.read(recv_size) + if not data: + break + buffers.append(data) + n = len(data) + if n >= left: + self._rbuf = data[left:] + buffers[-1] = data[:left] + break + buf_len += n + return "".join(buffers) + + def readline(self, size=-1): + data = self._rbuf + if size < 0: + # Read until \n or EOF, whichever comes first + if self._rbufsize <= 1: + # Speed up unbuffered case + assert data == "" + buffers = [] + while data != "\n": + data = self._sslobj.read(1) + if not data: + break + buffers.append(data) + return "".join(buffers) + nl = data.find('\n') + if nl >= 0: + nl += 1 + self._rbuf = data[nl:] + return data[:nl] + buffers = [] + if data: + buffers.append(data) + self._rbuf = "" + while True: + data = self._sslobj.read(self._rbufsize) + if not data: + break + buffers.append(data) + nl = data.find('\n') + if nl >= 0: + nl += 1 + self._rbuf = data[nl:] + buffers[-1] = data[:nl] + break + return "".join(buffers) + else: + # Read until size bytes or \n or EOF seen, whichever comes first + nl = data.find('\n', 0, size) + if nl >= 0: + nl += 1 + self._rbuf = data[nl:] + return data[:nl] + buf_len = len(data) + if buf_len >= size: + self._rbuf = data[size:] + return data[:size] + buffers = [] + if data: + buffers.append(data) + self._rbuf = "" + while True: + data = self._sslobj.read(self._rbufsize) + if not data: + break + buffers.append(data) + left = size - buf_len + nl = data.find('\n', 0, left) + if nl >= 0: + nl += 1 + self._rbuf = data[nl:] + buffers[-1] = data[:nl] + break + n = len(data) + if n >= left: + self._rbuf = data[left:] + buffers[-1] = data[:left] + break + buf_len += n + return "".join(buffers) + + def readlines(self, sizehint=0): + total = 0 + list = [] + while True: + line = self.readline() + if not line: + break + list.append(line) + total += len(line) + if sizehint and total >= sizehint: + break + return list + + # Iterator protocols + + def __iter__(self): + return self + + def next(self): + line = self.readline() + if not line: + raise StopIteration + return line + + + + +def wrap_socket(sock, keyfile=None, certfile=None, + server_side=False, cert_reqs=CERT_NONE, + ssl_version=PROTOCOL_SSLv23, ca_certs=None): + + return SSLSocket(sock, keyfile=keyfile, certfile=certfile, + server_side=server_side, cert_reqs=cert_reqs, + ssl_version=ssl_version, ca_certs=ca_certs) + # some utility functions def cert_time_to_seconds(cert_time): @@ -228,6 +478,71 @@ import time return time.mktime(time.strptime(cert_time, "%b %d %H:%M:%S %Y GMT")) +PEM_HEADER = "-----BEGIN CERTIFICATE-----" +PEM_FOOTER = "-----END CERTIFICATE-----" + +def DER_cert_to_PEM_cert(der_cert_bytes): + + """Takes a certificate in binary DER format and returns the + PEM version of it as a string.""" + + if hasattr(base64, 'standard_b64encode'): + # preferred because older API gets line-length wrong + f = base64.standard_b64encode(der_cert_bytes) + return (PEM_HEADER + '\n' + + textwrap.fill(f, 64) + + PEM_FOOTER + '\n') + else: + return (PEM_HEADER + '\n' + + base64.encodestring(der_cert_bytes) + + PEM_FOOTER + '\n') + +def PEM_cert_to_DER_cert(pem_cert_string): + + """Takes a certificate in ASCII PEM format and returns the + DER-encoded version of it as a byte sequence""" + + if not pem_cert_string.startswith(PEM_HEADER): + raise ValueError("Invalid PEM encoding; must start with %s" + % PEM_HEADER) + if not pem_cert_string.strip().endswith(PEM_FOOTER): + raise ValueError("Invalid PEM encoding; must end with %s" + % PEM_FOOTER) + d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] + return base64.decodestring(d) + +def get_server_certificate (addr, ssl_version=PROTOCOL_SSLv3, ca_certs=None): + + """Retrieve the certificate from the server at the specified address, + and return it as a PEM-encoded string. + If 'ca_certs' is specified, validate the server cert against it. + If 'ssl_version' is specified, use it in the connection attempt.""" + + host, port = addr + if (ca_certs is not None): + cert_reqs = CERT_REQUIRED + else: + cert_reqs = CERT_NONE + s = wrap_socket(socket(), ssl_version=ssl_version, + cert_reqs=cert_reqs, ca_certs=ca_certs) + s.connect(addr) + dercert = s.getpeercert(True) + s.close() + return DER_cert_to_PEM_cert(dercert) + +def get_protocol_name (protocol_code): + if protocol_code == PROTOCOL_TLSv1: + return "TLSv1" + elif protocol_code == PROTOCOL_SSLv23: + return "SSLv23" + elif protocol_code == PROTOCOL_SSLv2: + return "SSLv2" + elif protocol_code == PROTOCOL_SSLv3: + return "SSLv3" + else: + return "" + + # a replacement for the old socket.ssl function def sslwrap_simple (sock, keyfile=None, certfile=None): Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/abs.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/abs.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/abs.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- abs.decTest -- decimal absolute value -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- This set of tests primarily tests the existence of the operator. -- Additon, subtraction, rounding, and more overflows are tested @@ -106,9 +106,9 @@ absx215 abs 0.999E-999 -> 1.00E-999 Inexact Rounded Subnormal Underflow absx216 abs 0.099E-999 -> 1.0E-1000 Inexact Rounded Subnormal Underflow absx217 abs 0.009E-999 -> 1E-1001 Inexact Rounded Subnormal Underflow -absx218 abs 0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -absx219 abs 0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -absx220 abs 0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow +absx218 abs 0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +absx219 abs 0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +absx220 abs 0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped absx230 abs -1.00E-999 -> 1.00E-999 absx231 abs -0.1E-999 -> 1E-1000 Subnormal @@ -119,9 +119,9 @@ absx235 abs -0.999E-999 -> 1.00E-999 Inexact Rounded Subnormal Underflow absx236 abs -0.099E-999 -> 1.0E-1000 Inexact Rounded Subnormal Underflow absx237 abs -0.009E-999 -> 1E-1001 Inexact Rounded Subnormal Underflow -absx238 abs -0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -absx239 abs -0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -absx240 abs -0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow +absx238 abs -0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +absx239 abs -0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +absx240 abs -0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped -- long operand tests maxexponent: 999 Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/add.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/add.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/add.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------- +------/cancell---------------------------------------------------------- -- add.decTest -- decimal addition -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 precision: 9 rounding: half_up @@ -86,6 +86,7 @@ addx049 add '10000e+9' '7000' -> '10000000007000' addx050 add '10000e+9' '70000' -> '10000000070000' addx051 add '10000e+9' '700000' -> '10000000700000' +addx052 add '10000e+9' '7000000' -> '10000007000000' -- examples from decarith addx053 add '12' '7.00' -> '19.00' @@ -216,7 +217,7 @@ addx167 add '1.11' '7E+12' -> '7000000000001.11' addx168 add '-1' '7E+12' -> '6999999999999' --- 123456789012345 123456789012345 1 23456789012345 +-- 123456789012345 123456789012345 1 23456789012345 addx170 add '0.444444444444444' '0.555555555555563' -> '1.00000000000001' Inexact Rounded addx171 add '0.444444444444444' '0.555555555555562' -> '1.00000000000001' Inexact Rounded addx172 add '0.444444444444444' '0.555555555555561' -> '1.00000000000001' Inexact Rounded @@ -396,6 +397,7 @@ addx361 add 0E+50 10000E+1 -> 1.0000E+5 addx362 add 10000E+1 0E-50 -> 100000.0 Rounded addx363 add 10000E+1 10000E-50 -> 100000.0 Rounded Inexact +addx364 add 9.999999E+92 -9.999999E+92 -> 0E+86 -- a curiosity from JSR 13 testing rounding: half_down @@ -568,7 +570,7 @@ rounding: down addx561 add 1e-398 9.000000000000000E+384 -> 9.000000000000000E+384 Inexact Rounded addx562 add 0 9.000000000000000E+384 -> 9.000000000000000E+384 Rounded --- and using decimal64 bounds... +-- and using decimal64 bounds (see also ddadd.decTest) precision: 16 maxExponent: +384 minExponent: -383 @@ -576,6 +578,7 @@ addx563 add 1e-388 9.000000000000000E+374 -> 9.000000000000000E+374 Inexact Rounded addx564 add 0 9.000000000000000E+374 -> 9.000000000000000E+374 Rounded + -- some more residue effects with extreme rounding precision: 9 rounding: half_up @@ -955,26 +958,26 @@ addx912 add 0.10E-999 0 -> 1.0E-1000 Subnormal addx913 add 0.100E-999 0 -> 1.0E-1000 Subnormal Rounded addx914 add 0.01E-999 0 -> 1E-1001 Subnormal --- next is rounded to Emin +-- next is rounded to Nmin addx915 add 0.999E-999 0 -> 1.00E-999 Inexact Rounded Subnormal Underflow addx916 add 0.099E-999 0 -> 1.0E-1000 Inexact Rounded Subnormal Underflow addx917 add 0.009E-999 0 -> 1E-1001 Inexact Rounded Subnormal Underflow -addx918 add 0.001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow -addx919 add 0.0009E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow -addx920 add 0.0001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow +addx918 add 0.001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +addx919 add 0.0009E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +addx920 add 0.0001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped addx930 add -1.00E-999 0 -> -1.00E-999 addx931 add -0.1E-999 0 -> -1E-1000 Subnormal addx932 add -0.10E-999 0 -> -1.0E-1000 Subnormal addx933 add -0.100E-999 0 -> -1.0E-1000 Subnormal Rounded addx934 add -0.01E-999 0 -> -1E-1001 Subnormal --- next is rounded to Emin +-- next is rounded to Nmin addx935 add -0.999E-999 0 -> -1.00E-999 Inexact Rounded Subnormal Underflow addx936 add -0.099E-999 0 -> -1.0E-1000 Inexact Rounded Subnormal Underflow addx937 add -0.009E-999 0 -> -1E-1001 Inexact Rounded Subnormal Underflow -addx938 add -0.001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow -addx939 add -0.0009E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow -addx940 add -0.0001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow +addx938 add -0.001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +addx939 add -0.0009E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +addx940 add -0.0001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped -- some non-zero subnormal adds addx950 add 1.00E-999 0.1E-999 -> 1.10E-999 @@ -995,12 +998,43 @@ addx964 add 0.100E-999 -0.1E-999 -> 0E-1001 Clamped addx965 add 0.01E-999 -0.1E-999 -> -9E-1001 Subnormal addx966 add 0.999E-999 -0.1E-999 -> 9.0E-1000 Inexact Rounded Subnormal Underflow -addx967 add 0.099E-999 -0.1E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow +addx967 add 0.099E-999 -0.1E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped addx968 add 0.009E-999 -0.1E-999 -> -9E-1001 Inexact Rounded Subnormal Underflow addx969 add 0.001E-999 -0.1E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow addx970 add 0.0009E-999 -0.1E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow addx971 add 0.0001E-999 -0.1E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow +-- some 'real' numbers +maxExponent: 384 +minExponent: -383 +precision: 8 +addx566 add 99999061735E-394 0E-394 -> 9.999906E-384 Inexact Rounded Underflow Subnormal +precision: 7 +addx567 add 99999061735E-394 0E-394 -> 9.99991E-384 Inexact Rounded Underflow Subnormal +precision: 6 +addx568 add 99999061735E-394 0E-394 -> 9.9999E-384 Inexact Rounded Underflow Subnormal + +-- now the case where we can get underflow but the result is normal +-- [note this can't happen if the operands are also bounded, as we +-- cannot represent 1E-399, for example] +precision: 16 +rounding: half_up +maxExponent: 384 +minExponent: -383 + +addx571 add 1E-383 0 -> 1E-383 +addx572 add 1E-384 0 -> 1E-384 Subnormal +addx573 add 1E-383 1E-384 -> 1.1E-383 +addx574 subtract 1E-383 1E-384 -> 9E-384 Subnormal + +-- Here we explore the boundary of rounding a subnormal to Nmin +addx575 subtract 1E-383 1E-398 -> 9.99999999999999E-384 Subnormal +addx576 subtract 1E-383 1E-398 -> 9.99999999999999E-384 Subnormal +addx577 subtract 1E-383 1E-399 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +addx578 subtract 1E-383 1E-400 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +addx579 subtract 1E-383 1E-401 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +addx580 subtract 1E-383 1E-402 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded + -- check overflow edge case precision: 7 rounding: half_up @@ -1106,21 +1140,1565 @@ addx1139 add 1000E-101 -1e-200 -> 9.99E-99 Subnormal Inexact Rounded Underflow addx1140 add 100E-101 -1e-200 -> 9.9E-100 Subnormal Inexact Rounded Underflow addx1141 add 10E-101 -1e-200 -> 9E-101 Subnormal Inexact Rounded Underflow -addx1142 add 1E-101 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow -addx1143 add 0E-101 -1e-200 -> -0E-101 Subnormal Inexact Rounded Underflow -addx1144 add 1E-102 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow +addx1142 add 1E-101 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow Clamped +addx1143 add 0E-101 -1e-200 -> -0E-101 Subnormal Inexact Rounded Underflow Clamped +addx1144 add 1E-102 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow Clamped addx1151 add 10000E-102 -1e-200 -> 9.99E-99 Subnormal Inexact Rounded Underflow addx1152 add 1000E-102 -1e-200 -> 9.9E-100 Subnormal Inexact Rounded Underflow addx1153 add 100E-102 -1e-200 -> 9E-101 Subnormal Inexact Rounded Underflow -addx1154 add 10E-102 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow -addx1155 add 1E-102 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow -addx1156 add 0E-102 -1e-200 -> -0E-101 Subnormal Inexact Rounded Underflow -addx1157 add 1E-103 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow +addx1154 add 10E-102 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow Clamped +addx1155 add 1E-102 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow Clamped +addx1156 add 0E-102 -1e-200 -> -0E-101 Subnormal Inexact Rounded Underflow Clamped +addx1157 add 1E-103 -1e-200 -> 0E-101 Subnormal Inexact Rounded Underflow Clamped + +addx1160 add 100E-105 -1e-101 -> -0E-101 Subnormal Inexact Rounded Underflow Clamped +addx1161 add 100E-105 -1e-201 -> 0E-101 Subnormal Inexact Rounded Underflow Clamped + +-- tests based on Gunnar Degnbol's edge case +precision: 15 +rounding: half_up +maxExponent: 384 +minexponent: -383 + +addx1200 add 1E15 -0.5 -> 1.00000000000000E+15 Inexact Rounded +addx1201 add 1E15 -0.50 -> 1.00000000000000E+15 Inexact Rounded +addx1210 add 1E15 -0.51 -> 999999999999999 Inexact Rounded +addx1211 add 1E15 -0.501 -> 999999999999999 Inexact Rounded +addx1212 add 1E15 -0.5001 -> 999999999999999 Inexact Rounded +addx1213 add 1E15 -0.50001 -> 999999999999999 Inexact Rounded +addx1214 add 1E15 -0.500001 -> 999999999999999 Inexact Rounded +addx1215 add 1E15 -0.5000001 -> 999999999999999 Inexact Rounded +addx1216 add 1E15 -0.50000001 -> 999999999999999 Inexact Rounded +addx1217 add 1E15 -0.500000001 -> 999999999999999 Inexact Rounded +addx1218 add 1E15 -0.5000000001 -> 999999999999999 Inexact Rounded +addx1219 add 1E15 -0.50000000001 -> 999999999999999 Inexact Rounded +addx1220 add 1E15 -0.500000000001 -> 999999999999999 Inexact Rounded +addx1221 add 1E15 -0.5000000000001 -> 999999999999999 Inexact Rounded +addx1222 add 1E15 -0.50000000000001 -> 999999999999999 Inexact Rounded +addx1223 add 1E15 -0.500000000000001 -> 999999999999999 Inexact Rounded +addx1224 add 1E15 -0.5000000000000001 -> 999999999999999 Inexact Rounded +addx1225 add 1E15 -0.5000000000000000 -> 1.00000000000000E+15 Inexact Rounded +addx1230 add 1E15 -5000000.000000001 -> 999999995000000 Inexact Rounded + +precision: 16 + +addx1300 add 1E16 -0.5 -> 1.000000000000000E+16 Inexact Rounded +addx1310 add 1E16 -0.51 -> 9999999999999999 Inexact Rounded +addx1311 add 1E16 -0.501 -> 9999999999999999 Inexact Rounded +addx1312 add 1E16 -0.5001 -> 9999999999999999 Inexact Rounded +addx1313 add 1E16 -0.50001 -> 9999999999999999 Inexact Rounded +addx1314 add 1E16 -0.500001 -> 9999999999999999 Inexact Rounded +addx1315 add 1E16 -0.5000001 -> 9999999999999999 Inexact Rounded +addx1316 add 1E16 -0.50000001 -> 9999999999999999 Inexact Rounded +addx1317 add 1E16 -0.500000001 -> 9999999999999999 Inexact Rounded +addx1318 add 1E16 -0.5000000001 -> 9999999999999999 Inexact Rounded +addx1319 add 1E16 -0.50000000001 -> 9999999999999999 Inexact Rounded +addx1320 add 1E16 -0.500000000001 -> 9999999999999999 Inexact Rounded +addx1321 add 1E16 -0.5000000000001 -> 9999999999999999 Inexact Rounded +addx1322 add 1E16 -0.50000000000001 -> 9999999999999999 Inexact Rounded +addx1323 add 1E16 -0.500000000000001 -> 9999999999999999 Inexact Rounded +addx1324 add 1E16 -0.5000000000000001 -> 9999999999999999 Inexact Rounded +addx1325 add 1E16 -0.5000000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1326 add 1E16 -0.500000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1327 add 1E16 -0.50000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1328 add 1E16 -0.5000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1329 add 1E16 -0.500000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1330 add 1E16 -0.50000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1331 add 1E16 -0.5000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1332 add 1E16 -0.500000000 -> 1.000000000000000E+16 Inexact Rounded +addx1333 add 1E16 -0.50000000 -> 1.000000000000000E+16 Inexact Rounded +addx1334 add 1E16 -0.5000000 -> 1.000000000000000E+16 Inexact Rounded +addx1335 add 1E16 -0.500000 -> 1.000000000000000E+16 Inexact Rounded +addx1336 add 1E16 -0.50000 -> 1.000000000000000E+16 Inexact Rounded +addx1337 add 1E16 -0.5000 -> 1.000000000000000E+16 Inexact Rounded +addx1338 add 1E16 -0.500 -> 1.000000000000000E+16 Inexact Rounded +addx1339 add 1E16 -0.50 -> 1.000000000000000E+16 Inexact Rounded + +addx1340 add 1E16 -5000000.000010001 -> 9999999995000000 Inexact Rounded +addx1341 add 1E16 -5000000.000000001 -> 9999999995000000 Inexact Rounded + +addx1349 add 9999999999999999 0.4 -> 9999999999999999 Inexact Rounded +addx1350 add 9999999999999999 0.49 -> 9999999999999999 Inexact Rounded +addx1351 add 9999999999999999 0.499 -> 9999999999999999 Inexact Rounded +addx1352 add 9999999999999999 0.4999 -> 9999999999999999 Inexact Rounded +addx1353 add 9999999999999999 0.49999 -> 9999999999999999 Inexact Rounded +addx1354 add 9999999999999999 0.499999 -> 9999999999999999 Inexact Rounded +addx1355 add 9999999999999999 0.4999999 -> 9999999999999999 Inexact Rounded +addx1356 add 9999999999999999 0.49999999 -> 9999999999999999 Inexact Rounded +addx1357 add 9999999999999999 0.499999999 -> 9999999999999999 Inexact Rounded +addx1358 add 9999999999999999 0.4999999999 -> 9999999999999999 Inexact Rounded +addx1359 add 9999999999999999 0.49999999999 -> 9999999999999999 Inexact Rounded +addx1360 add 9999999999999999 0.499999999999 -> 9999999999999999 Inexact Rounded +addx1361 add 9999999999999999 0.4999999999999 -> 9999999999999999 Inexact Rounded +addx1362 add 9999999999999999 0.49999999999999 -> 9999999999999999 Inexact Rounded +addx1363 add 9999999999999999 0.499999999999999 -> 9999999999999999 Inexact Rounded +addx1364 add 9999999999999999 0.4999999999999999 -> 9999999999999999 Inexact Rounded +addx1365 add 9999999999999999 0.5000000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1367 add 9999999999999999 0.500000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1368 add 9999999999999999 0.50000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1369 add 9999999999999999 0.5000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1370 add 9999999999999999 0.500000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1371 add 9999999999999999 0.50000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1372 add 9999999999999999 0.5000000000 -> 1.000000000000000E+16 Inexact Rounded +addx1373 add 9999999999999999 0.500000000 -> 1.000000000000000E+16 Inexact Rounded +addx1374 add 9999999999999999 0.50000000 -> 1.000000000000000E+16 Inexact Rounded +addx1375 add 9999999999999999 0.5000000 -> 1.000000000000000E+16 Inexact Rounded +addx1376 add 9999999999999999 0.500000 -> 1.000000000000000E+16 Inexact Rounded +addx1377 add 9999999999999999 0.50000 -> 1.000000000000000E+16 Inexact Rounded +addx1378 add 9999999999999999 0.5000 -> 1.000000000000000E+16 Inexact Rounded +addx1379 add 9999999999999999 0.500 -> 1.000000000000000E+16 Inexact Rounded +addx1380 add 9999999999999999 0.50 -> 1.000000000000000E+16 Inexact Rounded +addx1381 add 9999999999999999 0.5 -> 1.000000000000000E+16 Inexact Rounded +addx1382 add 9999999999999999 0.5000000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1383 add 9999999999999999 0.500000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1384 add 9999999999999999 0.50000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1385 add 9999999999999999 0.5000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1386 add 9999999999999999 0.500000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1387 add 9999999999999999 0.50000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1388 add 9999999999999999 0.5000000001 -> 1.000000000000000E+16 Inexact Rounded +addx1389 add 9999999999999999 0.500000001 -> 1.000000000000000E+16 Inexact Rounded +addx1390 add 9999999999999999 0.50000001 -> 1.000000000000000E+16 Inexact Rounded +addx1391 add 9999999999999999 0.5000001 -> 1.000000000000000E+16 Inexact Rounded +addx1392 add 9999999999999999 0.500001 -> 1.000000000000000E+16 Inexact Rounded +addx1393 add 9999999999999999 0.50001 -> 1.000000000000000E+16 Inexact Rounded +addx1394 add 9999999999999999 0.5001 -> 1.000000000000000E+16 Inexact Rounded +addx1395 add 9999999999999999 0.501 -> 1.000000000000000E+16 Inexact Rounded +addx1396 add 9999999999999999 0.51 -> 1.000000000000000E+16 Inexact Rounded + +-- More GD edge cases, where difference between the unadjusted +-- exponents is larger than the maximum precision and one side is 0 +precision: 15 +rounding: half_up +maxExponent: 384 +minexponent: -383 + +addx1400 add 0 1.23456789012345 -> 1.23456789012345 +addx1401 add 0 1.23456789012345E-1 -> 0.123456789012345 +addx1402 add 0 1.23456789012345E-2 -> 0.0123456789012345 +addx1403 add 0 1.23456789012345E-3 -> 0.00123456789012345 +addx1404 add 0 1.23456789012345E-4 -> 0.000123456789012345 +addx1405 add 0 1.23456789012345E-5 -> 0.0000123456789012345 +addx1406 add 0 1.23456789012345E-6 -> 0.00000123456789012345 +addx1407 add 0 1.23456789012345E-7 -> 1.23456789012345E-7 +addx1408 add 0 1.23456789012345E-8 -> 1.23456789012345E-8 +addx1409 add 0 1.23456789012345E-9 -> 1.23456789012345E-9 +addx1410 add 0 1.23456789012345E-10 -> 1.23456789012345E-10 +addx1411 add 0 1.23456789012345E-11 -> 1.23456789012345E-11 +addx1412 add 0 1.23456789012345E-12 -> 1.23456789012345E-12 +addx1413 add 0 1.23456789012345E-13 -> 1.23456789012345E-13 +addx1414 add 0 1.23456789012345E-14 -> 1.23456789012345E-14 +addx1415 add 0 1.23456789012345E-15 -> 1.23456789012345E-15 +addx1416 add 0 1.23456789012345E-16 -> 1.23456789012345E-16 +addx1417 add 0 1.23456789012345E-17 -> 1.23456789012345E-17 +addx1418 add 0 1.23456789012345E-18 -> 1.23456789012345E-18 +addx1419 add 0 1.23456789012345E-19 -> 1.23456789012345E-19 + +-- same, precision 16.. +precision: 16 +addx1420 add 0 1.123456789012345 -> 1.123456789012345 +addx1421 add 0 1.123456789012345E-1 -> 0.1123456789012345 +addx1422 add 0 1.123456789012345E-2 -> 0.01123456789012345 +addx1423 add 0 1.123456789012345E-3 -> 0.001123456789012345 +addx1424 add 0 1.123456789012345E-4 -> 0.0001123456789012345 +addx1425 add 0 1.123456789012345E-5 -> 0.00001123456789012345 +addx1426 add 0 1.123456789012345E-6 -> 0.000001123456789012345 +addx1427 add 0 1.123456789012345E-7 -> 1.123456789012345E-7 +addx1428 add 0 1.123456789012345E-8 -> 1.123456789012345E-8 +addx1429 add 0 1.123456789012345E-9 -> 1.123456789012345E-9 +addx1430 add 0 1.123456789012345E-10 -> 1.123456789012345E-10 +addx1431 add 0 1.123456789012345E-11 -> 1.123456789012345E-11 +addx1432 add 0 1.123456789012345E-12 -> 1.123456789012345E-12 +addx1433 add 0 1.123456789012345E-13 -> 1.123456789012345E-13 +addx1434 add 0 1.123456789012345E-14 -> 1.123456789012345E-14 +addx1435 add 0 1.123456789012345E-15 -> 1.123456789012345E-15 +addx1436 add 0 1.123456789012345E-16 -> 1.123456789012345E-16 +addx1437 add 0 1.123456789012345E-17 -> 1.123456789012345E-17 +addx1438 add 0 1.123456789012345E-18 -> 1.123456789012345E-18 +addx1439 add 0 1.123456789012345E-19 -> 1.123456789012345E-19 + +-- same, reversed 0 +addx1440 add 1.123456789012345 0 -> 1.123456789012345 +addx1441 add 1.123456789012345E-1 0 -> 0.1123456789012345 +addx1442 add 1.123456789012345E-2 0 -> 0.01123456789012345 +addx1443 add 1.123456789012345E-3 0 -> 0.001123456789012345 +addx1444 add 1.123456789012345E-4 0 -> 0.0001123456789012345 +addx1445 add 1.123456789012345E-5 0 -> 0.00001123456789012345 +addx1446 add 1.123456789012345E-6 0 -> 0.000001123456789012345 +addx1447 add 1.123456789012345E-7 0 -> 1.123456789012345E-7 +addx1448 add 1.123456789012345E-8 0 -> 1.123456789012345E-8 +addx1449 add 1.123456789012345E-9 0 -> 1.123456789012345E-9 +addx1450 add 1.123456789012345E-10 0 -> 1.123456789012345E-10 +addx1451 add 1.123456789012345E-11 0 -> 1.123456789012345E-11 +addx1452 add 1.123456789012345E-12 0 -> 1.123456789012345E-12 +addx1453 add 1.123456789012345E-13 0 -> 1.123456789012345E-13 +addx1454 add 1.123456789012345E-14 0 -> 1.123456789012345E-14 +addx1455 add 1.123456789012345E-15 0 -> 1.123456789012345E-15 +addx1456 add 1.123456789012345E-16 0 -> 1.123456789012345E-16 +addx1457 add 1.123456789012345E-17 0 -> 1.123456789012345E-17 +addx1458 add 1.123456789012345E-18 0 -> 1.123456789012345E-18 +addx1459 add 1.123456789012345E-19 0 -> 1.123456789012345E-19 + +-- same, Es on the 0 +addx1460 add 1.123456789012345 0E-0 -> 1.123456789012345 +addx1461 add 1.123456789012345 0E-1 -> 1.123456789012345 +addx1462 add 1.123456789012345 0E-2 -> 1.123456789012345 +addx1463 add 1.123456789012345 0E-3 -> 1.123456789012345 +addx1464 add 1.123456789012345 0E-4 -> 1.123456789012345 +addx1465 add 1.123456789012345 0E-5 -> 1.123456789012345 +addx1466 add 1.123456789012345 0E-6 -> 1.123456789012345 +addx1467 add 1.123456789012345 0E-7 -> 1.123456789012345 +addx1468 add 1.123456789012345 0E-8 -> 1.123456789012345 +addx1469 add 1.123456789012345 0E-9 -> 1.123456789012345 +addx1470 add 1.123456789012345 0E-10 -> 1.123456789012345 +addx1471 add 1.123456789012345 0E-11 -> 1.123456789012345 +addx1472 add 1.123456789012345 0E-12 -> 1.123456789012345 +addx1473 add 1.123456789012345 0E-13 -> 1.123456789012345 +addx1474 add 1.123456789012345 0E-14 -> 1.123456789012345 +addx1475 add 1.123456789012345 0E-15 -> 1.123456789012345 +-- next four flag Rounded because the 0 extends the result +addx1476 add 1.123456789012345 0E-16 -> 1.123456789012345 Rounded +addx1477 add 1.123456789012345 0E-17 -> 1.123456789012345 Rounded +addx1478 add 1.123456789012345 0E-18 -> 1.123456789012345 Rounded +addx1479 add 1.123456789012345 0E-19 -> 1.123456789012345 Rounded + +-- sum of two opposite-sign operands is exactly 0 and floor => -0 +precision: 16 +maxExponent: 384 +minexponent: -383 + +rounding: half_up +-- exact zeros from zeros +addx1500 add 0 0E-19 -> 0E-19 +addx1501 add -0 0E-19 -> 0E-19 +addx1502 add 0 -0E-19 -> 0E-19 +addx1503 add -0 -0E-19 -> -0E-19 +addx1504 add 0E-400 0E-19 -> 0E-398 Clamped +addx1505 add -0E-400 0E-19 -> 0E-398 Clamped +addx1506 add 0E-400 -0E-19 -> 0E-398 Clamped +addx1507 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1511 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1512 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1513 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1514 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx1515 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1516 add -1E-401 1E-401 -> 0E-398 Clamped +addx1517 add 1E-401 -1E-401 -> 0E-398 Clamped +addx1518 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: half_down +-- exact zeros from zeros +addx1520 add 0 0E-19 -> 0E-19 +addx1521 add -0 0E-19 -> 0E-19 +addx1522 add 0 -0E-19 -> 0E-19 +addx1523 add -0 -0E-19 -> -0E-19 +addx1524 add 0E-400 0E-19 -> 0E-398 Clamped +addx1525 add -0E-400 0E-19 -> 0E-398 Clamped +addx1526 add 0E-400 -0E-19 -> 0E-398 Clamped +addx1527 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1531 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1532 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1533 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1534 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx1535 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1536 add -1E-401 1E-401 -> 0E-398 Clamped +addx1537 add 1E-401 -1E-401 -> 0E-398 Clamped +addx1538 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: half_even +-- exact zeros from zeros +addx1540 add 0 0E-19 -> 0E-19 +addx1541 add -0 0E-19 -> 0E-19 +addx1542 add 0 -0E-19 -> 0E-19 +addx1543 add -0 -0E-19 -> -0E-19 +addx1544 add 0E-400 0E-19 -> 0E-398 Clamped +addx1545 add -0E-400 0E-19 -> 0E-398 Clamped +addx1546 add 0E-400 -0E-19 -> 0E-398 Clamped +addx1547 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1551 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1552 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1553 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1554 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx1555 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1556 add -1E-401 1E-401 -> 0E-398 Clamped +addx1557 add 1E-401 -1E-401 -> 0E-398 Clamped +addx1558 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: up +-- exact zeros from zeros +addx1560 add 0 0E-19 -> 0E-19 +addx1561 add -0 0E-19 -> 0E-19 +addx1562 add 0 -0E-19 -> 0E-19 +addx1563 add -0 -0E-19 -> -0E-19 +addx1564 add 0E-400 0E-19 -> 0E-398 Clamped +addx1565 add -0E-400 0E-19 -> 0E-398 Clamped +addx1566 add 0E-400 -0E-19 -> 0E-398 Clamped +addx1567 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1571 add 1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx1572 add -1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx1573 add 1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +addx1574 add -1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +-- some exact zeros from non-zeros +addx1575 add 1E-401 1E-401 -> 1E-398 Subnormal Inexact Rounded Underflow +addx1576 add -1E-401 1E-401 -> 0E-398 Clamped +addx1577 add 1E-401 -1E-401 -> 0E-398 Clamped +addx1578 add -1E-401 -1E-401 -> -1E-398 Subnormal Inexact Rounded Underflow + +rounding: down +-- exact zeros from zeros +addx1580 add 0 0E-19 -> 0E-19 +addx1581 add -0 0E-19 -> 0E-19 +addx1582 add 0 -0E-19 -> 0E-19 +addx1583 add -0 -0E-19 -> -0E-19 +addx1584 add 0E-400 0E-19 -> 0E-398 Clamped +addx1585 add -0E-400 0E-19 -> 0E-398 Clamped +addx1586 add 0E-400 -0E-19 -> 0E-398 Clamped +addx1587 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1591 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1592 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1593 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1594 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx1595 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1596 add -1E-401 1E-401 -> 0E-398 Clamped +addx1597 add 1E-401 -1E-401 -> 0E-398 Clamped +addx1598 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: ceiling +-- exact zeros from zeros +addx1600 add 0 0E-19 -> 0E-19 +addx1601 add -0 0E-19 -> 0E-19 +addx1602 add 0 -0E-19 -> 0E-19 +addx1603 add -0 -0E-19 -> -0E-19 +addx1604 add 0E-400 0E-19 -> 0E-398 Clamped +addx1605 add -0E-400 0E-19 -> 0E-398 Clamped +addx1606 add 0E-400 -0E-19 -> 0E-398 Clamped +addx1607 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1611 add 1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx1612 add -1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx1613 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1614 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx1615 add 1E-401 1E-401 -> 1E-398 Subnormal Inexact Rounded Underflow +addx1616 add -1E-401 1E-401 -> 0E-398 Clamped +addx1617 add 1E-401 -1E-401 -> 0E-398 Clamped +addx1618 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +-- and the extra-special ugly case; unusual minuses marked by -- * +rounding: floor +-- exact zeros from zeros +addx1620 add 0 0E-19 -> 0E-19 +addx1621 add -0 0E-19 -> -0E-19 -- * +addx1622 add 0 -0E-19 -> -0E-19 -- * +addx1623 add -0 -0E-19 -> -0E-19 +addx1624 add 0E-400 0E-19 -> 0E-398 Clamped +addx1625 add -0E-400 0E-19 -> -0E-398 Clamped -- * +addx1626 add 0E-400 -0E-19 -> -0E-398 Clamped -- * +addx1627 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx1631 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1632 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1633 add 1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +addx1634 add -1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +-- some exact zeros from non-zeros +addx1635 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx1636 add -1E-401 1E-401 -> -0E-398 Clamped -- * +addx1637 add 1E-401 -1E-401 -> -0E-398 Clamped -- * +addx1638 add -1E-401 -1E-401 -> -1E-398 Subnormal Inexact Rounded Underflow + +-- BigDecimal problem testcases 2006.01.23 +precision: 16 +maxExponent: 384 +minexponent: -383 + +rounding: down +precision: 7 +addx1651 add 10001E+2 -2E+1 -> 1.00008E+6 +precision: 6 +addx1652 add 10001E+2 -2E+1 -> 1.00008E+6 +precision: 5 +addx1653 add 10001E+2 -2E+1 -> 1.0000E+6 Inexact Rounded +precision: 4 +addx1654 add 10001E+2 -2E+1 -> 1.000E+6 Inexact Rounded +precision: 3 +addx1655 add 10001E+2 -2E+1 -> 1.00E+6 Inexact Rounded +precision: 2 +addx1656 add 10001E+2 -2E+1 -> 1.0E+6 Inexact Rounded +precision: 1 +addx1657 add 10001E+2 -2E+1 -> 1E+6 Inexact Rounded + +rounding: half_even +precision: 7 +addx1661 add 10001E+2 -2E+1 -> 1.00008E+6 +precision: 6 +addx1662 add 10001E+2 -2E+1 -> 1.00008E+6 +precision: 5 +addx1663 add 10001E+2 -2E+1 -> 1.0001E+6 Inexact Rounded +precision: 4 +addx1664 add 10001E+2 -2E+1 -> 1.000E+6 Inexact Rounded +precision: 3 +addx1665 add 10001E+2 -2E+1 -> 1.00E+6 Inexact Rounded +precision: 2 +addx1666 add 10001E+2 -2E+1 -> 1.0E+6 Inexact Rounded +precision: 1 +addx1667 add 10001E+2 -2E+1 -> 1E+6 Inexact Rounded + +rounding: up +precision: 7 +addx1671 add 10001E+2 -2E+1 -> 1.00008E+6 +precision: 6 +addx1672 add 10001E+2 -2E+1 -> 1.00008E+6 +precision: 5 +addx1673 add 10001E+2 -2E+1 -> 1.0001E+6 Inexact Rounded +precision: 4 +addx1674 add 10001E+2 -2E+1 -> 1.001E+6 Inexact Rounded +precision: 3 +addx1675 add 10001E+2 -2E+1 -> 1.01E+6 Inexact Rounded +precision: 2 +addx1676 add 10001E+2 -2E+1 -> 1.1E+6 Inexact Rounded +precision: 1 +addx1677 add 10001E+2 -2E+1 -> 2E+6 Inexact Rounded + +precision: 34 +rounding: half_up +maxExponent: 6144 +minExponent: -6143 +-- Examples from SQL proposal (Krishna Kulkarni) +addx1701 add 130E-2 120E-2 -> 2.50 +addx1702 add 130E-2 12E-1 -> 2.50 +addx1703 add 130E-2 1E0 -> 2.30 +addx1704 add 1E2 1E4 -> 1.01E+4 +addx1705 subtract 130E-2 120E-2 -> 0.10 +addx1706 subtract 130E-2 12E-1 -> 0.10 +addx1707 subtract 130E-2 1E0 -> 0.30 +addx1708 subtract 1E2 1E4 -> -9.9E+3 + +------------------------------------------------------------------------ +-- Same as above, using decimal64 default parameters -- +------------------------------------------------------------------------ +precision: 16 +rounding: half_even +maxExponent: 384 +minexponent: -383 + +-- [first group are 'quick confidence check'] +addx6001 add 1 1 -> 2 +addx6002 add 2 3 -> 5 +addx6003 add '5.75' '3.3' -> 9.05 +addx6004 add '5' '-3' -> 2 +addx6005 add '-5' '-3' -> -8 +addx6006 add '-7' '2.5' -> -4.5 +addx6007 add '0.7' '0.3' -> 1.0 +addx6008 add '1.25' '1.25' -> 2.50 +addx6009 add '1.23456789' '1.00000000' -> '2.23456789' +addx6010 add '1.23456789' '1.00000011' -> '2.23456800' + +addx6011 add '0.44444444444444444' '0.55555555555555555' -> '1.000000000000000' Inexact Rounded +addx6012 add '0.44444444444444440' '0.55555555555555555' -> '1.000000000000000' Inexact Rounded +addx6013 add '0.44444444444444444' '0.55555555555555550' -> '0.9999999999999999' Inexact Rounded +addx6014 add '0.444444444444444449' '0' -> '0.4444444444444444' Inexact Rounded +addx6015 add '0.4444444444444444499' '0' -> '0.4444444444444444' Inexact Rounded +addx6016 add '0.44444444444444444999' '0' -> '0.4444444444444444' Inexact Rounded +addx6017 add '0.44444444444444445000' '0' -> '0.4444444444444444' Inexact Rounded +addx6018 add '0.44444444444444445001' '0' -> '0.4444444444444445' Inexact Rounded +addx6019 add '0.4444444444444444501' '0' -> '0.4444444444444445' Inexact Rounded +addx6020 add '0.444444444444444451' '0' -> '0.4444444444444445' Inexact Rounded + +addx6021 add 0 1 -> 1 +addx6022 add 1 1 -> 2 +addx6023 add 2 1 -> 3 +addx6024 add 3 1 -> 4 +addx6025 add 4 1 -> 5 +addx6026 add 5 1 -> 6 +addx6027 add 6 1 -> 7 +addx6028 add 7 1 -> 8 +addx6029 add 8 1 -> 9 +addx6030 add 9 1 -> 10 + +-- some carrying effects +addx6031 add '0.9998' '0.0000' -> '0.9998' +addx6032 add '0.9998' '0.0001' -> '0.9999' +addx6033 add '0.9998' '0.0002' -> '1.0000' +addx6034 add '0.9998' '0.0003' -> '1.0001' + +addx6035 add '70' '10000e+16' -> '1.000000000000000E+20' Inexact Rounded +addx6036 add '700' '10000e+16' -> '1.000000000000000E+20' Inexact Rounded +addx6037 add '7000' '10000e+16' -> '1.000000000000000E+20' Inexact Rounded +addx6038 add '70000' '10000e+16' -> '1.000000000000001E+20' Inexact Rounded +addx6039 add '700000' '10000e+16' -> '1.000000000000007E+20' Rounded + +-- symmetry: +addx6040 add '10000e+16' '70' -> '1.000000000000000E+20' Inexact Rounded +addx6041 add '10000e+16' '700' -> '1.000000000000000E+20' Inexact Rounded +addx6042 add '10000e+16' '7000' -> '1.000000000000000E+20' Inexact Rounded +addx6044 add '10000e+16' '70000' -> '1.000000000000001E+20' Inexact Rounded +addx6045 add '10000e+16' '700000' -> '1.000000000000007E+20' Rounded + +addx6046 add '10000e+9' '7' -> '10000000000007' +addx6047 add '10000e+9' '70' -> '10000000000070' +addx6048 add '10000e+9' '700' -> '10000000000700' +addx6049 add '10000e+9' '7000' -> '10000000007000' +addx6050 add '10000e+9' '70000' -> '10000000070000' +addx6051 add '10000e+9' '700000' -> '10000000700000' + +-- examples from decarith +addx6053 add '12' '7.00' -> '19.00' +addx6054 add '1.3' '-1.07' -> '0.23' +addx6055 add '1.3' '-1.30' -> '0.00' +addx6056 add '1.3' '-2.07' -> '-0.77' +addx6057 add '1E+2' '1E+4' -> '1.01E+4' + +-- from above +addx6061 add 1 '0.1' -> '1.1' +addx6062 add 1 '0.01' -> '1.01' +addx6063 add 1 '0.001' -> '1.001' +addx6064 add 1 '0.0001' -> '1.0001' +addx6065 add 1 '0.00001' -> '1.00001' +addx6066 add 1 '0.000001' -> '1.000001' +addx6067 add 1 '0.0000001' -> '1.0000001' +addx6068 add 1 '0.00000001' -> '1.00000001' + +-- cancellation to integer +addx6069 add 99999999999999123456789 -99999999999999E+9 -> 123456789 + +-- some funny zeros [in case of bad signum] +addx6070 add 1 0 -> 1 +addx6071 add 1 0. -> 1 +addx6072 add 1 .0 -> 1.0 +addx6073 add 1 0.0 -> 1.0 +addx6074 add 1 0.00 -> 1.00 +addx6075 add 0 1 -> 1 +addx6076 add 0. 1 -> 1 +addx6077 add .0 1 -> 1.0 +addx6078 add 0.0 1 -> 1.0 +addx6079 add 0.00 1 -> 1.00 -addx1160 add 100E-105 -1e-101 -> -0E-101 Subnormal Inexact Rounded Underflow -addx1161 add 100E-105 -1e-201 -> 0E-101 Subnormal Inexact Rounded Underflow +-- some carries +addx6080 add 9999999999999998 1 -> 9999999999999999 +addx6081 add 9999999999999999 1 -> 1.000000000000000E+16 Rounded +addx6082 add 999999999999999 1 -> 1000000000000000 +addx6083 add 9999999999999 1 -> 10000000000000 +addx6084 add 99999999999 1 -> 100000000000 +addx6085 add 999999999 1 -> 1000000000 +addx6086 add 9999999 1 -> 10000000 +addx6087 add 99999 1 -> 100000 +addx6088 add 999 1 -> 1000 +addx6089 add 9 1 -> 10 + + +-- more LHS swaps +addx6090 add '-56267E-10' 0 -> '-0.0000056267' +addx6091 add '-56267E-6' 0 -> '-0.056267' +addx6092 add '-56267E-5' 0 -> '-0.56267' +addx6093 add '-56267E-4' 0 -> '-5.6267' +addx6094 add '-56267E-3' 0 -> '-56.267' +addx6095 add '-56267E-2' 0 -> '-562.67' +addx6096 add '-56267E-1' 0 -> '-5626.7' +addx6097 add '-56267E-0' 0 -> '-56267' +addx6098 add '-5E-10' 0 -> '-5E-10' +addx6099 add '-5E-7' 0 -> '-5E-7' +addx6100 add '-5E-6' 0 -> '-0.000005' +addx6101 add '-5E-5' 0 -> '-0.00005' +addx6102 add '-5E-4' 0 -> '-0.0005' +addx6103 add '-5E-1' 0 -> '-0.5' +addx6104 add '-5E0' 0 -> '-5' +addx6105 add '-5E1' 0 -> '-50' +addx6106 add '-5E5' 0 -> '-500000' +addx6107 add '-5E15' 0 -> '-5000000000000000' +addx6108 add '-5E16' 0 -> '-5.000000000000000E+16' Rounded +addx6109 add '-5E17' 0 -> '-5.000000000000000E+17' Rounded +addx6110 add '-5E18' 0 -> '-5.000000000000000E+18' Rounded +addx6111 add '-5E100' 0 -> '-5.000000000000000E+100' Rounded +-- more RHS swaps +addx6113 add 0 '-56267E-10' -> '-0.0000056267' +addx6114 add 0 '-56267E-6' -> '-0.056267' +addx6116 add 0 '-56267E-5' -> '-0.56267' +addx6117 add 0 '-56267E-4' -> '-5.6267' +addx6119 add 0 '-56267E-3' -> '-56.267' +addx6120 add 0 '-56267E-2' -> '-562.67' +addx6121 add 0 '-56267E-1' -> '-5626.7' +addx6122 add 0 '-56267E-0' -> '-56267' +addx6123 add 0 '-5E-10' -> '-5E-10' +addx6124 add 0 '-5E-7' -> '-5E-7' +addx6125 add 0 '-5E-6' -> '-0.000005' +addx6126 add 0 '-5E-5' -> '-0.00005' +addx6127 add 0 '-5E-4' -> '-0.0005' +addx6128 add 0 '-5E-1' -> '-0.5' +addx6129 add 0 '-5E0' -> '-5' +addx6130 add 0 '-5E1' -> '-50' +addx6131 add 0 '-5E5' -> '-500000' +addx6132 add 0 '-5E15' -> '-5000000000000000' +addx6133 add 0 '-5E16' -> '-5.000000000000000E+16' Rounded +addx6134 add 0 '-5E17' -> '-5.000000000000000E+17' Rounded +addx6135 add 0 '-5E18' -> '-5.000000000000000E+18' Rounded +addx6136 add 0 '-5E100' -> '-5.000000000000000E+100' Rounded + +-- related +addx6137 add 1 '0E-19' -> '1.000000000000000' Rounded +addx6138 add -1 '0E-19' -> '-1.000000000000000' Rounded +addx6139 add '0E-19' 1 -> '1.000000000000000' Rounded +addx6140 add '0E-19' -1 -> '-1.000000000000000' Rounded +addx6141 add 1E+11 0.0000 -> '100000000000.0000' +addx6142 add 1E+11 0.00000 -> '100000000000.0000' Rounded +addx6143 add 0.000 1E+12 -> '1000000000000.000' +addx6144 add 0.0000 1E+12 -> '1000000000000.000' Rounded + +-- [some of the next group are really constructor tests] +addx6146 add '00.0' 0 -> '0.0' +addx6147 add '0.00' 0 -> '0.00' +addx6148 add 0 '0.00' -> '0.00' +addx6149 add 0 '00.0' -> '0.0' +addx6150 add '00.0' '0.00' -> '0.00' +addx6151 add '0.00' '00.0' -> '0.00' +addx6152 add '3' '.3' -> '3.3' +addx6153 add '3.' '.3' -> '3.3' +addx6154 add '3.0' '.3' -> '3.3' +addx6155 add '3.00' '.3' -> '3.30' +addx6156 add '3' '3' -> '6' +addx6157 add '3' '+3' -> '6' +addx6158 add '3' '-3' -> '0' +addx6159 add '0.3' '-0.3' -> '0.0' +addx6160 add '0.03' '-0.03' -> '0.00' + +-- try borderline precision, with carries, etc. +addx6161 add '1E+13' '-1' -> '9999999999999' +addx6162 add '1E+13' '1.11' -> '10000000000001.11' +addx6163 add '1.11' '1E+13' -> '10000000000001.11' +addx6164 add '-1' '1E+13' -> '9999999999999' +addx6165 add '7E+13' '-1' -> '69999999999999' +addx6166 add '7E+13' '1.11' -> '70000000000001.11' +addx6167 add '1.11' '7E+13' -> '70000000000001.11' +addx6168 add '-1' '7E+13' -> '69999999999999' + +-- 1234567890123456 1234567890123456 1 234567890123456 +addx6170 add '0.4444444444444444' '0.5555555555555563' -> '1.000000000000001' Inexact Rounded +addx6171 add '0.4444444444444444' '0.5555555555555562' -> '1.000000000000001' Inexact Rounded +addx6172 add '0.4444444444444444' '0.5555555555555561' -> '1.000000000000000' Inexact Rounded +addx6173 add '0.4444444444444444' '0.5555555555555560' -> '1.000000000000000' Inexact Rounded +addx6174 add '0.4444444444444444' '0.5555555555555559' -> '1.000000000000000' Inexact Rounded +addx6175 add '0.4444444444444444' '0.5555555555555558' -> '1.000000000000000' Inexact Rounded +addx6176 add '0.4444444444444444' '0.5555555555555557' -> '1.000000000000000' Inexact Rounded +addx6177 add '0.4444444444444444' '0.5555555555555556' -> '1.000000000000000' Rounded +addx6178 add '0.4444444444444444' '0.5555555555555555' -> '0.9999999999999999' +addx6179 add '0.4444444444444444' '0.5555555555555554' -> '0.9999999999999998' +addx6180 add '0.4444444444444444' '0.5555555555555553' -> '0.9999999999999997' +addx6181 add '0.4444444444444444' '0.5555555555555552' -> '0.9999999999999996' +addx6182 add '0.4444444444444444' '0.5555555555555551' -> '0.9999999999999995' +addx6183 add '0.4444444444444444' '0.5555555555555550' -> '0.9999999999999994' + +-- and some more, including residue effects and different roundings +rounding: half_up +addx6200 add '6543210123456789' 0 -> '6543210123456789' +addx6201 add '6543210123456789' 0.000000001 -> '6543210123456789' Inexact Rounded +addx6202 add '6543210123456789' 0.000001 -> '6543210123456789' Inexact Rounded +addx6203 add '6543210123456789' 0.1 -> '6543210123456789' Inexact Rounded +addx6204 add '6543210123456789' 0.4 -> '6543210123456789' Inexact Rounded +addx6205 add '6543210123456789' 0.49 -> '6543210123456789' Inexact Rounded +addx6206 add '6543210123456789' 0.499999 -> '6543210123456789' Inexact Rounded +addx6207 add '6543210123456789' 0.499999999 -> '6543210123456789' Inexact Rounded +addx6208 add '6543210123456789' 0.5 -> '6543210123456790' Inexact Rounded +addx6209 add '6543210123456789' 0.500000001 -> '6543210123456790' Inexact Rounded +addx6210 add '6543210123456789' 0.500001 -> '6543210123456790' Inexact Rounded +addx6211 add '6543210123456789' 0.51 -> '6543210123456790' Inexact Rounded +addx6212 add '6543210123456789' 0.6 -> '6543210123456790' Inexact Rounded +addx6213 add '6543210123456789' 0.9 -> '6543210123456790' Inexact Rounded +addx6214 add '6543210123456789' 0.99999 -> '6543210123456790' Inexact Rounded +addx6215 add '6543210123456789' 0.999999999 -> '6543210123456790' Inexact Rounded +addx6216 add '6543210123456789' 1 -> '6543210123456790' +addx6217 add '6543210123456789' 1.000000001 -> '6543210123456790' Inexact Rounded +addx6218 add '6543210123456789' 1.00001 -> '6543210123456790' Inexact Rounded +addx6219 add '6543210123456789' 1.1 -> '6543210123456790' Inexact Rounded + +rounding: half_even +addx6220 add '6543210123456789' 0 -> '6543210123456789' +addx6221 add '6543210123456789' 0.000000001 -> '6543210123456789' Inexact Rounded +addx6222 add '6543210123456789' 0.000001 -> '6543210123456789' Inexact Rounded +addx6223 add '6543210123456789' 0.1 -> '6543210123456789' Inexact Rounded +addx6224 add '6543210123456789' 0.4 -> '6543210123456789' Inexact Rounded +addx6225 add '6543210123456789' 0.49 -> '6543210123456789' Inexact Rounded +addx6226 add '6543210123456789' 0.499999 -> '6543210123456789' Inexact Rounded +addx6227 add '6543210123456789' 0.499999999 -> '6543210123456789' Inexact Rounded +addx6228 add '6543210123456789' 0.5 -> '6543210123456790' Inexact Rounded +addx6229 add '6543210123456789' 0.500000001 -> '6543210123456790' Inexact Rounded +addx6230 add '6543210123456789' 0.500001 -> '6543210123456790' Inexact Rounded +addx6231 add '6543210123456789' 0.51 -> '6543210123456790' Inexact Rounded +addx6232 add '6543210123456789' 0.6 -> '6543210123456790' Inexact Rounded +addx6233 add '6543210123456789' 0.9 -> '6543210123456790' Inexact Rounded +addx6234 add '6543210123456789' 0.99999 -> '6543210123456790' Inexact Rounded +addx6235 add '6543210123456789' 0.999999999 -> '6543210123456790' Inexact Rounded +addx6236 add '6543210123456789' 1 -> '6543210123456790' +addx6237 add '6543210123456789' 1.00000001 -> '6543210123456790' Inexact Rounded +addx6238 add '6543210123456789' 1.00001 -> '6543210123456790' Inexact Rounded +addx6239 add '6543210123456789' 1.1 -> '6543210123456790' Inexact Rounded +-- critical few with even bottom digit... +addx6240 add '6543210123456788' 0.499999999 -> '6543210123456788' Inexact Rounded +addx6241 add '6543210123456788' 0.5 -> '6543210123456788' Inexact Rounded +addx6242 add '6543210123456788' 0.500000001 -> '6543210123456789' Inexact Rounded + +rounding: down +addx6250 add '6543210123456789' 0 -> '6543210123456789' +addx6251 add '6543210123456789' 0.000000001 -> '6543210123456789' Inexact Rounded +addx6252 add '6543210123456789' 0.000001 -> '6543210123456789' Inexact Rounded +addx6253 add '6543210123456789' 0.1 -> '6543210123456789' Inexact Rounded +addx6254 add '6543210123456789' 0.4 -> '6543210123456789' Inexact Rounded +addx6255 add '6543210123456789' 0.49 -> '6543210123456789' Inexact Rounded +addx6256 add '6543210123456789' 0.499999 -> '6543210123456789' Inexact Rounded +addx6257 add '6543210123456789' 0.499999999 -> '6543210123456789' Inexact Rounded +addx6258 add '6543210123456789' 0.5 -> '6543210123456789' Inexact Rounded +addx6259 add '6543210123456789' 0.500000001 -> '6543210123456789' Inexact Rounded +addx6260 add '6543210123456789' 0.500001 -> '6543210123456789' Inexact Rounded +addx6261 add '6543210123456789' 0.51 -> '6543210123456789' Inexact Rounded +addx6262 add '6543210123456789' 0.6 -> '6543210123456789' Inexact Rounded +addx6263 add '6543210123456789' 0.9 -> '6543210123456789' Inexact Rounded +addx6264 add '6543210123456789' 0.99999 -> '6543210123456789' Inexact Rounded +addx6265 add '6543210123456789' 0.999999999 -> '6543210123456789' Inexact Rounded +addx6266 add '6543210123456789' 1 -> '6543210123456790' +addx6267 add '6543210123456789' 1.00000001 -> '6543210123456790' Inexact Rounded +addx6268 add '6543210123456789' 1.00001 -> '6543210123456790' Inexact Rounded +addx6269 add '6543210123456789' 1.1 -> '6543210123456790' Inexact Rounded + +-- 1 in last place tests +rounding: half_even +addx6301 add -1 1 -> 0 +addx6302 add 0 1 -> 1 +addx6303 add 1 1 -> 2 +addx6304 add 12 1 -> 13 +addx6305 add 98 1 -> 99 +addx6306 add 99 1 -> 100 +addx6307 add 100 1 -> 101 +addx6308 add 101 1 -> 102 +addx6309 add -1 -1 -> -2 +addx6310 add 0 -1 -> -1 +addx6311 add 1 -1 -> 0 +addx6312 add 12 -1 -> 11 +addx6313 add 98 -1 -> 97 +addx6314 add 99 -1 -> 98 +addx6315 add 100 -1 -> 99 +addx6316 add 101 -1 -> 100 + +addx6321 add -0.01 0.01 -> 0.00 +addx6322 add 0.00 0.01 -> 0.01 +addx6323 add 0.01 0.01 -> 0.02 +addx6324 add 0.12 0.01 -> 0.13 +addx6325 add 0.98 0.01 -> 0.99 +addx6326 add 0.99 0.01 -> 1.00 +addx6327 add 1.00 0.01 -> 1.01 +addx6328 add 1.01 0.01 -> 1.02 +addx6329 add -0.01 -0.01 -> -0.02 +addx6330 add 0.00 -0.01 -> -0.01 +addx6331 add 0.01 -0.01 -> 0.00 +addx6332 add 0.12 -0.01 -> 0.11 +addx6333 add 0.98 -0.01 -> 0.97 +addx6334 add 0.99 -0.01 -> 0.98 +addx6335 add 1.00 -0.01 -> 0.99 +addx6336 add 1.01 -0.01 -> 1.00 + +-- some more cases where adding 0 affects the coefficient +addx6340 add 1E+3 0 -> 1000 +addx6341 add 1E+15 0 -> 1000000000000000 +addx6342 add 1E+16 0 -> 1.000000000000000E+16 Rounded +addx6343 add 1E+17 0 -> 1.000000000000000E+17 Rounded +-- which simply follow from these cases ... +addx6344 add 1E+3 1 -> 1001 +addx6345 add 1E+15 1 -> 1000000000000001 +addx6346 add 1E+16 1 -> 1.000000000000000E+16 Inexact Rounded +addx6347 add 1E+17 1 -> 1.000000000000000E+17 Inexact Rounded +addx6348 add 1E+3 7 -> 1007 +addx6349 add 1E+15 7 -> 1000000000000007 +addx6350 add 1E+16 7 -> 1.000000000000001E+16 Inexact Rounded +addx6351 add 1E+17 7 -> 1.000000000000000E+17 Inexact Rounded + +-- tryzeros cases +addx6361 add 0E+50 10000E+1 -> 1.0000E+5 +addx6362 add 10000E+1 0E-50 -> 100000.0000000000 Rounded +addx6363 add 10000E+1 10000E-50 -> 100000.0000000000 Rounded Inexact +addx6364 add 12.34 0e-398 -> 12.34000000000000 Rounded + +-- ulp replacement tests +addx6400 add 1 77e-14 -> 1.00000000000077 +addx6401 add 1 77e-15 -> 1.000000000000077 +addx6402 add 1 77e-16 -> 1.000000000000008 Inexact Rounded +addx6403 add 1 77e-17 -> 1.000000000000001 Inexact Rounded +addx6404 add 1 77e-18 -> 1.000000000000000 Inexact Rounded +addx6405 add 1 77e-19 -> 1.000000000000000 Inexact Rounded +addx6406 add 1 77e-99 -> 1.000000000000000 Inexact Rounded + +addx6410 add 10 77e-14 -> 10.00000000000077 +addx6411 add 10 77e-15 -> 10.00000000000008 Inexact Rounded +addx6412 add 10 77e-16 -> 10.00000000000001 Inexact Rounded +addx6413 add 10 77e-17 -> 10.00000000000000 Inexact Rounded +addx6414 add 10 77e-18 -> 10.00000000000000 Inexact Rounded +addx6415 add 10 77e-19 -> 10.00000000000000 Inexact Rounded +addx6416 add 10 77e-99 -> 10.00000000000000 Inexact Rounded + +addx6420 add 77e-14 1 -> 1.00000000000077 +addx6421 add 77e-15 1 -> 1.000000000000077 +addx6422 add 77e-16 1 -> 1.000000000000008 Inexact Rounded +addx6423 add 77e-17 1 -> 1.000000000000001 Inexact Rounded +addx6424 add 77e-18 1 -> 1.000000000000000 Inexact Rounded +addx6425 add 77e-19 1 -> 1.000000000000000 Inexact Rounded +addx6426 add 77e-99 1 -> 1.000000000000000 Inexact Rounded + +addx6430 add 77e-14 10 -> 10.00000000000077 +addx6431 add 77e-15 10 -> 10.00000000000008 Inexact Rounded +addx6432 add 77e-16 10 -> 10.00000000000001 Inexact Rounded +addx6433 add 77e-17 10 -> 10.00000000000000 Inexact Rounded +addx6434 add 77e-18 10 -> 10.00000000000000 Inexact Rounded +addx6435 add 77e-19 10 -> 10.00000000000000 Inexact Rounded +addx6436 add 77e-99 10 -> 10.00000000000000 Inexact Rounded + +-- negative ulps +addx6440 add 1 -77e-14 -> 0.99999999999923 +addx6441 add 1 -77e-15 -> 0.999999999999923 +addx6442 add 1 -77e-16 -> 0.9999999999999923 +addx6443 add 1 -77e-17 -> 0.9999999999999992 Inexact Rounded +addx6444 add 1 -77e-18 -> 0.9999999999999999 Inexact Rounded +addx6445 add 1 -77e-19 -> 1.000000000000000 Inexact Rounded +addx6446 add 1 -77e-99 -> 1.000000000000000 Inexact Rounded + +addx6450 add 10 -77e-14 -> 9.99999999999923 +addx6451 add 10 -77e-15 -> 9.999999999999923 +addx6452 add 10 -77e-16 -> 9.999999999999992 Inexact Rounded +addx6453 add 10 -77e-17 -> 9.999999999999999 Inexact Rounded +addx6454 add 10 -77e-18 -> 10.00000000000000 Inexact Rounded +addx6455 add 10 -77e-19 -> 10.00000000000000 Inexact Rounded +addx6456 add 10 -77e-99 -> 10.00000000000000 Inexact Rounded + +addx6460 add -77e-14 1 -> 0.99999999999923 +addx6461 add -77e-15 1 -> 0.999999999999923 +addx6462 add -77e-16 1 -> 0.9999999999999923 +addx6463 add -77e-17 1 -> 0.9999999999999992 Inexact Rounded +addx6464 add -77e-18 1 -> 0.9999999999999999 Inexact Rounded +addx6465 add -77e-19 1 -> 1.000000000000000 Inexact Rounded +addx6466 add -77e-99 1 -> 1.000000000000000 Inexact Rounded + +addx6470 add -77e-14 10 -> 9.99999999999923 +addx6471 add -77e-15 10 -> 9.999999999999923 +addx6472 add -77e-16 10 -> 9.999999999999992 Inexact Rounded +addx6473 add -77e-17 10 -> 9.999999999999999 Inexact Rounded +addx6474 add -77e-18 10 -> 10.00000000000000 Inexact Rounded +addx6475 add -77e-19 10 -> 10.00000000000000 Inexact Rounded +addx6476 add -77e-99 10 -> 10.00000000000000 Inexact Rounded + +-- negative ulps +addx6480 add -1 77e-14 -> -0.99999999999923 +addx6481 add -1 77e-15 -> -0.999999999999923 +addx6482 add -1 77e-16 -> -0.9999999999999923 +addx6483 add -1 77e-17 -> -0.9999999999999992 Inexact Rounded +addx6484 add -1 77e-18 -> -0.9999999999999999 Inexact Rounded +addx6485 add -1 77e-19 -> -1.000000000000000 Inexact Rounded +addx6486 add -1 77e-99 -> -1.000000000000000 Inexact Rounded + +addx6490 add -10 77e-14 -> -9.99999999999923 +addx6491 add -10 77e-15 -> -9.999999999999923 +addx6492 add -10 77e-16 -> -9.999999999999992 Inexact Rounded +addx6493 add -10 77e-17 -> -9.999999999999999 Inexact Rounded +addx6494 add -10 77e-18 -> -10.00000000000000 Inexact Rounded +addx6495 add -10 77e-19 -> -10.00000000000000 Inexact Rounded +addx6496 add -10 77e-99 -> -10.00000000000000 Inexact Rounded + +addx6500 add 77e-14 -1 -> -0.99999999999923 +addx6501 add 77e-15 -1 -> -0.999999999999923 +addx6502 add 77e-16 -1 -> -0.9999999999999923 +addx6503 add 77e-17 -1 -> -0.9999999999999992 Inexact Rounded +addx6504 add 77e-18 -1 -> -0.9999999999999999 Inexact Rounded +addx6505 add 77e-19 -1 -> -1.000000000000000 Inexact Rounded +addx6506 add 77e-99 -1 -> -1.000000000000000 Inexact Rounded + +addx6510 add 77e-14 -10 -> -9.99999999999923 +addx6511 add 77e-15 -10 -> -9.999999999999923 +addx6512 add 77e-16 -10 -> -9.999999999999992 Inexact Rounded +addx6513 add 77e-17 -10 -> -9.999999999999999 Inexact Rounded +addx6514 add 77e-18 -10 -> -10.00000000000000 Inexact Rounded +addx6515 add 77e-19 -10 -> -10.00000000000000 Inexact Rounded +addx6516 add 77e-99 -10 -> -10.00000000000000 Inexact Rounded + + +-- long operands +addx6521 add 101234562345678000 0 -> 1.012345623456780E+17 Rounded +addx6522 add 0 101234562345678000 -> 1.012345623456780E+17 Rounded +addx6523 add 10123456234567800 0 -> 1.012345623456780E+16 Rounded +addx6524 add 0 10123456234567800 -> 1.012345623456780E+16 Rounded +addx6525 add 10123456234567890 0 -> 1.012345623456789E+16 Rounded +addx6526 add 0 10123456234567890 -> 1.012345623456789E+16 Rounded +addx6527 add 10123456234567891 0 -> 1.012345623456789E+16 Inexact Rounded +addx6528 add 0 10123456234567891 -> 1.012345623456789E+16 Inexact Rounded +addx6529 add 101234562345678901 0 -> 1.012345623456789E+17 Inexact Rounded +addx6530 add 0 101234562345678901 -> 1.012345623456789E+17 Inexact Rounded +addx6531 add 10123456234567896 0 -> 1.012345623456790E+16 Inexact Rounded +addx6532 add 0 10123456234567896 -> 1.012345623456790E+16 Inexact Rounded + +-- verify a query +rounding: down +addx6561 add 1e-398 9.000000000000000E+384 -> 9.000000000000000E+384 Inexact Rounded +addx6562 add 0 9.000000000000000E+384 -> 9.000000000000000E+384 Rounded +-- and using decimal64 bounds... +rounding: down +addx6563 add 1e-388 9.000000000000000E+374 -> 9.000000000000000E+374 Inexact Rounded +addx6564 add 0 9.000000000000000E+374 -> 9.000000000000000E+374 Rounded + +-- more zeros, etc. +rounding: half_even + +addx6701 add 5.00 1.00E-3 -> 5.00100 +addx6702 add 00.00 0.000 -> 0.000 +addx6703 add 00.00 0E-3 -> 0.000 +addx6704 add 0E-3 00.00 -> 0.000 + +addx6710 add 0E+3 00.00 -> 0.00 +addx6711 add 0E+3 00.0 -> 0.0 +addx6712 add 0E+3 00. -> 0 +addx6713 add 0E+3 00.E+1 -> 0E+1 +addx6714 add 0E+3 00.E+2 -> 0E+2 +addx6715 add 0E+3 00.E+3 -> 0E+3 +addx6716 add 0E+3 00.E+4 -> 0E+3 +addx6717 add 0E+3 00.E+5 -> 0E+3 +addx6718 add 0E+3 -00.0 -> 0.0 +addx6719 add 0E+3 -00. -> 0 +addx6731 add 0E+3 -00.E+1 -> 0E+1 + +addx6720 add 00.00 0E+3 -> 0.00 +addx6721 add 00.0 0E+3 -> 0.0 +addx6722 add 00. 0E+3 -> 0 +addx6723 add 00.E+1 0E+3 -> 0E+1 +addx6724 add 00.E+2 0E+3 -> 0E+2 +addx6725 add 00.E+3 0E+3 -> 0E+3 +addx6726 add 00.E+4 0E+3 -> 0E+3 +addx6727 add 00.E+5 0E+3 -> 0E+3 +addx6728 add -00.00 0E+3 -> 0.00 +addx6729 add -00.0 0E+3 -> 0.0 +addx6730 add -00. 0E+3 -> 0 + +addx6732 add 0 0 -> 0 +addx6733 add 0 -0 -> 0 +addx6734 add -0 0 -> 0 +addx6735 add -0 -0 -> -0 -- IEEE 854 special case + +addx6736 add 1 -1 -> 0 +addx6737 add -1 -1 -> -2 +addx6738 add 1 1 -> 2 +addx6739 add -1 1 -> 0 + +addx6741 add 0 -1 -> -1 +addx6742 add -0 -1 -> -1 +addx6743 add 0 1 -> 1 +addx6744 add -0 1 -> 1 +addx6745 add -1 0 -> -1 +addx6746 add -1 -0 -> -1 +addx6747 add 1 0 -> 1 +addx6748 add 1 -0 -> 1 + +addx6751 add 0.0 -1 -> -1.0 +addx6752 add -0.0 -1 -> -1.0 +addx6753 add 0.0 1 -> 1.0 +addx6754 add -0.0 1 -> 1.0 +addx6755 add -1.0 0 -> -1.0 +addx6756 add -1.0 -0 -> -1.0 +addx6757 add 1.0 0 -> 1.0 +addx6758 add 1.0 -0 -> 1.0 + +addx6761 add 0 -1.0 -> -1.0 +addx6762 add -0 -1.0 -> -1.0 +addx6763 add 0 1.0 -> 1.0 +addx6764 add -0 1.0 -> 1.0 +addx6765 add -1 0.0 -> -1.0 +addx6766 add -1 -0.0 -> -1.0 +addx6767 add 1 0.0 -> 1.0 +addx6768 add 1 -0.0 -> 1.0 + +addx6771 add 0.0 -1.0 -> -1.0 +addx6772 add -0.0 -1.0 -> -1.0 +addx6773 add 0.0 1.0 -> 1.0 +addx6774 add -0.0 1.0 -> 1.0 +addx6775 add -1.0 0.0 -> -1.0 +addx6776 add -1.0 -0.0 -> -1.0 +addx6777 add 1.0 0.0 -> 1.0 +addx6778 add 1.0 -0.0 -> 1.0 + +-- Specials +addx6780 add -Inf -Inf -> -Infinity +addx6781 add -Inf -1000 -> -Infinity +addx6782 add -Inf -1 -> -Infinity +addx6783 add -Inf -0 -> -Infinity +addx6784 add -Inf 0 -> -Infinity +addx6785 add -Inf 1 -> -Infinity +addx6786 add -Inf 1000 -> -Infinity +addx6787 add -1000 -Inf -> -Infinity +addx6788 add -Inf -Inf -> -Infinity +addx6789 add -1 -Inf -> -Infinity +addx6790 add -0 -Inf -> -Infinity +addx6791 add 0 -Inf -> -Infinity +addx6792 add 1 -Inf -> -Infinity +addx6793 add 1000 -Inf -> -Infinity +addx6794 add Inf -Inf -> NaN Invalid_operation + +addx6800 add Inf -Inf -> NaN Invalid_operation +addx6801 add Inf -1000 -> Infinity +addx6802 add Inf -1 -> Infinity +addx6803 add Inf -0 -> Infinity +addx6804 add Inf 0 -> Infinity +addx6805 add Inf 1 -> Infinity +addx6806 add Inf 1000 -> Infinity +addx6807 add Inf Inf -> Infinity +addx6808 add -1000 Inf -> Infinity +addx6809 add -Inf Inf -> NaN Invalid_operation +addx6810 add -1 Inf -> Infinity +addx6811 add -0 Inf -> Infinity +addx6812 add 0 Inf -> Infinity +addx6813 add 1 Inf -> Infinity +addx6814 add 1000 Inf -> Infinity +addx6815 add Inf Inf -> Infinity + +addx6821 add NaN -Inf -> NaN +addx6822 add NaN -1000 -> NaN +addx6823 add NaN -1 -> NaN +addx6824 add NaN -0 -> NaN +addx6825 add NaN 0 -> NaN +addx6826 add NaN 1 -> NaN +addx6827 add NaN 1000 -> NaN +addx6828 add NaN Inf -> NaN +addx6829 add NaN NaN -> NaN +addx6830 add -Inf NaN -> NaN +addx6831 add -1000 NaN -> NaN +addx6832 add -1 NaN -> NaN +addx6833 add -0 NaN -> NaN +addx6834 add 0 NaN -> NaN +addx6835 add 1 NaN -> NaN +addx6836 add 1000 NaN -> NaN +addx6837 add Inf NaN -> NaN + +addx6841 add sNaN -Inf -> NaN Invalid_operation +addx6842 add sNaN -1000 -> NaN Invalid_operation +addx6843 add sNaN -1 -> NaN Invalid_operation +addx6844 add sNaN -0 -> NaN Invalid_operation +addx6845 add sNaN 0 -> NaN Invalid_operation +addx6846 add sNaN 1 -> NaN Invalid_operation +addx6847 add sNaN 1000 -> NaN Invalid_operation +addx6848 add sNaN NaN -> NaN Invalid_operation +addx6849 add sNaN sNaN -> NaN Invalid_operation +addx6850 add NaN sNaN -> NaN Invalid_operation +addx6851 add -Inf sNaN -> NaN Invalid_operation +addx6852 add -1000 sNaN -> NaN Invalid_operation +addx6853 add -1 sNaN -> NaN Invalid_operation +addx6854 add -0 sNaN -> NaN Invalid_operation +addx6855 add 0 sNaN -> NaN Invalid_operation +addx6856 add 1 sNaN -> NaN Invalid_operation +addx6857 add 1000 sNaN -> NaN Invalid_operation +addx6858 add Inf sNaN -> NaN Invalid_operation +addx6859 add NaN sNaN -> NaN Invalid_operation + +-- propagating NaNs +addx6861 add NaN1 -Inf -> NaN1 +addx6862 add +NaN2 -1000 -> NaN2 +addx6863 add NaN3 1000 -> NaN3 +addx6864 add NaN4 Inf -> NaN4 +addx6865 add NaN5 +NaN6 -> NaN5 +addx6866 add -Inf NaN7 -> NaN7 +addx6867 add -1000 NaN8 -> NaN8 +addx6868 add 1000 NaN9 -> NaN9 +addx6869 add Inf +NaN10 -> NaN10 +addx6871 add sNaN11 -Inf -> NaN11 Invalid_operation +addx6872 add sNaN12 -1000 -> NaN12 Invalid_operation +addx6873 add sNaN13 1000 -> NaN13 Invalid_operation +addx6874 add sNaN14 NaN17 -> NaN14 Invalid_operation +addx6875 add sNaN15 sNaN18 -> NaN15 Invalid_operation +addx6876 add NaN16 sNaN19 -> NaN19 Invalid_operation +addx6877 add -Inf +sNaN20 -> NaN20 Invalid_operation +addx6878 add -1000 sNaN21 -> NaN21 Invalid_operation +addx6879 add 1000 sNaN22 -> NaN22 Invalid_operation +addx6880 add Inf sNaN23 -> NaN23 Invalid_operation +addx6881 add +NaN25 +sNaN24 -> NaN24 Invalid_operation +addx6882 add -NaN26 NaN28 -> -NaN26 +addx6883 add -sNaN27 sNaN29 -> -NaN27 Invalid_operation +addx6884 add 1000 -NaN30 -> -NaN30 +addx6885 add 1000 -sNaN31 -> -NaN31 Invalid_operation + +-- now the case where we can get underflow but the result is normal +-- [note this can't happen if the operands are also bounded, as we +-- cannot represent 1E-399, for example] + +addx6571 add 1E-383 0 -> 1E-383 +addx6572 add 1E-384 0 -> 1E-384 Subnormal +addx6573 add 1E-383 1E-384 -> 1.1E-383 +addx6574 subtract 1E-383 1E-384 -> 9E-384 Subnormal + +-- Here we explore the boundary of rounding a subnormal to Nmin +addx6575 subtract 1E-383 1E-398 -> 9.99999999999999E-384 Subnormal +addx6576 subtract 1E-383 1E-398 -> 9.99999999999999E-384 Subnormal +addx6577 subtract 1E-383 1E-399 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +addx6578 subtract 1E-383 1E-400 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +addx6579 subtract 1E-383 1E-401 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +addx6580 subtract 1E-383 1E-402 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded + +-- check overflow edge case +-- 1234567890123456 +addx6972 apply 9.999999999999999E+384 -> 9.999999999999999E+384 +addx6973 add 9.999999999999999E+384 1 -> 9.999999999999999E+384 Inexact Rounded +addx6974 add 9999999999999999E+369 1 -> 9.999999999999999E+384 Inexact Rounded +addx6975 add 9999999999999999E+369 1E+369 -> Infinity Overflow Inexact Rounded +addx6976 add 9999999999999999E+369 9E+368 -> Infinity Overflow Inexact Rounded +addx6977 add 9999999999999999E+369 8E+368 -> Infinity Overflow Inexact Rounded +addx6978 add 9999999999999999E+369 7E+368 -> Infinity Overflow Inexact Rounded +addx6979 add 9999999999999999E+369 6E+368 -> Infinity Overflow Inexact Rounded +addx6980 add 9999999999999999E+369 5E+368 -> Infinity Overflow Inexact Rounded +addx6981 add 9999999999999999E+369 4E+368 -> 9.999999999999999E+384 Inexact Rounded +addx6982 add 9999999999999999E+369 3E+368 -> 9.999999999999999E+384 Inexact Rounded +addx6983 add 9999999999999999E+369 2E+368 -> 9.999999999999999E+384 Inexact Rounded +addx6984 add 9999999999999999E+369 1E+368 -> 9.999999999999999E+384 Inexact Rounded + +addx6985 apply -9.999999999999999E+384 -> -9.999999999999999E+384 +addx6986 add -9.999999999999999E+384 -1 -> -9.999999999999999E+384 Inexact Rounded +addx6987 add -9999999999999999E+369 -1 -> -9.999999999999999E+384 Inexact Rounded +addx6988 add -9999999999999999E+369 -1E+369 -> -Infinity Overflow Inexact Rounded +addx6989 add -9999999999999999E+369 -9E+368 -> -Infinity Overflow Inexact Rounded +addx6990 add -9999999999999999E+369 -8E+368 -> -Infinity Overflow Inexact Rounded +addx6991 add -9999999999999999E+369 -7E+368 -> -Infinity Overflow Inexact Rounded +addx6992 add -9999999999999999E+369 -6E+368 -> -Infinity Overflow Inexact Rounded +addx6993 add -9999999999999999E+369 -5E+368 -> -Infinity Overflow Inexact Rounded +addx6994 add -9999999999999999E+369 -4E+368 -> -9.999999999999999E+384 Inexact Rounded +addx6995 add -9999999999999999E+369 -3E+368 -> -9.999999999999999E+384 Inexact Rounded +addx6996 add -9999999999999999E+369 -2E+368 -> -9.999999999999999E+384 Inexact Rounded +addx6997 add -9999999999999999E+369 -1E+368 -> -9.999999999999999E+384 Inexact Rounded + +-- And for round down full and subnormal results +rounding: down +addx61100 add 1e+2 -1e-383 -> 99.99999999999999 Rounded Inexact +addx61101 add 1e+1 -1e-383 -> 9.999999999999999 Rounded Inexact +addx61103 add +1 -1e-383 -> 0.9999999999999999 Rounded Inexact +addx61104 add 1e-1 -1e-383 -> 0.09999999999999999 Rounded Inexact +addx61105 add 1e-2 -1e-383 -> 0.009999999999999999 Rounded Inexact +addx61106 add 1e-3 -1e-383 -> 0.0009999999999999999 Rounded Inexact +addx61107 add 1e-4 -1e-383 -> 0.00009999999999999999 Rounded Inexact +addx61108 add 1e-5 -1e-383 -> 0.000009999999999999999 Rounded Inexact +addx61109 add 1e-6 -1e-383 -> 9.999999999999999E-7 Rounded Inexact + +rounding: ceiling +addx61110 add -1e+2 +1e-383 -> -99.99999999999999 Rounded Inexact +addx61111 add -1e+1 +1e-383 -> -9.999999999999999 Rounded Inexact +addx61113 add -1 +1e-383 -> -0.9999999999999999 Rounded Inexact +addx61114 add -1e-1 +1e-383 -> -0.09999999999999999 Rounded Inexact +addx61115 add -1e-2 +1e-383 -> -0.009999999999999999 Rounded Inexact +addx61116 add -1e-3 +1e-383 -> -0.0009999999999999999 Rounded Inexact +addx61117 add -1e-4 +1e-383 -> -0.00009999999999999999 Rounded Inexact +addx61118 add -1e-5 +1e-383 -> -0.000009999999999999999 Rounded Inexact +addx61119 add -1e-6 +1e-383 -> -9.999999999999999E-7 Rounded Inexact + +-- tests based on Gunnar Degnbol's edge case +rounding: half_even + +addx61300 add 1E16 -0.5 -> 1.000000000000000E+16 Inexact Rounded +addx61310 add 1E16 -0.51 -> 9999999999999999 Inexact Rounded +addx61311 add 1E16 -0.501 -> 9999999999999999 Inexact Rounded +addx61312 add 1E16 -0.5001 -> 9999999999999999 Inexact Rounded +addx61313 add 1E16 -0.50001 -> 9999999999999999 Inexact Rounded +addx61314 add 1E16 -0.500001 -> 9999999999999999 Inexact Rounded +addx61315 add 1E16 -0.5000001 -> 9999999999999999 Inexact Rounded +addx61316 add 1E16 -0.50000001 -> 9999999999999999 Inexact Rounded +addx61317 add 1E16 -0.500000001 -> 9999999999999999 Inexact Rounded +addx61318 add 1E16 -0.5000000001 -> 9999999999999999 Inexact Rounded +addx61319 add 1E16 -0.50000000001 -> 9999999999999999 Inexact Rounded +addx61320 add 1E16 -0.500000000001 -> 9999999999999999 Inexact Rounded +addx61321 add 1E16 -0.5000000000001 -> 9999999999999999 Inexact Rounded +addx61322 add 1E16 -0.50000000000001 -> 9999999999999999 Inexact Rounded +addx61323 add 1E16 -0.500000000000001 -> 9999999999999999 Inexact Rounded +addx61324 add 1E16 -0.5000000000000001 -> 9999999999999999 Inexact Rounded +addx61325 add 1E16 -0.5000000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61326 add 1E16 -0.500000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61327 add 1E16 -0.50000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61328 add 1E16 -0.5000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61329 add 1E16 -0.500000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61330 add 1E16 -0.50000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61331 add 1E16 -0.5000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61332 add 1E16 -0.500000000 -> 1.000000000000000E+16 Inexact Rounded +addx61333 add 1E16 -0.50000000 -> 1.000000000000000E+16 Inexact Rounded +addx61334 add 1E16 -0.5000000 -> 1.000000000000000E+16 Inexact Rounded +addx61335 add 1E16 -0.500000 -> 1.000000000000000E+16 Inexact Rounded +addx61336 add 1E16 -0.50000 -> 1.000000000000000E+16 Inexact Rounded +addx61337 add 1E16 -0.5000 -> 1.000000000000000E+16 Inexact Rounded +addx61338 add 1E16 -0.500 -> 1.000000000000000E+16 Inexact Rounded +addx61339 add 1E16 -0.50 -> 1.000000000000000E+16 Inexact Rounded + +addx61340 add 1E16 -5000000.000010001 -> 9999999995000000 Inexact Rounded +addx61341 add 1E16 -5000000.000000001 -> 9999999995000000 Inexact Rounded + +addx61349 add 9999999999999999 0.4 -> 9999999999999999 Inexact Rounded +addx61350 add 9999999999999999 0.49 -> 9999999999999999 Inexact Rounded +addx61351 add 9999999999999999 0.499 -> 9999999999999999 Inexact Rounded +addx61352 add 9999999999999999 0.4999 -> 9999999999999999 Inexact Rounded +addx61353 add 9999999999999999 0.49999 -> 9999999999999999 Inexact Rounded +addx61354 add 9999999999999999 0.499999 -> 9999999999999999 Inexact Rounded +addx61355 add 9999999999999999 0.4999999 -> 9999999999999999 Inexact Rounded +addx61356 add 9999999999999999 0.49999999 -> 9999999999999999 Inexact Rounded +addx61357 add 9999999999999999 0.499999999 -> 9999999999999999 Inexact Rounded +addx61358 add 9999999999999999 0.4999999999 -> 9999999999999999 Inexact Rounded +addx61359 add 9999999999999999 0.49999999999 -> 9999999999999999 Inexact Rounded +addx61360 add 9999999999999999 0.499999999999 -> 9999999999999999 Inexact Rounded +addx61361 add 9999999999999999 0.4999999999999 -> 9999999999999999 Inexact Rounded +addx61362 add 9999999999999999 0.49999999999999 -> 9999999999999999 Inexact Rounded +addx61363 add 9999999999999999 0.499999999999999 -> 9999999999999999 Inexact Rounded +addx61364 add 9999999999999999 0.4999999999999999 -> 9999999999999999 Inexact Rounded +addx61365 add 9999999999999999 0.5000000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61367 add 9999999999999999 0.500000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61368 add 9999999999999999 0.50000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61369 add 9999999999999999 0.5000000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61370 add 9999999999999999 0.500000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61371 add 9999999999999999 0.50000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61372 add 9999999999999999 0.5000000000 -> 1.000000000000000E+16 Inexact Rounded +addx61373 add 9999999999999999 0.500000000 -> 1.000000000000000E+16 Inexact Rounded +addx61374 add 9999999999999999 0.50000000 -> 1.000000000000000E+16 Inexact Rounded +addx61375 add 9999999999999999 0.5000000 -> 1.000000000000000E+16 Inexact Rounded +addx61376 add 9999999999999999 0.500000 -> 1.000000000000000E+16 Inexact Rounded +addx61377 add 9999999999999999 0.50000 -> 1.000000000000000E+16 Inexact Rounded +addx61378 add 9999999999999999 0.5000 -> 1.000000000000000E+16 Inexact Rounded +addx61379 add 9999999999999999 0.500 -> 1.000000000000000E+16 Inexact Rounded +addx61380 add 9999999999999999 0.50 -> 1.000000000000000E+16 Inexact Rounded +addx61381 add 9999999999999999 0.5 -> 1.000000000000000E+16 Inexact Rounded +addx61382 add 9999999999999999 0.5000000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61383 add 9999999999999999 0.500000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61384 add 9999999999999999 0.50000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61385 add 9999999999999999 0.5000000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61386 add 9999999999999999 0.500000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61387 add 9999999999999999 0.50000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61388 add 9999999999999999 0.5000000001 -> 1.000000000000000E+16 Inexact Rounded +addx61389 add 9999999999999999 0.500000001 -> 1.000000000000000E+16 Inexact Rounded +addx61390 add 9999999999999999 0.50000001 -> 1.000000000000000E+16 Inexact Rounded +addx61391 add 9999999999999999 0.5000001 -> 1.000000000000000E+16 Inexact Rounded +addx61392 add 9999999999999999 0.500001 -> 1.000000000000000E+16 Inexact Rounded +addx61393 add 9999999999999999 0.50001 -> 1.000000000000000E+16 Inexact Rounded +addx61394 add 9999999999999999 0.5001 -> 1.000000000000000E+16 Inexact Rounded +addx61395 add 9999999999999999 0.501 -> 1.000000000000000E+16 Inexact Rounded +addx61396 add 9999999999999999 0.51 -> 1.000000000000000E+16 Inexact Rounded + +-- More GD edge cases, where difference between the unadjusted +-- exponents is larger than the maximum precision and one side is 0 +addx61420 add 0 1.123456789012345 -> 1.123456789012345 +addx61421 add 0 1.123456789012345E-1 -> 0.1123456789012345 +addx61422 add 0 1.123456789012345E-2 -> 0.01123456789012345 +addx61423 add 0 1.123456789012345E-3 -> 0.001123456789012345 +addx61424 add 0 1.123456789012345E-4 -> 0.0001123456789012345 +addx61425 add 0 1.123456789012345E-5 -> 0.00001123456789012345 +addx61426 add 0 1.123456789012345E-6 -> 0.000001123456789012345 +addx61427 add 0 1.123456789012345E-7 -> 1.123456789012345E-7 +addx61428 add 0 1.123456789012345E-8 -> 1.123456789012345E-8 +addx61429 add 0 1.123456789012345E-9 -> 1.123456789012345E-9 +addx61430 add 0 1.123456789012345E-10 -> 1.123456789012345E-10 +addx61431 add 0 1.123456789012345E-11 -> 1.123456789012345E-11 +addx61432 add 0 1.123456789012345E-12 -> 1.123456789012345E-12 +addx61433 add 0 1.123456789012345E-13 -> 1.123456789012345E-13 +addx61434 add 0 1.123456789012345E-14 -> 1.123456789012345E-14 +addx61435 add 0 1.123456789012345E-15 -> 1.123456789012345E-15 +addx61436 add 0 1.123456789012345E-16 -> 1.123456789012345E-16 +addx61437 add 0 1.123456789012345E-17 -> 1.123456789012345E-17 +addx61438 add 0 1.123456789012345E-18 -> 1.123456789012345E-18 +addx61439 add 0 1.123456789012345E-19 -> 1.123456789012345E-19 + +-- same, reversed 0 +addx61440 add 1.123456789012345 0 -> 1.123456789012345 +addx61441 add 1.123456789012345E-1 0 -> 0.1123456789012345 +addx61442 add 1.123456789012345E-2 0 -> 0.01123456789012345 +addx61443 add 1.123456789012345E-3 0 -> 0.001123456789012345 +addx61444 add 1.123456789012345E-4 0 -> 0.0001123456789012345 +addx61445 add 1.123456789012345E-5 0 -> 0.00001123456789012345 +addx61446 add 1.123456789012345E-6 0 -> 0.000001123456789012345 +addx61447 add 1.123456789012345E-7 0 -> 1.123456789012345E-7 +addx61448 add 1.123456789012345E-8 0 -> 1.123456789012345E-8 +addx61449 add 1.123456789012345E-9 0 -> 1.123456789012345E-9 +addx61450 add 1.123456789012345E-10 0 -> 1.123456789012345E-10 +addx61451 add 1.123456789012345E-11 0 -> 1.123456789012345E-11 +addx61452 add 1.123456789012345E-12 0 -> 1.123456789012345E-12 +addx61453 add 1.123456789012345E-13 0 -> 1.123456789012345E-13 +addx61454 add 1.123456789012345E-14 0 -> 1.123456789012345E-14 +addx61455 add 1.123456789012345E-15 0 -> 1.123456789012345E-15 +addx61456 add 1.123456789012345E-16 0 -> 1.123456789012345E-16 +addx61457 add 1.123456789012345E-17 0 -> 1.123456789012345E-17 +addx61458 add 1.123456789012345E-18 0 -> 1.123456789012345E-18 +addx61459 add 1.123456789012345E-19 0 -> 1.123456789012345E-19 + +-- same, Es on the 0 +addx61460 add 1.123456789012345 0E-0 -> 1.123456789012345 +addx61461 add 1.123456789012345 0E-1 -> 1.123456789012345 +addx61462 add 1.123456789012345 0E-2 -> 1.123456789012345 +addx61463 add 1.123456789012345 0E-3 -> 1.123456789012345 +addx61464 add 1.123456789012345 0E-4 -> 1.123456789012345 +addx61465 add 1.123456789012345 0E-5 -> 1.123456789012345 +addx61466 add 1.123456789012345 0E-6 -> 1.123456789012345 +addx61467 add 1.123456789012345 0E-7 -> 1.123456789012345 +addx61468 add 1.123456789012345 0E-8 -> 1.123456789012345 +addx61469 add 1.123456789012345 0E-9 -> 1.123456789012345 +addx61470 add 1.123456789012345 0E-10 -> 1.123456789012345 +addx61471 add 1.123456789012345 0E-11 -> 1.123456789012345 +addx61472 add 1.123456789012345 0E-12 -> 1.123456789012345 +addx61473 add 1.123456789012345 0E-13 -> 1.123456789012345 +addx61474 add 1.123456789012345 0E-14 -> 1.123456789012345 +addx61475 add 1.123456789012345 0E-15 -> 1.123456789012345 +-- next four flag Rounded because the 0 extends the result +addx61476 add 1.123456789012345 0E-16 -> 1.123456789012345 Rounded +addx61477 add 1.123456789012345 0E-17 -> 1.123456789012345 Rounded +addx61478 add 1.123456789012345 0E-18 -> 1.123456789012345 Rounded +addx61479 add 1.123456789012345 0E-19 -> 1.123456789012345 Rounded + +-- sum of two opposite-sign operands is exactly 0 and floor => -0 +rounding: half_up +-- exact zeros from zeros +addx61500 add 0 0E-19 -> 0E-19 +addx61501 add -0 0E-19 -> 0E-19 +addx61502 add 0 -0E-19 -> 0E-19 +addx61503 add -0 -0E-19 -> -0E-19 +addx61504 add 0E-400 0E-19 -> 0E-398 Clamped +addx61505 add -0E-400 0E-19 -> 0E-398 Clamped +addx61506 add 0E-400 -0E-19 -> 0E-398 Clamped +addx61507 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61511 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61512 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61513 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61514 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx61515 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61516 add -1E-401 1E-401 -> 0E-398 Clamped +addx61517 add 1E-401 -1E-401 -> 0E-398 Clamped +addx61518 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: half_down +-- exact zeros from zeros +addx61520 add 0 0E-19 -> 0E-19 +addx61521 add -0 0E-19 -> 0E-19 +addx61522 add 0 -0E-19 -> 0E-19 +addx61523 add -0 -0E-19 -> -0E-19 +addx61524 add 0E-400 0E-19 -> 0E-398 Clamped +addx61525 add -0E-400 0E-19 -> 0E-398 Clamped +addx61526 add 0E-400 -0E-19 -> 0E-398 Clamped +addx61527 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61531 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61532 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61533 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61534 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx61535 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61536 add -1E-401 1E-401 -> 0E-398 Clamped +addx61537 add 1E-401 -1E-401 -> 0E-398 Clamped +addx61538 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: half_even +-- exact zeros from zeros +addx61540 add 0 0E-19 -> 0E-19 +addx61541 add -0 0E-19 -> 0E-19 +addx61542 add 0 -0E-19 -> 0E-19 +addx61543 add -0 -0E-19 -> -0E-19 +addx61544 add 0E-400 0E-19 -> 0E-398 Clamped +addx61545 add -0E-400 0E-19 -> 0E-398 Clamped +addx61546 add 0E-400 -0E-19 -> 0E-398 Clamped +addx61547 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61551 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61552 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61553 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61554 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx61555 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61556 add -1E-401 1E-401 -> 0E-398 Clamped +addx61557 add 1E-401 -1E-401 -> 0E-398 Clamped +addx61558 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: up +-- exact zeros from zeros +addx61560 add 0 0E-19 -> 0E-19 +addx61561 add -0 0E-19 -> 0E-19 +addx61562 add 0 -0E-19 -> 0E-19 +addx61563 add -0 -0E-19 -> -0E-19 +addx61564 add 0E-400 0E-19 -> 0E-398 Clamped +addx61565 add -0E-400 0E-19 -> 0E-398 Clamped +addx61566 add 0E-400 -0E-19 -> 0E-398 Clamped +addx61567 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61571 add 1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx61572 add -1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx61573 add 1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +addx61574 add -1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +-- some exact zeros from non-zeros +addx61575 add 1E-401 1E-401 -> 1E-398 Subnormal Inexact Rounded Underflow +addx61576 add -1E-401 1E-401 -> 0E-398 Clamped +addx61577 add 1E-401 -1E-401 -> 0E-398 Clamped +addx61578 add -1E-401 -1E-401 -> -1E-398 Subnormal Inexact Rounded Underflow + +rounding: down +-- exact zeros from zeros +addx61580 add 0 0E-19 -> 0E-19 +addx61581 add -0 0E-19 -> 0E-19 +addx61582 add 0 -0E-19 -> 0E-19 +addx61583 add -0 -0E-19 -> -0E-19 +addx61584 add 0E-400 0E-19 -> 0E-398 Clamped +addx61585 add -0E-400 0E-19 -> 0E-398 Clamped +addx61586 add 0E-400 -0E-19 -> 0E-398 Clamped +addx61587 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61591 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61592 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61593 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61594 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx61595 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61596 add -1E-401 1E-401 -> 0E-398 Clamped +addx61597 add 1E-401 -1E-401 -> 0E-398 Clamped +addx61598 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +rounding: ceiling +-- exact zeros from zeros +addx61600 add 0 0E-19 -> 0E-19 +addx61601 add -0 0E-19 -> 0E-19 +addx61602 add 0 -0E-19 -> 0E-19 +addx61603 add -0 -0E-19 -> -0E-19 +addx61604 add 0E-400 0E-19 -> 0E-398 Clamped +addx61605 add -0E-400 0E-19 -> 0E-398 Clamped +addx61606 add 0E-400 -0E-19 -> 0E-398 Clamped +addx61607 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61611 add 1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx61612 add -1E-401 1E-400 -> 1E-398 Subnormal Inexact Rounded Underflow +addx61613 add 1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61614 add -1E-401 -1E-400 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped +-- some exact zeros from non-zeros +addx61615 add 1E-401 1E-401 -> 1E-398 Subnormal Inexact Rounded Underflow +addx61616 add -1E-401 1E-401 -> 0E-398 Clamped +addx61617 add 1E-401 -1E-401 -> 0E-398 Clamped +addx61618 add -1E-401 -1E-401 -> -0E-398 Subnormal Inexact Rounded Underflow Clamped + +-- and the extra-special ugly case; unusual minuses marked by -- * +rounding: floor +-- exact zeros from zeros +addx61620 add 0 0E-19 -> 0E-19 +addx61621 add -0 0E-19 -> -0E-19 -- * +addx61622 add 0 -0E-19 -> -0E-19 -- * +addx61623 add -0 -0E-19 -> -0E-19 +addx61624 add 0E-400 0E-19 -> 0E-398 Clamped +addx61625 add -0E-400 0E-19 -> -0E-398 Clamped -- * +addx61626 add 0E-400 -0E-19 -> -0E-398 Clamped -- * +addx61627 add -0E-400 -0E-19 -> -0E-398 Clamped +-- inexact zeros +addx61631 add 1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61632 add -1E-401 1E-400 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61633 add 1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +addx61634 add -1E-401 -1E-400 -> -1E-398 Subnormal Inexact Rounded Underflow +-- some exact zeros from non-zeros +addx61635 add 1E-401 1E-401 -> 0E-398 Subnormal Inexact Rounded Underflow Clamped +addx61636 add -1E-401 1E-401 -> -0E-398 Clamped -- * +addx61637 add 1E-401 -1E-401 -> -0E-398 Clamped -- * +addx61638 add -1E-401 -1E-401 -> -1E-398 Subnormal Inexact Rounded Underflow + +-- Examples from SQL proposal (Krishna Kulkarni) +addx61701 add 130E-2 120E-2 -> 2.50 +addx61702 add 130E-2 12E-1 -> 2.50 +addx61703 add 130E-2 1E0 -> 2.30 +addx61704 add 1E2 1E4 -> 1.01E+4 +addx61705 subtract 130E-2 120E-2 -> 0.10 +addx61706 subtract 130E-2 12E-1 -> 0.10 +addx61707 subtract 130E-2 1E0 -> 0.30 +addx61708 subtract 1E2 1E4 -> -9.9E+3 + +-- Gappy coefficients; check residue handling even with full coefficient gap +rounding: half_even + +addx62001 add 1234567890123456 1 -> 1234567890123457 +addx62002 add 1234567890123456 0.6 -> 1234567890123457 Inexact Rounded +addx62003 add 1234567890123456 0.06 -> 1234567890123456 Inexact Rounded +addx62004 add 1234567890123456 6E-3 -> 1234567890123456 Inexact Rounded +addx62005 add 1234567890123456 6E-4 -> 1234567890123456 Inexact Rounded +addx62006 add 1234567890123456 6E-5 -> 1234567890123456 Inexact Rounded +addx62007 add 1234567890123456 6E-6 -> 1234567890123456 Inexact Rounded +addx62008 add 1234567890123456 6E-7 -> 1234567890123456 Inexact Rounded +addx62009 add 1234567890123456 6E-8 -> 1234567890123456 Inexact Rounded +addx62010 add 1234567890123456 6E-9 -> 1234567890123456 Inexact Rounded +addx62011 add 1234567890123456 6E-10 -> 1234567890123456 Inexact Rounded +addx62012 add 1234567890123456 6E-11 -> 1234567890123456 Inexact Rounded +addx62013 add 1234567890123456 6E-12 -> 1234567890123456 Inexact Rounded +addx62014 add 1234567890123456 6E-13 -> 1234567890123456 Inexact Rounded +addx62015 add 1234567890123456 6E-14 -> 1234567890123456 Inexact Rounded +addx62016 add 1234567890123456 6E-15 -> 1234567890123456 Inexact Rounded +addx62017 add 1234567890123456 6E-16 -> 1234567890123456 Inexact Rounded +addx62018 add 1234567890123456 6E-17 -> 1234567890123456 Inexact Rounded +addx62019 add 1234567890123456 6E-18 -> 1234567890123456 Inexact Rounded +addx62020 add 1234567890123456 6E-19 -> 1234567890123456 Inexact Rounded +addx62021 add 1234567890123456 6E-20 -> 1234567890123456 Inexact Rounded + +-- widening second argument at gap +addx62030 add 12345678 1 -> 12345679 +addx62031 add 12345678 0.1 -> 12345678.1 +addx62032 add 12345678 0.12 -> 12345678.12 +addx62033 add 12345678 0.123 -> 12345678.123 +addx62034 add 12345678 0.1234 -> 12345678.1234 +addx62035 add 12345678 0.12345 -> 12345678.12345 +addx62036 add 12345678 0.123456 -> 12345678.123456 +addx62037 add 12345678 0.1234567 -> 12345678.1234567 +addx62038 add 12345678 0.12345678 -> 12345678.12345678 +addx62039 add 12345678 0.123456789 -> 12345678.12345679 Inexact Rounded +addx62040 add 12345678 0.123456785 -> 12345678.12345678 Inexact Rounded +addx62041 add 12345678 0.1234567850 -> 12345678.12345678 Inexact Rounded +addx62042 add 12345678 0.1234567851 -> 12345678.12345679 Inexact Rounded +addx62043 add 12345678 0.12345678501 -> 12345678.12345679 Inexact Rounded +addx62044 add 12345678 0.123456785001 -> 12345678.12345679 Inexact Rounded +addx62045 add 12345678 0.1234567850001 -> 12345678.12345679 Inexact Rounded +addx62046 add 12345678 0.12345678500001 -> 12345678.12345679 Inexact Rounded +addx62047 add 12345678 0.123456785000001 -> 12345678.12345679 Inexact Rounded +addx62048 add 12345678 0.1234567850000001 -> 12345678.12345679 Inexact Rounded +addx62049 add 12345678 0.1234567850000000 -> 12345678.12345678 Inexact Rounded +-- 90123456 +rounding: half_even +addx62050 add 12345678 0.0234567750000000 -> 12345678.02345678 Inexact Rounded +addx62051 add 12345678 0.0034567750000000 -> 12345678.00345678 Inexact Rounded +addx62052 add 12345678 0.0004567750000000 -> 12345678.00045678 Inexact Rounded +addx62053 add 12345678 0.0000567750000000 -> 12345678.00005678 Inexact Rounded +addx62054 add 12345678 0.0000067750000000 -> 12345678.00000678 Inexact Rounded +addx62055 add 12345678 0.0000007750000000 -> 12345678.00000078 Inexact Rounded +addx62056 add 12345678 0.0000000750000000 -> 12345678.00000008 Inexact Rounded +addx62057 add 12345678 0.0000000050000000 -> 12345678.00000000 Inexact Rounded +addx62060 add 12345678 0.0234567750000001 -> 12345678.02345678 Inexact Rounded +addx62061 add 12345678 0.0034567750000001 -> 12345678.00345678 Inexact Rounded +addx62062 add 12345678 0.0004567750000001 -> 12345678.00045678 Inexact Rounded +addx62063 add 12345678 0.0000567750000001 -> 12345678.00005678 Inexact Rounded +addx62064 add 12345678 0.0000067750000001 -> 12345678.00000678 Inexact Rounded +addx62065 add 12345678 0.0000007750000001 -> 12345678.00000078 Inexact Rounded +addx62066 add 12345678 0.0000000750000001 -> 12345678.00000008 Inexact Rounded +addx62067 add 12345678 0.0000000050000001 -> 12345678.00000001 Inexact Rounded +-- far-out residues (full coefficient gap is 16+15 digits) +rounding: up +addx62070 add 12345678 1E-8 -> 12345678.00000001 +addx62071 add 12345678 1E-9 -> 12345678.00000001 Inexact Rounded +addx62072 add 12345678 1E-10 -> 12345678.00000001 Inexact Rounded +addx62073 add 12345678 1E-11 -> 12345678.00000001 Inexact Rounded +addx62074 add 12345678 1E-12 -> 12345678.00000001 Inexact Rounded +addx62075 add 12345678 1E-13 -> 12345678.00000001 Inexact Rounded +addx62076 add 12345678 1E-14 -> 12345678.00000001 Inexact Rounded +addx62077 add 12345678 1E-15 -> 12345678.00000001 Inexact Rounded +addx62078 add 12345678 1E-16 -> 12345678.00000001 Inexact Rounded +addx62079 add 12345678 1E-17 -> 12345678.00000001 Inexact Rounded +addx62080 add 12345678 1E-18 -> 12345678.00000001 Inexact Rounded +addx62081 add 12345678 1E-19 -> 12345678.00000001 Inexact Rounded +addx62082 add 12345678 1E-20 -> 12345678.00000001 Inexact Rounded +addx62083 add 12345678 1E-25 -> 12345678.00000001 Inexact Rounded +addx62084 add 12345678 1E-30 -> 12345678.00000001 Inexact Rounded +addx62085 add 12345678 1E-31 -> 12345678.00000001 Inexact Rounded +addx62086 add 12345678 1E-32 -> 12345678.00000001 Inexact Rounded +addx62087 add 12345678 1E-33 -> 12345678.00000001 Inexact Rounded +addx62088 add 12345678 1E-34 -> 12345678.00000001 Inexact Rounded +addx62089 add 12345678 1E-35 -> 12345678.00000001 Inexact Rounded + +-- payload decapitate +precision: 5 +addx62100 add 11 sNaN123456789 -> NaN56789 Invalid_operation +addx62101 add -11 -sNaN123456789 -> -NaN56789 Invalid_operation +addx62102 add 11 NaN123456789 -> NaN56789 +addx62103 add -11 -NaN123456789 -> -NaN56789 -- Null tests addx9990 add 10 # -> NaN Invalid_operation Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/base.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/base.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/base.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- base.decTest -- base decimal <--> string conversions -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,8 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 +extended: 1 -- This file tests base conversions from string to a decimal number -- and back to a string (in either Scientific or Engineering form) @@ -26,11 +27,10 @@ -- to conform to emax and precision settings (that is, numbers will -- conform to rules and exponent will be in permitted range). -precision: 15 +precision: 16 rounding: half_up -maxExponent: 999999999 -minExponent: -999999999 -extended: 1 +maxExponent: 384 +minExponent: -383 basx001 toSci 0 -> 0 basx002 toSci 1 -> 1 @@ -73,41 +73,62 @@ -- String [many more examples are implicitly tested elsewhere] -- strings without E cannot generate E in result -basx100 toSci "12" -> '12' -basx101 toSci "-76" -> '-76' -basx102 toSci "12.76" -> '12.76' -basx103 toSci "+12.76" -> '12.76' -basx104 toSci "012.76" -> '12.76' -basx105 toSci "+0.003" -> '0.003' -basx106 toSci "17." -> '17' -basx107 toSci ".5" -> '0.5' -basx108 toSci "044" -> '44' -basx109 toSci "0044" -> '44' -basx110 toSci "0.0005" -> '0.0005' -basx111 toSci "00.00005" -> '0.00005' -basx112 toSci "0.000005" -> '0.000005' -basx113 toSci "0.0000050" -> '0.0000050' -basx114 toSci "0.0000005" -> '5E-7' -basx115 toSci "0.00000005" -> '5E-8' -basx116 toSci "12345678.543210" -> '12345678.543210' -basx117 toSci "2345678.543210" -> '2345678.543210' -basx118 toSci "345678.543210" -> '345678.543210' -basx119 toSci "0345678.54321" -> '345678.54321' -basx120 toSci "345678.5432" -> '345678.5432' -basx121 toSci "+345678.5432" -> '345678.5432' -basx122 toSci "+0345678.5432" -> '345678.5432' -basx123 toSci "+00345678.5432" -> '345678.5432' -basx124 toSci "-345678.5432" -> '-345678.5432' -basx125 toSci "-0345678.5432" -> '-345678.5432' -basx126 toSci "-00345678.5432" -> '-345678.5432' +basx040 toSci "12" -> '12' +basx041 toSci "-76" -> '-76' +basx042 toSci "12.76" -> '12.76' +basx043 toSci "+12.76" -> '12.76' +basx044 toSci "012.76" -> '12.76' +basx045 toSci "+0.003" -> '0.003' +basx046 toSci "17." -> '17' +basx047 toSci ".5" -> '0.5' +basx048 toSci "044" -> '44' +basx049 toSci "0044" -> '44' +basx050 toSci "0.0005" -> '0.0005' +basx051 toSci "00.00005" -> '0.00005' +basx052 toSci "0.000005" -> '0.000005' +basx053 toSci "0.0000050" -> '0.0000050' +basx054 toSci "0.0000005" -> '5E-7' +basx055 toSci "0.00000005" -> '5E-8' +basx056 toSci "12345678.543210" -> '12345678.543210' +basx057 toSci "2345678.543210" -> '2345678.543210' +basx058 toSci "345678.543210" -> '345678.543210' +basx059 toSci "0345678.54321" -> '345678.54321' +basx060 toSci "345678.5432" -> '345678.5432' +basx061 toSci "+345678.5432" -> '345678.5432' +basx062 toSci "+0345678.5432" -> '345678.5432' +basx063 toSci "+00345678.5432" -> '345678.5432' +basx064 toSci "-345678.5432" -> '-345678.5432' +basx065 toSci "-0345678.5432" -> '-345678.5432' +basx066 toSci "-00345678.5432" -> '-345678.5432' -- examples -basx127 toSci "5E-6" -> '0.000005' -basx128 toSci "50E-7" -> '0.0000050' -basx129 toSci "5E-7" -> '5E-7' - +basx067 toSci "5E-6" -> '0.000005' +basx068 toSci "50E-7" -> '0.0000050' +basx069 toSci "5E-7" -> '5E-7' -- [No exotics as no Unicode] +-- rounded with dots in all (including edge) places +basx071 toSci .1234567890123456123 -> 0.1234567890123456 Inexact Rounded +basx072 toSci 1.234567890123456123 -> 1.234567890123456 Inexact Rounded +basx073 toSci 12.34567890123456123 -> 12.34567890123456 Inexact Rounded +basx074 toSci 123.4567890123456123 -> 123.4567890123456 Inexact Rounded +basx075 toSci 1234.567890123456123 -> 1234.567890123456 Inexact Rounded +basx076 toSci 12345.67890123456123 -> 12345.67890123456 Inexact Rounded +basx077 toSci 123456.7890123456123 -> 123456.7890123456 Inexact Rounded +basx078 toSci 1234567.890123456123 -> 1234567.890123456 Inexact Rounded +basx079 toSci 12345678.90123456123 -> 12345678.90123456 Inexact Rounded +basx080 toSci 123456789.0123456123 -> 123456789.0123456 Inexact Rounded +basx081 toSci 1234567890.123456123 -> 1234567890.123456 Inexact Rounded +basx082 toSci 12345678901.23456123 -> 12345678901.23456 Inexact Rounded +basx083 toSci 123456789012.3456123 -> 123456789012.3456 Inexact Rounded +basx084 toSci 1234567890123.456123 -> 1234567890123.456 Inexact Rounded +basx085 toSci 12345678901234.56123 -> 12345678901234.56 Inexact Rounded +basx086 toSci 123456789012345.6123 -> 123456789012345.6 Inexact Rounded +basx087 toSci 1234567890123456.123 -> 1234567890123456 Inexact Rounded +basx088 toSci 12345678901234561.23 -> 1.234567890123456E+16 Inexact Rounded +basx089 toSci 123456789012345612.3 -> 1.234567890123456E+17 Inexact Rounded +basx090 toSci 1234567890123456123. -> 1.234567890123456E+18 Inexact Rounded + -- Numbers with E basx130 toSci "0.000E-1" -> '0.0000' basx131 toSci "0.000E-2" -> '0.00000' @@ -225,21 +246,6 @@ basx262 toSci "0.1265E+8" -> '1.265E+7' basx263 toSci "0.1265E+20" -> '1.265E+19' -basx270 toSci "0.09e999" -> '9E+997' -basx271 toSci "0.9e999" -> '9E+998' -basx272 toSci "9e999" -> '9E+999' -basx273 toSci "9.9e999" -> '9.9E+999' -basx274 toSci "9.99e999" -> '9.99E+999' -basx275 toSci "9.99e-999" -> '9.99E-999' -basx276 toSci "9.9e-999" -> '9.9E-999' -basx277 toSci "9e-999" -> '9E-999' -basx279 toSci "99e-999" -> '9.9E-998' -basx280 toSci "999e-999" -> '9.99E-997' -basx281 toSci '0.9e-998' -> '9E-999' -basx282 toSci '0.09e-997' -> '9E-999' -basx283 toSci '0.1e1000' -> '1E+999' -basx284 toSci '10e-1000' -> '1.0E-999' - -- some more negative zeros [systematic tests below] basx290 toSci "-0.000E-1" -> '-0.0000' basx291 toSci "-0.000E-2" -> '-0.00000' @@ -418,6 +424,22 @@ basx474 toSci 1000000009000 -> 1.00000001E+12 Rounded Inexact basx475 toEng 1000000009000 -> 1.00000001E+12 Rounded Inexact +-- all-nines rounding +precision: 9 +rounding: half_up +basx270 toSci 999999999 -> 999999999 +basx271 toSci 9999999990 -> 9.99999999E+9 Rounded +basx272 toSci 9999999991 -> 9.99999999E+9 Rounded Inexact +basx273 toSci 9999999992 -> 9.99999999E+9 Rounded Inexact +basx274 toSci 9999999993 -> 9.99999999E+9 Rounded Inexact +basx275 toSci 9999999994 -> 9.99999999E+9 Rounded Inexact +basx276 toSci 9999999995 -> 1.00000000E+10 Rounded Inexact +basx277 toSci 9999999996 -> 1.00000000E+10 Rounded Inexact +basx278 toSci 9999999997 -> 1.00000000E+10 Rounded Inexact +basx279 toSci 9999999998 -> 1.00000000E+10 Rounded Inexact +basx280 toSci 9999999999 -> 1.00000000E+10 Rounded Inexact +basx281 toSci 9999999999999999 -> 1.00000000E+16 Rounded Inexact + -- check rounding modes heeded precision: 5 rounding: ceiling @@ -425,11 +447,11 @@ bsrx402 toSci 1.234549 -> 1.2346 Rounded Inexact bsrx403 toSci 1.234550 -> 1.2346 Rounded Inexact bsrx404 toSci 1.234551 -> 1.2346 Rounded Inexact -rounding: down +rounding: up bsrx405 toSci 1.23450 -> 1.2345 Rounded -bsrx406 toSci 1.234549 -> 1.2345 Rounded Inexact -bsrx407 toSci 1.234550 -> 1.2345 Rounded Inexact -bsrx408 toSci 1.234551 -> 1.2345 Rounded Inexact +bsrx406 toSci 1.234549 -> 1.2346 Rounded Inexact +bsrx407 toSci 1.234550 -> 1.2346 Rounded Inexact +bsrx408 toSci 1.234551 -> 1.2346 Rounded Inexact rounding: floor bsrx410 toSci 1.23450 -> 1.2345 Rounded bsrx411 toSci 1.234549 -> 1.2345 Rounded Inexact @@ -464,11 +486,11 @@ bsrx502 toSci -1.234549 -> -1.2345 Rounded Inexact bsrx503 toSci -1.234550 -> -1.2345 Rounded Inexact bsrx504 toSci -1.234551 -> -1.2345 Rounded Inexact -rounding: down +rounding: up bsrx505 toSci -1.23450 -> -1.2345 Rounded -bsrx506 toSci -1.234549 -> -1.2345 Rounded Inexact -bsrx507 toSci -1.234550 -> -1.2345 Rounded Inexact -bsrx508 toSci -1.234551 -> -1.2345 Rounded Inexact +bsrx506 toSci -1.234549 -> -1.2346 Rounded Inexact +bsrx507 toSci -1.234550 -> -1.2346 Rounded Inexact +bsrx508 toSci -1.234551 -> -1.2346 Rounded Inexact rounding: floor bsrx510 toSci -1.23450 -> -1.2345 Rounded bsrx511 toSci -1.234549 -> -1.2346 Rounded Inexact @@ -498,6 +520,24 @@ bsrx534 toSci -1.234650 -> -1.2347 Rounded Inexact bsrx535 toSci -1.234551 -> -1.2346 Rounded Inexact +-- a few larger exponents +maxExponent: 999999999 +minExponent: -999999999 +basx480 toSci "0.09e999" -> '9E+997' +basx481 toSci "0.9e999" -> '9E+998' +basx482 toSci "9e999" -> '9E+999' +basx483 toSci "9.9e999" -> '9.9E+999' +basx484 toSci "9.99e999" -> '9.99E+999' +basx485 toSci "9.99e-999" -> '9.99E-999' +basx486 toSci "9.9e-999" -> '9.9E-999' +basx487 toSci "9e-999" -> '9E-999' +basx489 toSci "99e-999" -> '9.9E-998' +basx490 toSci "999e-999" -> '9.99E-997' +basx491 toSci '0.9e-998' -> '9E-999' +basx492 toSci '0.09e-997' -> '9E-999' +basx493 toSci '0.1e1000' -> '1E+999' +basx494 toSci '10e-1000' -> '1.0E-999' + rounding: half_up precision: 9 @@ -580,32 +620,23 @@ basx574 toSci "xNaN" -> NaN Conversion_syntax basx575 toSci "0sNaN" -> NaN Conversion_syntax --- subnormals and overflows -basx576 toSci '99e999999999' -> Infinity Overflow Inexact Rounded -basx577 toSci '999e999999999' -> Infinity Overflow Inexact Rounded -basx578 toSci '0.9e-999999999' -> 9E-1000000000 Subnormal -basx579 toSci '0.09e-999999999' -> 9E-1000000001 Subnormal -basx580 toSci '0.1e1000000000' -> 1E+999999999 -basx581 toSci '10e-1000000000' -> 1.0E-999999999 -basx582 toSci '0.9e9999999999' -> Infinity Overflow Inexact Rounded -basx583 toSci '99e-9999999999' -> 0E-1000000007 Underflow Subnormal Inexact Rounded -basx584 toSci '111e9999999999' -> Infinity Overflow Inexact Rounded -basx585 toSci '1111e-9999999999' -> 0E-1000000007 Underflow Subnormal Inexact Rounded -basx586 toSci '1111e-99999999999' -> 0E-1000000007 Underflow Subnormal Inexact Rounded -basx587 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded --- negatives the same -basx588 toSci '-99e999999999' -> -Infinity Overflow Inexact Rounded -basx589 toSci '-999e999999999' -> -Infinity Overflow Inexact Rounded -basx590 toSci '-0.9e-999999999' -> -9E-1000000000 Subnormal -basx591 toSci '-0.09e-999999999' -> -9E-1000000001 Subnormal -basx592 toSci '-0.1e1000000000' -> -1E+999999999 -basx593 toSci '-10e-1000000000' -> -1.0E-999999999 -basx594 toSci '-0.9e9999999999' -> -Infinity Overflow Inexact Rounded -basx595 toSci '-99e-9999999999' -> -0E-1000000007 Underflow Subnormal Inexact Rounded -basx596 toSci '-111e9999999999' -> -Infinity Overflow Inexact Rounded -basx597 toSci '-1111e-9999999999' -> -0E-1000000007 Underflow Subnormal Inexact Rounded -basx598 toSci '-1111e-99999999999' -> -0E-1000000007 Underflow Subnormal Inexact Rounded -basx599 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded +-- some baddies with dots and Es and dots and specials +basx576 toSci 'e+1' -> NaN Conversion_syntax +basx577 toSci '.e+1' -> NaN Conversion_syntax +basx578 toSci '+.e+1' -> NaN Conversion_syntax +basx579 toSci '-.e+' -> NaN Conversion_syntax +basx580 toSci '-.e' -> NaN Conversion_syntax +basx581 toSci 'E+1' -> NaN Conversion_syntax +basx582 toSci '.E+1' -> NaN Conversion_syntax +basx583 toSci '+.E+1' -> NaN Conversion_syntax +basx584 toSci '-.E+' -> NaN Conversion_syntax +basx585 toSci '-.E' -> NaN Conversion_syntax + +basx586 toSci '.NaN' -> NaN Conversion_syntax +basx587 toSci '-.NaN' -> NaN Conversion_syntax +basx588 toSci '+.sNaN' -> NaN Conversion_syntax +basx589 toSci '+.Inf' -> NaN Conversion_syntax +basx590 toSci '.Infinity' -> NaN Conversion_syntax -- Zeros basx601 toSci 0.000000000 -> 0E-9 @@ -686,6 +717,17 @@ basx678 toSci 0.00E-8 -> 0E-10 basx679 toSci 0.00E-9 -> 0E-11 +basx680 toSci 000000. -> 0 +basx681 toSci 00000. -> 0 +basx682 toSci 0000. -> 0 +basx683 toSci 000. -> 0 +basx684 toSci 00. -> 0 +basx685 toSci 0. -> 0 +basx686 toSci +00000. -> 0 +basx687 toSci -00000. -> -0 +basx688 toSci +0. -> 0 +basx689 toSci -0. -> -0 + -- Specials precision: 4 basx700 toSci "NaN" -> NaN @@ -868,6 +910,62 @@ basx878 toEng 0.00E-8 -> 0.0E-9 basx879 toEng 0.00E-9 -> 0.00E-9 + +rounding: half_up +precision: 9 +-- subnormals and overflows +basx906 toSci '99e999999999' -> Infinity Overflow Inexact Rounded +basx907 toSci '999e999999999' -> Infinity Overflow Inexact Rounded +basx908 toSci '0.9e-999999999' -> 9E-1000000000 Subnormal +basx909 toSci '0.09e-999999999' -> 9E-1000000001 Subnormal +basx910 toSci '0.1e1000000000' -> 1E+999999999 +basx911 toSci '10e-1000000000' -> 1.0E-999999999 +basx912 toSci '0.9e9999999999' -> Infinity Overflow Inexact Rounded +basx913 toSci '99e-9999999999' -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +basx914 toSci '111e9999999999' -> Infinity Overflow Inexact Rounded +basx915 toSci '1111e-9999999999' -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +basx916 toSci '1111e-99999999999' -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +basx917 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded +-- negatives the same +basx918 toSci '-99e999999999' -> -Infinity Overflow Inexact Rounded +basx919 toSci '-999e999999999' -> -Infinity Overflow Inexact Rounded +basx920 toSci '-0.9e-999999999' -> -9E-1000000000 Subnormal +basx921 toSci '-0.09e-999999999' -> -9E-1000000001 Subnormal +basx922 toSci '-0.1e1000000000' -> -1E+999999999 +basx923 toSci '-10e-1000000000' -> -1.0E-999999999 +basx924 toSci '-0.9e9999999999' -> -Infinity Overflow Inexact Rounded +basx925 toSci '-99e-9999999999' -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +basx926 toSci '-111e9999999999' -> -Infinity Overflow Inexact Rounded +basx927 toSci '-1111e-9999999999' -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +basx928 toSci '-1111e-99999999999' -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +basx929 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded + +rounding: ceiling +basx930 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded +basx931 toSci '-7e1000000000' -> -9.99999999E+999999999 Overflow Inexact Rounded +rounding: up +basx932 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded +basx933 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded +rounding: down +basx934 toSci '7e1000000000' -> 9.99999999E+999999999 Overflow Inexact Rounded +basx935 toSci '-7e1000000000' -> -9.99999999E+999999999 Overflow Inexact Rounded +rounding: floor +basx936 toSci '7e1000000000' -> 9.99999999E+999999999 Overflow Inexact Rounded +basx937 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded + +rounding: half_up +basx938 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded +basx939 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded +rounding: half_even +basx940 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded +basx941 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded +rounding: half_down +basx942 toSci '7e1000000000' -> Infinity Overflow Inexact Rounded +basx943 toSci '-7e1000000000' -> -Infinity Overflow Inexact Rounded + +rounding: half_even + + -- Giga exponent initial tests maxExponent: 999999999 minExponent: -999999999 @@ -987,8 +1085,8 @@ emax226 toSci 1E-8 -> 1E-8 Subnormal emax227 toSci 1E-9 -> 1E-9 Subnormal emax228 toSci 1E-10 -> 1E-10 Subnormal -emax229 toSci 1E-11 -> 0E-10 Underflow Subnormal Inexact Rounded -emax230 toSci 1E-12 -> 0E-10 Underflow Subnormal Inexact Rounded +emax229 toSci 1E-11 -> 0E-10 Underflow Subnormal Inexact Rounded Clamped +emax230 toSci 1E-12 -> 0E-10 Underflow Subnormal Inexact Rounded Clamped maxexponent: 7 minexponent: -7 @@ -1003,7 +1101,7 @@ maxexponent: 9 minexponent: -9 -emax240 toSci 1E-21 -> 0E-17 Subnormal Underflow Inexact Rounded +emax240 toSci 1E-21 -> 0E-17 Subnormal Underflow Inexact Rounded Clamped emax241 toSci 1E-10 -> 1E-10 Subnormal emax242 toSci 1E-9 -> 1E-9 emax243 toSci 1E-8 -> 1E-8 @@ -1015,7 +1113,7 @@ maxexponent: 10 -- boundary minexponent: -10 -emax250 toSci 1E-21 -> 0E-18 Underflow Subnormal Inexact Rounded +emax250 toSci 1E-21 -> 0E-18 Underflow Subnormal Inexact Rounded Clamped emax251 toSci 1E-11 -> 1E-11 Subnormal emax252 toSci 1E-10 -> 1E-10 emax253 toSci 1E-9 -> 1E-9 @@ -1025,7 +1123,7 @@ emax257 toSci 1E+10 -> 1E+10 emax258 toSci 1E+11 -> Infinity Overflow Inexact Rounded -emax260 toSci 1.00E-21 -> 0E-18 Underflow Subnormal Inexact Rounded +emax260 toSci 1.00E-21 -> 0E-18 Underflow Subnormal Inexact Rounded Clamped emax261 toSci 1.00E-11 -> 1.00E-11 Subnormal emax262 toSci 1.00E-10 -> 1.00E-10 emax263 toSci 1.00E-9 -> 1.00E-9 @@ -1034,7 +1132,7 @@ emax266 toSci 1.00E+9 -> 1.00E+9 emax267 toSci 1.00E+10 -> 1.00E+10 emax268 toSci 1.00E+11 -> Infinity Overflow Inexact Rounded -emax270 toSci 9.99E-21 -> 0E-18 Underflow Subnormal Inexact Rounded +emax270 toSci 9.99E-21 -> 0E-18 Underflow Subnormal Inexact Rounded Clamped emax271 toSci 9.99E-11 -> 9.99E-11 Subnormal emax272 toSci 9.99E-10 -> 9.99E-10 emax273 toSci 9.99E-9 -> 9.99E-9 @@ -1046,7 +1144,7 @@ maxexponent: 99 minexponent: -99 -emax280 toSci 1E-120 -> 0E-107 Underflow Subnormal Inexact Rounded +emax280 toSci 1E-120 -> 0E-107 Underflow Subnormal Inexact Rounded Clamped emax281 toSci 1E-100 -> 1E-100 Subnormal emax282 toSci 1E-99 -> 1E-99 emax283 toSci 1E-98 -> 1E-98 @@ -1093,7 +1191,7 @@ maxexponent: 999999999 minexponent: -999999999 -emax347 toSci 1E-1000000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +emax347 toSci 1E-1000000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped emax348 toSci 1E-1000000007 -> 1E-1000000007 Subnormal emax349 toSci 1E-1000000000 -> 1E-1000000000 Subnormal emax350 toSci 1E-999999999 -> 1E-999999999 @@ -1103,7 +1201,7 @@ emax354 toSci 1.000E-999999999 -> 1.000E-999999999 emax355 toSci 1.000E+999999999 -> 1.000E+999999999 emax356 toSci 1.000E+1000000000 -> Infinity Overflow Inexact Rounded -emax357 toSci 1.001E-1000000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +emax357 toSci 1.001E-1000000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped emax358 toSci 1.001E-1000000007 -> 1E-1000000007 Subnormal Inexact Rounded Underflow emax359 toSci 1.001E-1000000000 -> 1.001E-1000000000 Subnormal emax360 toSci 1.001E-999999999 -> 1.001E-999999999 @@ -1113,7 +1211,7 @@ emax364 toSci 9.000E-999999999 -> 9.000E-999999999 emax365 toSci 9.000E+999999999 -> 9.000E+999999999 emax366 toSci 9.000E+1000000000 -> Infinity Overflow Inexact Rounded -emax367 toSci 9.999E-1000000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +emax367 toSci 9.999E-1000000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped emax368 toSci 9.999E-1000000008 -> 1E-1000000007 Underflow Subnormal Inexact Rounded emax369 toSci 9.999E-1000000007 -> 1.0E-1000000006 Underflow Subnormal Inexact Rounded emax370 toSci 9.999E-1000000000 -> 9.999E-1000000000 Subnormal @@ -1129,11 +1227,11 @@ emax379 toSci -1.000E-999999999 -> -1.000E-999999999 emax380 toSci -1.000E+999999999 -> -1.000E+999999999 emax381 toSci -1.000E+1000000000 -> -Infinity Overflow Inexact Rounded -emax382 toSci -1.001E-1000000008 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +emax382 toSci -1.001E-1000000008 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped emax383 toSci -1.001E-999999999 -> -1.001E-999999999 emax384 toSci -1.001E+999999999 -> -1.001E+999999999 emax385 toSci -1.001E+1000000000 -> -Infinity Overflow Inexact Rounded -emax386 toSci -9.000E-1000000123 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +emax386 toSci -9.000E-1000000123 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped emax387 toSci -9.000E-999999999 -> -9.000E-999999999 emax388 toSci -9.000E+999999999 -> -9.000E+999999999 emax389 toSci -9.000E+1000000000 -> -Infinity Overflow Inexact Rounded @@ -1168,11 +1266,11 @@ emax417 toSci 0.000250E-999 -> 2E-1003 Underflow Subnormal Inexact Rounded emax418 toSci 0.000251E-999 -> 3E-1003 Underflow Subnormal Inexact Rounded emax419 toSci 0.00009E-999 -> 1E-1003 Underflow Subnormal Inexact Rounded -emax420 toSci 0.00005E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded -emax421 toSci 0.00003E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded -emax422 toSci 0.000009E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded -emax423 toSci 0.000005E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded -emax424 toSci 0.000003E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded +emax420 toSci 0.00005E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +emax421 toSci 0.00003E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +emax422 toSci 0.000009E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +emax423 toSci 0.000005E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +emax424 toSci 0.000003E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped emax425 toSci 0.001049E-999 -> 1.0E-1002 Underflow Subnormal Inexact Rounded emax426 toSci 0.001050E-999 -> 1.0E-1002 Underflow Subnormal Inexact Rounded @@ -1223,9 +1321,9 @@ emax473 toSci 0.0099999E-999 -> 1.00E-1001 Underflow Subnormal Inexact Rounded emax474 toSci 0.00099999E-999 -> 1.0E-1002 Underflow Subnormal Inexact Rounded emax475 toSci 0.000099999E-999 -> 1E-1003 Underflow Subnormal Inexact Rounded -emax476 toSci 0.0000099999E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded -emax477 toSci 0.00000099999E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded -emax478 toSci 0.000000099999E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded +emax476 toSci 0.0000099999E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +emax477 toSci 0.00000099999E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +emax478 toSci 0.000000099999E-999 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped -- Exponents with insignificant leading zeros precision: 16 @@ -1248,9 +1346,9 @@ basx1021 tosci 1e+2147483649 -> Infinity Overflow Inexact Rounded basx1022 tosci 1e+2147483648 -> Infinity Overflow Inexact Rounded basx1023 tosci 1e+2147483647 -> Infinity Overflow Inexact Rounded -basx1024 tosci 1e-2147483647 -> 0E-1000000014 Underflow Subnormal Inexact Rounded -basx1025 tosci 1e-2147483648 -> 0E-1000000014 Underflow Subnormal Inexact Rounded -basx1026 tosci 1e-2147483649 -> 0E-1000000014 Underflow Subnormal Inexact Rounded +basx1024 tosci 1e-2147483647 -> 0E-1000000014 Underflow Subnormal Inexact Rounded Clamped +basx1025 tosci 1e-2147483648 -> 0E-1000000014 Underflow Subnormal Inexact Rounded Clamped +basx1026 tosci 1e-2147483649 -> 0E-1000000014 Underflow Subnormal Inexact Rounded Clamped -- same unbalanced precision: 7 maxExponent: 96 @@ -1258,9 +1356,9 @@ basx1031 tosci 1e+2147483649 -> Infinity Overflow Inexact Rounded basx1032 tosci 1e+2147483648 -> Infinity Overflow Inexact Rounded basx1033 tosci 1e+2147483647 -> Infinity Overflow Inexact Rounded -basx1034 tosci 1e-2147483647 -> 0E-101 Underflow Subnormal Inexact Rounded -basx1035 tosci 1e-2147483648 -> 0E-101 Underflow Subnormal Inexact Rounded -basx1036 tosci 1e-2147483649 -> 0E-101 Underflow Subnormal Inexact Rounded +basx1034 tosci 1e-2147483647 -> 0E-101 Underflow Subnormal Inexact Rounded Clamped +basx1035 tosci 1e-2147483648 -> 0E-101 Underflow Subnormal Inexact Rounded Clamped +basx1036 tosci 1e-2147483649 -> 0E-101 Underflow Subnormal Inexact Rounded Clamped -- check for double-rounded subnormals precision: 5 @@ -1270,3 +1368,44 @@ basx1042 toSci 1.52445E-80 -> 1.524E-80 Inexact Rounded Subnormal Underflow basx1043 toSci 1.52446E-80 -> 1.524E-80 Inexact Rounded Subnormal Underflow +-- clamped zeros [see also clamp.decTest] +precision: 34 +maxExponent: 6144 +minExponent: -6143 + +basx1061 apply 0e+10000 -> 0E+6144 Clamped +basx1062 apply 0e-10000 -> 0E-6176 Clamped +basx1063 apply -0e+10000 -> -0E+6144 Clamped +basx1064 apply -0e-10000 -> -0E-6176 Clamped + +precision: 16 +maxExponent: 384 +minExponent: -383 + +basx1065 apply 0e+10000 -> 0E+384 Clamped +basx1066 apply 0e-10000 -> 0E-398 Clamped +basx1067 apply -0e+10000 -> -0E+384 Clamped +basx1068 apply -0e-10000 -> -0E-398 Clamped + +-- same with IEEE clamping +clamp: 1 + +precision: 34 +maxExponent: 6144 +minExponent: -6143 + +basx1071 apply 0e+10000 -> 0E+6111 Clamped +basx1072 apply 0e-10000 -> 0E-6176 Clamped +basx1073 apply -0e+10000 -> -0E+6111 Clamped +basx1074 apply -0e-10000 -> -0E-6176 Clamped + +precision: 16 +maxExponent: 384 +minExponent: -383 + +basx1075 apply 0e+10000 -> 0E+369 Clamped +basx1076 apply 0e-10000 -> 0E-398 Clamped +basx1077 apply -0e+10000 -> -0E+369 Clamped +basx1078 apply -0e-10000 -> -0E-398 Clamped + + Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/clamp.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/clamp.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/clamp.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- clamp.decTest -- clamped exponent tests (format-independent) -- --- Copyright (c) IBM Corporation, 2000, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 2000, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- This set of tests uses the same limits as the 8-byte concrete -- representation, but applies clamping without using format-specific @@ -73,10 +73,10 @@ clam093 apply 1.00000000001e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded clam094 apply 1.00000000000001e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded clam095 apply 1.000000000000001e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded -clam096 apply 0.1e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded -clam097 apply 0.00000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded -clam098 apply 0.00000000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded -clam099 apply 0.000000000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded +clam096 apply 0.1e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded Clamped +clam097 apply 0.00000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded Clamped +clam098 apply 0.00000000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded Clamped +clam099 apply 0.000000000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded Clamped -- Same again, negatives -- Nmax and similar @@ -112,10 +112,10 @@ clam193 apply -1.00000000001e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded clam194 apply -1.00000000000001e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded clam195 apply -1.000000000000001e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded -clam196 apply -0.1e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded -clam197 apply -0.00000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded -clam198 apply -0.00000000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded -clam199 apply -0.000000000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded +clam196 apply -0.1e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded Clamped +clam197 apply -0.00000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded Clamped +clam198 apply -0.00000000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded Clamped +clam199 apply -0.000000000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded Clamped -- zeros clam401 apply 0E-500 -> 0E-398 Clamped @@ -184,6 +184,20 @@ clam671 apply 9E+369 -> 9E+369 clam673 apply 9E+368 -> 9E+368 +-- subnormals clamped to 0-Etiny +precision: 16 +maxExponent: 384 +minExponent: -383 +clam681 apply 7E-398 -> 7E-398 Subnormal +clam682 apply 0E-398 -> 0E-398 +clam683 apply 7E-399 -> 1E-398 Subnormal Underflow Inexact Rounded +clam684 apply 4E-399 -> 0E-398 Clamped Subnormal Underflow Inexact Rounded +clam685 apply 7E-400 -> 0E-398 Clamped Subnormal Underflow Inexact Rounded +clam686 apply 7E-401 -> 0E-398 Clamped Subnormal Underflow Inexact Rounded +clam687 apply 0E-399 -> 0E-398 Clamped +clam688 apply 0E-400 -> 0E-398 Clamped +clam689 apply 0E-401 -> 0E-398 Clamped + -- example from documentation precision: 7 rounding: half_even Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/compare.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/compare.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/compare.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ --- compare.decTest -- decimal comparison -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +-- compare.decTest -- decimal comparison that allows quiet NaNs -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,11 +17,11 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- Note that we cannot assume add/subtract tests cover paths adequately, -- here, because the code might be quite different (comparison cannot --- overflow or underflow, so actual subtractions are not necesary). +-- overflow or underflow, so actual subtractions are not necessary). extended: 1 @@ -112,10 +112,10 @@ -- now some cases which might overflow if subtract were used maxexponent: 999999999 minexponent: -999999999 -comx090 compare 9.99999999E+999999999 9.99999999E+999999999 -> 0 -comx091 compare -9.99999999E+999999999 9.99999999E+999999999 -> -1 -comx092 compare 9.99999999E+999999999 -9.99999999E+999999999 -> 1 -comx093 compare -9.99999999E+999999999 -9.99999999E+999999999 -> 0 +comx095 compare 9.99999999E+999999999 9.99999999E+999999999 -> 0 +comx096 compare -9.99999999E+999999999 9.99999999E+999999999 -> -1 +comx097 compare 9.99999999E+999999999 -9.99999999E+999999999 -> 1 +comx098 compare -9.99999999E+999999999 -9.99999999E+999999999 -> 0 -- some differing length/exponent cases comx100 compare 7.0 7.0 -> 0 @@ -265,6 +265,21 @@ comx449 compare -8 -.9E+1 -> 1 comx450 compare -8 -90E-1 -> 1 +-- misalignment traps for little-endian +comx451 compare 1.0 0.1 -> 1 +comx452 compare 0.1 1.0 -> -1 +comx453 compare 10.0 0.1 -> 1 +comx454 compare 0.1 10.0 -> -1 +comx455 compare 100 1.0 -> 1 +comx456 compare 1.0 100 -> -1 +comx457 compare 1000 10.0 -> 1 +comx458 compare 10.0 1000 -> -1 +comx459 compare 10000 100.0 -> 1 +comx460 compare 100.0 10000 -> -1 +comx461 compare 100000 1000.0 -> 1 +comx462 compare 1000.0 100000 -> -1 +comx463 compare 1000000 10000.0 -> 1 +comx464 compare 10000.0 1000000 -> -1 -- testcases that subtract to lots of zeros at boundaries [pgr] precision: 40 @@ -362,7 +377,7 @@ comx569 compare 1E+13 1 -> 1 comx570 compare 1E+14 1 -> 1 comx571 compare 1E+15 1 -> 1 --- similar with an useful coefficient, one side only +-- similar with a useful coefficient, one side only comx580 compare 0.000000987654321 1E-15 -> 1 comx581 compare 0.000000987654321 1E-14 -> 1 comx582 compare 0.000000987654321 1E-13 -> 1 @@ -712,6 +727,32 @@ comx907 compare -1e-777777777 1e-411111111 -> -1 comx908 compare -1e-777777777 -1e-411111111 -> 1 +-- spread zeros +comx910 compare 0E-383 0 -> 0 +comx911 compare 0E-383 -0 -> 0 +comx912 compare -0E-383 0 -> 0 +comx913 compare -0E-383 -0 -> 0 +comx914 compare 0E-383 0E+384 -> 0 +comx915 compare 0E-383 -0E+384 -> 0 +comx916 compare -0E-383 0E+384 -> 0 +comx917 compare -0E-383 -0E+384 -> 0 +comx918 compare 0 0E+384 -> 0 +comx919 compare 0 -0E+384 -> 0 +comx920 compare -0 0E+384 -> 0 +comx921 compare -0 -0E+384 -> 0 +comx930 compare 0E+384 0 -> 0 +comx931 compare 0E+384 -0 -> 0 +comx932 compare -0E+384 0 -> 0 +comx933 compare -0E+384 -0 -> 0 +comx934 compare 0E+384 0E-383 -> 0 +comx935 compare 0E+384 -0E-383 -> 0 +comx936 compare -0E+384 0E-383 -> 0 +comx937 compare -0E+384 -0E-383 -> 0 +comx938 compare 0 0E-383 -> 0 +comx939 compare 0 -0E-383 -> 0 +comx940 compare -0 0E-383 -> 0 +comx941 compare -0 -0E-383 -> 0 + -- Null tests comx990 compare 10 # -> NaN Invalid_operation comx991 compare # 10 -> NaN Invalid_operation Deleted: /python/branches/py3k-importlib/Lib/test/decimaltestdata/decimal128.decTest ============================================================================== --- /python/branches/py3k-importlib/Lib/test/decimaltestdata/decimal128.decTest Fri Sep 21 03:17:09 2007 +++ (empty file) @@ -1,441 +0,0 @@ ------------------------------------------------------------------------- --- decimal128.decTest -- decimal sixteen-byte format testcases -- --- Copyright (c) IBM Corporation, 2000, 2003. All rights reserved. -- ------------------------------------------------------------------------- --- Please see the document "General Decimal Arithmetic Testcases" -- --- at http://www2.hursley.ibm.com/decimal for the description of -- --- these testcases. -- --- -- --- These testcases are experimental ('beta' versions), and they -- --- may contain errors. They are offered on an as-is basis. In -- --- particular, achieving the same results as the tests here is not -- --- a guarantee that an implementation complies with any Standard -- --- or specification. The tests are not exhaustive. -- --- -- --- Please send comments, suggestions, and corrections to the author: -- --- Mike Cowlishaw, IBM Fellow -- --- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- --- mfc at uk.ibm.com -- ------------------------------------------------------------------------- -version: 2.39 - --- This set of tests is for the sixteen-byte concrete representation. --- Its characteristics are: --- --- 1 bit sign --- 5 bits combination field --- 12 bits exponent continuation --- 110 bits coefficient continuation --- --- Total exponent length 14 bits --- Total coefficient length 114 bits (34 digits) --- --- Elimit = 12287 (maximum encoded exponent) --- Emax = 6144 (largest exponent value) --- Emin = -6143 (smallest exponent value) --- bias = 6176 (subtracted from encoded exponent) = -Etiny - -extended: 1 -precision: 34 -rounding: half_up -maxExponent: 6144 -minExponent: -6143 - --- General testcases --- (mostly derived from the Strawman 4 document and examples) -decg001 apply #A20780000000000000000000000003D0 -> -7.50 -decg002 apply -7.50 -> #A20780000000000000000000000003D0 - --- Normality -decf010 apply 1234567890123456789012345678901234 -> #2608134b9c1e28e56f3c127177823534 -decf011 apply 1234567890123456789012345678901234.0 -> #2608134b9c1e28e56f3c127177823534 Rounded -decf012 apply 1234567890123456789012345678901234.1 -> #2608134b9c1e28e56f3c127177823534 Rounded Inexact -decf013 apply -1234567890123456789012345678901234 -> #a608134b9c1e28e56f3c127177823534 -decf014 apply -1234567890123456789012345678901234.0 -> #a608134b9c1e28e56f3c127177823534 Rounded -decf015 apply -1234567890123456789012345678901234.1 -> #a608134b9c1e28e56f3c127177823534 Rounded Inexact - - --- Nmax and similar -decf022 apply 9.999999999999999999999999999999999E+6144 -> #77ffcff3fcff3fcff3fcff3fcff3fcff -decf023 apply #77ffcff3fcff3fcff3fcff3fcff3fcff -> 9.999999999999999999999999999999999E+6144 -decf024 apply 1.234567890123456789012345678901234E+6144 -> #47ffd34b9c1e28e56f3c127177823534 -decf025 apply #47ffd34b9c1e28e56f3c127177823534 -> 1.234567890123456789012345678901234E+6144 --- fold-downs (more below) -decf030 apply 1.23E+6144 -> #47ffd300000000000000000000000000 Clamped -decf031 apply #47ffd300000000000000000000000000 -> 1.230000000000000000000000000000000E+6144 -decf032 apply 1E+6144 -> #47ffc000000000000000000000000000 Clamped -decf033 apply #47ffc000000000000000000000000000 -> 1.000000000000000000000000000000000E+6144 - --- overflows -maxExponent: 9999 -- set high so conversion causes the overflow -minExponent: -9999 -decf040 apply 10E+6144 -> #78000000000000000000000000000000 Overflow Rounded Inexact -decf041 apply 1.000000000000000E+6145 -> #78000000000000000000000000000000 Overflow Rounded Inexact -maxExponent: 6144 -minExponent: -6143 - -decf051 apply 12345 -> #220800000000000000000000000049c5 -decf052 apply #220800000000000000000000000049c5 -> 12345 -decf053 apply 1234 -> #22080000000000000000000000000534 -decf054 apply #22080000000000000000000000000534 -> 1234 -decf055 apply 123 -> #220800000000000000000000000000a3 -decf056 apply #220800000000000000000000000000a3 -> 123 -decf057 apply 12 -> #22080000000000000000000000000012 -decf058 apply #22080000000000000000000000000012 -> 12 -decf059 apply 1 -> #22080000000000000000000000000001 -decf060 apply #22080000000000000000000000000001 -> 1 -decf061 apply 1.23 -> #220780000000000000000000000000a3 -decf062 apply #220780000000000000000000000000a3 -> 1.23 -decf063 apply 123.45 -> #220780000000000000000000000049c5 -decf064 apply #220780000000000000000000000049c5 -> 123.45 - --- Nmin and below -decf071 apply 1E-6143 -> #00084000000000000000000000000001 -decf072 apply #00084000000000000000000000000001 -> 1E-6143 -decf073 apply 1.000000000000000000000000000000000E-6143 -> #04000000000000000000000000000000 -decf074 apply #04000000000000000000000000000000 -> 1.000000000000000000000000000000000E-6143 -decf075 apply 1.000000000000000000000000000000001E-6143 -> #04000000000000000000000000000001 -decf076 apply #04000000000000000000000000000001 -> 1.000000000000000000000000000000001E-6143 - -decf077 apply 0.100000000000000000000000000000000E-6143 -> #00000800000000000000000000000000 Subnormal -decf078 apply #00000800000000000000000000000000 -> 1.00000000000000000000000000000000E-6144 Subnormal -decf079 apply 0.000000000000000000000000000000010E-6143 -> #00000000000000000000000000000010 Subnormal -decf080 apply #00000000000000000000000000000010 -> 1.0E-6175 Subnormal -decf081 apply 0.00000000000000000000000000000001E-6143 -> #00004000000000000000000000000001 Subnormal -decf082 apply #00004000000000000000000000000001 -> 1E-6175 Subnormal -decf083 apply 0.000000000000000000000000000000001E-6143 -> #00000000000000000000000000000001 Subnormal -decf084 apply #00000000000000000000000000000001 -> 1E-6176 Subnormal - --- underflows -decf090 apply 1e-6176 -> #00000000000000000000000000000001 Subnormal -decf091 apply 1.9e-6176 -> #00000000000000000000000000000002 Subnormal Underflow Inexact Rounded -decf092 apply 1.1e-6176 -> #00000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf093 apply 1.00000000001e-6176 -> #00000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf094 apply 1.00000000000001e-6176 -> #00000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf095 apply 1.000000000000001e-6176 -> #00000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf096 apply 0.1e-6176 -> #00000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf097 apply 0.00000000001e-6176 -> #00000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf098 apply 0.00000000000001e-6176 -> #00000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf099 apply 0.000000000000001e-6176 -> #00000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf100 apply 999999999999999999999999999999999e-6176 -> #00000ff3fcff3fcff3fcff3fcff3fcff Subnormal - --- same again, negatives --- Nmax and similar -decf122 apply -9.999999999999999999999999999999999E+6144 -> #f7ffcff3fcff3fcff3fcff3fcff3fcff -decf123 apply #f7ffcff3fcff3fcff3fcff3fcff3fcff -> -9.999999999999999999999999999999999E+6144 -decf124 apply -1.234567890123456789012345678901234E+6144 -> #c7ffd34b9c1e28e56f3c127177823534 -decf125 apply #c7ffd34b9c1e28e56f3c127177823534 -> -1.234567890123456789012345678901234E+6144 --- fold-downs (more below) -decf130 apply -1.23E+6144 -> #c7ffd300000000000000000000000000 Clamped -decf131 apply #c7ffd300000000000000000000000000 -> -1.230000000000000000000000000000000E+6144 -decf132 apply -1E+6144 -> #c7ffc000000000000000000000000000 Clamped -decf133 apply #c7ffc000000000000000000000000000 -> -1.000000000000000000000000000000000E+6144 - --- overflows -maxExponent: 9999 -- set high so conversion causes the overflow -minExponent: -9999 -decf140 apply -10E+6144 -> #f8000000000000000000000000000000 Overflow Rounded Inexact -decf141 apply -1.000000000000000E+6145 -> #f8000000000000000000000000000000 Overflow Rounded Inexact -maxExponent: 6144 -minExponent: -6143 - -decf151 apply -12345 -> #a20800000000000000000000000049c5 -decf152 apply #a20800000000000000000000000049c5 -> -12345 -decf153 apply -1234 -> #a2080000000000000000000000000534 -decf154 apply #a2080000000000000000000000000534 -> -1234 -decf155 apply -123 -> #a20800000000000000000000000000a3 -decf156 apply #a20800000000000000000000000000a3 -> -123 -decf157 apply -12 -> #a2080000000000000000000000000012 -decf158 apply #a2080000000000000000000000000012 -> -12 -decf159 apply -1 -> #a2080000000000000000000000000001 -decf160 apply #a2080000000000000000000000000001 -> -1 -decf161 apply -1.23 -> #a20780000000000000000000000000a3 -decf162 apply #a20780000000000000000000000000a3 -> -1.23 -decf163 apply -123.45 -> #a20780000000000000000000000049c5 -decf164 apply #a20780000000000000000000000049c5 -> -123.45 - --- Nmin and below -decf171 apply -1E-6143 -> #80084000000000000000000000000001 -decf172 apply #80084000000000000000000000000001 -> -1E-6143 -decf173 apply -1.000000000000000000000000000000000E-6143 -> #84000000000000000000000000000000 -decf174 apply #84000000000000000000000000000000 -> -1.000000000000000000000000000000000E-6143 -decf175 apply -1.000000000000000000000000000000001E-6143 -> #84000000000000000000000000000001 -decf176 apply #84000000000000000000000000000001 -> -1.000000000000000000000000000000001E-6143 - -decf177 apply -0.100000000000000000000000000000000E-6143 -> #80000800000000000000000000000000 Subnormal -decf178 apply #80000800000000000000000000000000 -> -1.00000000000000000000000000000000E-6144 Subnormal -decf179 apply -0.000000000000000000000000000000010E-6143 -> #80000000000000000000000000000010 Subnormal -decf180 apply #80000000000000000000000000000010 -> -1.0E-6175 Subnormal -decf181 apply -0.00000000000000000000000000000001E-6143 -> #80004000000000000000000000000001 Subnormal -decf182 apply #80004000000000000000000000000001 -> -1E-6175 Subnormal -decf183 apply -0.000000000000000000000000000000001E-6143 -> #80000000000000000000000000000001 Subnormal -decf184 apply #80000000000000000000000000000001 -> -1E-6176 Subnormal - --- underflows -decf190 apply -1e-6176 -> #80000000000000000000000000000001 Subnormal -decf191 apply -1.9e-6176 -> #80000000000000000000000000000002 Subnormal Underflow Inexact Rounded -decf192 apply -1.1e-6176 -> #80000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf193 apply -1.00000000001e-6176 -> #80000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf194 apply -1.00000000000001e-6176 -> #80000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf195 apply -1.000000000000001e-6176 -> #80000000000000000000000000000001 Subnormal Underflow Inexact Rounded -decf196 apply -0.1e-6176 -> #80000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf197 apply -0.00000000001e-6176 -> #80000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf198 apply -0.00000000000001e-6176 -> #80000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf199 apply -0.000000000000001e-6176 -> #80000000000000000000000000000000 Subnormal Underflow Inexact Rounded -decf200 apply -999999999999999999999999999999999e-6176 -> #80000ff3fcff3fcff3fcff3fcff3fcff Subnormal - --- zeros -decf400 apply 0E-8000 -> #00000000000000000000000000000000 Clamped -decf401 apply 0E-6177 -> #00000000000000000000000000000000 Clamped -decf402 apply 0E-6176 -> #00000000000000000000000000000000 -decf403 apply #00000000000000000000000000000000 -> 0E-6176 -decf404 apply 0.000000000000000000000000000000000E-6143 -> #00000000000000000000000000000000 -decf405 apply #00000000000000000000000000000000 -> 0E-6176 -decf406 apply 0E-2 -> #22078000000000000000000000000000 -decf407 apply #22078000000000000000000000000000 -> 0.00 -decf408 apply 0 -> #22080000000000000000000000000000 -decf409 apply #22080000000000000000000000000000 -> 0 -decf410 apply 0E+3 -> #2208c000000000000000000000000000 -decf411 apply #2208c000000000000000000000000000 -> 0E+3 -decf412 apply 0E+6111 -> #43ffc000000000000000000000000000 -decf413 apply #43ffc000000000000000000000000000 -> 0E+6111 --- clamped zeros... -decf414 apply 0E+6112 -> #43ffc000000000000000000000000000 Clamped -decf415 apply #43ffc000000000000000000000000000 -> 0E+6111 -decf416 apply 0E+6144 -> #43ffc000000000000000000000000000 Clamped -decf417 apply #43ffc000000000000000000000000000 -> 0E+6111 -decf418 apply 0E+8000 -> #43ffc000000000000000000000000000 Clamped -decf419 apply #43ffc000000000000000000000000000 -> 0E+6111 - --- negative zeros -decf420 apply -0E-8000 -> #80000000000000000000000000000000 Clamped -decf421 apply -0E-6177 -> #80000000000000000000000000000000 Clamped -decf422 apply -0E-6176 -> #80000000000000000000000000000000 -decf423 apply #80000000000000000000000000000000 -> -0E-6176 -decf424 apply -0.000000000000000000000000000000000E-6143 -> #80000000000000000000000000000000 -decf425 apply #80000000000000000000000000000000 -> -0E-6176 -decf426 apply -0E-2 -> #a2078000000000000000000000000000 -decf427 apply #a2078000000000000000000000000000 -> -0.00 -decf428 apply -0 -> #a2080000000000000000000000000000 -decf429 apply #a2080000000000000000000000000000 -> -0 -decf430 apply -0E+3 -> #a208c000000000000000000000000000 -decf431 apply #a208c000000000000000000000000000 -> -0E+3 -decf432 apply -0E+6111 -> #c3ffc000000000000000000000000000 -decf433 apply #c3ffc000000000000000000000000000 -> -0E+6111 --- clamped zeros... -decf434 apply -0E+6112 -> #c3ffc000000000000000000000000000 Clamped -decf435 apply #c3ffc000000000000000000000000000 -> -0E+6111 -decf436 apply -0E+6144 -> #c3ffc000000000000000000000000000 Clamped -decf437 apply #c3ffc000000000000000000000000000 -> -0E+6111 -decf438 apply -0E+8000 -> #c3ffc000000000000000000000000000 Clamped -decf439 apply #c3ffc000000000000000000000000000 -> -0E+6111 - --- Specials -decf500 apply Infinity -> #78000000000000000000000000000000 -decf501 apply #78787878787878787878787878787878 -> #78000000000000000000000000000000 -decf502 apply #78000000000000000000000000000000 -> Infinity -decf503 apply #79797979797979797979797979797979 -> #78000000000000000000000000000000 -decf504 apply #79000000000000000000000000000000 -> Infinity -decf505 apply #7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a -> #78000000000000000000000000000000 -decf506 apply #7a000000000000000000000000000000 -> Infinity -decf507 apply #7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b -> #78000000000000000000000000000000 -decf508 apply #7b000000000000000000000000000000 -> Infinity - -decf509 apply NaN -> #7c000000000000000000000000000000 -decf510 apply #7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c -> #7c003c7c7c7c7c7c7c7c7c7c7c7c7c7c -decf511 apply #7c000000000000000000000000000000 -> NaN -decf512 apply #7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d -> #7c003d7d7d7d7d7d7d7d7d7d7d7d7d7d -decf513 apply #7d000000000000000000000000000000 -> NaN -decf514 apply #7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e -> #7e003e7e7c7e7e7e7e7c7e7e7e7e7c7e -decf515 apply #7e000000000000000000000000000000 -> sNaN -decf516 apply #7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f -> #7e003f7f7c7f7f7f7f7c7f7f7f7f7c7f -decf517 apply #7f000000000000000000000000000000 -> sNaN -decf518 apply #7fffffffffffffffffffffffffffffff -> sNaN999999999999999999999999999999999 -decf519 apply #7fffffffffffffffffffffffffffffff -> #7e000ff3fcff3fcff3fcff3fcff3fcff - -decf520 apply -Infinity -> #f8000000000000000000000000000000 -decf521 apply #f8787878787878787878787878787878 -> #f8000000000000000000000000000000 -decf522 apply #f8000000000000000000000000000000 -> -Infinity -decf523 apply #f9797979797979797979797979797979 -> #f8000000000000000000000000000000 -decf524 apply #f9000000000000000000000000000000 -> -Infinity -decf525 apply #fa7a7a7a7a7a7a7a7a7a7a7a7a7a7a7a -> #f8000000000000000000000000000000 -decf526 apply #fa000000000000000000000000000000 -> -Infinity -decf527 apply #fb7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b -> #f8000000000000000000000000000000 -decf528 apply #fb000000000000000000000000000000 -> -Infinity - -decf529 apply -NaN -> #fc000000000000000000000000000000 -decf530 apply #fc7c7c7c7c7c7c7c7c7c7c7c7c7c7c7c -> #fc003c7c7c7c7c7c7c7c7c7c7c7c7c7c -decf531 apply #fc000000000000000000000000000000 -> -NaN -decf532 apply #fd7d7d7d7d7d7d7d7d7d7d7d7d7d7d7d -> #fc003d7d7d7d7d7d7d7d7d7d7d7d7d7d -decf533 apply #fd000000000000000000000000000000 -> -NaN -decf534 apply #fe7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e -> #fe003e7e7c7e7e7e7e7c7e7e7e7e7c7e -decf535 apply #fe000000000000000000000000000000 -> -sNaN -decf536 apply #ff7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f -> #fe003f7f7c7f7f7f7f7c7f7f7f7f7c7f -decf537 apply #ff000000000000000000000000000000 -> -sNaN -decf538 apply #ffffffffffffffffffffffffffffffff -> -sNaN999999999999999999999999999999999 -decf539 apply #ffffffffffffffffffffffffffffffff -> #fe000ff3fcff3fcff3fcff3fcff3fcff - -decf540 apply NaN -> #7c000000000000000000000000000000 -decf541 apply NaN0 -> #7c000000000000000000000000000000 -decf542 apply NaN1 -> #7c000000000000000000000000000001 -decf543 apply NaN12 -> #7c000000000000000000000000000012 -decf544 apply NaN79 -> #7c000000000000000000000000000079 -decf545 apply NaN12345 -> #7c0000000000000000000000000049c5 -decf546 apply NaN123456 -> #7c000000000000000000000000028e56 -decf547 apply NaN799799 -> #7c0000000000000000000000000f7fdf -decf548 apply NaN799799799799799799799799799799799 -> #7c003dff7fdff7fdff7fdff7fdff7fdf -decf549 apply NaN999999999999999999999999999999999 -> #7c000ff3fcff3fcff3fcff3fcff3fcff -decf550 apply NaN1234567890123456789012345678901234 -> #7c000000000000000000000000000000 -- too many digits - --- fold-down full sequence -decf600 apply 1E+6145 -> #78000000000000000000000000000000 Overflow Inexact Rounded -decf601 apply 1E+6144 -> #47ffc000000000000000000000000000 Clamped -decf602 apply #47ffc000000000000000000000000000 -> 1.000000000000000000000000000000000E+6144 -decf603 apply 1E+6143 -> #43ffc800000000000000000000000000 Clamped -decf604 apply #43ffc800000000000000000000000000 -> 1.00000000000000000000000000000000E+6143 -decf605 apply 1E+6142 -> #43ffc100000000000000000000000000 Clamped -decf606 apply #43ffc100000000000000000000000000 -> 1.0000000000000000000000000000000E+6142 -decf607 apply 1E+6141 -> #43ffc010000000000000000000000000 Clamped -decf608 apply #43ffc010000000000000000000000000 -> 1.000000000000000000000000000000E+6141 -decf609 apply 1E+6140 -> #43ffc002000000000000000000000000 Clamped -decf610 apply #43ffc002000000000000000000000000 -> 1.00000000000000000000000000000E+6140 -decf611 apply 1E+6139 -> #43ffc000400000000000000000000000 Clamped -decf612 apply #43ffc000400000000000000000000000 -> 1.0000000000000000000000000000E+6139 -decf613 apply 1E+6138 -> #43ffc000040000000000000000000000 Clamped -decf614 apply #43ffc000040000000000000000000000 -> 1.000000000000000000000000000E+6138 -decf615 apply 1E+6137 -> #43ffc000008000000000000000000000 Clamped -decf616 apply #43ffc000008000000000000000000000 -> 1.00000000000000000000000000E+6137 -decf617 apply 1E+6136 -> #43ffc000001000000000000000000000 Clamped -decf618 apply #43ffc000001000000000000000000000 -> 1.0000000000000000000000000E+6136 -decf619 apply 1E+6135 -> #43ffc000000100000000000000000000 Clamped -decf620 apply #43ffc000000100000000000000000000 -> 1.000000000000000000000000E+6135 -decf621 apply 1E+6134 -> #43ffc000000020000000000000000000 Clamped -decf622 apply #43ffc000000020000000000000000000 -> 1.00000000000000000000000E+6134 -decf623 apply 1E+6133 -> #43ffc000000004000000000000000000 Clamped -decf624 apply #43ffc000000004000000000000000000 -> 1.0000000000000000000000E+6133 -decf625 apply 1E+6132 -> #43ffc000000000400000000000000000 Clamped -decf626 apply #43ffc000000000400000000000000000 -> 1.000000000000000000000E+6132 -decf627 apply 1E+6131 -> #43ffc000000000080000000000000000 Clamped -decf628 apply #43ffc000000000080000000000000000 -> 1.00000000000000000000E+6131 -decf629 apply 1E+6130 -> #43ffc000000000010000000000000000 Clamped -decf630 apply #43ffc000000000010000000000000000 -> 1.0000000000000000000E+6130 -decf631 apply 1E+6129 -> #43ffc000000000001000000000000000 Clamped -decf632 apply #43ffc000000000001000000000000000 -> 1.000000000000000000E+6129 -decf633 apply 1E+6128 -> #43ffc000000000000200000000000000 Clamped -decf634 apply #43ffc000000000000200000000000000 -> 1.00000000000000000E+6128 -decf635 apply 1E+6127 -> #43ffc000000000000040000000000000 Clamped -decf636 apply #43ffc000000000000040000000000000 -> 1.0000000000000000E+6127 -decf637 apply 1E+6126 -> #43ffc000000000000004000000000000 Clamped -decf638 apply #43ffc000000000000004000000000000 -> 1.000000000000000E+6126 -decf639 apply 1E+6125 -> #43ffc000000000000000800000000000 Clamped -decf640 apply #43ffc000000000000000800000000000 -> 1.00000000000000E+6125 -decf641 apply 1E+6124 -> #43ffc000000000000000100000000000 Clamped -decf642 apply #43ffc000000000000000100000000000 -> 1.0000000000000E+6124 -decf643 apply 1E+6123 -> #43ffc000000000000000010000000000 Clamped -decf644 apply #43ffc000000000000000010000000000 -> 1.000000000000E+6123 -decf645 apply 1E+6122 -> #43ffc000000000000000002000000000 Clamped -decf646 apply #43ffc000000000000000002000000000 -> 1.00000000000E+6122 -decf647 apply 1E+6121 -> #43ffc000000000000000000400000000 Clamped -decf648 apply #43ffc000000000000000000400000000 -> 1.0000000000E+6121 -decf649 apply 1E+6120 -> #43ffc000000000000000000040000000 Clamped -decf650 apply #43ffc000000000000000000040000000 -> 1.000000000E+6120 -decf651 apply 1E+6119 -> #43ffc000000000000000000008000000 Clamped -decf652 apply #43ffc000000000000000000008000000 -> 1.00000000E+6119 -decf653 apply 1E+6118 -> #43ffc000000000000000000001000000 Clamped -decf654 apply #43ffc000000000000000000001000000 -> 1.0000000E+6118 -decf655 apply 1E+6117 -> #43ffc000000000000000000000100000 Clamped -decf656 apply #43ffc000000000000000000000100000 -> 1.000000E+6117 -decf657 apply 1E+6116 -> #43ffc000000000000000000000020000 Clamped -decf658 apply #43ffc000000000000000000000020000 -> 1.00000E+6116 -decf659 apply 1E+6115 -> #43ffc000000000000000000000004000 Clamped -decf660 apply #43ffc000000000000000000000004000 -> 1.0000E+6115 -decf661 apply 1E+6114 -> #43ffc000000000000000000000000400 Clamped -decf662 apply #43ffc000000000000000000000000400 -> 1.000E+6114 -decf663 apply 1E+6113 -> #43ffc000000000000000000000000080 Clamped -decf664 apply #43ffc000000000000000000000000080 -> 1.00E+6113 -decf665 apply 1E+6112 -> #43ffc000000000000000000000000010 Clamped -decf666 apply #43ffc000000000000000000000000010 -> 1.0E+6112 -decf667 apply 1E+6111 -> #43ffc000000000000000000000000001 -decf668 apply #43ffc000000000000000000000000001 -> 1E+6111 -decf669 apply 1E+6110 -> #43ff8000000000000000000000000001 -decf670 apply #43ff8000000000000000000000000001 -> 1E+6110 - --- Selected DPD codes -decf700 apply #22080000000000000000000000000000 -> 0 -decf701 apply #22080000000000000000000000000009 -> 9 -decf702 apply #22080000000000000000000000000010 -> 10 -decf703 apply #22080000000000000000000000000019 -> 19 -decf704 apply #22080000000000000000000000000020 -> 20 -decf705 apply #22080000000000000000000000000029 -> 29 -decf706 apply #22080000000000000000000000000030 -> 30 -decf707 apply #22080000000000000000000000000039 -> 39 -decf708 apply #22080000000000000000000000000040 -> 40 -decf709 apply #22080000000000000000000000000049 -> 49 -decf710 apply #22080000000000000000000000000050 -> 50 -decf711 apply #22080000000000000000000000000059 -> 59 -decf712 apply #22080000000000000000000000000060 -> 60 -decf713 apply #22080000000000000000000000000069 -> 69 -decf714 apply #22080000000000000000000000000070 -> 70 -decf715 apply #22080000000000000000000000000071 -> 71 -decf716 apply #22080000000000000000000000000072 -> 72 -decf717 apply #22080000000000000000000000000073 -> 73 -decf718 apply #22080000000000000000000000000074 -> 74 -decf719 apply #22080000000000000000000000000075 -> 75 -decf720 apply #22080000000000000000000000000076 -> 76 -decf721 apply #22080000000000000000000000000077 -> 77 -decf722 apply #22080000000000000000000000000078 -> 78 -decf723 apply #22080000000000000000000000000079 -> 79 - -decf730 apply #2208000000000000000000000000029e -> 994 -decf731 apply #2208000000000000000000000000029f -> 995 -decf732 apply #220800000000000000000000000002a0 -> 520 -decf733 apply #220800000000000000000000000002a1 -> 521 - --- DPD: one of each of the huffman groups -decf740 apply #220800000000000000000000000003f7 -> 777 -decf741 apply #220800000000000000000000000003f8 -> 778 -decf742 apply #220800000000000000000000000003eb -> 787 -decf743 apply #2208000000000000000000000000037d -> 877 -decf744 apply #2208000000000000000000000000039f -> 997 -decf745 apply #220800000000000000000000000003bf -> 979 -decf746 apply #220800000000000000000000000003df -> 799 -decf747 apply #2208000000000000000000000000006e -> 888 - - --- DPD all-highs cases (includes the 24 redundant codes) -decf750 apply #2208000000000000000000000000006e -> 888 -decf751 apply #2208000000000000000000000000016e -> 888 -decf752 apply #2208000000000000000000000000026e -> 888 -decf753 apply #2208000000000000000000000000036e -> 888 -decf754 apply #2208000000000000000000000000006f -> 889 -decf755 apply #2208000000000000000000000000016f -> 889 -decf756 apply #2208000000000000000000000000026f -> 889 -decf757 apply #2208000000000000000000000000036f -> 889 - -decf760 apply #2208000000000000000000000000007e -> 898 -decf761 apply #2208000000000000000000000000017e -> 898 -decf762 apply #2208000000000000000000000000027e -> 898 -decf763 apply #2208000000000000000000000000037e -> 898 -decf764 apply #2208000000000000000000000000007f -> 899 -decf765 apply #2208000000000000000000000000017f -> 899 -decf766 apply #2208000000000000000000000000027f -> 899 -decf767 apply #2208000000000000000000000000037f -> 899 - -decf770 apply #220800000000000000000000000000ee -> 988 -decf771 apply #220800000000000000000000000001ee -> 988 -decf772 apply #220800000000000000000000000002ee -> 988 -decf773 apply #220800000000000000000000000003ee -> 988 -decf774 apply #220800000000000000000000000000ef -> 989 -decf775 apply #220800000000000000000000000001ef -> 989 -decf776 apply #220800000000000000000000000002ef -> 989 -decf777 apply #220800000000000000000000000003ef -> 989 - -decf780 apply #220800000000000000000000000000fe -> 998 -decf781 apply #220800000000000000000000000001fe -> 998 -decf782 apply #220800000000000000000000000002fe -> 998 -decf783 apply #220800000000000000000000000003fe -> 998 -decf784 apply #220800000000000000000000000000ff -> 999 -decf785 apply #220800000000000000000000000001ff -> 999 -decf786 apply #220800000000000000000000000002ff -> 999 -decf787 apply #220800000000000000000000000003ff -> 999 - Deleted: /python/branches/py3k-importlib/Lib/test/decimaltestdata/decimal32.decTest ============================================================================== --- /python/branches/py3k-importlib/Lib/test/decimaltestdata/decimal32.decTest Fri Sep 21 03:17:09 2007 +++ (empty file) @@ -1,385 +0,0 @@ ------------------------------------------------------------------------- --- decimal32.decTest -- decimal four-byte format testcases -- --- Copyright (c) IBM Corporation, 2000, 2003. All rights reserved. -- ------------------------------------------------------------------------- --- Please see the document "General Decimal Arithmetic Testcases" -- --- at http://www2.hursley.ibm.com/decimal for the description of -- --- these testcases. -- --- -- --- These testcases are experimental ('beta' versions), and they -- --- may contain errors. They are offered on an as-is basis. In -- --- particular, achieving the same results as the tests here is not -- --- a guarantee that an implementation complies with any Standard -- --- or specification. The tests are not exhaustive. -- --- -- --- Please send comments, suggestions, and corrections to the author: -- --- Mike Cowlishaw, IBM Fellow -- --- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- --- mfc at uk.ibm.com -- ------------------------------------------------------------------------- -version: 2.39 - --- This set of tests is for the four-byte concrete representation. --- Its characteristics are: --- --- 1 bit sign --- 5 bits combination field --- 6 bits exponent continuation --- 20 bits coefficient continuation --- --- Total exponent length 8 bits --- Total coefficient length 24 bits (7 digits) --- --- Elimit = 191 (maximum encoded exponent) --- Emax = 96 (largest exponent value) --- Emin = -95 (smallest exponent value) --- bias = 101 (subtracted from encoded exponent) = -Etiny - -extended: 1 -precision: 7 -rounding: half_up -maxExponent: 96 -minExponent: -95 - --- General testcases --- (mostly derived from the Strawman 4 document and examples) -decd001 apply #A23003D0 -> -7.50 -decd002 apply -7.50 -> #A23003D0 - --- Normality -decd010 apply 1234567 -> #2654d2e7 -decd011 apply 1234567.0 -> #2654d2e7 Rounded -decd012 apply 1234567.1 -> #2654d2e7 Rounded Inexact -decd013 apply -1234567 -> #a654d2e7 -decd014 apply -1234567.0 -> #a654d2e7 Rounded -decd015 apply -1234567.1 -> #a654d2e7 Rounded Inexact - - --- Nmax and similar -decd022 apply 9.999999E+96 -> #77f3fcff -decd023 apply #77f3fcff -> 9.999999E+96 -decd024 apply 1.234567E+96 -> #47f4d2e7 -decd025 apply #47f4d2e7 -> 1.234567E+96 --- fold-downs (more below) -decd030 apply 1.23E+96 -> #47f4c000 Clamped -decd031 apply #47f4c000 -> 1.230000E+96 -decd032 apply 1E+96 -> #47f00000 Clamped -decd033 apply #47f00000 -> 1.000000E+96 - --- overflows -maxExponent: 999 -- set high so conversion causes the overflow -minExponent: -999 -decd040 apply 10E+96 -> #78000000 Overflow Rounded Inexact -decd041 apply 1.000000E+97 -> #78000000 Overflow Rounded Inexact -maxExponent: 96 -minExponent: -95 - -decd051 apply 12345 -> #225049c5 -decd052 apply #225049c5 -> 12345 -decd053 apply 1234 -> #22500534 -decd054 apply #22500534 -> 1234 -decd055 apply 123 -> #225000a3 -decd056 apply #225000a3 -> 123 -decd057 apply 12 -> #22500012 -decd058 apply #22500012 -> 12 -decd059 apply 1 -> #22500001 -decd060 apply #22500001 -> 1 -decd061 apply 1.23 -> #223000a3 -decd062 apply #223000a3 -> 1.23 -decd063 apply 123.45 -> #223049c5 -decd064 apply #223049c5 -> 123.45 - --- Nmin and below -decd071 apply 1E-95 -> #00600001 -decd072 apply #00600001 -> 1E-95 -decd073 apply 1.000000E-95 -> #04000000 -decd074 apply #04000000 -> 1.000000E-95 -decd075 apply 1.000001E-95 -> #04000001 -decd076 apply #04000001 -> 1.000001E-95 - -decd077 apply 0.100000E-95 -> #00020000 Subnormal -decd07x apply 1.00000E-96 -> 1.00000E-96 Subnormal -decd078 apply #00020000 -> 1.00000E-96 Subnormal -decd079 apply 0.000010E-95 -> #00000010 Subnormal -decd080 apply #00000010 -> 1.0E-100 Subnormal -decd081 apply 0.000001E-95 -> #00000001 Subnormal -decd082 apply #00000001 -> 1E-101 Subnormal -decd083 apply 1e-101 -> #00000001 Subnormal -decd084 apply #00000001 -> 1E-101 Subnormal -decd08x apply 1e-101 -> 1E-101 Subnormal - --- underflows -decd090 apply 1e-101 -> #00000001 Subnormal -decd091 apply 1.9e-101 -> #00000002 Subnormal Underflow Inexact Rounded -decd092 apply 1.1e-101 -> #00000001 Subnormal Underflow Inexact Rounded -decd093 apply 1.001e-101 -> #00000001 Subnormal Underflow Inexact Rounded -decd094 apply 1.000001e-101 -> #00000001 Subnormal Underflow Inexact Rounded -decd095 apply 1.0000001e-101 -> #00000001 Subnormal Underflow Inexact Rounded -decd096 apply 0.1e-101 -> #00000000 Subnormal Underflow Inexact Rounded -decd097 apply 0.001e-101 -> #00000000 Subnormal Underflow Inexact Rounded -decd098 apply 0.000001e-101 -> #00000000 Subnormal Underflow Inexact Rounded -decd099 apply 0.0000001e-101 -> #00000000 Subnormal Underflow Inexact Rounded - --- same again, negatives -- - --- Nmax and similar -decd122 apply -9.999999E+96 -> #f7f3fcff -decd123 apply #f7f3fcff -> -9.999999E+96 -decd124 apply -1.234567E+96 -> #c7f4d2e7 -decd125 apply #c7f4d2e7 -> -1.234567E+96 --- fold-downs (more below) -decd130 apply -1.23E+96 -> #c7f4c000 Clamped -decd131 apply #c7f4c000 -> -1.230000E+96 -decd132 apply -1E+96 -> #c7f00000 Clamped -decd133 apply #c7f00000 -> -1.000000E+96 - --- overflows -maxExponent: 999 -- set high so conversion causes the overflow -minExponent: -999 -decd140 apply -10E+96 -> #f8000000 Overflow Rounded Inexact -decd141 apply -1.000000E+97 -> #f8000000 Overflow Rounded Inexact -maxExponent: 96 -minExponent: -95 - -decd151 apply -12345 -> #a25049c5 -decd152 apply #a25049c5 -> -12345 -decd153 apply -1234 -> #a2500534 -decd154 apply #a2500534 -> -1234 -decd155 apply -123 -> #a25000a3 -decd156 apply #a25000a3 -> -123 -decd157 apply -12 -> #a2500012 -decd158 apply #a2500012 -> -12 -decd159 apply -1 -> #a2500001 -decd160 apply #a2500001 -> -1 -decd161 apply -1.23 -> #a23000a3 -decd162 apply #a23000a3 -> -1.23 -decd163 apply -123.45 -> #a23049c5 -decd164 apply #a23049c5 -> -123.45 - --- Nmin and below -decd171 apply -1E-95 -> #80600001 -decd172 apply #80600001 -> -1E-95 -decd173 apply -1.000000E-95 -> #84000000 -decd174 apply #84000000 -> -1.000000E-95 -decd175 apply -1.000001E-95 -> #84000001 -decd176 apply #84000001 -> -1.000001E-95 - -decd177 apply -0.100000E-95 -> #80020000 Subnormal -decd178 apply #80020000 -> -1.00000E-96 Subnormal -decd179 apply -0.000010E-95 -> #80000010 Subnormal -decd180 apply #80000010 -> -1.0E-100 Subnormal -decd181 apply -0.000001E-95 -> #80000001 Subnormal -decd182 apply #80000001 -> -1E-101 Subnormal -decd183 apply -1e-101 -> #80000001 Subnormal -decd184 apply #80000001 -> -1E-101 Subnormal - --- underflows -decd190 apply -1e-101 -> #80000001 Subnormal -decd191 apply -1.9e-101 -> #80000002 Subnormal Underflow Inexact Rounded -decd192 apply -1.1e-101 -> #80000001 Subnormal Underflow Inexact Rounded -decd193 apply -1.001e-101 -> #80000001 Subnormal Underflow Inexact Rounded -decd194 apply -1.000001e-101 -> #80000001 Subnormal Underflow Inexact Rounded -decd195 apply -1.0000001e-101 -> #80000001 Subnormal Underflow Inexact Rounded -decd196 apply -0.1e-101 -> #80000000 Subnormal Underflow Inexact Rounded -decd197 apply -0.001e-101 -> #80000000 Subnormal Underflow Inexact Rounded -decd198 apply -0.000001e-101 -> #80000000 Subnormal Underflow Inexact Rounded -decd199 apply -0.0000001e-101 -> #80000000 Subnormal Underflow Inexact Rounded - --- zeros -decd400 apply 0E-400 -> #00000000 Clamped -decd401 apply 0E-101 -> #00000000 -decd402 apply #00000000 -> 0E-101 -decd403 apply 0.000000E-95 -> #00000000 -decd404 apply #00000000 -> 0E-101 -decd405 apply 0E-2 -> #22300000 -decd406 apply #22300000 -> 0.00 -decd407 apply 0 -> #22500000 -decd408 apply #22500000 -> 0 -decd409 apply 0E+3 -> #22800000 -decd410 apply #22800000 -> 0E+3 -decd411 apply 0E+90 -> #43f00000 -decd412 apply #43f00000 -> 0E+90 --- clamped zeros... -decd413 apply 0E+91 -> #43f00000 Clamped -decd414 apply #43f00000 -> 0E+90 -decd415 apply 0E+96 -> #43f00000 Clamped -decd416 apply #43f00000 -> 0E+90 -decd417 apply 0E+400 -> #43f00000 Clamped -decd418 apply #43f00000 -> 0E+90 - --- negative zeros -decd420 apply -0E-400 -> #80000000 Clamped -decd421 apply -0E-101 -> #80000000 -decd422 apply #80000000 -> -0E-101 -decd423 apply -0.000000E-95 -> #80000000 -decd424 apply #80000000 -> -0E-101 -decd425 apply -0E-2 -> #a2300000 -decd426 apply #a2300000 -> -0.00 -decd427 apply -0 -> #a2500000 -decd428 apply #a2500000 -> -0 -decd429 apply -0E+3 -> #a2800000 -decd430 apply #a2800000 -> -0E+3 -decd431 apply -0E+90 -> #c3f00000 -decd432 apply #c3f00000 -> -0E+90 --- clamped zeros... -decd433 apply -0E+91 -> #c3f00000 Clamped -decd434 apply #c3f00000 -> -0E+90 -decd435 apply -0E+96 -> #c3f00000 Clamped -decd436 apply #c3f00000 -> -0E+90 -decd437 apply -0E+400 -> #c3f00000 Clamped -decd438 apply #c3f00000 -> -0E+90 - --- Specials -decd500 apply Infinity -> #78000000 -decd501 apply #78787878 -> #78000000 -decd502 apply #78000000 -> Infinity -decd503 apply #79797979 -> #78000000 -decd504 apply #79000000 -> Infinity -decd505 apply #7a7a7a7a -> #78000000 -decd506 apply #7a000000 -> Infinity -decd507 apply #7b7b7b7b -> #78000000 -decd508 apply #7b000000 -> Infinity -decd509 apply #7c7c7c7c -> #7c0c7c7c - -decd510 apply NaN -> #7c000000 -decd511 apply #7c000000 -> NaN -decd512 apply #7d7d7d7d -> #7c0d7d7d -decd513 apply #7d000000 -> NaN -decd514 apply #7e7e7e7e -> #7e0e7c7e -decd515 apply #7e000000 -> sNaN -decd516 apply #7f7f7f7f -> #7e0f7c7f -decd517 apply #7f000000 -> sNaN -decd518 apply #7fffffff -> sNaN999999 -decd519 apply #7fffffff -> #7e03fcff - -decd520 apply -Infinity -> #f8000000 -decd521 apply #f8787878 -> #f8000000 -decd522 apply #f8000000 -> -Infinity -decd523 apply #f9797979 -> #f8000000 -decd524 apply #f9000000 -> -Infinity -decd525 apply #fa7a7a7a -> #f8000000 -decd526 apply #fa000000 -> -Infinity -decd527 apply #fb7b7b7b -> #f8000000 -decd528 apply #fb000000 -> -Infinity - -decd529 apply -NaN -> #fc000000 -decd530 apply #fc7c7c7c -> #fc0c7c7c -decd531 apply #fc000000 -> -NaN -decd532 apply #fd7d7d7d -> #fc0d7d7d -decd533 apply #fd000000 -> -NaN -decd534 apply #fe7e7e7e -> #fe0e7c7e -decd535 apply #fe000000 -> -sNaN -decd536 apply #ff7f7f7f -> #fe0f7c7f -decd537 apply #ff000000 -> -sNaN -decd538 apply #ffffffff -> -sNaN999999 -decd539 apply #ffffffff -> #fe03fcff - --- diagnostic NaNs -decd540 apply NaN -> #7c000000 -decd541 apply NaN0 -> #7c000000 -decd542 apply NaN1 -> #7c000001 -decd543 apply NaN12 -> #7c000012 -decd544 apply NaN79 -> #7c000079 -decd545 apply NaN12345 -> #7c0049c5 -decd546 apply NaN123456 -> #7c028e56 -decd547 apply NaN799799 -> #7c0f7fdf -decd548 apply NaN999999 -> #7c03fcff -decd549 apply NaN1234567 -> #7c000000 -- too many digits - - --- fold-down full sequence -decd601 apply 1E+96 -> #47f00000 Clamped -decd602 apply #47f00000 -> 1.000000E+96 -decd603 apply 1E+95 -> #43f20000 Clamped -decd604 apply #43f20000 -> 1.00000E+95 -decd605 apply 1E+94 -> #43f04000 Clamped -decd606 apply #43f04000 -> 1.0000E+94 -decd607 apply 1E+93 -> #43f00400 Clamped -decd608 apply #43f00400 -> 1.000E+93 -decd609 apply 1E+92 -> #43f00080 Clamped -decd610 apply #43f00080 -> 1.00E+92 -decd611 apply 1E+91 -> #43f00010 Clamped -decd612 apply #43f00010 -> 1.0E+91 -decd613 apply 1E+90 -> #43f00001 -decd614 apply #43f00001 -> 1E+90 - - --- Selected DPD codes -decd700 apply #22500000 -> 0 -decd701 apply #22500009 -> 9 -decd702 apply #22500010 -> 10 -decd703 apply #22500019 -> 19 -decd704 apply #22500020 -> 20 -decd705 apply #22500029 -> 29 -decd706 apply #22500030 -> 30 -decd707 apply #22500039 -> 39 -decd708 apply #22500040 -> 40 -decd709 apply #22500049 -> 49 -decd710 apply #22500050 -> 50 -decd711 apply #22500059 -> 59 -decd712 apply #22500060 -> 60 -decd713 apply #22500069 -> 69 -decd714 apply #22500070 -> 70 -decd715 apply #22500071 -> 71 -decd716 apply #22500072 -> 72 -decd717 apply #22500073 -> 73 -decd718 apply #22500074 -> 74 -decd719 apply #22500075 -> 75 -decd720 apply #22500076 -> 76 -decd721 apply #22500077 -> 77 -decd722 apply #22500078 -> 78 -decd723 apply #22500079 -> 79 - -decd730 apply #2250029e -> 994 -decd731 apply #2250029f -> 995 -decd732 apply #225002a0 -> 520 -decd733 apply #225002a1 -> 521 - --- DPD: one of each of the huffman groups -decd740 apply #225003f7 -> 777 -decd741 apply #225003f8 -> 778 -decd742 apply #225003eb -> 787 -decd743 apply #2250037d -> 877 -decd744 apply #2250039f -> 997 -decd745 apply #225003bf -> 979 -decd746 apply #225003df -> 799 -decd747 apply #2250006e -> 888 - - --- DPD all-highs cases (includes the 24 redundant codes) -decd750 apply #2250006e -> 888 -decd751 apply #2250016e -> 888 -decd752 apply #2250026e -> 888 -decd753 apply #2250036e -> 888 -decd754 apply #2250006f -> 889 -decd755 apply #2250016f -> 889 -decd756 apply #2250026f -> 889 -decd757 apply #2250036f -> 889 - -decd760 apply #2250007e -> 898 -decd761 apply #2250017e -> 898 -decd762 apply #2250027e -> 898 -decd763 apply #2250037e -> 898 -decd764 apply #2250007f -> 899 -decd765 apply #2250017f -> 899 -decd766 apply #2250027f -> 899 -decd767 apply #2250037f -> 899 - -decd770 apply #225000ee -> 988 -decd771 apply #225001ee -> 988 -decd772 apply #225002ee -> 988 -decd773 apply #225003ee -> 988 -decd774 apply #225000ef -> 989 -decd775 apply #225001ef -> 989 -decd776 apply #225002ef -> 989 -decd777 apply #225003ef -> 989 - -decd780 apply #225000fe -> 998 -decd781 apply #225001fe -> 998 -decd782 apply #225002fe -> 998 -decd783 apply #225003fe -> 998 -decd784 apply #225000ff -> 999 -decd785 apply #225001ff -> 999 -decd786 apply #225002ff -> 999 -decd787 apply #225003ff -> 999 - Deleted: /python/branches/py3k-importlib/Lib/test/decimaltestdata/decimal64.decTest ============================================================================== --- /python/branches/py3k-importlib/Lib/test/decimaltestdata/decimal64.decTest Fri Sep 21 03:17:09 2007 +++ (empty file) @@ -1,444 +0,0 @@ ------------------------------------------------------------------------- --- decimal64.decTest -- decimal eight-byte format testcases -- --- Copyright (c) IBM Corporation, 2000, 2003. All rights reserved. -- ------------------------------------------------------------------------- --- Please see the document "General Decimal Arithmetic Testcases" -- --- at http://www2.hursley.ibm.com/decimal for the description of -- --- these testcases. -- --- -- --- These testcases are experimental ('beta' versions), and they -- --- may contain errors. They are offered on an as-is basis. In -- --- particular, achieving the same results as the tests here is not -- --- a guarantee that an implementation complies with any Standard -- --- or specification. The tests are not exhaustive. -- --- -- --- Please send comments, suggestions, and corrections to the author: -- --- Mike Cowlishaw, IBM Fellow -- --- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- --- mfc at uk.ibm.com -- ------------------------------------------------------------------------- -version: 2.39 - --- This set of tests is for the eight-byte concrete representation. --- Its characteristics are: --- --- 1 bit sign --- 5 bits combination field --- 8 bits exponent continuation --- 50 bits coefficient continuation --- --- Total exponent length 10 bits --- Total coefficient length 54 bits (16 digits) --- --- Elimit = 767 (maximum encoded exponent) --- Emax = 384 (largest exponent value) --- Emin = -383 (smallest exponent value) --- bias = 398 (subtracted from encoded exponent) = -Etiny - -extended: 1 -precision: 16 -rounding: half_up -maxExponent: 384 -minExponent: -383 - --- General testcases --- (mostly derived from the Strawman 4 document and examples) -dece001 apply #A2300000000003D0 -> -7.50 -dece002 apply -7.50 -> #A2300000000003D0 - --- Normality -dece010 apply 1234567890123456 -> #263934b9c1e28e56 -dece011 apply 1234567890123456.0 -> #263934b9c1e28e56 Rounded -dece012 apply 1234567890123456.1 -> #263934b9c1e28e56 Rounded Inexact -dece013 apply -1234567890123456 -> #a63934b9c1e28e56 -dece014 apply -1234567890123456.0 -> #a63934b9c1e28e56 Rounded -dece015 apply -1234567890123456.1 -> #a63934b9c1e28e56 Rounded Inexact - - --- Nmax and similar -dece022 apply 9.999999999999999E+384 -> #77fcff3fcff3fcff -dece023 apply #77fcff3fcff3fcff -> 9.999999999999999E+384 -dece024 apply 1.234567890123456E+384 -> #47fd34b9c1e28e56 -dece025 apply #47fd34b9c1e28e56 -> 1.234567890123456E+384 --- fold-downs (more below) -dece030 apply 1.23E+384 -> #47fd300000000000 Clamped -dece031 apply #47fd300000000000 -> 1.230000000000000E+384 -dece032 apply 1E+384 -> #47fc000000000000 Clamped -dece033 apply #47fc000000000000 -> 1.000000000000000E+384 - --- overflows -maxExponent: 999 -- set high so conversion causes the overflow -minExponent: -999 -dece040 apply 10E+384 -> #7800000000000000 Overflow Rounded Inexact -dece041 apply 1.000000000000000E+385 -> #7800000000000000 Overflow Rounded Inexact -maxExponent: 384 -minExponent: -383 - -dece051 apply 12345 -> #22380000000049c5 -dece052 apply #22380000000049c5 -> 12345 -dece053 apply 1234 -> #2238000000000534 -dece054 apply #2238000000000534 -> 1234 -dece055 apply 123 -> #22380000000000a3 -dece056 apply #22380000000000a3 -> 123 -dece057 apply 12 -> #2238000000000012 -dece058 apply #2238000000000012 -> 12 -dece059 apply 1 -> #2238000000000001 -dece060 apply #2238000000000001 -> 1 -dece061 apply 1.23 -> #22300000000000a3 -dece062 apply #22300000000000a3 -> 1.23 -dece063 apply 123.45 -> #22300000000049c5 -dece064 apply #22300000000049c5 -> 123.45 - --- Nmin and below -dece071 apply 1E-383 -> #003c000000000001 -dece072 apply #003c000000000001 -> 1E-383 -dece073 apply 1.000000000000000E-383 -> #0400000000000000 -dece074 apply #0400000000000000 -> 1.000000000000000E-383 -dece075 apply 1.000000000000001E-383 -> #0400000000000001 -dece076 apply #0400000000000001 -> 1.000000000000001E-383 - -dece077 apply 0.100000000000000E-383 -> #0000800000000000 Subnormal -dece078 apply #0000800000000000 -> 1.00000000000000E-384 Subnormal -dece079 apply 0.000000000000010E-383 -> #0000000000000010 Subnormal -dece080 apply #0000000000000010 -> 1.0E-397 Subnormal -dece081 apply 0.00000000000001E-383 -> #0004000000000001 Subnormal -dece082 apply #0004000000000001 -> 1E-397 Subnormal -dece083 apply 0.000000000000001E-383 -> #0000000000000001 Subnormal -dece084 apply #0000000000000001 -> 1E-398 Subnormal - --- underflows -dece090 apply 1e-398 -> #0000000000000001 Subnormal -dece091 apply 1.9e-398 -> #0000000000000002 Subnormal Underflow Inexact Rounded -dece092 apply 1.1e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded -dece093 apply 1.00000000001e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded -dece094 apply 1.00000000000001e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded -dece095 apply 1.000000000000001e-398 -> #0000000000000001 Subnormal Underflow Inexact Rounded -dece096 apply 0.1e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded -dece097 apply 0.00000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded -dece098 apply 0.00000000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded -dece099 apply 0.000000000000001e-398 -> #0000000000000000 Subnormal Underflow Inexact Rounded - --- Same again, negatives --- Nmax and similar -dece122 apply -9.999999999999999E+384 -> #f7fcff3fcff3fcff -dece123 apply #f7fcff3fcff3fcff -> -9.999999999999999E+384 -dece124 apply -1.234567890123456E+384 -> #c7fd34b9c1e28e56 -dece125 apply #c7fd34b9c1e28e56 -> -1.234567890123456E+384 --- fold-downs (more below) -dece130 apply -1.23E+384 -> #c7fd300000000000 Clamped -dece131 apply #c7fd300000000000 -> -1.230000000000000E+384 -dece132 apply -1E+384 -> #c7fc000000000000 Clamped -dece133 apply #c7fc000000000000 -> -1.000000000000000E+384 - --- overflows -maxExponent: 999 -- set high so conversion causes the overflow -minExponent: -999 -dece140 apply -10E+384 -> #f800000000000000 Overflow Rounded Inexact -dece141 apply -1.000000000000000E+385 -> #f800000000000000 Overflow Rounded Inexact -maxExponent: 384 -minExponent: -383 - -dece151 apply -12345 -> #a2380000000049c5 -dece152 apply #a2380000000049c5 -> -12345 -dece153 apply -1234 -> #a238000000000534 -dece154 apply #a238000000000534 -> -1234 -dece155 apply -123 -> #a2380000000000a3 -dece156 apply #a2380000000000a3 -> -123 -dece157 apply -12 -> #a238000000000012 -dece158 apply #a238000000000012 -> -12 -dece159 apply -1 -> #a238000000000001 -dece160 apply #a238000000000001 -> -1 -dece161 apply -1.23 -> #a2300000000000a3 -dece162 apply #a2300000000000a3 -> -1.23 -dece163 apply -123.45 -> #a2300000000049c5 -dece164 apply #a2300000000049c5 -> -123.45 - --- Nmin and below -dece171 apply -1E-383 -> #803c000000000001 -dece172 apply #803c000000000001 -> -1E-383 -dece173 apply -1.000000000000000E-383 -> #8400000000000000 -dece174 apply #8400000000000000 -> -1.000000000000000E-383 -dece175 apply -1.000000000000001E-383 -> #8400000000000001 -dece176 apply #8400000000000001 -> -1.000000000000001E-383 - -dece177 apply -0.100000000000000E-383 -> #8000800000000000 Subnormal -dece178 apply #8000800000000000 -> -1.00000000000000E-384 Subnormal -dece179 apply -0.000000000000010E-383 -> #8000000000000010 Subnormal -dece180 apply #8000000000000010 -> -1.0E-397 Subnormal -dece181 apply -0.00000000000001E-383 -> #8004000000000001 Subnormal -dece182 apply #8004000000000001 -> -1E-397 Subnormal -dece183 apply -0.000000000000001E-383 -> #8000000000000001 Subnormal -dece184 apply #8000000000000001 -> -1E-398 Subnormal - --- underflows -dece189 apply -1e-398 -> #8000000000000001 Subnormal -dece190 apply -1.0e-398 -> #8000000000000001 Subnormal Rounded -dece191 apply -1.9e-398 -> #8000000000000002 Subnormal Underflow Inexact Rounded -dece192 apply -1.1e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded -dece193 apply -1.00000000001e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded -dece194 apply -1.00000000000001e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded -dece195 apply -1.000000000000001e-398 -> #8000000000000001 Subnormal Underflow Inexact Rounded -dece196 apply -0.1e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded -dece197 apply -0.00000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded -dece198 apply -0.00000000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded -dece199 apply -0.000000000000001e-398 -> #8000000000000000 Subnormal Underflow Inexact Rounded - --- zeros -dece401 apply 0E-500 -> #0000000000000000 Clamped -dece402 apply 0E-400 -> #0000000000000000 Clamped -dece403 apply 0E-398 -> #0000000000000000 -dece404 apply #0000000000000000 -> 0E-398 -dece405 apply 0.000000000000000E-383 -> #0000000000000000 -dece406 apply #0000000000000000 -> 0E-398 -dece407 apply 0E-2 -> #2230000000000000 -dece408 apply #2230000000000000 -> 0.00 -dece409 apply 0 -> #2238000000000000 -dece410 apply #2238000000000000 -> 0 -dece411 apply 0E+3 -> #2244000000000000 -dece412 apply #2244000000000000 -> 0E+3 -dece413 apply 0E+369 -> #43fc000000000000 -dece414 apply #43fc000000000000 -> 0E+369 --- clamped zeros... -dece415 apply 0E+370 -> #43fc000000000000 Clamped -dece416 apply #43fc000000000000 -> 0E+369 -dece417 apply 0E+384 -> #43fc000000000000 Clamped -dece418 apply #43fc000000000000 -> 0E+369 -dece419 apply 0E+400 -> #43fc000000000000 Clamped -dece420 apply #43fc000000000000 -> 0E+369 -dece421 apply 0E+500 -> #43fc000000000000 Clamped -dece422 apply #43fc000000000000 -> 0E+369 - --- negative zeros -dece431 apply -0E-400 -> #8000000000000000 Clamped -dece432 apply -0E-400 -> #8000000000000000 Clamped -dece433 apply -0E-398 -> #8000000000000000 -dece434 apply #8000000000000000 -> -0E-398 -dece435 apply -0.000000000000000E-383 -> #8000000000000000 -dece436 apply #8000000000000000 -> -0E-398 -dece437 apply -0E-2 -> #a230000000000000 -dece438 apply #a230000000000000 -> -0.00 -dece439 apply -0 -> #a238000000000000 -dece440 apply #a238000000000000 -> -0 -dece441 apply -0E+3 -> #a244000000000000 -dece442 apply #a244000000000000 -> -0E+3 -dece443 apply -0E+369 -> #c3fc000000000000 -dece444 apply #c3fc000000000000 -> -0E+369 --- clamped zeros... -dece445 apply -0E+370 -> #c3fc000000000000 Clamped -dece446 apply #c3fc000000000000 -> -0E+369 -dece447 apply -0E+384 -> #c3fc000000000000 Clamped -dece448 apply #c3fc000000000000 -> -0E+369 -dece449 apply -0E+400 -> #c3fc000000000000 Clamped -dece450 apply #c3fc000000000000 -> -0E+369 -dece451 apply -0E+500 -> #c3fc000000000000 Clamped -dece452 apply #c3fc000000000000 -> -0E+369 - --- Specials -dece500 apply Infinity -> #7800000000000000 -dece501 apply #7878787878787878 -> #7800000000000000 -dece502 apply #7800000000000000 -> Infinity -dece503 apply #7979797979797979 -> #7800000000000000 -dece504 apply #7900000000000000 -> Infinity -dece505 apply #7a7a7a7a7a7a7a7a -> #7800000000000000 -dece506 apply #7a00000000000000 -> Infinity -dece507 apply #7b7b7b7b7b7b7b7b -> #7800000000000000 -dece508 apply #7b00000000000000 -> Infinity - -dece509 apply NaN -> #7c00000000000000 -dece510 apply #7c7c7c7c7c7c7c7c -> #7c007c7c7c7c7c7c -dece511 apply #7c00000000000000 -> NaN -dece512 apply #7d7d7d7d7d7d7d7d -> #7c017d7d7d7d7d7d -dece513 apply #7d00000000000000 -> NaN -dece514 apply #7e7e7e7e7e7e7e7e -> #7e007e7e7e7e7c7e -dece515 apply #7e00000000000000 -> sNaN -dece516 apply #7f7f7f7f7f7f7f7f -> #7e007f7f7f7f7c7f -dece517 apply #7f00000000000000 -> sNaN -dece518 apply #7fffffffffffffff -> sNaN999999999999999 -dece519 apply #7fffffffffffffff -> #7e00ff3fcff3fcff - -dece520 apply -Infinity -> #f800000000000000 -dece521 apply #f878787878787878 -> #f800000000000000 -dece522 apply #f800000000000000 -> -Infinity -dece523 apply #f979797979797979 -> #f800000000000000 -dece524 apply #f900000000000000 -> -Infinity -dece525 apply #fa7a7a7a7a7a7a7a -> #f800000000000000 -dece526 apply #fa00000000000000 -> -Infinity -dece527 apply #fb7b7b7b7b7b7b7b -> #f800000000000000 -dece528 apply #fb00000000000000 -> -Infinity - -dece529 apply -NaN -> #fc00000000000000 -dece530 apply #fc7c7c7c7c7c7c7c -> #fc007c7c7c7c7c7c -dece531 apply #fc00000000000000 -> -NaN -dece532 apply #fd7d7d7d7d7d7d7d -> #fc017d7d7d7d7d7d -dece533 apply #fd00000000000000 -> -NaN -dece534 apply #fe7e7e7e7e7e7e7e -> #fe007e7e7e7e7c7e -dece535 apply #fe00000000000000 -> -sNaN -dece536 apply #ff7f7f7f7f7f7f7f -> #fe007f7f7f7f7c7f -dece537 apply #ff00000000000000 -> -sNaN -dece538 apply #ffffffffffffffff -> -sNaN999999999999999 -dece539 apply #ffffffffffffffff -> #fe00ff3fcff3fcff - --- diagnostic NaNs -dece540 apply NaN -> #7c00000000000000 -dece541 apply NaN0 -> #7c00000000000000 -dece542 apply NaN1 -> #7c00000000000001 -dece543 apply NaN12 -> #7c00000000000012 -dece544 apply NaN79 -> #7c00000000000079 -dece545 apply NaN12345 -> #7c000000000049c5 -dece546 apply NaN123456 -> #7c00000000028e56 -dece547 apply NaN799799 -> #7c000000000f7fdf -dece548 apply NaN799799799799799 -> #7c03dff7fdff7fdf -dece549 apply NaN999999999999999 -> #7c00ff3fcff3fcff -dece550 apply NaN1234567890123456 -> #7c00000000000000 -- too many digits - --- fold-down full sequence -dece601 apply 1E+384 -> #47fc000000000000 Clamped -dece602 apply #47fc000000000000 -> 1.000000000000000E+384 -dece603 apply 1E+383 -> #43fc800000000000 Clamped -dece604 apply #43fc800000000000 -> 1.00000000000000E+383 -dece605 apply 1E+382 -> #43fc100000000000 Clamped -dece606 apply #43fc100000000000 -> 1.0000000000000E+382 -dece607 apply 1E+381 -> #43fc010000000000 Clamped -dece608 apply #43fc010000000000 -> 1.000000000000E+381 -dece609 apply 1E+380 -> #43fc002000000000 Clamped -dece610 apply #43fc002000000000 -> 1.00000000000E+380 -dece611 apply 1E+379 -> #43fc000400000000 Clamped -dece612 apply #43fc000400000000 -> 1.0000000000E+379 -dece613 apply 1E+378 -> #43fc000040000000 Clamped -dece614 apply #43fc000040000000 -> 1.000000000E+378 -dece615 apply 1E+377 -> #43fc000008000000 Clamped -dece616 apply #43fc000008000000 -> 1.00000000E+377 -dece617 apply 1E+376 -> #43fc000001000000 Clamped -dece618 apply #43fc000001000000 -> 1.0000000E+376 -dece619 apply 1E+375 -> #43fc000000100000 Clamped -dece620 apply #43fc000000100000 -> 1.000000E+375 -dece621 apply 1E+374 -> #43fc000000020000 Clamped -dece622 apply #43fc000000020000 -> 1.00000E+374 -dece623 apply 1E+373 -> #43fc000000004000 Clamped -dece624 apply #43fc000000004000 -> 1.0000E+373 -dece625 apply 1E+372 -> #43fc000000000400 Clamped -dece626 apply #43fc000000000400 -> 1.000E+372 -dece627 apply 1E+371 -> #43fc000000000080 Clamped -dece628 apply #43fc000000000080 -> 1.00E+371 -dece629 apply 1E+370 -> #43fc000000000010 Clamped -dece630 apply #43fc000000000010 -> 1.0E+370 -dece631 apply 1E+369 -> #43fc000000000001 -dece632 apply #43fc000000000001 -> 1E+369 -dece633 apply 1E+368 -> #43f8000000000001 -dece634 apply #43f8000000000001 -> 1E+368 --- same with 9s -dece641 apply 9E+384 -> #77fc000000000000 Clamped -dece642 apply #77fc000000000000 -> 9.000000000000000E+384 -dece643 apply 9E+383 -> #43fc8c0000000000 Clamped -dece644 apply #43fc8c0000000000 -> 9.00000000000000E+383 -dece645 apply 9E+382 -> #43fc1a0000000000 Clamped -dece646 apply #43fc1a0000000000 -> 9.0000000000000E+382 -dece647 apply 9E+381 -> #43fc090000000000 Clamped -dece648 apply #43fc090000000000 -> 9.000000000000E+381 -dece649 apply 9E+380 -> #43fc002300000000 Clamped -dece650 apply #43fc002300000000 -> 9.00000000000E+380 -dece651 apply 9E+379 -> #43fc000680000000 Clamped -dece652 apply #43fc000680000000 -> 9.0000000000E+379 -dece653 apply 9E+378 -> #43fc000240000000 Clamped -dece654 apply #43fc000240000000 -> 9.000000000E+378 -dece655 apply 9E+377 -> #43fc000008c00000 Clamped -dece656 apply #43fc000008c00000 -> 9.00000000E+377 -dece657 apply 9E+376 -> #43fc000001a00000 Clamped -dece658 apply #43fc000001a00000 -> 9.0000000E+376 -dece659 apply 9E+375 -> #43fc000000900000 Clamped -dece660 apply #43fc000000900000 -> 9.000000E+375 -dece661 apply 9E+374 -> #43fc000000023000 Clamped -dece662 apply #43fc000000023000 -> 9.00000E+374 -dece663 apply 9E+373 -> #43fc000000006800 Clamped -dece664 apply #43fc000000006800 -> 9.0000E+373 -dece665 apply 9E+372 -> #43fc000000002400 Clamped -dece666 apply #43fc000000002400 -> 9.000E+372 -dece667 apply 9E+371 -> #43fc00000000008c Clamped -dece668 apply #43fc00000000008c -> 9.00E+371 -dece669 apply 9E+370 -> #43fc00000000001a Clamped -dece670 apply #43fc00000000001a -> 9.0E+370 -dece671 apply 9E+369 -> #43fc000000000009 -dece672 apply #43fc000000000009 -> 9E+369 -dece673 apply 9E+368 -> #43f8000000000009 -dece674 apply #43f8000000000009 -> 9E+368 - - --- Selected DPD codes -dece700 apply #2238000000000000 -> 0 -dece701 apply #2238000000000009 -> 9 -dece702 apply #2238000000000010 -> 10 -dece703 apply #2238000000000019 -> 19 -dece704 apply #2238000000000020 -> 20 -dece705 apply #2238000000000029 -> 29 -dece706 apply #2238000000000030 -> 30 -dece707 apply #2238000000000039 -> 39 -dece708 apply #2238000000000040 -> 40 -dece709 apply #2238000000000049 -> 49 -dece710 apply #2238000000000050 -> 50 -dece711 apply #2238000000000059 -> 59 -dece712 apply #2238000000000060 -> 60 -dece713 apply #2238000000000069 -> 69 -dece714 apply #2238000000000070 -> 70 -dece715 apply #2238000000000071 -> 71 -dece716 apply #2238000000000072 -> 72 -dece717 apply #2238000000000073 -> 73 -dece718 apply #2238000000000074 -> 74 -dece719 apply #2238000000000075 -> 75 -dece720 apply #2238000000000076 -> 76 -dece721 apply #2238000000000077 -> 77 -dece722 apply #2238000000000078 -> 78 -dece723 apply #2238000000000079 -> 79 - -dece730 apply #223800000000029e -> 994 -dece731 apply #223800000000029f -> 995 -dece732 apply #22380000000002a0 -> 520 -dece733 apply #22380000000002a1 -> 521 - --- DPD: one of each of the huffman groups -dece740 apply #22380000000003f7 -> 777 -dece741 apply #22380000000003f8 -> 778 -dece742 apply #22380000000003eb -> 787 -dece743 apply #223800000000037d -> 877 -dece744 apply #223800000000039f -> 997 -dece745 apply #22380000000003bf -> 979 -dece746 apply #22380000000003df -> 799 -dece747 apply #223800000000006e -> 888 - - --- DPD all-highs cases (includes the 24 redundant codes) -dece750 apply #223800000000006e -> 888 -dece751 apply #223800000000016e -> 888 -dece752 apply #223800000000026e -> 888 -dece753 apply #223800000000036e -> 888 -dece754 apply #223800000000006f -> 889 -dece755 apply #223800000000016f -> 889 -dece756 apply #223800000000026f -> 889 -dece757 apply #223800000000036f -> 889 - -dece760 apply #223800000000007e -> 898 -dece761 apply #223800000000017e -> 898 -dece762 apply #223800000000027e -> 898 -dece763 apply #223800000000037e -> 898 -dece764 apply #223800000000007f -> 899 -dece765 apply #223800000000017f -> 899 -dece766 apply #223800000000027f -> 899 -dece767 apply #223800000000037f -> 899 - -dece770 apply #22380000000000ee -> 988 -dece771 apply #22380000000001ee -> 988 -dece772 apply #22380000000002ee -> 988 -dece773 apply #22380000000003ee -> 988 -dece774 apply #22380000000000ef -> 989 -dece775 apply #22380000000001ef -> 989 -dece776 apply #22380000000002ef -> 989 -dece777 apply #22380000000003ef -> 989 - -dece780 apply #22380000000000fe -> 998 -dece781 apply #22380000000001fe -> 998 -dece782 apply #22380000000002fe -> 998 -dece783 apply #22380000000003fe -> 998 -dece784 apply #22380000000000ff -> 999 -dece785 apply #22380000000001ff -> 999 -dece786 apply #22380000000002ff -> 999 -dece787 apply #22380000000003ff -> 999 - Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/divide.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/divide.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/divide.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- divide.decTest -- decimal division -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -47,41 +47,45 @@ divx018 divide 2. 2 -> 1 divx019 divide 20 20 -> 1 -divx020 divide 187 187 -> 1 -divx021 divide 5 2 -> 2.5 -divx022 divide 5 2.0 -> 2.5 -divx023 divide 5 2.000 -> 2.5 -divx024 divide 5 0.20 -> 25 -divx025 divide 5 0.200 -> 25 -divx026 divide 10 1 -> 10 -divx027 divide 100 1 -> 100 -divx028 divide 1000 1 -> 1000 -divx029 divide 1000 100 -> 10 - -divx030 divide 1 2 -> 0.5 -divx031 divide 1 4 -> 0.25 -divx032 divide 1 8 -> 0.125 -divx033 divide 1 16 -> 0.0625 -divx034 divide 1 32 -> 0.03125 -divx035 divide 1 64 -> 0.015625 -divx040 divide 1 -2 -> -0.5 -divx041 divide 1 -4 -> -0.25 -divx042 divide 1 -8 -> -0.125 -divx043 divide 1 -16 -> -0.0625 -divx044 divide 1 -32 -> -0.03125 -divx045 divide 1 -64 -> -0.015625 -divx050 divide -1 2 -> -0.5 -divx051 divide -1 4 -> -0.25 -divx052 divide -1 8 -> -0.125 -divx053 divide -1 16 -> -0.0625 -divx054 divide -1 32 -> -0.03125 -divx055 divide -1 64 -> -0.015625 -divx060 divide -1 -2 -> 0.5 -divx061 divide -1 -4 -> 0.25 -divx062 divide -1 -8 -> 0.125 -divx063 divide -1 -16 -> 0.0625 -divx064 divide -1 -32 -> 0.03125 -divx065 divide -1 -64 -> 0.015625 +divx020 divide 187 187 -> 1 +divx021 divide 5 2 -> 2.5 +divx022 divide 50 20 -> 2.5 +divx023 divide 500 200 -> 2.5 +divx024 divide 50.0 20.0 -> 2.5 +divx025 divide 5.00 2.00 -> 2.5 +divx026 divide 5 2.0 -> 2.5 +divx027 divide 5 2.000 -> 2.5 +divx028 divide 5 0.20 -> 25 +divx029 divide 5 0.200 -> 25 +divx030 divide 10 1 -> 10 +divx031 divide 100 1 -> 100 +divx032 divide 1000 1 -> 1000 +divx033 divide 1000 100 -> 10 + +divx035 divide 1 2 -> 0.5 +divx036 divide 1 4 -> 0.25 +divx037 divide 1 8 -> 0.125 +divx038 divide 1 16 -> 0.0625 +divx039 divide 1 32 -> 0.03125 +divx040 divide 1 64 -> 0.015625 +divx041 divide 1 -2 -> -0.5 +divx042 divide 1 -4 -> -0.25 +divx043 divide 1 -8 -> -0.125 +divx044 divide 1 -16 -> -0.0625 +divx045 divide 1 -32 -> -0.03125 +divx046 divide 1 -64 -> -0.015625 +divx047 divide -1 2 -> -0.5 +divx048 divide -1 4 -> -0.25 +divx049 divide -1 8 -> -0.125 +divx050 divide -1 16 -> -0.0625 +divx051 divide -1 32 -> -0.03125 +divx052 divide -1 64 -> -0.015625 +divx053 divide -1 -2 -> 0.5 +divx054 divide -1 -4 -> 0.25 +divx055 divide -1 -8 -> 0.125 +divx056 divide -1 -16 -> 0.0625 +divx057 divide -1 -32 -> 0.03125 +divx058 divide -1 -64 -> 0.015625 divx070 divide 999999999 1 -> 999999999 divx071 divide 999999999.4 1 -> 999999999 Inexact Rounded @@ -763,9 +767,9 @@ divx964 divide 1e-600000000 1e+400000005 -> 1E-1000000005 Subnormal divx965 divide 1e-600000000 1e+400000006 -> 1E-1000000006 Subnormal divx966 divide 1e-600000000 1e+400000007 -> 1E-1000000007 Subnormal -divx967 divide 1e-600000000 1e+400000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -divx968 divide 1e-600000000 1e+400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -divx969 divide 1e-600000000 1e+400000010 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +divx967 divide 1e-600000000 1e+400000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +divx968 divide 1e-600000000 1e+400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +divx969 divide 1e-600000000 1e+400000010 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -- [no equivalent of 'subnormal' for overflow] divx970 divide 1e+600000000 1e-400000001 -> Infinity Overflow Inexact Rounded divx971 divide 1e+600000000 1e-400000002 -> Infinity Overflow Inexact Rounded @@ -779,10 +783,10 @@ divx979 divide 1e+600000000 1e-400000010 -> Infinity Overflow Inexact Rounded -- Sign after overflow and underflow -divx980 divide 1e-600000000 1e+400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -divx981 divide 1e-600000000 -1e+400000009 -> -0E-1000000007 Underflow Subnormal Inexact Rounded -divx982 divide -1e-600000000 1e+400000009 -> -0E-1000000007 Underflow Subnormal Inexact Rounded -divx983 divide -1e-600000000 -1e+400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +divx980 divide 1e-600000000 1e+400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +divx981 divide 1e-600000000 -1e+400000009 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +divx982 divide -1e-600000000 1e+400000009 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +divx983 divide -1e-600000000 -1e+400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped divx984 divide 1e+600000000 1e-400000009 -> Infinity Overflow Inexact Rounded divx985 divide 1e+600000000 -1e-400000009 -> -Infinity Overflow Inexact Rounded divx986 divide -1e+600000000 1e-400000009 -> -Infinity Overflow Inexact Rounded @@ -812,6 +816,38 @@ -- 1.465811965811965811965811965811965811966E+7000 divx1010 divide 343E6000 234E-1000 -> Infinity Overflow Inexact Rounded +precision: 34 +rounding: half_up +maxExponent: 6144 +minExponent: -6143 + +-- Examples from SQL proposal (Krishna Kulkarni) +precision: 7 +divx1021 divide 1E0 1E0 -> 1 +divx1022 divide 1E0 2E0 -> 0.5 +divx1023 divide 1E0 3E0 -> 0.3333333 Inexact Rounded +divx1024 divide 100E-2 1000E-3 -> 1 +divx1025 divide 24E-1 2E0 -> 1.2 +divx1026 divide 2400E-3 2E0 -> 1.200 +divx1027 divide 5E0 2E0 -> 2.5 +divx1028 divide 5E0 20E-1 -> 2.5 +divx1029 divide 5E0 2000E-3 -> 2.5 +divx1030 divide 5E0 2E-1 -> 25 +divx1031 divide 5E0 20E-2 -> 25 +divx1032 divide 480E-2 3E0 -> 1.60 +divx1033 divide 47E-1 2E0 -> 2.35 + +-- ECMAScript bad examples +rounding: half_down +precision: 7 +divx1050 divide 5 9 -> 0.5555556 Inexact Rounded +rounding: half_even +divx1051 divide 5 11 -> 0.4545455 Inexact Rounded + +-- payload decapitate +precision: 5 +divx1055 divide sNaN987654321 1 -> NaN54321 Invalid_operation + -- Null tests divx9998 divide 10 # -> NaN Invalid_operation divx9999 divide # 10 -> NaN Invalid_operation Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/divideint.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/divideint.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/divideint.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- divideint.decTest -- decimal integer division -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -234,6 +234,22 @@ dvix287 divideint 0.1 9999e-999999997 -> NaN Division_impossible dvix288 divideint 0.1 99999e-999999997 -> NaN Division_impossible +-- GD edge cases: lhs smaller than rhs but more digits +dvix301 divideint 0.9 2 -> 0 +dvix302 divideint 0.9 2.0 -> 0 +dvix303 divideint 0.9 2.1 -> 0 +dvix304 divideint 0.9 2.00 -> 0 +dvix305 divideint 0.9 2.01 -> 0 +dvix306 divideint 0.12 1 -> 0 +dvix307 divideint 0.12 1.0 -> 0 +dvix308 divideint 0.12 1.00 -> 0 +dvix309 divideint 0.12 1.0 -> 0 +dvix310 divideint 0.12 1.00 -> 0 +dvix311 divideint 0.12 2 -> 0 +dvix312 divideint 0.12 2.0 -> 0 +dvix313 divideint 0.12 2.1 -> 0 +dvix314 divideint 0.12 2.00 -> 0 +dvix315 divideint 0.12 2.01 -> 0 -- overflow and underflow tests [from divide] maxexponent: 999999999 Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/inexact.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/inexact.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/inexact.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- inexact.decTest -- decimal inexact and rounded edge cases -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/max.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/max.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/max.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- max.decTest -- decimal maximum -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- we assume that base comparison is tested in compare.decTest, so -- these mainly cover special cases and rounding @@ -331,6 +331,33 @@ maxx466 max -1000 -1E+3 -> -1000 maxx467 max -1E+3 -1000 -> -1000 +-- rounding (results treated as though plus) +maxexponent: 999999999 +minexponent: -999999999 +precision: 3 + +maxx470 max 1 .5 -> 1 +maxx471 max 10 5 -> 10 +maxx472 max 100 50 -> 100 +maxx473 max 1000 500 -> 1.00E+3 Rounded +maxx474 max 10000 5000 -> 1.00E+4 Rounded +maxx475 max 6 .5 -> 6 +maxx476 max 66 5 -> 66 +maxx477 max 666 50 -> 666 +maxx478 max 6666 500 -> 6.67E+3 Rounded Inexact +maxx479 max 66666 5000 -> 6.67E+4 Rounded Inexact +maxx480 max 33333 5000 -> 3.33E+4 Rounded Inexact +maxx481 max .5 1 -> 1 +maxx482 max .5 10 -> 10 +maxx483 max .5 100 -> 100 +maxx484 max .5 1000 -> 1.00E+3 Rounded +maxx485 max .5 10000 -> 1.00E+4 Rounded +maxx486 max .5 6 -> 6 +maxx487 max .5 66 -> 66 +maxx488 max .5 666 -> 666 +maxx489 max .5 6666 -> 6.67E+3 Rounded Inexact +maxx490 max .5 66666 -> 6.67E+4 Rounded Inexact +maxx491 max .5 33333 -> 3.33E+4 Rounded Inexact -- overflow tests maxexponent: 999999999 @@ -348,13 +375,13 @@ maxx512 max 0.10E-999 0 -> 1.0E-1000 Subnormal maxx513 max 0.100E-999 0 -> 1.0E-1000 Subnormal Rounded maxx514 max 0.01E-999 0 -> 1E-1001 Subnormal --- next is rounded to Emin +-- next is rounded to Nmin maxx515 max 0.999E-999 0 -> 1.00E-999 Inexact Rounded Subnormal Underflow maxx516 max 0.099E-999 0 -> 1.0E-1000 Inexact Rounded Subnormal Underflow maxx517 max 0.009E-999 0 -> 1E-1001 Inexact Rounded Subnormal Underflow -maxx518 max 0.001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow -maxx519 max 0.0009E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow -maxx520 max 0.0001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow +maxx518 max 0.001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +maxx519 max 0.0009E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +maxx520 max 0.0001E-999 0 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped maxx530 max -1.00E-999 0 -> 0 maxx531 max -0.1E-999 0 -> 0 @@ -368,6 +395,27 @@ maxx539 max -0.0009E-999 0 -> 0 maxx540 max -0.0001E-999 0 -> 0 +-- misalignment traps for little-endian +precision: 9 +maxx551 max 1.0 0.1 -> 1.0 +maxx552 max 0.1 1.0 -> 1.0 +maxx553 max 10.0 0.1 -> 10.0 +maxx554 max 0.1 10.0 -> 10.0 +maxx555 max 100 1.0 -> 100 +maxx556 max 1.0 100 -> 100 +maxx557 max 1000 10.0 -> 1000 +maxx558 max 10.0 1000 -> 1000 +maxx559 max 10000 100.0 -> 10000 +maxx560 max 100.0 10000 -> 10000 +maxx661 max 100000 1000.0 -> 100000 +maxx662 max 1000.0 100000 -> 100000 +maxx663 max 1000000 10000.0 -> 1000000 +maxx664 max 10000.0 1000000 -> 1000000 + +-- payload decapitate +precision: 5 +maxx670 max 11 -sNaN12345678901 -> -NaN78901 Invalid_operation + -- Null tests maxx900 max 10 # -> NaN Invalid_operation maxx901 max # 10 -> NaN Invalid_operation Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/min.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/min.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/min.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- min.decTest -- decimal minimum -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- we assume that base comparison is tested in compare.decTest, so -- these mainly cover special cases and rounding @@ -320,6 +320,34 @@ mnmx466 min -1000 -1E+3 -> -1E+3 mnmx467 min -1E+3 -1000 -> -1E+3 +-- rounding (results treated as though plus) +maxexponent: 999999999 +minexponent: -999999999 +precision: 3 + +mnmx470 min 1 5 -> 1 +mnmx471 min 10 50 -> 10 +mnmx472 min 100 500 -> 100 +mnmx473 min 1000 5000 -> 1.00E+3 Rounded +mnmx474 min 10000 50000 -> 1.00E+4 Rounded +mnmx475 min 6 50 -> 6 +mnmx476 min 66 500 -> 66 +mnmx477 min 666 5000 -> 666 +mnmx478 min 6666 50000 -> 6.67E+3 Rounded Inexact +mnmx479 min 66666 500000 -> 6.67E+4 Rounded Inexact +mnmx480 min 33333 500000 -> 3.33E+4 Rounded Inexact +mnmx481 min 75401 1 -> 1 +mnmx482 min 75402 10 -> 10 +mnmx483 min 75403 100 -> 100 +mnmx484 min 75404 1000 -> 1.00E+3 Rounded +mnmx485 min 75405 10000 -> 1.00E+4 Rounded +mnmx486 min 75406 6 -> 6 +mnmx487 min 75407 66 -> 66 +mnmx488 min 75408 666 -> 666 +mnmx489 min 75409 6666 -> 6.67E+3 Rounded Inexact +mnmx490 min 75410 66666 -> 6.67E+4 Rounded Inexact +mnmx491 min 75411 33333 -> 3.33E+4 Rounded Inexact + -- overflow tests maxexponent: 999999999 @@ -349,14 +377,30 @@ mnmx532 min -0.10E-999 0 -> -1.0E-1000 Subnormal mnmx533 min -0.100E-999 0 -> -1.0E-1000 Subnormal Rounded mnmx534 min -0.01E-999 0 -> -1E-1001 Subnormal --- next is rounded to Emin +-- next is rounded to Nmin mnmx535 min -0.999E-999 0 -> -1.00E-999 Inexact Rounded Subnormal Underflow mnmx536 min -0.099E-999 0 -> -1.0E-1000 Inexact Rounded Subnormal Underflow mnmx537 min -0.009E-999 0 -> -1E-1001 Inexact Rounded Subnormal Underflow -mnmx538 min -0.001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow -mnmx539 min -0.0009E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow -mnmx540 min -0.0001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow +mnmx538 min -0.001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +mnmx539 min -0.0009E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +mnmx540 min -0.0001E-999 0 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +-- misalignment traps for little-endian +precision: 9 +mnmx551 min 1.0 0.1 -> 0.1 +mnmx552 min 0.1 1.0 -> 0.1 +mnmx553 min 10.0 0.1 -> 0.1 +mnmx554 min 0.1 10.0 -> 0.1 +mnmx555 min 100 1.0 -> 1.0 +mnmx556 min 1.0 100 -> 1.0 +mnmx557 min 1000 10.0 -> 10.0 +mnmx558 min 10.0 1000 -> 10.0 +mnmx559 min 10000 100.0 -> 100.0 +mnmx560 min 100.0 10000 -> 100.0 +mnmx561 min 100000 1000.0 -> 1000.0 +mnmx562 min 1000.0 100000 -> 1000.0 +mnmx563 min 1000000 10000.0 -> 10000.0 +mnmx564 min 10000.0 1000000 -> 10000.0 -- Null tests mnm900 min 10 # -> NaN Invalid_operation Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/minus.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/minus.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/minus.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- minus.decTest -- decimal negation -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- This set of tests primarily tests the existence of the operator. -- Subtraction, rounding, and more overflows are tested elsewhere. @@ -127,9 +127,9 @@ minx115 minus 0.999E-999 -> -1.00E-999 Inexact Rounded Subnormal Underflow minx116 minus 0.099E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow minx117 minus 0.009E-999 -> -1E-1001 Inexact Rounded Subnormal Underflow -minx118 minus 0.001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow -minx119 minus 0.0009E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow -minx120 minus 0.0001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow +minx118 minus 0.001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +minx119 minus 0.0009E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +minx120 minus 0.0001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped minx130 minus -1.00E-999 -> 1.00E-999 minx131 minus -0.1E-999 -> 1E-1000 Subnormal @@ -140,9 +140,9 @@ minx135 minus -0.999E-999 -> 1.00E-999 Inexact Rounded Subnormal Underflow minx136 minus -0.099E-999 -> 1.0E-1000 Inexact Rounded Subnormal Underflow minx137 minus -0.009E-999 -> 1E-1001 Inexact Rounded Subnormal Underflow -minx138 minus -0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -minx139 minus -0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -minx140 minus -0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow +minx138 minus -0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +minx139 minus -0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +minx140 minus -0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped -- long operand checks Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/multiply.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/multiply.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/multiply.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- multiply.decTest -- decimal multiplication -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -44,21 +44,28 @@ mulx015 multiply 2.50 4 -> 10.00 precision: 6 mulx016 multiply 2.50 4 -> 10.00 -mulx017 multiply 9.999999999 9.999999999 -> 100.000 Inexact Rounded +mulx017 multiply 9.999999999 9.999999999 -> 100.000 Inexact Rounded +mulx018 multiply 9.999999999 -9.999999999 -> -100.000 Inexact Rounded +mulx019 multiply -9.999999999 9.999999999 -> -100.000 Inexact Rounded +mulx020 multiply -9.999999999 -9.999999999 -> 100.000 Inexact Rounded -- 1999.12.21: next one is a edge case if intermediate longs are used precision: 15 -mulx019 multiply 999999999999 9765625 -> 9.76562499999023E+18 Inexact Rounded +mulx059 multiply 999999999999 9765625 -> 9.76562499999023E+18 Inexact Rounded precision: 30 mulx160 multiply 999999999999 9765625 -> 9765624999990234375 precision: 9 ----- -- zeros, etc. -mulx020 multiply 0 0 -> 0 -mulx021 multiply 0 -0 -> -0 -mulx022 multiply -0 0 -> -0 -mulx023 multiply -0 -0 -> 0 +mulx021 multiply 0 0 -> 0 +mulx022 multiply 0 -0 -> -0 +mulx023 multiply -0 0 -> -0 +mulx024 multiply -0 -0 -> 0 +mulx025 multiply -0.0 -0.0 -> 0.00 +mulx026 multiply -0.0 -0.0 -> 0.00 +mulx027 multiply -0.0 -0.0 -> 0.00 +mulx028 multiply -0.0 -0.0 -> 0.00 mulx030 multiply 5.00 1E-3 -> 0.00500 mulx031 multiply 00.00 0.000 -> 0.00000 mulx032 multiply 00.00 0E-3 -> 0.00000 -- rhs is 0 @@ -94,17 +101,17 @@ -- test some intermediate lengths precision: 9 -mulx080 multiply 0.1 123456789 -> 12345678.9 -mulx081 multiply 0.1 1234567891 -> 123456789 Inexact Rounded -mulx082 multiply 0.1 12345678912 -> 1.23456789E+9 Inexact Rounded -mulx083 multiply 0.1 12345678912345 -> 1.23456789E+12 Inexact Rounded -mulx084 multiply 0.1 123456789 -> 12345678.9 +mulx080 multiply 0.1 123456789 -> 12345678.9 +mulx081 multiply 0.1 1234567891 -> 123456789 Inexact Rounded +mulx082 multiply 0.1 12345678912 -> 1.23456789E+9 Inexact Rounded +mulx083 multiply 0.1 12345678912345 -> 1.23456789E+12 Inexact Rounded +mulx084 multiply 0.1 123456789 -> 12345678.9 precision: 8 -mulx085 multiply 0.1 12345678912 -> 1.2345679E+9 Inexact Rounded -mulx086 multiply 0.1 12345678912345 -> 1.2345679E+12 Inexact Rounded +mulx085 multiply 0.1 12345678912 -> 1.2345679E+9 Inexact Rounded +mulx086 multiply 0.1 12345678912345 -> 1.2345679E+12 Inexact Rounded precision: 7 -mulx087 multiply 0.1 12345678912 -> 1.234568E+9 Inexact Rounded -mulx088 multiply 0.1 12345678912345 -> 1.234568E+12 Inexact Rounded +mulx087 multiply 0.1 12345678912 -> 1.234568E+9 Inexact Rounded +mulx088 multiply 0.1 12345678912345 -> 1.234568E+12 Inexact Rounded precision: 9 mulx090 multiply 123456789 0.1 -> 12345678.9 @@ -280,6 +287,41 @@ precision: 1 mulx278 multiply 30269.587755640502150977251770554 4.8046009735990873395936309640543 -> 1E+5 Inexact Rounded +-- test some edge cases with exact rounding +maxexponent: 9999 +minexponent: -9999 +precision: 9 +mulx301 multiply 9 9 -> 81 +mulx302 multiply 9 90 -> 810 +mulx303 multiply 9 900 -> 8100 +mulx304 multiply 9 9000 -> 81000 +mulx305 multiply 9 90000 -> 810000 +mulx306 multiply 9 900000 -> 8100000 +mulx307 multiply 9 9000000 -> 81000000 +mulx308 multiply 9 90000000 -> 810000000 +mulx309 multiply 9 900000000 -> 8.10000000E+9 Rounded +mulx310 multiply 9 9000000000 -> 8.10000000E+10 Rounded +mulx311 multiply 9 90000000000 -> 8.10000000E+11 Rounded +mulx312 multiply 9 900000000000 -> 8.10000000E+12 Rounded +mulx313 multiply 9 9000000000000 -> 8.10000000E+13 Rounded +mulx314 multiply 9 90000000000000 -> 8.10000000E+14 Rounded +mulx315 multiply 9 900000000000000 -> 8.10000000E+15 Rounded +mulx316 multiply 9 9000000000000000 -> 8.10000000E+16 Rounded +mulx317 multiply 9 90000000000000000 -> 8.10000000E+17 Rounded +mulx318 multiply 9 900000000000000000 -> 8.10000000E+18 Rounded +mulx319 multiply 9 9000000000000000000 -> 8.10000000E+19 Rounded +mulx320 multiply 9 90000000000000000000 -> 8.10000000E+20 Rounded +mulx321 multiply 9 900000000000000000000 -> 8.10000000E+21 Rounded +mulx322 multiply 9 9000000000000000000000 -> 8.10000000E+22 Rounded +mulx323 multiply 9 90000000000000000000000 -> 8.10000000E+23 Rounded + +-- fastpath breakers +precision: 29 +mulx330 multiply 1.491824697641270317824852952837224 1.105170918075647624811707826490246514675628614562883537345747603 -> 1.6487212707001281468486507878 Inexact Rounded +precision: 55 +mulx331 multiply 0.8958341352965282506768545828765117803873717284891040428 0.8958341352965282506768545828765117803873717284891040428 -> 0.8025187979624784829842553829934069955890983696752228299 Inexact Rounded + + -- tryzeros cases precision: 7 rounding: half_up @@ -486,10 +528,10 @@ mulx752 multiply 1e+777777777 -1e+411111111 -> -Infinity Overflow Inexact Rounded mulx753 multiply -1e+777777777 1e+411111111 -> -Infinity Overflow Inexact Rounded mulx754 multiply -1e+777777777 -1e+411111111 -> Infinity Overflow Inexact Rounded -mulx755 multiply 1e-777777777 1e-411111111 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -mulx756 multiply 1e-777777777 -1e-411111111 -> -0E-1000000007 Underflow Subnormal Inexact Rounded -mulx757 multiply -1e-777777777 1e-411111111 -> -0E-1000000007 Underflow Subnormal Inexact Rounded -mulx758 multiply -1e-777777777 -1e-411111111 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +mulx755 multiply 1e-777777777 1e-411111111 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +mulx756 multiply 1e-777777777 -1e-411111111 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +mulx757 multiply -1e-777777777 1e-411111111 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +mulx758 multiply -1e-777777777 -1e-411111111 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -- 'subnormal' boundary (all hard underflow or overflow in base arithemtic) precision: 9 @@ -500,9 +542,9 @@ mulx764 multiply 1e-600000000 1e-400000005 -> 1E-1000000005 Subnormal mulx765 multiply 1e-600000000 1e-400000006 -> 1E-1000000006 Subnormal mulx766 multiply 1e-600000000 1e-400000007 -> 1E-1000000007 Subnormal -mulx767 multiply 1e-600000000 1e-400000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -mulx768 multiply 1e-600000000 1e-400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -mulx769 multiply 1e-600000000 1e-400000010 -> 0E-1000000007 Underflow Subnormal Inexact Rounded +mulx767 multiply 1e-600000000 1e-400000008 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +mulx768 multiply 1e-600000000 1e-400000009 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +mulx769 multiply 1e-600000000 1e-400000010 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -- [no equivalent of 'subnormal' for overflow] mulx770 multiply 1e+600000000 1e+400000001 -> Infinity Overflow Inexact Rounded mulx771 multiply 1e+600000000 1e+400000002 -> Infinity Overflow Inexact Rounded @@ -520,31 +562,31 @@ mulx780 multiply 1e-600000000 1e-400000007 -> 1E-1000000007 Subnormal mulx781 multiply 1e-600000000 1e-400000008 -> 1E-1000000008 Subnormal mulx782 multiply 1e-600000000 1e-400000097 -> 1E-1000000097 Subnormal -mulx783 multiply 1e-600000000 1e-400000098 -> 0E-1000000097 Underflow Subnormal Inexact Rounded +mulx783 multiply 1e-600000000 1e-400000098 -> 0E-1000000097 Underflow Subnormal Inexact Rounded Clamped precision: 999 mulx784 multiply 1e-600000000 1e-400000997 -> 1E-1000000997 Subnormal -mulx785 multiply 1e-600000000 1e-400000998 -> 0E-1000000997 Underflow Subnormal Inexact Rounded +mulx785 multiply 1e-600000000 1e-400000998 -> 0E-1000000997 Underflow Subnormal Inexact Rounded Clamped -- following testcases [through mulx800] not yet run against code precision: 9999 mulx786 multiply 1e-600000000 1e-400009997 -> 1E-1000009997 Subnormal -mulx787 multiply 1e-600000000 1e-400009998 -> 0E-1000009997 Underflow Subnormal Inexact Rounded +mulx787 multiply 1e-600000000 1e-400009998 -> 0E-1000009997 Underflow Subnormal Inexact Rounded Clamped precision: 99999 mulx788 multiply 1e-600000000 1e-400099997 -> 1E-1000099997 Subnormal -mulx789 multiply 1e-600000000 1e-400099998 -> 0E-1000099997 Underflow Subnormal Inexact Rounded +mulx789 multiply 1e-600000000 1e-400099998 -> 0E-1000099997 Underflow Subnormal Inexact Rounded Clamped precision: 999999 mulx790 multiply 1e-600000000 1e-400999997 -> 1E-1000999997 Subnormal -mulx791 multiply 1e-600000000 1e-400999998 -> 0E-1000999997 Underflow Subnormal Inexact Rounded +mulx791 multiply 1e-600000000 1e-400999998 -> 0E-1000999997 Underflow Subnormal Inexact Rounded Clamped precision: 9999999 mulx792 multiply 1e-600000000 1e-409999997 -> 1E-1009999997 Subnormal -mulx793 multiply 1e-600000000 1e-409999998 -> 0E-1009999997 Underflow Subnormal Inexact Rounded +mulx793 multiply 1e-600000000 1e-409999998 -> 0E-1009999997 Underflow Subnormal Inexact Rounded Clamped precision: 99999999 mulx794 multiply 1e-600000000 1e-499999997 -> 1E-1099999997 Subnormal -mulx795 multiply 1e-600000000 1e-499999998 -> 0E-1099999997 Underflow Subnormal Inexact Rounded +mulx795 multiply 1e-600000000 1e-499999998 -> 0E-1099999997 Underflow Subnormal Inexact Rounded Clamped precision: 999999999 mulx796 multiply 1e-999999999 1e-999999997 -> 1E-1999999996 Subnormal mulx797 multiply 1e-999999999 1e-999999998 -> 1E-1999999997 Subnormal -mulx798 multiply 1e-999999999 1e-999999999 -> 0E-1999999997 Underflow Subnormal Inexact Rounded +mulx798 multiply 1e-999999999 1e-999999999 -> 0E-1999999997 Underflow Subnormal Inexact Rounded Clamped mulx799 multiply 1e-600000000 1e-400000007 -> 1E-1000000007 Subnormal mulx800 multiply 1e-600000000 1e-400000008 -> 1E-1000000008 Subnormal @@ -573,19 +615,19 @@ mulx817 multiply 2.51E-999 1e-4 -> 3E-1003 Underflow Subnormal Inexact Rounded mulx818 multiply 1E-999 1e-4 -> 1E-1003 Subnormal -mulx819 multiply 3E-999 1e-5 -> 0E-1003 Underflow Subnormal Inexact Rounded -mulx820 multiply 5E-999 1e-5 -> 0E-1003 Underflow Subnormal Inexact Rounded +mulx819 multiply 3E-999 1e-5 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped +mulx820 multiply 5E-999 1e-5 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped mulx821 multiply 7E-999 1e-5 -> 1E-1003 Underflow Subnormal Inexact Rounded mulx822 multiply 9E-999 1e-5 -> 1E-1003 Underflow Subnormal Inexact Rounded mulx823 multiply 9.9E-999 1e-5 -> 1E-1003 Underflow Subnormal Inexact Rounded mulx824 multiply 1E-999 -1e-4 -> -1E-1003 Subnormal -mulx825 multiply 3E-999 -1e-5 -> -0E-1003 Underflow Subnormal Inexact Rounded -mulx826 multiply -5E-999 1e-5 -> -0E-1003 Underflow Subnormal Inexact Rounded +mulx825 multiply 3E-999 -1e-5 -> -0E-1003 Underflow Subnormal Inexact Rounded Clamped +mulx826 multiply -5E-999 1e-5 -> -0E-1003 Underflow Subnormal Inexact Rounded Clamped mulx827 multiply 7E-999 -1e-5 -> -1E-1003 Underflow Subnormal Inexact Rounded mulx828 multiply -9E-999 1e-5 -> -1E-1003 Underflow Subnormal Inexact Rounded mulx829 multiply 9.9E-999 -1e-5 -> -1E-1003 Underflow Subnormal Inexact Rounded -mulx830 multiply 3.0E-999 -1e-5 -> -0E-1003 Underflow Subnormal Inexact Rounded +mulx830 multiply 3.0E-999 -1e-5 -> -0E-1003 Underflow Subnormal Inexact Rounded Clamped mulx831 multiply 1.0E-501 1e-501 -> 1.0E-1002 Subnormal mulx832 multiply 2.0E-501 2e-501 -> 4.0E-1002 Subnormal @@ -595,7 +637,7 @@ mulx836 multiply 40.0E-501 40e-501 -> 1.6000E-999 -- squares -mulx840 multiply 1E-502 1e-502 -> 0E-1003 Underflow Subnormal Inexact Rounded +mulx840 multiply 1E-502 1e-502 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped mulx841 multiply 1E-501 1e-501 -> 1E-1002 Subnormal mulx842 multiply 2E-501 2e-501 -> 4E-1002 Subnormal mulx843 multiply 4E-501 4e-501 -> 1.6E-1001 Subnormal @@ -604,7 +646,7 @@ mulx846 multiply 40E-501 40e-501 -> 1.600E-999 -- cubes -mulx850 multiply 1E-670 1e-335 -> 0E-1003 Underflow Subnormal Inexact Rounded +mulx850 multiply 1E-670 1e-335 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped mulx851 multiply 1E-668 1e-334 -> 1E-1002 Subnormal mulx852 multiply 4E-668 2e-334 -> 8E-1002 Subnormal mulx853 multiply 9E-668 3e-334 -> 2.7E-1001 Subnormal @@ -612,7 +654,7 @@ mulx855 multiply 25E-668 5e-334 -> 1.25E-1000 Subnormal mulx856 multiply 10E-668 100e-334 -> 1.000E-999 --- test from 0.099 ** 999 at 15 digits +-- test derived from result of 0.099 ** 999 at 15 digits with unlimited exponent precision: 19 mulx860 multiply 6636851557994578716E-520 6636851557994578716E-520 -> 4.40477986028551E-1003 Underflow Subnormal Inexact Rounded @@ -629,14 +671,16 @@ precision: 5 maxexponent: 79 minexponent: -79 -mulx881 multiply 1.2347E-40 1.2347E-40 -> 1.524E-80 Inexact Rounded Subnormal Underflow -mulx882 multiply 1.234E-40 1.234E-40 -> 1.523E-80 Inexact Rounded Subnormal Underflow -mulx883 multiply 1.23E-40 1.23E-40 -> 1.513E-80 Inexact Rounded Subnormal Underflow -mulx884 multiply 1.2E-40 1.2E-40 -> 1.44E-80 Subnormal -mulx885 multiply 1.2E-40 1.2E-41 -> 1.44E-81 Subnormal -mulx886 multiply 1.2E-40 1.2E-42 -> 1.4E-82 Subnormal Inexact Rounded Underflow -mulx887 multiply 1.2E-40 1.3E-42 -> 1.6E-82 Subnormal Inexact Rounded Underflow -mulx888 multiply 1.3E-40 1.3E-42 -> 1.7E-82 Subnormal Inexact Rounded Underflow +mulx881 multiply 1.2347E-40 1.2347E-40 -> 1.524E-80 Inexact Rounded Subnormal Underflow +mulx882 multiply 1.234E-40 1.234E-40 -> 1.523E-80 Inexact Rounded Subnormal Underflow +mulx883 multiply 1.23E-40 1.23E-40 -> 1.513E-80 Inexact Rounded Subnormal Underflow +mulx884 multiply 1.2E-40 1.2E-40 -> 1.44E-80 Subnormal +mulx885 multiply 1.2E-40 1.2E-41 -> 1.44E-81 Subnormal +mulx886 multiply 1.2E-40 1.2E-42 -> 1.4E-82 Subnormal Inexact Rounded Underflow +mulx887 multiply 1.2E-40 1.3E-42 -> 1.6E-82 Subnormal Inexact Rounded Underflow +mulx888 multiply 1.3E-40 1.3E-42 -> 1.7E-82 Subnormal Inexact Rounded Underflow +mulx889 multiply 1.3E-40 1.3E-43 -> 2E-83 Subnormal Inexact Rounded Underflow +mulx890 multiply 1.3E-41 1.3E-43 -> 0E-83 Clamped Subnormal Inexact Rounded Underflow mulx891 multiply 1.2345E-39 1.234E-40 -> 1.5234E-79 Inexact Rounded mulx892 multiply 1.23456E-39 1.234E-40 -> 1.5234E-79 Inexact Rounded @@ -645,7 +689,43 @@ mulx895 multiply 1.2345E-41 1.234E-40 -> 1.52E-81 Inexact Rounded Subnormal Underflow mulx896 multiply 1.23456E-41 1.234E-40 -> 1.52E-81 Inexact Rounded Subnormal Underflow +-- Now explore the case where we get a normal result with Underflow +precision: 16 +rounding: half_up +maxExponent: 384 +minExponent: -383 + +mulx900 multiply 0.3000000000E-191 0.3000000000E-191 -> 9.00000000000000E-384 Subnormal Rounded +mulx901 multiply 0.3000000001E-191 0.3000000001E-191 -> 9.00000000600000E-384 Underflow Inexact Subnormal Rounded +mulx902 multiply 9.999999999999999E-383 0.0999999999999 -> 9.99999999999000E-384 Underflow Inexact Subnormal Rounded +mulx903 multiply 9.999999999999999E-383 0.09999999999999 -> 9.99999999999900E-384 Underflow Inexact Subnormal Rounded +mulx904 multiply 9.999999999999999E-383 0.099999999999999 -> 9.99999999999990E-384 Underflow Inexact Subnormal Rounded +mulx905 multiply 9.999999999999999E-383 0.0999999999999999 -> 9.99999999999999E-384 Underflow Inexact Subnormal Rounded +-- prove operands are exact +mulx906 multiply 9.999999999999999E-383 1 -> 9.999999999999999E-383 +mulx907 multiply 1 0.09999999999999999 -> 0.09999999999999999 +-- the next rounds to Nmin +mulx908 multiply 9.999999999999999E-383 0.09999999999999999 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +mulx909 multiply 9.999999999999999E-383 0.099999999999999999 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +mulx910 multiply 9.999999999999999E-383 0.0999999999999999999 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded +mulx911 multiply 9.999999999999999E-383 0.09999999999999999999 -> 1.000000000000000E-383 Underflow Inexact Subnormal Rounded + + +-- Examples from SQL proposal (Krishna Kulkarni) +precision: 34 +rounding: half_up +maxExponent: 6144 +minExponent: -6143 +mulx1001 multiply 130E-2 120E-2 -> 1.5600 +mulx1002 multiply 130E-2 12E-1 -> 1.560 +mulx1003 multiply 130E-2 1E0 -> 1.30 +mulx1004 multiply 1E2 1E4 -> 1E+6 + +-- payload decapitate +precision: 5 +mulx1010 multiply 11 -sNaN1234567890 -> -NaN67890 Invalid_operation + -- Null tests -mulx900 multiply 10 # -> NaN Invalid_operation -mulx901 multiply # 10 -> NaN Invalid_operation +mulx990 multiply 10 # -> NaN Invalid_operation +mulx991 multiply # 10 -> NaN Invalid_operation Deleted: /python/branches/py3k-importlib/Lib/test/decimaltestdata/normalize.decTest ============================================================================== --- /python/branches/py3k-importlib/Lib/test/decimaltestdata/normalize.decTest Fri Sep 21 03:17:09 2007 +++ (empty file) @@ -1,225 +0,0 @@ ------------------------------------------------------------------------- --- normalize.decTest -- remove trailing zeros -- --- Copyright (c) IBM Corporation, 2003. All rights reserved. -- ------------------------------------------------------------------------- --- Please see the document "General Decimal Arithmetic Testcases" -- --- at http://www2.hursley.ibm.com/decimal for the description of -- --- these testcases. -- --- -- --- These testcases are experimental ('beta' versions), and they -- --- may contain errors. They are offered on an as-is basis. In -- --- particular, achieving the same results as the tests here is not -- --- a guarantee that an implementation complies with any Standard -- --- or specification. The tests are not exhaustive. -- --- -- --- Please send comments, suggestions, and corrections to the author: -- --- Mike Cowlishaw, IBM Fellow -- --- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- --- mfc at uk.ibm.com -- ------------------------------------------------------------------------- -version: 2.39 - -extended: 1 -precision: 9 -rounding: half_up -maxExponent: 999 -minexponent: -999 - -nrmx001 normalize '1' -> '1' -nrmx002 normalize '-1' -> '-1' -nrmx003 normalize '1.00' -> '1' -nrmx004 normalize '-1.00' -> '-1' -nrmx005 normalize '0' -> '0' -nrmx006 normalize '0.00' -> '0' -nrmx007 normalize '00.0' -> '0' -nrmx008 normalize '00.00' -> '0' -nrmx009 normalize '00' -> '0' -nrmx010 normalize '0E+1' -> '0' -nrmx011 normalize '0E+5' -> '0' - -nrmx012 normalize '-2' -> '-2' -nrmx013 normalize '2' -> '2' -nrmx014 normalize '-2.00' -> '-2' -nrmx015 normalize '2.00' -> '2' -nrmx016 normalize '-0' -> '-0' -nrmx017 normalize '-0.00' -> '-0' -nrmx018 normalize '-00.0' -> '-0' -nrmx019 normalize '-00.00' -> '-0' -nrmx020 normalize '-00' -> '-0' -nrmx021 normalize '-0E+5' -> '-0' -nrmx022 normalize '-0E+1' -> '-0' - -nrmx030 normalize '+0.1' -> '0.1' -nrmx031 normalize '-0.1' -> '-0.1' -nrmx032 normalize '+0.01' -> '0.01' -nrmx033 normalize '-0.01' -> '-0.01' -nrmx034 normalize '+0.001' -> '0.001' -nrmx035 normalize '-0.001' -> '-0.001' -nrmx036 normalize '+0.000001' -> '0.000001' -nrmx037 normalize '-0.000001' -> '-0.000001' -nrmx038 normalize '+0.000000000001' -> '1E-12' -nrmx039 normalize '-0.000000000001' -> '-1E-12' - -nrmx041 normalize 1.1 -> 1.1 -nrmx042 normalize 1.10 -> 1.1 -nrmx043 normalize 1.100 -> 1.1 -nrmx044 normalize 1.110 -> 1.11 -nrmx045 normalize -1.1 -> -1.1 -nrmx046 normalize -1.10 -> -1.1 -nrmx047 normalize -1.100 -> -1.1 -nrmx048 normalize -1.110 -> -1.11 -nrmx049 normalize 9.9 -> 9.9 -nrmx050 normalize 9.90 -> 9.9 -nrmx051 normalize 9.900 -> 9.9 -nrmx052 normalize 9.990 -> 9.99 -nrmx053 normalize -9.9 -> -9.9 -nrmx054 normalize -9.90 -> -9.9 -nrmx055 normalize -9.900 -> -9.9 -nrmx056 normalize -9.990 -> -9.99 - --- some trailing fractional zeros with zeros in units -nrmx060 normalize 10.0 -> 1E+1 -nrmx061 normalize 10.00 -> 1E+1 -nrmx062 normalize 100.0 -> 1E+2 -nrmx063 normalize 100.00 -> 1E+2 -nrmx064 normalize 1.1000E+3 -> 1.1E+3 -nrmx065 normalize 1.10000E+3 -> 1.1E+3 -nrmx066 normalize -10.0 -> -1E+1 -nrmx067 normalize -10.00 -> -1E+1 -nrmx068 normalize -100.0 -> -1E+2 -nrmx069 normalize -100.00 -> -1E+2 -nrmx070 normalize -1.1000E+3 -> -1.1E+3 -nrmx071 normalize -1.10000E+3 -> -1.1E+3 - --- some insignificant trailing zeros with positive exponent -nrmx080 normalize 10E+1 -> 1E+2 -nrmx081 normalize 100E+1 -> 1E+3 -nrmx082 normalize 1.0E+2 -> 1E+2 -nrmx083 normalize 1.0E+3 -> 1E+3 -nrmx084 normalize 1.1E+3 -> 1.1E+3 -nrmx085 normalize 1.00E+3 -> 1E+3 -nrmx086 normalize 1.10E+3 -> 1.1E+3 -nrmx087 normalize -10E+1 -> -1E+2 -nrmx088 normalize -100E+1 -> -1E+3 -nrmx089 normalize -1.0E+2 -> -1E+2 -nrmx090 normalize -1.0E+3 -> -1E+3 -nrmx091 normalize -1.1E+3 -> -1.1E+3 -nrmx092 normalize -1.00E+3 -> -1E+3 -nrmx093 normalize -1.10E+3 -> -1.1E+3 - --- some significant trailing zeros, were we to be trimming -nrmx100 normalize 11 -> 11 -nrmx101 normalize 10 -> 1E+1 -nrmx102 normalize 10. -> 1E+1 -nrmx103 normalize 1.1E+1 -> 11 -nrmx104 normalize 1.0E+1 -> 1E+1 -nrmx105 normalize 1.10E+2 -> 1.1E+2 -nrmx106 normalize 1.00E+2 -> 1E+2 -nrmx107 normalize 1.100E+3 -> 1.1E+3 -nrmx108 normalize 1.000E+3 -> 1E+3 -nrmx109 normalize 1.000000E+6 -> 1E+6 -nrmx110 normalize -11 -> -11 -nrmx111 normalize -10 -> -1E+1 -nrmx112 normalize -10. -> -1E+1 -nrmx113 normalize -1.1E+1 -> -11 -nrmx114 normalize -1.0E+1 -> -1E+1 -nrmx115 normalize -1.10E+2 -> -1.1E+2 -nrmx116 normalize -1.00E+2 -> -1E+2 -nrmx117 normalize -1.100E+3 -> -1.1E+3 -nrmx118 normalize -1.000E+3 -> -1E+3 -nrmx119 normalize -1.00000E+5 -> -1E+5 -nrmx120 normalize -1.000000E+6 -> -1E+6 -nrmx121 normalize -10.00000E+6 -> -1E+7 -nrmx122 normalize -100.0000E+6 -> -1E+8 -nrmx123 normalize -1000.000E+6 -> -1E+9 -nrmx124 normalize -10000.00E+6 -> -1E+10 -nrmx125 normalize -100000.0E+6 -> -1E+11 -nrmx126 normalize -1000000.E+6 -> -1E+12 - --- examples from decArith -nrmx140 normalize '2.1' -> '2.1' -nrmx141 normalize '-2.0' -> '-2' -nrmx142 normalize '1.200' -> '1.2' -nrmx143 normalize '-120' -> '-1.2E+2' -nrmx144 normalize '120.00' -> '1.2E+2' -nrmx145 normalize '0.00' -> '0' - --- overflow tests -maxexponent: 999999999 -minexponent: -999999999 -precision: 3 -nrmx160 normalize 9.999E+999999999 -> Infinity Inexact Overflow Rounded -nrmx161 normalize -9.999E+999999999 -> -Infinity Inexact Overflow Rounded - --- subnormals and underflow -precision: 3 -maxexponent: 999 -minexponent: -999 -nrmx210 normalize 1.00E-999 -> 1E-999 -nrmx211 normalize 0.1E-999 -> 1E-1000 Subnormal -nrmx212 normalize 0.10E-999 -> 1E-1000 Subnormal -nrmx213 normalize 0.100E-999 -> 1E-1000 Subnormal Rounded -nrmx214 normalize 0.01E-999 -> 1E-1001 Subnormal --- next is rounded to Emin -nrmx215 normalize 0.999E-999 -> 1E-999 Inexact Rounded Subnormal Underflow -nrmx216 normalize 0.099E-999 -> 1E-1000 Inexact Rounded Subnormal Underflow -nrmx217 normalize 0.009E-999 -> 1E-1001 Inexact Rounded Subnormal Underflow -nrmx218 normalize 0.001E-999 -> 0 Inexact Rounded Subnormal Underflow -nrmx219 normalize 0.0009E-999 -> 0 Inexact Rounded Subnormal Underflow -nrmx220 normalize 0.0001E-999 -> 0 Inexact Rounded Subnormal Underflow - -nrmx230 normalize -1.00E-999 -> -1E-999 -nrmx231 normalize -0.1E-999 -> -1E-1000 Subnormal -nrmx232 normalize -0.10E-999 -> -1E-1000 Subnormal -nrmx233 normalize -0.100E-999 -> -1E-1000 Subnormal Rounded -nrmx234 normalize -0.01E-999 -> -1E-1001 Subnormal --- next is rounded to Emin -nrmx235 normalize -0.999E-999 -> -1E-999 Inexact Rounded Subnormal Underflow -nrmx236 normalize -0.099E-999 -> -1E-1000 Inexact Rounded Subnormal Underflow -nrmx237 normalize -0.009E-999 -> -1E-1001 Inexact Rounded Subnormal Underflow -nrmx238 normalize -0.001E-999 -> -0 Inexact Rounded Subnormal Underflow -nrmx239 normalize -0.0009E-999 -> -0 Inexact Rounded Subnormal Underflow -nrmx240 normalize -0.0001E-999 -> -0 Inexact Rounded Subnormal Underflow - --- more reshaping -precision: 9 -nrmx260 normalize '56260E-10' -> '0.000005626' -nrmx261 normalize '56260E-5' -> '0.5626' -nrmx262 normalize '56260E-2' -> '562.6' -nrmx263 normalize '56260E-1' -> '5626' -nrmx265 normalize '56260E-0' -> '5.626E+4' -nrmx266 normalize '56260E+0' -> '5.626E+4' -nrmx267 normalize '56260E+1' -> '5.626E+5' -nrmx268 normalize '56260E+2' -> '5.626E+6' -nrmx269 normalize '56260E+3' -> '5.626E+7' -nrmx270 normalize '56260E+4' -> '5.626E+8' -nrmx271 normalize '56260E+5' -> '5.626E+9' -nrmx272 normalize '56260E+6' -> '5.626E+10' -nrmx280 normalize '-56260E-10' -> '-0.000005626' -nrmx281 normalize '-56260E-5' -> '-0.5626' -nrmx282 normalize '-56260E-2' -> '-562.6' -nrmx283 normalize '-56260E-1' -> '-5626' -nrmx285 normalize '-56260E-0' -> '-5.626E+4' -nrmx286 normalize '-56260E+0' -> '-5.626E+4' -nrmx287 normalize '-56260E+1' -> '-5.626E+5' -nrmx288 normalize '-56260E+2' -> '-5.626E+6' -nrmx289 normalize '-56260E+3' -> '-5.626E+7' -nrmx290 normalize '-56260E+4' -> '-5.626E+8' -nrmx291 normalize '-56260E+5' -> '-5.626E+9' -nrmx292 normalize '-56260E+6' -> '-5.626E+10' - - --- specials -nrmx820 normalize 'Inf' -> 'Infinity' -nrmx821 normalize '-Inf' -> '-Infinity' -nrmx822 normalize NaN -> NaN -nrmx823 normalize sNaN -> NaN Invalid_operation -nrmx824 normalize NaN101 -> NaN101 -nrmx825 normalize sNaN010 -> NaN10 Invalid_operation -nrmx827 normalize -NaN -> -NaN -nrmx828 normalize -sNaN -> -NaN Invalid_operation -nrmx829 normalize -NaN101 -> -NaN101 -nrmx830 normalize -sNaN010 -> -NaN10 Invalid_operation - --- Null test -nrmx900 normalize # -> NaN Invalid_operation Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/plus.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/plus.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/plus.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- plus.decTest -- decimal monadic addition -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- This set of tests primarily tests the existence of the operator. -- Addition and rounding, and most overflows, are tested elsewhere. @@ -138,9 +138,9 @@ plux215 plus 0.999E-999 -> 1.00E-999 Inexact Rounded Subnormal Underflow plux216 plus 0.099E-999 -> 1.0E-1000 Inexact Rounded Subnormal Underflow plux217 plus 0.009E-999 -> 1E-1001 Inexact Rounded Subnormal Underflow -plux218 plus 0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -plux219 plus 0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -plux220 plus 0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow +plux218 plus 0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +plux219 plus 0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +plux220 plus 0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped plux230 plus -1.00E-999 -> -1.00E-999 plux231 plus -0.1E-999 -> -1E-1000 Subnormal @@ -151,9 +151,23 @@ plux235 plus -0.999E-999 -> -1.00E-999 Inexact Rounded Subnormal Underflow plux236 plus -0.099E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow plux237 plus -0.009E-999 -> -1E-1001 Inexact Rounded Subnormal Underflow -plux238 plus -0.001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow -plux239 plus -0.0009E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow -plux240 plus -0.0001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow +plux238 plus -0.001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +plux239 plus -0.0009E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +plux240 plus -0.0001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped + +-- subnormals clamped to 0-Etiny +precision: 16 +maxExponent: 384 +minExponent: -383 +plux251 plus 7E-398 -> 7E-398 Subnormal +plux252 plus 0E-398 -> 0E-398 +plux253 plus 7E-399 -> 1E-398 Subnormal Underflow Inexact Rounded +plux254 plus 4E-399 -> 0E-398 Clamped Subnormal Underflow Inexact Rounded +plux255 plus 7E-400 -> 0E-398 Clamped Subnormal Underflow Inexact Rounded +plux256 plus 7E-401 -> 0E-398 Clamped Subnormal Underflow Inexact Rounded +plux257 plus 0E-399 -> 0E-398 Clamped +plux258 plus 0E-400 -> 0E-398 Clamped +plux259 plus 0E-401 -> 0E-398 Clamped -- long operand checks maxexponent: 999 Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/power.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/power.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/power.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ----------------------------------------------------------------------- --- power.decTest -- decimal exponentiation -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +------------------------------------------------------------------------ +-- power.decTest -- decimal exponentiation [power(x, y)] -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,17 +17,17 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 --- This set of testcases tests raising numbers to an integer power only. --- If arbitrary powers were supported, 1 ulp differences would be --- permitted. +-- In addition to the power operator testcases here, see also the file +-- powersqrt.decTest which includes all the tests from +-- squareroot.decTest implemented using power(x, 0.5) extended: 1 -precision: 9 -rounding: half_up -maxExponent: 999 -minexponent: -999 +precision: 16 +rounding: half_even +maxExponent: 384 +minExponent: -383 -- base checks. Note 0**0 is an error. powx001 power '0' '0' -> NaN Invalid_operation @@ -52,51 +52,54 @@ powx022 power '2' '12' -> '4096' powx023 power '2' '15' -> '32768' powx024 power '2' '16' -> '65536' -powx025 power '2' '31' -> '2.14748365E+9' Inexact Rounded +powx025 power '2' '31' -> '2147483648' +-- NB 0 not stripped in next +powx026 power '2' '32' -> '4294967296' + +precision: 9 +powx027 power '2' '31' -> '2.14748365E+9' Inexact Rounded -- NB 0 not stripped in next -powx026 power '2' '32' -> '4.29496730E+9' Inexact Rounded +powx028 power '2' '32' -> '4.29496730E+9' Inexact Rounded precision: 10 -powx027 power '2' '31' -> '2147483648' -powx028 power '2' '32' -> '4294967296' +powx029 power '2' '31' -> '2147483648' +powx030 power '2' '32' -> '4294967296' precision: 9 -powx030 power '3' '2' -> 9 -powx031 power '4' '2' -> 16 -powx032 power '5' '2' -> 25 -powx033 power '6' '2' -> 36 -powx034 power '7' '2' -> 49 -powx035 power '8' '2' -> 64 -powx036 power '9' '2' -> 81 -powx037 power '10' '2' -> 100 -powx038 power '11' '2' -> 121 -powx039 power '12' '2' -> 144 - -powx040 power '3' '3' -> 27 -powx041 power '4' '3' -> 64 -powx042 power '5' '3' -> 125 -powx043 power '6' '3' -> 216 -powx044 power '7' '3' -> 343 - -powx050 power '10' '0' -> 1 -powx051 power '10' '1' -> 10 -powx052 power '10' '2' -> 100 -powx053 power '10' '3' -> 1000 -powx054 power '10' '4' -> 10000 -powx055 power '10' '5' -> 100000 -powx056 power '10' '6' -> 1000000 -powx057 power '10' '7' -> 10000000 -powx058 power '10' '8' -> 100000000 -powx059 power '10' '9' -> 1.00000000E+9 Rounded -powx060 power '10' '22' -> 1.00000000E+22 Rounded -powx061 power '10' '77' -> 1.00000000E+77 Rounded -powx062 power '10' '99' -> 1.00000000E+99 Rounded - -maxexponent: 999999999 -minexponent: -999999999 -powx063 power '10' '999999999' -> '1.00000000E+999999999' Rounded -powx064 power '10' '999999998' -> '1.00000000E+999999998' Rounded -powx065 power '10' '999999997' -> '1.00000000E+999999997' Rounded -powx066 power '10' '333333333' -> '1.00000000E+333333333' Rounded +powx031 power '3' '2' -> 9 +powx032 power '4' '2' -> 16 +powx033 power '5' '2' -> 25 +powx034 power '6' '2' -> 36 +powx035 power '7' '2' -> 49 +powx036 power '8' '2' -> 64 +powx037 power '9' '2' -> 81 +powx038 power '10' '2' -> 100 +powx039 power '11' '2' -> 121 +powx040 power '12' '2' -> 144 + +powx041 power '3' '3' -> 27 +powx042 power '4' '3' -> 64 +powx043 power '5' '3' -> 125 +powx044 power '6' '3' -> 216 +powx045 power '7' '3' -> 343 +powx047 power '-3' '3' -> -27 +powx048 power '-4' '3' -> -64 +powx049 power '-5' '3' -> -125 +powx050 power '-6' '3' -> -216 +powx051 power '-7' '3' -> -343 + +powx052 power '10' '0' -> 1 +powx053 power '10' '1' -> 10 +powx054 power '10' '2' -> 100 +powx055 power '10' '3' -> 1000 +powx056 power '10' '4' -> 10000 +powx057 power '10' '5' -> 100000 +powx058 power '10' '6' -> 1000000 +powx059 power '10' '7' -> 10000000 +powx060 power '10' '8' -> 100000000 +powx061 power '10' '9' -> 1.00000000E+9 Rounded +powx062 power '10' '22' -> 1.00000000E+22 Rounded +powx063 power '10' '77' -> 1.00000000E+77 Rounded +powx064 power '10' '99' -> 1.00000000E+99 Rounded powx070 power '0.3' '0' -> '1' powx071 power '0.3' '1' -> '0.3' @@ -127,71 +130,52 @@ powx095 power 101 7 -> 1.07213535E+14 Inexact Rounded -- negative powers -powx101 power '2' '-1' -> 0.5 -powx102 power '2' '-2' -> 0.25 -powx103 power '2' '-4' -> 0.0625 -powx104 power '2' '-8' -> 0.00390625 -powx105 power '2' '-16' -> 0.0000152587891 Inexact Rounded -powx106 power '2' '-32' -> 2.32830644E-10 Inexact Rounded -powx108 power '2' '-64' -> 5.42101086E-20 Inexact Rounded -powx110 power '10' '-8' -> 1E-8 -powx111 power '10' '-7' -> 1E-7 -powx112 power '10' '-6' -> 0.000001 -powx113 power '10' '-5' -> 0.00001 -powx114 power '10' '-4' -> 0.0001 -powx115 power '10' '-3' -> 0.001 -powx116 power '10' '-2' -> 0.01 -powx117 power '10' '-1' -> 0.1 - -powx118 power '10' '-333333333' -> 1E-333333333 -powx119 power '10' '-999999998' -> 1E-999999998 -powx120 power '10' '-999999999' -> 1E-999999999 -powx121 power '10' '-77' -> '1E-77' -powx122 power '10' '-22' -> '1E-22' - -powx123 power '2' '-1' -> '0.5' -powx124 power '2' '-2' -> '0.25' -powx125 power '2' '-4' -> '0.0625' -powx126 power '0' '-1' -> Infinity Division_by_zero -powx127 power '0' '-2' -> Infinity Division_by_zero -powx128 power -0 '-1' -> -Infinity Division_by_zero -powx129 power -0 '-2' -> Infinity Division_by_zero - --- out-of-range edge cases -powx181 power '7' '999999998' -> 2.10892313E+845098038 Inexact Rounded -powx182 power '7' '999999999' -> 1.47624619E+845098039 Inexact Rounded -powx183 power '7' '1000000000' -> NaN Invalid_operation -powx184 power '7' '1000000001' -> NaN Invalid_operation -powx185 power '7' '10000000000' -> NaN Invalid_operation -powx186 power '7' '-1000000001' -> NaN Invalid_operation -powx187 power '7' '-1000000000' -> NaN Invalid_operation -powx189 power '7' '-999999999' -> 6.77393787E-845098040 Inexact Rounded -powx190 power '7' '-999999998' -> 4.74175651E-845098039 Inexact Rounded - --- some baddies [more below] -powx191 power '2' '2.000001' -> NaN Invalid_operation -powx192 power '2' '2.00000000' -> 4 -powx193 power '2' '2.000000001' -> NaN Invalid_operation -powx194 power '2' '2.0000000001' -> NaN Invalid_operation +powx099 power '1' '-1' -> 1 +powx100 power '3' '-1' -> 0.333333333 Inexact Rounded +powx101 power '2' '-1' -> 0.5 +powx102 power '2' '-2' -> 0.25 +powx103 power '2' '-4' -> 0.0625 +powx104 power '2' '-8' -> 0.00390625 +powx105 power '2' '-16' -> 0.0000152587891 Inexact Rounded +powx106 power '2' '-32' -> 2.32830644E-10 Inexact Rounded +powx108 power '2' '-64' -> 5.42101086E-20 Inexact Rounded +powx110 power '10' '-8' -> 1E-8 +powx111 power '10' '-7' -> 1E-7 +powx112 power '10' '-6' -> 0.000001 +powx113 power '10' '-5' -> 0.00001 +powx114 power '10' '-4' -> 0.0001 +powx115 power '10' '-3' -> 0.001 +powx116 power '10' '-2' -> 0.01 +powx117 power '10' '-1' -> 0.1 +powx121 power '10' '-77' -> '1E-77' +powx122 power '10' '-22' -> '1E-22' + +powx123 power '2' '-1' -> '0.5' +powx124 power '2' '-2' -> '0.25' +powx125 power '2' '-4' -> '0.0625' + +powx126 power '0' '-1' -> Infinity +powx127 power '0' '-2' -> Infinity +powx128 power -0 '-1' -> -Infinity +powx129 power -0 '-2' -> Infinity -- "0.5" tests from original Rexx diagnostics [loop unrolled] -powx200 power 0.5 0 -> 1 -powx201 power 0.5 1 -> 0.5 -powx202 power 0.5 2 -> 0.25 -powx203 power 0.5 3 -> 0.125 -powx204 power 0.5 4 -> 0.0625 -powx205 power 0.5 5 -> 0.03125 -powx206 power 0.5 6 -> 0.015625 -powx207 power 0.5 7 -> 0.0078125 -powx208 power 0.5 8 -> 0.00390625 -powx209 power 0.5 9 -> 0.001953125 -powx210 power 0.5 10 -> 0.0009765625 +powx200 power 0.5 0 -> 1 +powx201 power 0.5 1 -> 0.5 +powx202 power 0.5 2 -> 0.25 +powx203 power 0.5 3 -> 0.125 +powx204 power 0.5 4 -> 0.0625 +powx205 power 0.5 5 -> 0.03125 +powx206 power 0.5 6 -> 0.015625 +powx207 power 0.5 7 -> 0.0078125 +powx208 power 0.5 8 -> 0.00390625 +powx209 power 0.5 9 -> 0.001953125 +powx210 power 0.5 10 -> 0.0009765625 + +powx211 power 1 100000000 -> 1 +powx212 power 1 999999998 -> 1 +powx213 power 1 999999999 -> 1 --- A (rare) case where the last digit is not within 0.5 ULP -precision: 9 -powx215 power "-21971575.0E+31454441" "-7" -> "-4.04549503E-220181139" Inexact Rounded -precision: 20 -powx216 power "-21971575.0E+31454441" "-7" -> "-4.0454950249324891788E-220181139" Inexact Rounded -- The Vienna case. Checks both setup and 1/acc working precision -- Modified 1998.12.14 as RHS no longer rounded before use (must fit) @@ -201,185 +185,64 @@ -- Modified 2002.10.06 -- finally, no input rounding -- With input rounding, result would be 8.74E-2226 precision: 3 +maxexponent: 5000 +minexponent: -5000 powx219 power '123456789E+10' '-1.23000e+2' -> '5.54E-2226' Inexact Rounded --- whole number checks -precision: 9 -powx221 power 1 1234 -> 1 -precision: 4 -powx222 power 1 1234 -> 1 -precision: 3 -powx223 power 1 1234 -> 1 -powx224 power 1 12.34e+2 -> 1 -powx225 power 1 12.3 -> NaN Invalid_operation -powx226 power 1 12.0 -> 1 -powx227 power 1 1.01 -> NaN Invalid_operation -powx228 power 2 1.00 -> 2 -powx229 power 2 2.00 -> 4 -precision: 9 -powx230 power 1 1.0001 -> NaN Invalid_operation -powx231 power 1 1.0000001 -> NaN Invalid_operation -powx232 power 1 1.0000000001 -> NaN Invalid_operation -powx233 power 1 1.0000000000001 -> NaN Invalid_operation -precision: 5 -powx234 power 1 1.0001 -> NaN Invalid_operation -powx235 power 1 1.0000001 -> NaN Invalid_operation -powx236 power 1 1.0000000001 -> NaN Invalid_operation -powx237 power 1 1.0000000000001 -> NaN Invalid_operation -powx238 power 1 1.0000000000001 -> NaN Invalid_operation - -maxexponent: 999999999 -minexponent: -999999999 -powx239 power 1 5.67E-987654321 -> NaN Invalid_operation - -powx240 power 1 100000000 -> 1 -powx241 power 1 999999998 -> 1 -powx242 power 1 999999999 -> 1 -powx243 power 1 1000000000 -> NaN Invalid_operation -powx244 power 1 9999999999 -> NaN Invalid_operation - --- Checks for 'Too much precision needed' --- For x^12, digits+elength+1 = digits+3 -precision: 999999999 -powx249 add 1 1 -> 2 -- check basic operation at this precision -powx250 power 2 12 -> Infinity Overflow -precision: 999999998 -powx251 power 2 12 -> Infinity Overflow -precision: 999999997 -powx252 power 2 12 -> Infinity Overflow -precision: 999999996 -powx253 power 2 12 -> 4096 -precision: 999999995 -powx254 power 2 12 -> 4096 - -- zeros maxexponent: +96 minexponent: -95 precision: 7 -powx260 power 0E-34 3 -> 0E-101 Clamped -powx261 power 0E-33 3 -> 0E-99 -powx262 power 0E-32 3 -> 0E-96 -powx263 power 0E-30 3 -> 0E-90 -powx264 power 0E-10 3 -> 0E-30 -powx265 power 0E-1 3 -> 0.000 -powx266 power 0E+0 3 -> 0 -powx267 power 0 3 -> 0 -powx268 power 0E+1 3 -> 0E+3 -powx269 power 0E+10 3 -> 0E+30 -powx270 power 0E+30 3 -> 0E+90 -powx271 power 0E+32 3 -> 0E+96 -powx272 power 0E+33 3 -> 0E+96 Clamped - --- overflow and underflow tests -maxexponent: 999999999 -minexponent: -999999999 -precision: 9 -powx280 power 9 999999999 -> 3.05550054E+954242508 Inexact Rounded -powx281 power 10 999999999 -> 1.00000000E+999999999 Rounded -powx282 power 10.0001 999999999 -> Infinity Overflow Inexact Rounded -powx283 power 10.1 999999999 -> Infinity Overflow Inexact Rounded -powx284 power 11 999999999 -> Infinity Overflow Inexact Rounded -powx285 power 12 999999999 -> Infinity Overflow Inexact Rounded -powx286 power 999 999999999 -> Infinity Overflow Inexact Rounded -powx287 power 999999 999999999 -> Infinity Overflow Inexact Rounded -powx288 power 999999999 999999999 -> Infinity Overflow Inexact Rounded -powx289 power 9.9E999999999 999999999 -> Infinity Overflow Inexact Rounded - -powx290 power 0.5 999999999 -> 4.33559594E-301029996 Inexact Rounded -powx291 power 0.1 999999999 -> 1E-999999999 -- unrounded -powx292 power 0.09 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx293 power 0.05 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx294 power 0.01 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx295 power 0.0001 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx297 power 0.0000001 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx298 power 0.0000000001 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx299 power 1E-999999999 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped - -powx310 power -9 999999999 -> -3.05550054E+954242508 Inexact Rounded -powx311 power -10 999999999 -> -1.00000000E+999999999 Rounded -powx312 power -10.0001 999999999 -> -Infinity Overflow Inexact Rounded -powx313 power -10.1 999999999 -> -Infinity Overflow Inexact Rounded -powx314 power -11 999999999 -> -Infinity Overflow Inexact Rounded -powx315 power -12 999999999 -> -Infinity Overflow Inexact Rounded -powx316 power -999 999999999 -> -Infinity Overflow Inexact Rounded -powx317 power -999999 999999999 -> -Infinity Overflow Inexact Rounded -powx318 power -999999999 999999999 -> -Infinity Overflow Inexact Rounded -powx319 power -9.9E999999999 999999999 -> -Infinity Overflow Inexact Rounded - -powx320 power -0.5 999999999 -> -4.33559594E-301029996 Inexact Rounded -powx321 power -0.1 999999999 -> -1E-999999999 -powx322 power -0.09 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx323 power -0.05 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx324 power -0.01 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx325 power -0.0001 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx327 power -0.0000001 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx328 power -0.0000000001 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx329 power -1E-999999999 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx223 power 0E-30 3 -> 0 +powx224 power 0E-10 3 -> 0 +powx225 power 0E-1 3 -> 0 +powx226 power 0E+0 3 -> 0 +powx227 power 0 3 -> 0 +powx228 power 0E+1 3 -> 0 +powx229 power 0E+10 3 -> 0 +powx230 power 0E+30 3 -> 0 +powx231 power 3 0E-30 -> 1 +powx232 power 3 0E-10 -> 1 +powx233 power 3 0E-1 -> 1 +powx234 power 3 0E+0 -> 1 +powx235 power 3 0 -> 1 +powx236 power 3 0E+1 -> 1 +powx237 power 3 0E+10 -> 1 +powx238 power 3 0E+30 -> 1 +powx239 power 0E-30 -3 -> Infinity +powx240 power 0E-10 -3 -> Infinity +powx241 power 0E-1 -3 -> Infinity +powx242 power 0E+0 -3 -> Infinity +powx243 power 0 -3 -> Infinity +powx244 power 0E+1 -3 -> Infinity +powx245 power 0E+10 -3 -> Infinity +powx246 power 0E+30 -3 -> Infinity +powx247 power -3 0E-30 -> 1 +powx248 power -3 0E-10 -> 1 +powx249 power -3 0E-1 -> 1 +powx250 power -3 0E+0 -> 1 +powx251 power -3 0 -> 1 +powx252 power -3 0E+1 -> 1 +powx253 power -3 0E+10 -> 1 +powx254 power -3 0E+30 -> 1 --- note no trim of next result -powx330 power -9 999999998 -> 3.39500060E+954242507 Inexact Rounded -powx331 power -10 999999998 -> 1.00000000E+999999998 Rounded -powx332 power -10.0001 999999998 -> Infinity Overflow Inexact Rounded -powx333 power -10.1 999999998 -> Infinity Overflow Inexact Rounded -powx334 power -11 999999998 -> Infinity Overflow Inexact Rounded -powx335 power -12 999999998 -> Infinity Overflow Inexact Rounded -powx336 power -999 999999998 -> Infinity Overflow Inexact Rounded -powx337 power -999999 999999998 -> Infinity Overflow Inexact Rounded -powx338 power -999999999 999999998 -> Infinity Overflow Inexact Rounded -powx339 power -9.9E999999999 999999998 -> Infinity Overflow Inexact Rounded - -powx340 power -0.5 999999998 -> 8.67119187E-301029996 Inexact Rounded -powx341 power -0.1 999999998 -> 1E-999999998 -- NB exact unrounded -powx342 power -0.09 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx343 power -0.05 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx344 power -0.01 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx345 power -0.0001 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx347 power -0.0000001 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx348 power -0.0000000001 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx349 power -1E-999999999 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped - --- some subnormals +-- a few lhs negatives precision: 9 --- [precision is 9, so smallest exponent is -1000000007 -powx350 power 1e-1 500000000 -> 1E-500000000 -powx351 power 1e-2 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped -powx352 power 1e-2 500000000 -> 1E-1000000000 Subnormal -powx353 power 1e-2 500000001 -> 1E-1000000002 Subnormal -powx354 power 1e-2 500000002 -> 1E-1000000004 Subnormal -powx355 power 1e-2 500000003 -> 1E-1000000006 Subnormal -powx356 power 1e-2 500000004 -> 0E-1000000007 Underflow Subnormal Inexact Rounded - -powx360 power 0.010001 500000000 -> 4.34941988E-999978287 Inexact Rounded -powx361 power 0.010000001 500000000 -> 5.18469257E-999999979 Inexact Rounded -powx362 power 0.010000001 500000001 -> 5.18469309E-999999981 Inexact Rounded -powx363 power 0.0100000009 500000000 -> 3.49342003E-999999981 Inexact Rounded -powx364 power 0.0100000001 500000000 -> 1.48413155E-999999998 Inexact Rounded -powx365 power 0.01 500000000 -> 1E-1000000000 Subnormal -powx366 power 0.0099999999 500000000 -> 6.7379E-1000000003 Underflow Subnormal Inexact Rounded -powx367 power 0.0099999998 500000000 -> 4.54E-1000000005 Underflow Subnormal Inexact Rounded -powx368 power 0.0099999997 500000000 -> 3E-1000000007 Underflow Subnormal Inexact Rounded -powx369 power 0.0099999996 500000000 -> 0E-1000000007 Underflow Subnormal Inexact Rounded -powx370 power 0.009 500000000 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped - --- 1/subnormal -> overflow -powx371 power 1e-1 -500000000 -> 1E+500000000 -powx372 power 1e-2 -999999999 -> Infinity Overflow Inexact Rounded -powx373 power 1e-2 -500000000 -> Infinity Overflow Inexact Rounded -powx374 power 1e-2 -500000001 -> Infinity Overflow Inexact Rounded -powx375 power 1e-2 -500000002 -> Infinity Overflow Inexact Rounded -powx376 power 1e-2 -500000003 -> Infinity Overflow Inexact Rounded -powx377 power 1e-2 -500000004 -> Infinity Overflow Inexact Rounded - -powx381 power 0.010001 -500000000 -> 2.29915719E+999978286 Inexact Rounded -powx382 power 0.010000001 -500000000 -> 1.92875467E+999999978 Inexact Rounded -powx383 power 0.010000001 -500000001 -> 1.92875448E+999999980 Inexact Rounded -powx384 power 0.0100000009 -500000000 -> 2.86252438E+999999980 Inexact Rounded -powx385 power 0.0100000001 -500000000 -> 6.73794717E+999999997 Inexact Rounded -powx386 power 0.01 -500000000 -> Infinity Overflow Inexact Rounded -powx387 power 0.009999 -500000000 -> Infinity Overflow Inexact Rounded - --- negative power giving subnormal -powx388 power 100.000001 -500000000 -> 6.7379E-1000000003 Underflow Subnormal Inexact Rounded +maxExponent: 999 +minexponent: -999 +powx260 power -10 '0' -> 1 +powx261 power -10 '1' -> -10 +powx262 power -10 '2' -> 100 +powx263 power -10 '3' -> -1000 +powx264 power -10 '4' -> 10000 +powx265 power -10 '5' -> -100000 +powx266 power -10 '6' -> 1000000 +powx267 power -10 '7' -> -10000000 +powx268 power -10 '8' -> 100000000 +powx269 power -10 '9' -> -1.00000000E+9 Rounded +powx270 power -10 '22' -> 1.00000000E+22 Rounded +powx271 power -10 '77' -> -1.00000000E+77 Rounded +powx272 power -10 '99' -> -1.00000000E+99 Rounded -- some more edge cases precision: 15 @@ -389,8 +252,9 @@ powx392 power 0.099 999 -> 4.360732062E-1004 Underflow Subnormal Inexact Rounded powx393 power 0.098 999 -> 1.71731E-1008 Underflow Subnormal Inexact Rounded powx394 power 0.097 999 -> 6E-1013 Underflow Subnormal Inexact Rounded -powx395 power 0.096 999 -> 0E-1013 Underflow Subnormal Inexact Rounded +powx395 power 0.096 999 -> 0E-1013 Underflow Subnormal Inexact Rounded Clamped powx396 power 0.01 999 -> 0E-1013 Underflow Subnormal Inexact Rounded Clamped +powx397 power 0.02 100000000 -> 0E-1013 Underflow Subnormal Inexact Rounded Clamped -- multiply tests are here to aid checking and test for consistent handling -- of underflow @@ -399,7 +263,7 @@ minexponent: -999 -- squares -mulx400 multiply 1E-502 1e-502 -> 0E-1003 Subnormal Inexact Underflow Rounded +mulx400 multiply 1E-502 1e-502 -> 0E-1003 Subnormal Inexact Underflow Rounded Clamped mulx401 multiply 1E-501 1e-501 -> 1E-1002 Subnormal mulx402 multiply 2E-501 2e-501 -> 4E-1002 Subnormal mulx403 multiply 4E-501 4e-501 -> 1.6E-1001 Subnormal @@ -407,7 +271,7 @@ mulx405 multiply 30E-501 30e-501 -> 9.00E-1000 Subnormal mulx406 multiply 40E-501 40e-501 -> 1.600E-999 -powx400 power 1E-502 2 -> 0E-1003 Underflow Subnormal Inexact Rounded +powx400 power 1E-502 2 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped powx401 power 1E-501 2 -> 1E-1002 Subnormal powx402 power 2E-501 2 -> 4E-1002 Subnormal powx403 power 4E-501 2 -> 1.6E-1001 Subnormal @@ -416,7 +280,7 @@ powx406 power 40E-501 2 -> 1.600E-999 -- cubes -mulx410 multiply 1E-670 1e-335 -> 0E-1003 Underflow Subnormal Inexact Rounded +mulx410 multiply 1E-670 1e-335 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped mulx411 multiply 1E-668 1e-334 -> 1E-1002 Subnormal mulx412 multiply 4E-668 2e-334 -> 8E-1002 Subnormal mulx413 multiply 9E-668 3e-334 -> 2.7E-1001 Subnormal @@ -424,7 +288,7 @@ mulx415 multiply 25E-668 5e-334 -> 1.25E-1000 Subnormal mulx416 multiply 10E-668 100e-334 -> 1.000E-999 -powx410 power 1E-335 3 -> 0E-1003 Underflow Subnormal Inexact Rounded +powx410 power 1E-335 3 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped powx411 power 1E-334 3 -> 1E-1002 Subnormal powx412 power 2E-334 3 -> 8E-1002 Subnormal powx413 power 3E-334 3 -> 2.7E-1001 Subnormal @@ -442,24 +306,24 @@ powx423 power 2.5E+499 -2 -> 1.6E-999 powx424 power 2.5E+500 -2 -> 1.6E-1001 Subnormal powx425 power 2.5E+501 -2 -> 2E-1003 Underflow Subnormal Inexact Rounded -powx426 power 2.5E+502 -2 -> 0E-1003 Underflow Subnormal Inexact Rounded +powx426 power 2.5E+502 -2 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped powx427 power 0.25E+499 -2 -> 1.6E-997 powx428 power 0.25E+500 -2 -> 1.6E-999 powx429 power 0.25E+501 -2 -> 1.6E-1001 Subnormal powx430 power 0.25E+502 -2 -> 2E-1003 Underflow Subnormal Inexact Rounded -powx431 power 0.25E+503 -2 -> 0E-1003 Underflow Subnormal Inexact Rounded +powx431 power 0.25E+503 -2 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped powx432 power 0.04E+499 -2 -> 6.25E-996 powx433 power 0.04E+500 -2 -> 6.25E-998 powx434 power 0.04E+501 -2 -> 6.25E-1000 Subnormal -powx435 power 0.04E+502 -2 -> 6.3E-1002 Underflow Subnormal Inexact Rounded +powx435 power 0.04E+502 -2 -> 6.2E-1002 Underflow Subnormal Inexact Rounded powx436 power 0.04E+503 -2 -> 1E-1003 Underflow Subnormal Inexact Rounded -powx437 power 0.04E+504 -2 -> 0E-1003 Underflow Subnormal Inexact Rounded +powx437 power 0.04E+504 -2 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped powx441 power 0.04E+334 -3 -> 1.5625E-998 powx442 power 0.04E+335 -3 -> 1.56E-1001 Underflow Subnormal Inexact Rounded -powx443 power 0.04E+336 -3 -> 0E-1003 Underflow Subnormal Inexact Rounded +powx443 power 0.04E+336 -3 -> 0E-1003 Underflow Subnormal Inexact Rounded Clamped powx444 power 0.25E+333 -3 -> 6.4E-998 powx445 power 0.25E+334 -3 -> 6.4E-1001 Subnormal powx446 power 0.25E+335 -3 -> 1E-1003 Underflow Subnormal Inexact Rounded @@ -467,7 +331,7 @@ -- check sign for cubes and a few squares powx448 power -0.04E+334 -3 -> -1.5625E-998 powx449 power -0.04E+335 -3 -> -1.56E-1001 Underflow Subnormal Inexact Rounded -powx450 power -0.04E+336 -3 -> -0E-1003 Underflow Subnormal Inexact Rounded +powx450 power -0.04E+336 -3 -> -0E-1003 Underflow Subnormal Inexact Rounded Clamped powx451 power -0.25E+333 -3 -> -6.4E-998 powx452 power -0.25E+334 -3 -> -6.4E-1001 Subnormal powx453 power -0.25E+335 -3 -> -1E-1003 Underflow Subnormal Inexact Rounded @@ -475,7 +339,7 @@ powx455 power -0.04E+499 -2 -> 6.25E-996 powx456 power -0.04E+500 -2 -> 6.25E-998 powx457 power -0.04E+501 -2 -> 6.25E-1000 Subnormal -powx458 power -0.04E+502 -2 -> 6.3E-1002 Underflow Subnormal Inexact Rounded +powx458 power -0.04E+502 -2 -> 6.2E-1002 Underflow Subnormal Inexact Rounded -- test -0s precision: 9 @@ -488,123 +352,124 @@ powx566 power -1 0 -> 1 powx567 power -1 -0 -> 1 powx568 power 0 1 -> 0 -powx569 power 0 -1 -> Infinity Division_by_zero +powx569 power 0 -1 -> Infinity powx570 power -0 1 -> -0 -powx571 power -0 -1 -> -Infinity Division_by_zero +powx571 power -0 -1 -> -Infinity powx572 power 0 2 -> 0 -powx573 power 0 -2 -> Infinity Division_by_zero +powx573 power 0 -2 -> Infinity powx574 power -0 2 -> 0 -powx575 power -0 -2 -> Infinity Division_by_zero +powx575 power -0 -2 -> Infinity powx576 power 0 3 -> 0 -powx577 power 0 -3 -> Infinity Division_by_zero +powx577 power 0 -3 -> Infinity powx578 power -0 3 -> -0 -powx579 power -0 -3 -> -Infinity Division_by_zero +powx579 power -0 -3 -> -Infinity -- Specials -powx580 power Inf -Inf -> NaN Invalid_operation +powx580 power Inf -Inf -> 0 powx581 power Inf -1000 -> 0 powx582 power Inf -1 -> 0 -powx583 power Inf -0 -> 1 -powx584 power Inf 0 -> 1 -powx585 power Inf 1 -> Infinity -powx586 power Inf 1000 -> Infinity -powx587 power Inf Inf -> NaN Invalid_operation -powx588 power -1000 Inf -> NaN Invalid_operation -powx589 power -Inf Inf -> NaN Invalid_operation -powx590 power -1 Inf -> NaN Invalid_operation -powx591 power -0 Inf -> NaN Invalid_operation -powx592 power 0 Inf -> NaN Invalid_operation -powx593 power 1 Inf -> NaN Invalid_operation -powx594 power 1000 Inf -> NaN Invalid_operation -powx595 power Inf Inf -> NaN Invalid_operation +powx583 power Inf -0.5 -> 0 +powx584 power Inf -0 -> 1 +powx585 power Inf 0 -> 1 +powx586 power Inf 0.5 -> Infinity +powx587 power Inf 1 -> Infinity +powx588 power Inf 1000 -> Infinity +powx589 power Inf Inf -> Infinity +powx590 power -1000 Inf -> NaN Invalid_operation +powx591 power -Inf Inf -> NaN Invalid_operation +powx592 power -1 Inf -> NaN Invalid_operation +powx593 power -0.5 Inf -> NaN Invalid_operation +powx594 power -0 Inf -> 0 +powx595 power 0 Inf -> 0 +powx596 power 0.5 Inf -> 0 +powx597 power 1 Inf -> 1.00000000 Inexact Rounded +powx598 power 1000 Inf -> Infinity +powx599 power Inf Inf -> Infinity powx600 power -Inf -Inf -> NaN Invalid_operation powx601 power -Inf -1000 -> 0 powx602 power -Inf -1 -> -0 -powx603 power -Inf -0 -> 1 -powx604 power -Inf 0 -> 1 -powx605 power -Inf 1 -> -Infinity -powx606 power -Inf 1000 -> Infinity -powx607 power -Inf Inf -> NaN Invalid_operation -powx608 power -1000 Inf -> NaN Invalid_operation -powx609 power -Inf -Inf -> NaN Invalid_operation -powx610 power -1 -Inf -> NaN Invalid_operation -powx611 power -0 -Inf -> NaN Invalid_operation -powx612 power 0 -Inf -> NaN Invalid_operation -powx613 power 1 -Inf -> NaN Invalid_operation -powx614 power 1000 -Inf -> NaN Invalid_operation -powx615 power Inf -Inf -> NaN Invalid_operation +powx603 power -Inf -0.5 -> NaN Invalid_operation +powx604 power -Inf -0 -> 1 +powx605 power -Inf 0 -> 1 +powx606 power -Inf 0.5 -> NaN Invalid_operation +powx607 power -Inf 1 -> -Infinity +powx608 power -Inf 1000 -> Infinity +powx609 power -Inf Inf -> NaN Invalid_operation +powx610 power -1000 Inf -> NaN Invalid_operation +powx611 power -Inf -Inf -> NaN Invalid_operation +powx612 power -1 -Inf -> NaN Invalid_operation +powx613 power -0.5 -Inf -> NaN Invalid_operation +powx614 power -0 -Inf -> Infinity +powx615 power 0 -Inf -> Infinity +powx616 power 0.5 -Inf -> Infinity +powx617 power 1 -Inf -> 1.00000000 Inexact Rounded +powx618 power 1000 -Inf -> 0 +powx619 power Inf -Inf -> 0 -powx621 power NaN -Inf -> NaN Invalid_operation +powx621 power NaN -Inf -> NaN powx622 power NaN -1000 -> NaN powx623 power NaN -1 -> NaN -powx624 power NaN -0 -> NaN -powx625 power NaN 0 -> NaN -powx626 power NaN 1 -> NaN -powx627 power NaN 1000 -> NaN -powx628 power NaN Inf -> NaN Invalid_operation -powx629 power NaN NaN -> NaN -powx630 power -Inf NaN -> NaN -powx631 power -1000 NaN -> NaN -powx632 power -1 NaN -> NaN -powx633 power -0 NaN -> NaN -powx634 power 0 NaN -> NaN -powx635 power 1 NaN -> NaN -powx636 power 1000 NaN -> NaN -powx637 power Inf NaN -> NaN +powx624 power NaN -0.5 -> NaN +powx625 power NaN -0 -> NaN +powx626 power NaN 0 -> NaN +powx627 power NaN 0.5 -> NaN +powx628 power NaN 1 -> NaN +powx629 power NaN 1000 -> NaN +powx630 power NaN Inf -> NaN +powx631 power NaN NaN -> NaN +powx632 power -Inf NaN -> NaN +powx633 power -1000 NaN -> NaN +powx634 power -1 NaN -> NaN +powx635 power -0 NaN -> NaN +powx636 power 0 NaN -> NaN +powx637 power 1 NaN -> NaN +powx638 power 1000 NaN -> NaN +powx639 power Inf NaN -> NaN powx641 power sNaN -Inf -> NaN Invalid_operation powx642 power sNaN -1000 -> NaN Invalid_operation powx643 power sNaN -1 -> NaN Invalid_operation -powx644 power sNaN -0 -> NaN Invalid_operation -powx645 power sNaN 0 -> NaN Invalid_operation -powx646 power sNaN 1 -> NaN Invalid_operation -powx647 power sNaN 1000 -> NaN Invalid_operation -powx648 power sNaN NaN -> NaN Invalid_operation -powx649 power sNaN sNaN -> NaN Invalid_operation -powx650 power NaN sNaN -> NaN Invalid_operation -powx651 power -Inf sNaN -> NaN Invalid_operation -powx652 power -1000 sNaN -> NaN Invalid_operation -powx653 power -1 sNaN -> NaN Invalid_operation -powx654 power -0 sNaN -> NaN Invalid_operation -powx655 power 0 sNaN -> NaN Invalid_operation -powx656 power 1 sNaN -> NaN Invalid_operation -powx657 power 1000 sNaN -> NaN Invalid_operation -powx658 power Inf sNaN -> NaN Invalid_operation -powx659 power NaN sNaN -> NaN Invalid_operation +powx644 power sNaN -0.5 -> NaN Invalid_operation +powx645 power sNaN -0 -> NaN Invalid_operation +powx646 power sNaN 0 -> NaN Invalid_operation +powx647 power sNaN 0.5 -> NaN Invalid_operation +powx648 power sNaN 1 -> NaN Invalid_operation +powx649 power sNaN 1000 -> NaN Invalid_operation +powx650 power sNaN NaN -> NaN Invalid_operation +powx651 power sNaN sNaN -> NaN Invalid_operation +powx652 power NaN sNaN -> NaN Invalid_operation +powx653 power -Inf sNaN -> NaN Invalid_operation +powx654 power -1000 sNaN -> NaN Invalid_operation +powx655 power -1 sNaN -> NaN Invalid_operation +powx656 power -0.5 sNaN -> NaN Invalid_operation +powx657 power -0 sNaN -> NaN Invalid_operation +powx658 power 0 sNaN -> NaN Invalid_operation +powx659 power 0.5 sNaN -> NaN Invalid_operation +powx660 power 1 sNaN -> NaN Invalid_operation +powx661 power 1000 sNaN -> NaN Invalid_operation +powx662 power Inf sNaN -> NaN Invalid_operation +powx663 power NaN sNaN -> NaN Invalid_operation -- NaN propagation -powx660 power NaN3 sNaN7 -> NaN7 Invalid_operation -powx661 power sNaN8 NaN6 -> NaN8 Invalid_operation -powx662 power 1 sNaN7 -> NaN7 Invalid_operation -powx663 power sNaN8 1 -> NaN8 Invalid_operation -powx664 power Inf sNaN7 -> NaN7 Invalid_operation -powx665 power sNaN8 Inf -> NaN Invalid_operation -powx666 power Inf NaN9 -> NaN9 -powx667 power NaN6 Inf -> NaN Invalid_operation -powx668 power 1 NaN5 -> NaN5 -powx669 power NaN2 1 -> NaN2 -powx670 power NaN2 Nan4 -> NaN2 -powx671 power NaN Nan4 -> NaN -powx672 power NaN345 Nan -> NaN345 -powx673 power Inf -sNaN7 -> -NaN7 Invalid_operation -powx674 power -sNaN8 Inf -> NaN Invalid_operation -powx675 power Inf -NaN9 -> -NaN9 -powx676 power -NaN6 Inf -> NaN Invalid_operation -powx677 power -NaN2 -Nan4 -> -NaN2 - --- Examples from extended specification -powx690 power Inf -2 -> 0 -powx691 power Inf -1 -> 0 -powx692 power Inf 0 -> 1 -powx693 power Inf 1 -> Infinity -powx694 power Inf 2 -> Infinity -powx695 power -Inf -2 -> 0 -powx696 power -Inf -1 -> -0 -powx697 power -Inf 0 -> 1 -powx698 power -Inf 1 -> -Infinity -powx699 power -Inf 2 -> Infinity -powx700 power 0 0 -> NaN Invalid_operation +powx670 power NaN3 sNaN7 -> NaN7 Invalid_operation +powx671 power sNaN8 NaN6 -> NaN8 Invalid_operation +powx672 power 1 sNaN7 -> NaN7 Invalid_operation +powx673 power sNaN8 1 -> NaN8 Invalid_operation +powx674 power Inf sNaN7 -> NaN7 Invalid_operation +powx675 power sNaN8 Inf -> NaN8 Invalid_operation +powx676 power Inf NaN9 -> NaN9 +powx677 power NaN6 Inf -> NaN6 +powx678 power 1 NaN5 -> NaN5 +powx679 power NaN2 1 -> NaN2 +powx680 power NaN2 Nan4 -> NaN2 +powx681 power NaN Nan4 -> NaN +powx682 power NaN345 Nan -> NaN345 +powx683 power Inf -sNaN7 -> -NaN7 Invalid_operation +powx684 power -sNaN8 Inf -> -NaN8 Invalid_operation +powx685 power Inf -NaN9 -> -NaN9 +powx686 power -NaN6 Inf -> -NaN6 +powx687 power -NaN2 -Nan4 -> -NaN2 -- long operand and RHS range checks maxexponent: 999 @@ -616,15 +481,6 @@ powx704 power 1234567891 1 -> 1.23456789E+9 Inexact Rounded powx705 power 12345678901 1 -> 1.23456789E+10 Inexact Rounded powx706 power 1234567896 1 -> 1.23456790E+9 Inexact Rounded -powx707 power 1 12345678000 -> NaN Invalid_operation -powx708 power 1 1234567800 -> NaN Invalid_operation -powx709 power 1 1234567890 -> NaN Invalid_operation -powx710 power 1 11234567891 -> NaN Invalid_operation -powx711 power 1 12345678901 -> NaN Invalid_operation -powx712 power 1 1234567896 -> NaN Invalid_operation -powx713 power 1 -1234567896 -> NaN Invalid_operation -powx714 power 1 1000000000 -> NaN Invalid_operation -powx715 power 1 -1000000000 -> NaN Invalid_operation precision: 15 -- still checking @@ -634,12 +490,182 @@ powx744 power 1234567891 1 -> 1234567891 powx745 power 12345678901 1 -> 12345678901 powx746 power 1234567896 1 -> 1234567896 -powx747 power 1 12345678000 -> NaN Invalid_operation -powx748 power 1 -1234567896 -> NaN Invalid_operation -powx749 power 1 1000000000 -> NaN Invalid_operation -powx740 power 1 -1000000000 -> NaN Invalid_operation --- check for double-rounded subnormals +maxexponent: 999999 +minexponent: -999999 +precision: 9 + +-- near out-of-range edge cases +powx163 power '10' '999999' -> '1.00000000E+999999' Rounded +powx164 power '10' '999998' -> '1.00000000E+999998' Rounded +powx165 power '10' '999997' -> '1.00000000E+999997' Rounded +powx166 power '10' '333333' -> '1.00000000E+333333' Rounded +powx183 power '7' '1000000' -> 1.09651419E+845098 Inexact Rounded +powx184 power '7' '1000001' -> 7.67559934E+845098 Inexact Rounded +powx186 power '7' '-1000001' -> 1.30282986E-845099 Inexact Rounded +powx187 power '7' '-1000000' -> 9.11980901E-845099 Inexact Rounded +powx118 power '10' '-333333' -> 1E-333333 +powx119 power '10' '-999998' -> 1E-999998 +powx120 power '10' '-999999' -> 1E-999999 +powx181 power '7' '999998' -> 2.23778406E+845096 Inexact Rounded +powx182 power '7' '999999' -> 1.56644884E+845097 Inexact Rounded +powx189 power '7' '-999999' -> 6.38386631E-845098 Inexact Rounded +powx190 power '7' '-999998' -> 4.46870641E-845097 Inexact Rounded + +-- overflow and underflow tests +precision: 9 + +powx277 power 9 999999 -> 3.59084629E+954241 Inexact Rounded +powx278 power 9.99999999 999999 -> 9.99000501E+999998 Inexact Rounded +powx279 power 10 999999 -> 1.00000000E+999999 Rounded +powx280 power 10.0000001 999999 -> 1.01005016E+999999 Inexact Rounded +powx281 power 10.000001 999999 -> 1.10517080E+999999 Inexact Rounded +powx282 power 10.00001 999999 -> 2.71827775E+999999 Inexact Rounded +powx283 power 10.0001 999999 -> Infinity Overflow Inexact Rounded +powx285 power 11 999999 -> Infinity Overflow Inexact Rounded +powx286 power 12 999999 -> Infinity Overflow Inexact Rounded +powx287 power 999 999999 -> Infinity Overflow Inexact Rounded +powx288 power 999999999 999999 -> Infinity Overflow Inexact Rounded +powx289 power 9.9E999999999 999999 -> Infinity Overflow Inexact Rounded + +powx290 power 0.5 999999 -> 2.02006812E-301030 Inexact Rounded +powx291 power 0.1 999999 -> 1E-999999 -- unrounded +powx292 power 0.09 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx293 power 0.05 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx294 power 0.01 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx295 power 0.0001 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx297 power 0.0000001 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx298 power 0.0000000001 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx299 power 1E-999999999 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped + +powx310 power -9 999999 -> -3.59084629E+954241 Inexact Rounded +powx311 power -10 999999 -> -1.00000000E+999999 Rounded +powx312 power -10.0001 999999 -> -Infinity Overflow Inexact Rounded +powx313 power -10.1 999999 -> -Infinity Overflow Inexact Rounded +powx314 power -11 999999 -> -Infinity Overflow Inexact Rounded +powx315 power -12 999999 -> -Infinity Overflow Inexact Rounded +powx316 power -999 999999 -> -Infinity Overflow Inexact Rounded +powx317 power -999999 999999 -> -Infinity Overflow Inexact Rounded +powx318 power -999999999 999999 -> -Infinity Overflow Inexact Rounded +powx319 power -9.9E999999999 999999 -> -Infinity Overflow Inexact Rounded + +powx320 power -0.5 999999 -> -2.02006812E-301030 Inexact Rounded +powx321 power -0.1 999999 -> -1E-999999 +powx322 power -0.09 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx323 power -0.05 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx324 power -0.01 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx325 power -0.0001 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx327 power -0.0000001 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx328 power -0.0000000001 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx329 power -1E-999999999 999999 -> -0E-1000007 Underflow Subnormal Inexact Rounded Clamped + +-- note no trim of next result +powx330 power -9 999998 -> 3.98982921E+954240 Inexact Rounded +powx331 power -10 999998 -> 1.00000000E+999998 Rounded +powx332 power -10.0001 999998 -> Infinity Overflow Inexact Rounded +powx333 power -10.1 999998 -> Infinity Overflow Inexact Rounded +powx334 power -11 999998 -> Infinity Overflow Inexact Rounded +powx335 power -12 999998 -> Infinity Overflow Inexact Rounded +powx336 power -999 999998 -> Infinity Overflow Inexact Rounded +powx337 power -999999 999998 -> Infinity Overflow Inexact Rounded +powx338 power -999999999 999998 -> Infinity Overflow Inexact Rounded +powx339 power -9.9E999999999 999998 -> Infinity Overflow Inexact Rounded + +powx340 power -0.5 999998 -> 4.04013624E-301030 Inexact Rounded +powx341 power -0.1 999998 -> 1E-999998 -- NB exact unrounded +powx342 power -0.09 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx343 power -0.05 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx344 power -0.01 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx345 power -0.0001 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx347 power -0.0000001 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx348 power -0.0000000001 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx349 power -1E-999999999 999998 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped + +-- some subnormals +precision: 9 +-- [precision is 9, so smallest exponent is -1000000007 +powx350 power 1e-1 500000 -> 1E-500000 +powx351 power 1e-2 999999 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped +powx352 power 1e-2 500000 -> 1E-1000000 Subnormal +powx353 power 1e-2 500001 -> 1E-1000002 Subnormal +powx354 power 1e-2 500002 -> 1E-1000004 Subnormal +powx355 power 1e-2 500003 -> 1E-1000006 Subnormal +powx356 power 1e-2 500004 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped + +powx360 power 0.010001 500000 -> 5.17176082E-999979 Inexact Rounded +powx361 power 0.010000001 500000 -> 1.0512711E-1000000 Underflow Subnormal Inexact Rounded +powx362 power 0.010000001 500001 -> 1.05127E-1000002 Underflow Subnormal Inexact Rounded +powx363 power 0.0100000009 500000 -> 1.0460279E-1000000 Underflow Subnormal Inexact Rounded +powx364 power 0.0100000001 500000 -> 1.0050125E-1000000 Underflow Subnormal Inexact Rounded +powx365 power 0.01 500000 -> 1E-1000000 Subnormal +powx366 power 0.0099999999 500000 -> 9.950125E-1000001 Underflow Subnormal Inexact Rounded +powx367 power 0.0099999998 500000 -> 9.900498E-1000001 Underflow Subnormal Inexact Rounded +powx368 power 0.0099999997 500000 -> 9.851119E-1000001 Underflow Subnormal Inexact Rounded +powx369 power 0.0099999996 500000 -> 9.801987E-1000001 Underflow Subnormal Inexact Rounded +powx370 power 0.009 500000 -> 0E-1000007 Underflow Subnormal Inexact Rounded Clamped + +-- 1/subnormal -> overflow +powx371 power 1e-1 -500000 -> 1E+500000 +powx372 power 1e-2 -999999 -> Infinity Overflow Inexact Rounded +powx373 power 1e-2 -500000 -> Infinity Overflow Inexact Rounded +powx374 power 1e-2 -500001 -> Infinity Overflow Inexact Rounded +powx375 power 1e-2 -500002 -> Infinity Overflow Inexact Rounded +powx376 power 1e-2 -500003 -> Infinity Overflow Inexact Rounded +powx377 power 1e-2 -500004 -> Infinity Overflow Inexact Rounded + +powx381 power 0.010001 -500000 -> 1.93357743E+999978 Inexact Rounded +powx382 power 0.010000001 -500000 -> 9.51229427E+999999 Inexact Rounded +powx383 power 0.010000001 -500001 -> Infinity Overflow Inexact Rounded +powx384 power 0.0100000009 -500000 -> 9.55997484E+999999 Inexact Rounded +powx385 power 0.0100000001 -500000 -> 9.95012479E+999999 Inexact Rounded +powx386 power 0.01 -500000 -> Infinity Overflow Inexact Rounded +powx387 power 0.009999 -500000 -> Infinity Overflow Inexact Rounded + +-- negative power giving subnormal +powx388 power 100.000001 -500000 -> 9.950125E-1000001 Underflow Subnormal Inexact Rounded + + +-- test some 'false integer' boundaries +precision: 16 +rounding: half_even +maxExponent: 384 +minExponent: -383 +powx501 power 100 1E+1 -> 1.000000000000000E+20 Rounded +powx502 power 100 1E+2 -> 1.000000000000000E+200 Rounded +powx503 power 100 1E+3 -> Infinity Overflow Inexact Rounded +powx504 power 100 1E+4 -> Infinity Overflow Inexact Rounded +powx505 power 100 1E+5 -> Infinity Overflow Inexact Rounded +powx506 power 100 1E+6 -> Infinity Overflow Inexact Rounded +powx507 power 100 1E+7 -> Infinity Overflow Inexact Rounded +powx508 power 100 1E+8 -> Infinity Overflow Inexact Rounded +powx509 power 100 1E+9 -> Infinity Overflow Inexact Rounded +powx510 power 100 1E+10 -> Infinity Overflow Inexact Rounded +powx511 power 100 1E+11 -> Infinity Overflow Inexact Rounded +powx512 power 100 1E+12 -> Infinity Overflow Inexact Rounded +powx513 power 100 1E+13 -> Infinity Overflow Inexact Rounded +powx514 power 100 1E+14 -> Infinity Overflow Inexact Rounded +powx515 power 100 1E+15 -> Infinity Overflow Inexact Rounded +powx516 power 100 1E+16 -> Infinity Overflow Inexact Rounded +powx517 power 100 1E+17 -> Infinity Overflow Inexact Rounded +powx518 power 100 1E+18 -> Infinity Overflow Inexact Rounded +powx519 power 100 1E+19 -> Infinity Overflow Inexact Rounded +powx520 power 100 1E+20 -> Infinity Overflow Inexact Rounded +powx521 power 100 1E+21 -> Infinity Overflow Inexact Rounded +powx522 power 100 1E+22 -> Infinity Overflow Inexact Rounded +powx523 power 100 1E+23 -> Infinity Overflow Inexact Rounded +powx524 power 100 1E+24 -> Infinity Overflow Inexact Rounded +powx525 power 100 1E+25 -> Infinity Overflow Inexact Rounded +powx526 power 100 1E+26 -> Infinity Overflow Inexact Rounded +powx527 power 100 1E+27 -> Infinity Overflow Inexact Rounded +powx528 power 100 1E+28 -> Infinity Overflow Inexact Rounded +powx529 power 100 1E+29 -> Infinity Overflow Inexact Rounded +powx530 power 100 1E+30 -> Infinity Overflow Inexact Rounded +powx531 power 100 1E+40 -> Infinity Overflow Inexact Rounded +powx532 power 100 1E+50 -> Infinity Overflow Inexact Rounded +powx533 power 100 1E+100 -> Infinity Overflow Inexact Rounded +powx534 power 100 1E+383 -> Infinity Overflow Inexact Rounded + +-- a check for double-rounded subnormals precision: 5 maxexponent: 79 minexponent: -79 @@ -649,3 +675,950 @@ powx900 power 1 # -> NaN Invalid_operation powx901 power # 1 -> NaN Invalid_operation +---------------------------------------------------------------------- +-- Below here are tests with a precision or context outside of the -- +-- decNumber 'mathematical functions' restricted range. These -- +-- remain supported in decNumber to minimize breakage, but may be -- +-- outside the range of other implementations. -- +---------------------------------------------------------------------- +maxexponent: 999999999 +minexponent: -999999999 +precision: 9 +powx1063 power '10' '999999999' -> '1.00000000E+999999999' Rounded +powx1064 power '10' '999999998' -> '1.00000000E+999999998' Rounded +powx1065 power '10' '999999997' -> '1.00000000E+999999997' Rounded +powx1066 power '10' '333333333' -> '1.00000000E+333333333' Rounded +-- next two are integer-out-of range +powx1183 power '7' '1000000000' -> NaN Invalid_context +powx1184 power '7' '1000000001' -> NaN Invalid_context +powx1186 power '7' '-1000000001' -> 1.38243630E-845098041 Inexact Rounded +powx1187 power '7' '-1000000000' -> 9.67705411E-845098041 Inexact Rounded + +-- out-of-range edge cases +powx1118 power '10' '-333333333' -> 1E-333333333 +powx1119 power '10' '-999999998' -> 1E-999999998 +powx1120 power '10' '-999999999' -> 1E-999999999 +powx1181 power '7' '999999998' -> 2.10892313E+845098038 Inexact Rounded +powx1182 power '7' '999999999' -> 1.47624619E+845098039 Inexact Rounded +powx1189 power '7' '-999999999' -> 6.77393787E-845098040 Inexact Rounded +powx1190 power '7' '-999999998' -> 4.74175651E-845098039 Inexact Rounded + +-- A (rare) case where the last digit is not within 0.5 ULP with classic precision +precision: 9 +powx1215 power "-21971575.0E+31454441" "-7" -> "-4.04549502E-220181139" Inexact Rounded +precision: 20 +powx1216 power "-21971575.0E+31454441" "-7" -> "-4.0454950249324891788E-220181139" Inexact Rounded + +-- overflow and underflow tests +precision: 9 +powx1280 power 9 999999999 -> 3.05550054E+954242508 Inexact Rounded +powx1281 power 10 999999999 -> 1.00000000E+999999999 Rounded +powx1282 power 10.0001 999999999 -> Infinity Overflow Inexact Rounded +powx1283 power 10.1 999999999 -> Infinity Overflow Inexact Rounded +powx1284 power 11 999999999 -> Infinity Overflow Inexact Rounded +powx1285 power 12 999999999 -> Infinity Overflow Inexact Rounded +powx1286 power 999 999999999 -> Infinity Overflow Inexact Rounded +powx1287 power 999999 999999999 -> Infinity Overflow Inexact Rounded +powx1288 power 999999999 999999999 -> Infinity Overflow Inexact Rounded +powx1289 power 9.9E999999999 999999999 -> Infinity Overflow Inexact Rounded + +powx1290 power 0.5 999999999 -> 4.33559594E-301029996 Inexact Rounded +powx1291 power 0.1 999999999 -> 1E-999999999 -- unrounded +powx1292 power 0.09 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1293 power 0.05 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1294 power 0.01 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1295 power 0.0001 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1297 power 0.0000001 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1298 power 0.0000000001 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1299 power 1E-999999999 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped + +powx1310 power -9 999999999 -> -3.05550054E+954242508 Inexact Rounded +powx1311 power -10 999999999 -> -1.00000000E+999999999 Rounded +powx1312 power -10.0001 999999999 -> -Infinity Overflow Inexact Rounded +powx1313 power -10.1 999999999 -> -Infinity Overflow Inexact Rounded +powx1314 power -11 999999999 -> -Infinity Overflow Inexact Rounded +powx1315 power -12 999999999 -> -Infinity Overflow Inexact Rounded +powx1316 power -999 999999999 -> -Infinity Overflow Inexact Rounded +powx1317 power -999999 999999999 -> -Infinity Overflow Inexact Rounded +powx1318 power -999999999 999999999 -> -Infinity Overflow Inexact Rounded +powx1319 power -9.9E999999999 999999999 -> -Infinity Overflow Inexact Rounded + +powx1320 power -0.5 999999999 -> -4.33559594E-301029996 Inexact Rounded +powx1321 power -0.1 999999999 -> -1E-999999999 +powx1322 power -0.09 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1323 power -0.05 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1324 power -0.01 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1325 power -0.0001 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1327 power -0.0000001 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1328 power -0.0000000001 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1329 power -1E-999999999 999999999 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped + +-- note no trim of next result +powx1330 power -9 999999998 -> 3.39500060E+954242507 Inexact Rounded +powx1331 power -10 999999998 -> 1.00000000E+999999998 Rounded +powx1332 power -10.0001 999999998 -> Infinity Overflow Inexact Rounded +powx1333 power -10.1 999999998 -> Infinity Overflow Inexact Rounded +powx1334 power -11 999999998 -> Infinity Overflow Inexact Rounded +powx1335 power -12 999999998 -> Infinity Overflow Inexact Rounded +powx1336 power -999 999999998 -> Infinity Overflow Inexact Rounded +powx1337 power -999999 999999998 -> Infinity Overflow Inexact Rounded +powx1338 power -999999999 999999998 -> Infinity Overflow Inexact Rounded +powx1339 power -9.9E999999999 999999998 -> Infinity Overflow Inexact Rounded + +powx1340 power -0.5 999999998 -> 8.67119187E-301029996 Inexact Rounded +powx1341 power -0.1 999999998 -> 1E-999999998 -- NB exact unrounded +powx1342 power -0.09 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1343 power -0.05 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1344 power -0.01 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1345 power -0.0001 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1347 power -0.0000001 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1348 power -0.0000000001 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1349 power -1E-999999999 999999998 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped + +-- some subnormals +precision: 9 +-- [precision is 9, so smallest exponent is -1000000007 +powx1350 power 1e-1 500000000 -> 1E-500000000 +powx1351 power 1e-2 999999999 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1352 power 1e-2 500000000 -> 1E-1000000000 Subnormal +powx1353 power 1e-2 500000001 -> 1E-1000000002 Subnormal +powx1354 power 1e-2 500000002 -> 1E-1000000004 Subnormal +powx1355 power 1e-2 500000003 -> 1E-1000000006 Subnormal +powx1356 power 1e-2 500000004 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped + +powx1360 power 0.010001 500000000 -> 4.34941988E-999978287 Inexact Rounded +powx1361 power 0.010000001 500000000 -> 5.18469257E-999999979 Inexact Rounded +powx1362 power 0.010000001 500000001 -> 5.18469309E-999999981 Inexact Rounded +powx1363 power 0.0100000009 500000000 -> 3.49342003E-999999981 Inexact Rounded +powx1364 power 0.0100000001 500000000 -> 1.48413155E-999999998 Inexact Rounded +powx1365 power 0.01 500000000 -> 1E-1000000000 Subnormal +powx1366 power 0.0099999999 500000000 -> 6.7379E-1000000003 Underflow Subnormal Inexact Rounded +powx1367 power 0.0099999998 500000000 -> 4.54E-1000000005 Underflow Subnormal Inexact Rounded +powx1368 power 0.0099999997 500000000 -> 3E-1000000007 Underflow Subnormal Inexact Rounded +powx1369 power 0.0099999996 500000000 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped +powx1370 power 0.009 500000000 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped + +-- 1/subnormal -> overflow +powx1371 power 1e-1 -500000000 -> 1E+500000000 +powx1372 power 1e-2 -999999999 -> Infinity Overflow Inexact Rounded +powx1373 power 1e-2 -500000000 -> Infinity Overflow Inexact Rounded +powx1374 power 1e-2 -500000001 -> Infinity Overflow Inexact Rounded +powx1375 power 1e-2 -500000002 -> Infinity Overflow Inexact Rounded +powx1376 power 1e-2 -500000003 -> Infinity Overflow Inexact Rounded +powx1377 power 1e-2 -500000004 -> Infinity Overflow Inexact Rounded + +powx1381 power 0.010001 -500000000 -> 2.29915719E+999978286 Inexact Rounded +powx1382 power 0.010000001 -500000000 -> 1.92875467E+999999978 Inexact Rounded +powx1383 power 0.010000001 -500000001 -> 1.92875448E+999999980 Inexact Rounded +powx1384 power 0.0100000009 -500000000 -> 2.86252438E+999999980 Inexact Rounded +powx1385 power 0.0100000001 -500000000 -> 6.73794717E+999999997 Inexact Rounded +powx1386 power 0.01 -500000000 -> Infinity Overflow Inexact Rounded +powx1387 power 0.009999 -500000000 -> Infinity Overflow Inexact Rounded + +-- negative power giving subnormal +powx1388 power 100.000001 -500000000 -> 6.7379E-1000000003 Underflow Subnormal Inexact Rounded + +---------------------------------------------------------------------- +-- Below here are the tests with a non-integer rhs, including the -- +-- tests that previously caused Invalid operation. An integer-only -- +-- (on rhs) implementation should handle all the tests above as -- +-- shown, and would flag most of the following tests as Invalid. -- +---------------------------------------------------------------------- +precision: 16 +rounding: half_even +maxExponent: 384 +minExponent: -383 + +powx2000 power 7 '10000000000' -> Infinity Overflow Inexact Rounded +powx2001 power 2 '2.000001' -> 4.000002772589683 Inexact Rounded +powx2002 power 2 '2.00000000' -> 4 +powx2003 power 2 '2.000000001' -> 4.000000002772589 Inexact Rounded +powx2004 power 2 '2.0000000001' -> 4.000000000277259 Inexact Rounded +powx2005 power 2 '2.00000000001' -> 4.000000000027726 Inexact Rounded +powx2006 power 2 '2.000000000001' -> 4.000000000002773 Inexact Rounded +powx2007 power 2 '2.0000000000001' -> 4.000000000000277 Inexact Rounded +powx2008 power 2 '2.00000000000001' -> 4.000000000000028 Inexact Rounded +powx2009 power 2 '2.000000000000001' -> 4.000000000000003 Inexact Rounded +powx2010 power 2 '2.0000000000000001' -> 4.000000000000000 Inexact Rounded +-- 1 234567890123456 + +powx2011 power 1 1234 -> 1 +precision: 4 +powx2012 power 1 1234 -> 1 +precision: 3 +powx2013 power 1 1234 -> 1 +powx2014 power 1 12.34e+2 -> 1 +powx2015 power 1 12.3 -> 1.00 Inexact Rounded +powx2016 power 1 12.0 -> 1 +powx2017 power 1 1.01 -> 1.00 Inexact Rounded +powx2018 power 2 1.00 -> 2 +powx2019 power 2 2.00 -> 4 +precision: 9 +powx2030 power 1 1.0001 -> 1.00000000 Inexact Rounded +powx2031 power 1 1.0000001 -> 1.00000000 Inexact Rounded +powx2032 power 1 1.0000000001 -> 1.00000000 Inexact Rounded +powx2033 power 1 1.0000000000001 -> 1.00000000 Inexact Rounded +precision: 5 +powx2034 power 1 1.0001 -> 1.0000 Inexact Rounded +powx2035 power 1 1.0000001 -> 1.0000 Inexact Rounded +powx2036 power 1 1.0000000001 -> 1.0000 Inexact Rounded +powx2037 power 1 1.0000000000001 -> 1.0000 Inexact Rounded +powx2038 power 1 1.0000000000001 -> 1.0000 Inexact Rounded + +rounding: ceiling +precision: 3 +powx2039 power 1 1.01 -> 1.00 Inexact Rounded +powx2040 power 1 12.3 -> 1.00 Inexact Rounded +rounding: half_even + +-- 1 ** any integer, including big ones, should be exact +powx2041 power 1 1000000000 -> 1 +powx2042 power 1 9999999999 -> 1 +powx2043 power 1 12345678000 -> 1 +powx2044 power 1 1234567800 -> 1 +powx2045 power 1 1234567890 -> 1 +powx2046 power 1 11234567891 -> 1 +powx2047 power 1 12345678901 -> 1 +powx2048 power 1 1234567896 -> 1 +powx2049 power 1 -1234567896 -> 1 +powx2051 power 1 1000000000 -> 1 +powx2052 power 1 -1000000000 -> 1 +powx2053 power 1 12345678000 -> 1 +powx2054 power 1 -1234567896 -> 1 +powx2055 power 1 1000000000 -> 1 +powx2056 power 1 4300000000 -> 1 +powx2057 power 1 -1000000000 -> 1 +-- negatives ... but not out of range for decNumber +powx2061 power -1 100000 -> 1 +powx2062 power -1 999999 -> -1 +powx2063 power -1 1278000 -> 1 +powx2064 power -1 127803 -> -1 +powx2065 power -1 127890 -> 1 +powx2066 power -1 1167891 -> -1 +powx2067 power -1 1278901 -> -1 +powx2068 power -1 127896 -> 1 +powx2069 power -1 -167897 -> -1 +powx2071 power -1 100000 -> 1 +powx2072 power -1 -100001 -> -1 +powx2073 power -1 1278000 -> 1 +powx2074 power -1 -167896 -> 1 +powx2075 power -1 100000 -> 1 +powx2076 power -1 -100009 -> -1 + +-- The above were derived from the earlier version of power.decTest; +-- now start new tests for power(x,y) for non-integer y +precision: 9 + +-- tests from specification +powx2081 power 2 3 -> '8' +powx2082 power -2 3 -> '-8' +powx2083 power 2 -3 -> '0.125' +powx2084 power 1.7 '8' -> '69.7575744' Inexact Rounded +powx2085 power 10 0.301029996 -> 2.00000000 Inexact Rounded +powx2086 power Infinity '-1' -> '0' +powx2087 power Infinity '0' -> '1' +powx2088 power Infinity '1' -> 'Infinity' +powx2089 power -Infinity '-1' -> '-0' +powx2090 power -Infinity '0' -> '1' +powx2091 power -Infinity '1' -> '-Infinity' +powx2092 power -Infinity '2' -> 'Infinity' +powx2093 power 0 0 -> 'NaN' Invalid_operation + +precision: 16 +rounding: half_even +maxExponent: 384 +minExponent: -383 + +-- basics +powx2100 power 1E-7 1E-7 -> 0.9999983881917339 Inexact Rounded +powx2101 power 0.003 1E-7 -> 0.9999994190858697 Inexact Rounded +powx2102 power 0.7 1E-7 -> 0.9999999643325062 Inexact Rounded +powx2103 power 1.2 1E-7 -> 1.000000018232156 Inexact Rounded +powx2104 power 71 1E-7 -> 1.000000426268079 Inexact Rounded +powx2105 power 9E+9 1E-7 -> 1.000002292051668 Inexact Rounded + +powx2110 power 1E-7 0.003 -> 0.9527961640236519 Inexact Rounded +powx2111 power 0.003 0.003 -> 0.9827235503366797 Inexact Rounded +powx2112 power 0.7 0.003 -> 0.9989305474406207 Inexact Rounded +powx2113 power 1.2 0.003 -> 1.000547114282834 Inexact Rounded +powx2114 power 71 0.003 -> 1.012870156273545 Inexact Rounded +powx2115 power 9E+9 0.003 -> 1.071180671278787 Inexact Rounded + +powx2120 power 1E-7 0.7 -> 0.00001258925411794167 Inexact Rounded +powx2121 power 0.003 0.7 -> 0.01713897630281030 Inexact Rounded +powx2122 power 0.7 0.7 -> 0.7790559126704491 Inexact Rounded +powx2123 power 1.2 0.7 -> 1.136126977198889 Inexact Rounded +powx2124 power 71 0.7 -> 19.76427300093870 Inexact Rounded +powx2125 power 9E+9 0.7 -> 9289016.976853710 Inexact Rounded + +powx2130 power 1E-7 1.2 -> 3.981071705534973E-9 Inexact Rounded +powx2131 power 0.003 1.2 -> 0.0009387403933595694 Inexact Rounded +powx2132 power 0.7 1.2 -> 0.6518049405663864 Inexact Rounded +powx2133 power 1.2 1.2 -> 1.244564747203978 Inexact Rounded +powx2134 power 71 1.2 -> 166.5367244638552 Inexact Rounded +powx2135 power 9E+9 1.2 -> 881233526124.8791 Inexact Rounded + +powx2140 power 1E-7 71 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +powx2141 power 0.003 71 -> 7.509466514979725E-180 Inexact Rounded +powx2142 power 0.7 71 -> 1.004525211269079E-11 Inexact Rounded +powx2143 power 1.2 71 -> 418666.7483186515 Inexact Rounded +powx2144 power 71 71 -> 2.750063734834616E+131 Inexact Rounded +powx2145 power 9E+9 71 -> Infinity Inexact Rounded Overflow + +powx2150 power 1E-7 9E+9 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +powx2151 power 0.003 9E+9 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +powx2152 power 0.7 9E+9 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +powx2153 power 1.2 9E+9 -> Infinity Inexact Rounded Overflow +powx2154 power 71 9E+9 -> Infinity Inexact Rounded Overflow +powx2155 power 9E+9 9E+9 -> Infinity Inexact Rounded Overflow + +-- number line milestones with lhs<1 and lhs>1 + +-- Overflow boundary (Nmax) +powx2202 power 71 207.966651583983200 -> Infinity Inexact Rounded Overflow +powx2201 power 71 207.966651583983199 -> 9.999999999999994E+384 Inexact Rounded +powx2204 power 0.003 -152.603449817093577 -> Infinity Inexact Rounded Overflow +powx2203 power 0.003 -152.603449817093576 -> 9.999999999999994E+384 Inexact Rounded + +-- Nmin boundary +powx2211 power 71 -206.886305341988480 -> 1.000000000000005E-383 Inexact Rounded +powx2212 power 71 -206.886305341988481 -> 1.000000000000001E-383 Inexact Rounded +powx2213 power 71 -206.886305341988482 -> 9.99999999999997E-384 Inexact Rounded Underflow Subnormal +powx2214 power 71 -206.886305341988483 -> 9.99999999999992E-384 Inexact Rounded Underflow Subnormal +-- 9.999999999999924565357019820 + +powx2215 power 0.003 151.810704623238543 -> 1.000000000000009E-383 Inexact Rounded +powx2216 power 0.003 151.810704623238544 -> 1.000000000000003E-383 Inexact Rounded +powx2217 power 0.003 151.810704623238545 -> 9.99999999999997E-384 Inexact Rounded Underflow Subnormal +powx2218 power 0.003 151.810704623238546 -> 9.99999999999991E-384 Inexact Rounded Underflow Subnormal + +-- Ntiny boundary, these edge cases determined using half_up rounding +rounding: half_up +powx2221 power 71 -215.151510469220498 -> 1E-398 Inexact Rounded Underflow Subnormal +powx2222 power 71 -215.151510469220499 -> 1E-398 Inexact Rounded Underflow Subnormal +powx2223 power 71 -215.151510469220500 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +powx2224 power 71 -215.151510469220501 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped + +powx2225 power 0.003 157.875613618285691 -> 1E-398 Inexact Rounded Underflow Subnormal +powx2226 power 0.003 157.875613618285692 -> 1E-398 Inexact Rounded Underflow Subnormal +powx2227 power 0.003 157.875613618285693 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +powx2228 power 0.003 220 -> 0E-398 Inexact Rounded Underflow Subnormal Clamped +rounding: half_even + +-- power(10, y) are important ... + +-- Integer powers are exact, unless over/underflow +powx2301 power 10 385 -> Infinity Overflow Inexact Rounded +powx2302 power 10 384 -> 1.000000000000000E+384 Rounded +powx2303 power 10 17 -> 1.000000000000000E+17 Rounded +powx2304 power 10 16 -> 1.000000000000000E+16 Rounded +powx2305 power 10 15 -> 1000000000000000 +powx2306 power 10 10 -> 10000000000 +powx2307 power 10 5 -> 100000 +powx2308 power 10 1 -> 10 +powx2309 power 10 0 -> 1 +powx2310 power 10 -1 -> 0.1 +powx2311 power 10 -5 -> 0.00001 +powx2312 power 10 -6 -> 0.000001 +powx2313 power 10 -7 -> 1E-7 +powx2314 power 10 -8 -> 1E-8 +powx2315 power 10 -9 -> 1E-9 +powx2316 power 10 -10 -> 1E-10 +powx2317 power 10 -383 -> 1E-383 +powx2318 power 10 -384 -> 1E-384 Subnormal +powx2319 power 10 -385 -> 1E-385 Subnormal +powx2320 power 10 -397 -> 1E-397 Subnormal +powx2321 power 10 -398 -> 1E-398 Subnormal +powx2322 power 10 -399 -> 0E-398 Subnormal Underflow Inexact Rounded Clamped +powx2323 power 10 -400 -> 0E-398 Subnormal Underflow Inexact Rounded Clamped + +-- Independent sanity check: 1961 Godfrey & Siddons four-figure logs +powx2351 power 10 0.0000 -> 1 +powx2352 power 10 0.3010 -> 1.999861869632744 Inexact Rounded +powx2353 power 10 0.4771 -> 2.999853181190793 Inexact Rounded +powx2354 power 10 0.6021 -> 4.000368510461250 Inexact Rounded +powx2355 power 10 0.6990 -> 5.000345349769785 Inexact Rounded +powx2356 power 10 0.7782 -> 6.000673538641164 Inexact Rounded +powx2357 power 10 0.8451 -> 7.000031591308969 Inexact Rounded +powx2358 power 10 0.9031 -> 8.000184448550990 Inexact Rounded +powx2359 power 10 0.9542 -> 8.999119108700520 Inexact Rounded +powx2360 power 10 0.9956 -> 9.899197750805841 Inexact Rounded +powx2361 power 10 0.9996 -> 9.990793899844618 Inexact Rounded +precision: 4 +powx2371 power 10 0.0000 -> 1 +powx2372 power 10 0.3010 -> 2.000 Inexact Rounded +powx2373 power 10 0.4771 -> 3.000 Inexact Rounded +powx2374 power 10 0.6021 -> 4.000 Inexact Rounded +powx2375 power 10 0.6990 -> 5.000 Inexact Rounded +powx2376 power 10 0.7782 -> 6.001 Inexact Rounded +powx2377 power 10 0.8451 -> 7.000 Inexact Rounded +powx2378 power 10 0.9031 -> 8.000 Inexact Rounded +powx2379 power 10 0.9542 -> 8.999 Inexact Rounded +powx2380 power 10 0.9956 -> 9.899 Inexact Rounded +powx2381 power 10 0.9996 -> 9.991 Inexact Rounded + +-- 10**x ~=2 (inverse of the test in log10.decTest) +precision: 50 +powx2401 power 10 0.30102999566398119521373889472449302676818988146211 -> 2.0000000000000000000000000000000000000000000000000 Inexact Rounded +precision: 49 +powx2402 power 10 0.3010299956639811952137388947244930267681898814621 -> 2.000000000000000000000000000000000000000000000000 Inexact Rounded +precision: 48 +powx2403 power 10 0.301029995663981195213738894724493026768189881462 -> 2.00000000000000000000000000000000000000000000000 Inexact Rounded +precision: 47 +powx2404 power 10 0.30102999566398119521373889472449302676818988146 -> 2.0000000000000000000000000000000000000000000000 Inexact Rounded +precision: 46 +powx2405 power 10 0.3010299956639811952137388947244930267681898815 -> 2.000000000000000000000000000000000000000000000 Inexact Rounded +precision: 45 +powx2406 power 10 0.301029995663981195213738894724493026768189881 -> 2.00000000000000000000000000000000000000000000 Inexact Rounded +precision: 44 +powx2407 power 10 0.30102999566398119521373889472449302676818988 -> 2.0000000000000000000000000000000000000000000 Inexact Rounded +precision: 43 +powx2408 power 10 0.3010299956639811952137388947244930267681899 -> 2.000000000000000000000000000000000000000000 Inexact Rounded +precision: 42 +powx2409 power 10 0.301029995663981195213738894724493026768190 -> 2.00000000000000000000000000000000000000000 Inexact Rounded +precision: 41 +powx2410 power 10 0.30102999566398119521373889472449302676819 -> 2.0000000000000000000000000000000000000000 Inexact Rounded +precision: 40 +powx2411 power 10 0.3010299956639811952137388947244930267682 -> 2.000000000000000000000000000000000000000 Inexact Rounded +precision: 39 +powx2412 power 10 0.301029995663981195213738894724493026768 -> 2.00000000000000000000000000000000000000 Inexact Rounded +precision: 38 +powx2413 power 10 0.30102999566398119521373889472449302677 -> 2.0000000000000000000000000000000000000 Inexact Rounded +precision: 37 +powx2414 power 10 0.3010299956639811952137388947244930268 -> 2.000000000000000000000000000000000000 Inexact Rounded +precision: 36 +powx2415 power 10 0.301029995663981195213738894724493027 -> 2.00000000000000000000000000000000000 Inexact Rounded +precision: 35 +powx2416 power 10 0.30102999566398119521373889472449303 -> 2.0000000000000000000000000000000000 Inexact Rounded +precision: 34 +powx2417 power 10 0.3010299956639811952137388947244930 -> 2.000000000000000000000000000000000 Inexact Rounded +precision: 33 +powx2418 power 10 0.301029995663981195213738894724493 -> 2.00000000000000000000000000000000 Inexact Rounded +precision: 32 +powx2419 power 10 0.30102999566398119521373889472449 -> 2.0000000000000000000000000000000 Inexact Rounded +precision: 31 +powx2420 power 10 0.3010299956639811952137388947245 -> 2.000000000000000000000000000000 Inexact Rounded +precision: 30 +powx2421 power 10 0.301029995663981195213738894725 -> 2.00000000000000000000000000000 Inexact Rounded +precision: 29 +powx2422 power 10 0.30102999566398119521373889472 -> 2.0000000000000000000000000000 Inexact Rounded +precision: 28 +powx2423 power 10 0.3010299956639811952137388947 -> 2.000000000000000000000000000 Inexact Rounded +precision: 27 +powx2424 power 10 0.301029995663981195213738895 -> 2.00000000000000000000000000 Inexact Rounded +precision: 26 +powx2425 power 10 0.30102999566398119521373889 -> 2.0000000000000000000000000 Inexact Rounded +precision: 25 +powx2426 power 10 0.3010299956639811952137389 -> 2.000000000000000000000000 Inexact Rounded +precision: 24 +powx2427 power 10 0.301029995663981195213739 -> 2.00000000000000000000000 Inexact Rounded +precision: 23 +powx2428 power 10 0.30102999566398119521374 -> 2.0000000000000000000000 Inexact Rounded +precision: 22 +powx2429 power 10 0.3010299956639811952137 -> 2.000000000000000000000 Inexact Rounded +precision: 21 +powx2430 power 10 0.301029995663981195214 -> 2.00000000000000000000 Inexact Rounded +precision: 20 +powx2431 power 10 0.30102999566398119521 -> 2.0000000000000000000 Inexact Rounded +precision: 19 +powx2432 power 10 0.3010299956639811952 -> 2.000000000000000000 Inexact Rounded +precision: 18 +powx2433 power 10 0.301029995663981195 -> 2.00000000000000000 Inexact Rounded +precision: 17 +powx2434 power 10 0.30102999566398120 -> 2.0000000000000000 Inexact Rounded +precision: 16 +powx2435 power 10 0.3010299956639812 -> 2.000000000000000 Inexact Rounded +precision: 15 +powx2436 power 10 0.301029995663981 -> 2.00000000000000 Inexact Rounded +precision: 14 +powx2437 power 10 0.30102999566398 -> 2.0000000000000 Inexact Rounded +precision: 13 +powx2438 power 10 0.3010299956640 -> 2.000000000000 Inexact Rounded +precision: 12 +powx2439 power 10 0.301029995664 -> 2.00000000000 Inexact Rounded +precision: 11 +powx2440 power 10 0.30102999566 -> 2.0000000000 Inexact Rounded +precision: 10 +powx2441 power 10 0.3010299957 -> 2.000000000 Inexact Rounded +precision: 9 +powx2442 power 10 0.301029996 -> 2.00000000 Inexact Rounded +precision: 8 +powx2443 power 10 0.30103000 -> 2.0000000 Inexact Rounded +precision: 7 +powx2444 power 10 0.3010300 -> 2.000000 Inexact Rounded +precision: 6 +powx2445 power 10 0.301030 -> 2.00000 Inexact Rounded +precision: 5 +powx2446 power 10 0.30103 -> 2.0000 Inexact Rounded +precision: 4 +powx2447 power 10 0.3010 -> 2.000 Inexact Rounded +precision: 3 +powx2448 power 10 0.301 -> 2.00 Inexact Rounded +precision: 2 +powx2449 power 10 0.30 -> 2.0 Inexact Rounded +precision: 1 +powx2450 power 10 0.3 -> 2 Inexact Rounded + +maxExponent: 384 +minExponent: -383 +precision: 16 +rounding: half_even + +-- Close-to-e tests +precision: 34 +powx2500 power 10 0.4342944819032518276511289189166048 -> 2.718281828459045235360287471352661 Inexact Rounded +powx2501 power 10 0.4342944819032518276511289189166049 -> 2.718281828459045235360287471352661 Inexact Rounded +powx2502 power 10 0.4342944819032518276511289189166050 -> 2.718281828459045235360287471352662 Inexact Rounded +powx2503 power 10 0.4342944819032518276511289189166051 -> 2.718281828459045235360287471352663 Inexact Rounded +powx2504 power 10 0.4342944819032518276511289189166052 -> 2.718281828459045235360287471352663 Inexact Rounded + +-- e**e, 16->34 +powx2505 power 2.718281828459045 2.718281828459045 -> '15.15426224147925705633739513098219' Inexact Rounded + +-- Sequence around an integer +powx2512 power 10 2.9999999999999999999999999999999997 -> 999.9999999999999999999999999999993 Inexact Rounded +powx2513 power 10 2.9999999999999999999999999999999998 -> 999.9999999999999999999999999999995 Inexact Rounded +powx2514 power 10 2.9999999999999999999999999999999999 -> 999.9999999999999999999999999999998 Inexact Rounded +powx2515 power 10 3.0000000000000000000000000000000000 -> 1000 +powx2516 power 10 3.0000000000000000000000000000000001 -> 1000.000000000000000000000000000000 Inexact Rounded +powx2517 power 10 3.0000000000000000000000000000000002 -> 1000.000000000000000000000000000000 Inexact Rounded +powx2518 power 10 3.0000000000000000000000000000000003 -> 1000.000000000000000000000000000001 Inexact Rounded + +-- randomly generated tests +maxExponent: 384 +minExponent: -383 + +-- P=34, within 0-999 -- positive arg2 +Precision: 34 +powx3201 power 5.301557744131969249145904611290735 369.3175647984435534243813466380579 -> 3.427165676345688240023113326603960E+267 Inexact Rounded +powx3202 power 0.0000000000506875655819165973738225 21.93514102704466434121826965196878 -> 1.498169860033487321566659495340789E-226 Inexact Rounded +powx3203 power 97.88877680721519917858007810494043 5.159898445242793470476673109899554 -> 18705942904.43290467281449559427982 Inexact Rounded +powx3204 power 7.380441015594399747973924380493799 17.93614173904818313507525109033288 -> 3715757985820076.273336082702577274 Inexact Rounded +powx3205 power 2.045623627647350918819219169855040 1082.999652407430697958175966996254 -> 4.208806435006704867447150904279854E+336 Inexact Rounded +powx3206 power 0.0000000762582873112118926142955423 20.30534237055073996975203864170432 -> 2.967574278677013090697130349198877E-145 Inexact Rounded +powx3207 power 0.0000000000194091470907814855660535 14.71164213947722238856835440242911 -> 2.564391397469554735037158345963280E-158 Inexact Rounded +powx3208 power 0.0000000000509434185382818596853504 20.97051498204188277347203735421595 -> 1.420157372748083000927138678417272E-216 Inexact Rounded +powx3209 power 0.0005389217212073307301395750745119 43.96798225485747315858678755538971 -> 1.957850185781292007977898626137240E-144 Inexact Rounded +powx3210 power 498.5690105989136050444077447411198 128.1038813807243375878831104745803 -> 3.882212970903893127009102293596268E+345 Inexact Rounded +powx3211 power 0.0000000935428918637303954281938975 5.736933454863278597460091596496099 -> 4.733219644540496152403967823635195E-41 Inexact Rounded +powx3212 power 8.581586784734161309180363110126352 252.0229459968869784643374981477208 -> 1.907464842458674622356177850049873E+235 Inexact Rounded +powx3213 power 294.1005302951621709143320795278305 155.5466374141708615975111014663722 -> 9.251717033292072959166737280729728E+383 Inexact Rounded +powx3214 power 0.0000000041253343654396865855722090 19.00170974760425576247662125110472 -> 4.779566288553864405790921353593512E-160 Inexact Rounded +powx3215 power 0.0000000000046912257352141395184092 24.66089523148729269098773236636878 -> 4.205126874048597849476723538057527E-280 Inexact Rounded +powx3216 power 0.0000000000036796674296520639450494 22.09713956900694689234335912523078 -> 2.173081843837539818472071316420405E-253 Inexact Rounded +powx3217 power 9.659887100303037657934372148567685 277.3765665424320875993026404492216 -> 1.614974043145519382749740616665041E+273 Inexact Rounded +powx3218 power 0.0000083231310642229204398943076403 29.33123211782131466471359128190372 -> 1.013330439786660210757226597785328E-149 Inexact Rounded +powx3219 power 0.0938084859086450954956863725653664 262.6091918199905272837286784975012 -> 1.262802485286301066967555821509344E-270 Inexact Rounded +powx3220 power 8.194926977580900145696305910223304 184.3705133945546202012995485297248 -> 2.696353910907824016690021495828584E+168 Inexact Rounded +powx3221 power 72.39594594653085161522285114566120 168.7721909489321402152033939836725 -> 7.379858293630460043361584410795031E+313 Inexact Rounded +powx3222 power 0.0000000000003436856010144185445537 26.34329868961274988994452526178983 -> 4.585379573595865689605567720192768E-329 Inexact Rounded +powx3223 power 20.18365633762226550254542489492623 127.2099705237021350103678072707790 -> 1.020919629336979353690271762206060E+166 Inexact Rounded +powx3224 power 0.0000000553723990761530290129268131 8.157597566134754638015199501162405 -> 6.349030513396147480954474615067145E-60 Inexact Rounded +powx3225 power 0.0001028742674265840656614682618035 93.99842317306603797965470281716482 -> 1.455871110222736531854990397769940E-375 Inexact Rounded +powx3226 power 95.90195152775543876489746343266050 143.5992850002211509777720799352475 -> 3.881540015848530405189834366588567E+284 Inexact Rounded +powx3227 power 0.0000000000041783747057233878360333 12.14591167764993506821334760954430 -> 6.190998557456885985124592807383163E-139 Inexact Rounded +powx3228 power 0.5572830497086740798434917090018768 1001.921811263919522230330241349166 -> 3.871145158537170450093833881625838E-255 Inexact Rounded +powx3229 power 516.4754759779093954790813881333232 29.23812463126309057800793645336343 -> 2.110986192408878294012450052929185E+79 Inexact Rounded +powx3230 power 0.0000835892099464584776847299020706 27.64279992884843877453592659341588 -> 1.891535098905506689512376224943293E-113 Inexact Rounded +powx3231 power 72.45836577748571838139900165184955 166.2562890735032545091688015160084 -> 1.784091549041561516923092542939141E+309 Inexact Rounded +powx3232 power 305.1823317643335924007629563009032 83.01065159508472884219290136319623 -> 1.757493136164395229602456782779110E+206 Inexact Rounded +powx3233 power 7.108527102951713603542835791733786 145.7057852766236365450463428821948 -> 1.285934774113104362663619896550528E+124 Inexact Rounded +powx3234 power 6.471393503175464828149365697049824 64.11741937262455725284754171995720 -> 9.978990355881803195280027533011699E+51 Inexact Rounded +powx3235 power 39.72898094138459885662380866268385 239.9677288017447400786672779735168 -> 5.422218208517098335832848487375086E+383 Inexact Rounded +powx3236 power 0.0002865592332736973000183287329933 90.34733869590583787065642532641096 -> 8.293733126976212033209243257136796E-321 Inexact Rounded +powx3237 power 0.0000011343384394864811195077357936 1.926568285528399656789140809399396 -> 3.516055639378350146874261077470142E-12 Inexact Rounded +powx3238 power 0.0000000035321610295065299384889224 7.583861778824284092434085265265582 -> 7.970899823817369764381976286536230E-65 Inexact Rounded +powx3239 power 657.5028301569352677543770758346683 90.55778453811965116200206020172758 -> 1.522530898581564200655160665723268E+255 Inexact Rounded +powx3240 power 8.484756398325748879450577520251447 389.7468292476262478578280531222417 -> 8.595142803587368093392510310811218E+361 Inexact Rounded + +-- P=16, within 0-99 -- positive arg2 +Precision: 16 +powx3101 power 0.0000215524639223 48.37532522355252 -> 1.804663257287277E-226 Inexact Rounded +powx3102 power 00.80705856227999 2706.777535121391 -> 1.029625065876157E-252 Inexact Rounded +powx3103 power 3.445441676383689 428.5185892455830 -> 1.657401683096454E+230 Inexact Rounded +powx3104 power 0.0040158689495826 159.5725558816240 -> 4.255743665762492E-383 Inexact Rounded +powx3105 power 0.0000841553281215 38.32504413453944 -> 6.738653902512052E-157 Inexact Rounded +powx3106 power 0.7322610252571353 502.1254457674118 -> 1.109978126985943E-68 Inexact Rounded +powx3107 power 10.75052532144880 67.34180604734781 -> 2.873015019470189E+69 Inexact Rounded +powx3108 power 26.20425952945617 104.6002671186488 -> 2.301859355777030E+148 Inexact Rounded +powx3109 power 0.0000055737473850 31.16285859005424 -> 1.883348470100446E-164 Inexact Rounded +powx3110 power 61.06096011360700 10.93608439088726 -> 3.382686473028249E+19 Inexact Rounded +powx3111 power 9.340880853257137 179.9094938131726 -> 3.819299795937696E+174 Inexact Rounded +powx3112 power 0.0000050767371756 72.03346394186741 -> 4.216236691569869E-382 Inexact Rounded +powx3113 power 6.838478807860596 47.49665590602285 -> 4.547621630099203E+39 Inexact Rounded +powx3114 power 0.1299324346439081 397.7440523576938 -> 3.065047705553981E-353 Inexact Rounded +powx3115 power 0.0003418047034264 20.00516791512018 -> 4.546189665380487E-70 Inexact Rounded +powx3116 power 0.0001276899611715 78.12968287355703 -> 5.960217405063995E-305 Inexact Rounded +powx3117 power 25.93160588180509 252.6245071004620 -> 1.472171597589146E+357 Inexact Rounded +powx3118 power 35.47516857763178 86.14723037360925 -> 3.324299908481125E+133 Inexact Rounded +powx3119 power 0.0000048171086721 43.31965603038666 -> 4.572331516616228E-231 Inexact Rounded +powx3120 power 17.97652681097851 144.4684576550292 -> 1.842509906097860E+181 Inexact Rounded +powx3121 power 3.622765141518729 305.1948680344950 -> 4.132320967578704E+170 Inexact Rounded +powx3122 power 0.0080959002453519 143.9899444945627 -> 6.474627812947047E-302 Inexact Rounded +powx3123 power 9.841699927276571 299.2466668837188 -> 1.489097656208736E+297 Inexact Rounded +powx3124 power 0.0786659206232355 347.4750796962570 -> 2.05764809646925E-384 Inexact Rounded Underflow Subnormal +powx3125 power 0.0000084459792645 52.47348690745487 -> 6.076251876516942E-267 Inexact Rounded +powx3126 power 27.86589909967504 191.7296537102283 -> 1.157064112989386E+277 Inexact Rounded +powx3127 power 0.0000419907937234 58.44957702730767 -> 1.496950672075162E-256 Inexact Rounded +powx3128 power 0.0000664977739382 80.06749213261876 -> 3.488517620107875E-335 Inexact Rounded +powx3129 power 58.49554484886656 125.8480768373499 -> 2.449089862146640E+222 Inexact Rounded +powx3130 power 15.02820060024449 212.3527988973338 -> 8.307913932682067E+249 Inexact Rounded +powx3131 power 0.0002650089942992 30.92173123678761 -> 2.517827664836147E-111 Inexact Rounded +powx3132 power 0.0007342977426578 69.49168880741123 -> 1.600168665674440E-218 Inexact Rounded +powx3133 power 0.0063816068650629 150.1400094183812 -> 2.705057295799001E-330 Inexact Rounded +powx3134 power 9.912921122728791 297.8274013633411 -> 4.967624993438900E+296 Inexact Rounded +powx3135 power 1.988603563989245 768.4862967922182 -> 2.692842474899596E+229 Inexact Rounded +powx3136 power 8.418014519517691 164.2431359980725 -> 9.106211585888836E+151 Inexact Rounded +powx3137 power 6.068823604450686 120.2955212365837 -> 1.599431918105982E+94 Inexact Rounded +powx3138 power 56.90062738303850 54.90468294683645 -> 2.312839177902428E+96 Inexact Rounded +powx3139 power 5.710905139750871 73.44608752962156 -> 3.775876053709929E+55 Inexact Rounded +powx3140 power 0.0000017446761203 1.223981492228899 -> 8.952936595465635E-8 Inexact Rounded + +-- P=7, within 0-9 -- positive arg2 +Precision: 7 +powx3001 power 8.738689 55.96523 -> 4.878180E+52 Inexact Rounded +powx3002 power 0.0404763 147.4965 -> 3.689722E-206 Inexact Rounded +powx3003 power 0.0604232 76.69778 -> 3.319183E-94 Inexact Rounded +powx3004 power 0.0058855 107.5018 -> 1.768875E-240 Inexact Rounded +powx3005 power 2.058302 1173.050 -> 5.778899E+367 Inexact Rounded +powx3006 power 0.0056998 85.70157 -> 4.716783E-193 Inexact Rounded +powx3007 power 0.8169297 3693.537 -> 4.475962E-325 Inexact Rounded +powx3008 power 0.2810153 659.9568 -> 1.533177E-364 Inexact Rounded +powx3009 power 4.617478 15.68308 -> 2.629748E+10 Inexact Rounded +powx3010 power 0.0296418 244.2302 -> 6.207949E-374 Inexact Rounded +powx3011 power 0.0036456 127.9987 -> 8.120891E-313 Inexact Rounded +powx3012 power 0.5012813 577.5418 -> 6.088802E-174 Inexact Rounded +powx3013 power 0.0033275 119.9800 -> 5.055049E-298 Inexact Rounded +powx3014 power 0.0037652 111.7092 -> 1.560351E-271 Inexact Rounded +powx3015 power 0.6463252 239.0568 -> 4.864564E-46 Inexact Rounded +powx3016 power 4.784378 475.0521 -> 8.964460E+322 Inexact Rounded +powx3017 power 4.610305 563.1791 -> 6.290298E+373 Inexact Rounded +powx3018 power 0.0175167 80.52208 -> 3.623472E-142 Inexact Rounded +powx3019 power 5.238307 356.7944 -> 4.011461E+256 Inexact Rounded +powx3020 power 0.0003527 96.26347 -> 4.377932E-333 Inexact Rounded +powx3021 power 0.0015155 136.0516 -> 2.57113E-384 Inexact Rounded Underflow Subnormal +powx3022 power 5.753573 273.2340 -> 4.373184E+207 Inexact Rounded +powx3023 power 7.778665 332.7917 -> 3.060640E+296 Inexact Rounded +powx3024 power 1.432479 2046.064 -> 2.325829E+319 Inexact Rounded +powx3025 power 5.610516 136.4563 -> 1.607502E+102 Inexact Rounded +powx3026 power 0.0050697 137.4513 -> 3.522315E-316 Inexact Rounded +powx3027 power 5.678737 85.16253 -> 1.713909E+64 Inexact Rounded +powx3028 power 0.0816167 236.1973 -> 9.228802E-258 Inexact Rounded +powx3029 power 0.2602805 562.0157 -> 2.944556E-329 Inexact Rounded +powx3030 power 0.0080936 24.25367 -> 1.839755E-51 Inexact Rounded +powx3031 power 4.092016 82.94603 -> 5.724948E+50 Inexact Rounded +powx3032 power 0.0078255 7.204184 -> 6.675342E-16 Inexact Rounded +powx3033 power 0.9917693 29846.44 -> 7.430177E-108 Inexact Rounded +powx3034 power 1.610380 301.2467 -> 2.170142E+62 Inexact Rounded +powx3035 power 0.0588236 212.1097 -> 1.023196E-261 Inexact Rounded +powx3036 power 2.498069 531.4647 -> 2.054561E+211 Inexact Rounded +powx3037 power 9.964342 326.5438 -> 1.089452E+326 Inexact Rounded +powx3038 power 0.0820626 268.8718 -> 1.107350E-292 Inexact Rounded +powx3039 power 6.176486 360.7779 -> 1.914449E+285 Inexact Rounded +powx3040 power 4.206363 16.17288 -> 1.231314E+10 Inexact Rounded + +-- P=34, within 0-999 -- negative arg2 +Precision: 34 +powx3701 power 376.0915270000109486633402827007902 -35.69822349904102131649243701958463 -> 1.165722831225506457828653413200143E-92 Inexact Rounded +powx3702 power 0.0000000503747440074613191665845314 -9.520308341497979093021813571450575 -> 3.000432478861883953977971226770410E+69 Inexact Rounded +powx3703 power 290.6858731495339778337953407938308 -118.5459048597789693292455673428367 -> 9.357969047113989238392527565200302E-293 Inexact Rounded +powx3704 power 4.598864607620052062908700928454182 -299.8323667698931125720218537483753 -> 2.069641269855413539579128114448478E-199 Inexact Rounded +powx3705 power 2.556952676986830645708349254938903 -425.1755373251941383147998924703593 -> 4.428799777833598654260883861514638E-174 Inexact Rounded +powx3706 power 0.0000005656198763404221986640610118 -32.83361380678301321230028730075315 -> 1.340270622401829145968477601029251E+205 Inexact Rounded +powx3707 power 012.4841978642452960750801410372125 -214.3734291828712962809866663321921 -> 9.319857751170603140459057535971202E-236 Inexact Rounded +powx3708 power 0.0000000056041586148066919174315551 -37.21129049213858341528033343116533 -> 1.118345010652454313186702341873169E+307 Inexact Rounded +powx3709 power 0.0694569218941833767199998804202152 -8.697509072368973932501239815677732 -> 11862866995.51026489032838174290271 Inexact Rounded +powx3710 power 6.380984024259450398729243522354144 -451.0635696889193561457985486366827 -> 8.800353109387322474809325670314330E-364 Inexact Rounded +powx3711 power 786.0264840756809048288007204917801 -43.09935384678762773057342161718540 -> 1.616324183365644133979585419925934E-125 Inexact Rounded +powx3712 power 96.07836427113204744101287948445130 -185.1414572546330024388914720271876 -> 8.586320815218383004023264980018610E-368 Inexact Rounded +powx3713 power 0.0000000002332189796855870659792406 -5.779561613164628076880609893753327 -> 4.678450775876385793618570483345066E+55 Inexact Rounded +powx3714 power 0.7254146672024602242369943237968857 -2115.512891397828615710130092245691 -> 8.539080958041689288202111403102495E+294 Inexact Rounded +powx3715 power 0.0017380543649702864796144008592137 -6.307668017761022788220578633538713 -> 256309141459075651.2275798017695017 Inexact Rounded +powx3716 power 05.29498758952276908267649116142379 -287.3233896734103442991981056134167 -> 1.039130027847489364009368608104291E-208 Inexact Rounded +powx3717 power 15.64403593865932622003462779104178 -110.5296633358063267478609032002475 -> 9.750540276026524527375125980296142E-133 Inexact Rounded +powx3718 power 89.69639006761571087634945077373508 -181.3209914139357665609268339422627 -> 8.335034232277762924539395632025281E-355 Inexact Rounded +powx3719 power 6.974087483731006359914914110135058 -174.6815625746710345173615508179842 -> 4.553072265122011176641590109568031E-148 Inexact Rounded +powx3720 power 0.0034393024010554821130553772681993 -93.60931598413919272595497100497364 -> 4.067468855817145539589988349449394E+230 Inexact Rounded +powx3721 power 63.32834072300379155053737260965633 -168.3926799435088324825751446957616 -> 4.207907835462640471617519501741094E-304 Inexact Rounded +powx3722 power 00.00216088174206276369011255907785 -70.12279562855442784757874508991013 -> 8.000657143378187029609343435067057E+186 Inexact Rounded +powx3723 power 934.5957982703545893572134393004375 -102.2287735565878252484031426026726 -> 2.073813769209257617246544424827240E-304 Inexact Rounded +powx3724 power 107.9116792558793921873995885441177 -44.11941092260869786313838181499158 -> 2.005476533631183268912552168759595E-90 Inexact Rounded +powx3725 power 0.0000000000188049827381428191769262 -19.32118917192242027966847501724073 -> 1.713174297100918857053338286389034E+207 Inexact Rounded +powx3726 power 614.9820907366248142166636259027728 -4.069913257030791586645250035698123 -> 4.462432572576935752713876293746717E-12 Inexact Rounded +powx3727 power 752.0655175769182096165651274049422 -22.59292060348797472013598378334370 -> 1.039881526694635205040192531504131E-65 Inexact Rounded +powx3728 power 72.20446632047659449616175456059013 -175.4705356401853924020842356605072 -> 7.529540175791582421966947814549028E-327 Inexact Rounded +powx3729 power 518.8346486600403405764055847937416 -65.87320268592761588756963215588232 -> 1.420189426992170936958891180073151E-179 Inexact Rounded +powx3730 power 3.457164372003960576453458502270716 -440.3201118177861273814529713443698 -> 6.176418595751201287186292664257369E-238 Inexact Rounded +powx3731 power 7.908352793344189720739467675503991 -298.6646112894719680394152664740255 -> 5.935857120229147638104675057695125E-269 Inexact Rounded +powx3732 power 0.0000004297399403788595027926075086 -22.66504617185071293588817501468339 -> 2.012270405520600820469665145636204E+144 Inexact Rounded +powx3733 power 0.0000008592124097322966354868716443 -9.913109586558030204789520190180906 -> 1.354958763843310237046818832755215E+60 Inexact Rounded +powx3734 power 161.4806080561258105880907470989925 -70.72907837434814261716311990271578 -> 6.632555003698945544941329872901929E-157 Inexact Rounded +powx3735 power 0.0000000090669568624173832705631918 -36.53759624613665940127058439106640 -> 7.161808401023414735428130112941559E+293 Inexact Rounded +powx3736 power 0.0000000000029440295978365709342752 -1.297354238738921988884421117731562 -> 911731060579291.7661267358872917380 Inexact Rounded +powx3737 power 21.37477220144832172175460425143692 -76.95949933640539226475686997477889 -> 4.481741242418091914011962399912885E-103 Inexact Rounded +powx3738 power 0.0000000000186657798201636342150903 -20.18296240350678245567049161730909 -> 3.483954007114900406906338526575672E+216 Inexact Rounded +powx3739 power 0.0006522464792960191985996959126792 -80.03762491483514679886504099194414 -> 9.266548513614215557228467517053035E+254 Inexact Rounded +powx3740 power 0.0000000032851343694200568966168055 -21.53462116926375512242403160008026 -> 4.873201679668455240861376213601189E+182 Inexact Rounded + +-- P=16, within 0-99 -- negative arg2 +Precision: 16 +powx3601 power 0.0000151338748474 -40.84655618364688 -> 7.628470824137755E+196 Inexact Rounded +powx3602 power 0.1542771848654862 -435.8830009466800 -> 6.389817177800744E+353 Inexact Rounded +powx3603 power 48.28477749367364 -218.5929209902050 -> 8.531049532576154E-369 Inexact Rounded +powx3604 power 7.960775891584911 -12.78113732182505 -> 3.053270889769488E-12 Inexact Rounded +powx3605 power 0.9430340651863058 -9010.470056913748 -> 3.313374654923807E+229 Inexact Rounded +powx3606 power 0.0000202661501602 -65.57915207383306 -> 5.997379176536464E+307 Inexact Rounded +powx3607 power 04.33007440798390 -232.0476834666588 -> 2.007827183010456E-148 Inexact Rounded +powx3608 power 0.0000141944643914 -11.32407921958717 -> 7.902934485074846E+54 Inexact Rounded +powx3609 power 0.0000021977758261 -53.53706138253307 -> 8.195631772317815E+302 Inexact Rounded +powx3610 power 39.51297655474188 -19.40370976012326 -> 1.040699608072659E-31 Inexact Rounded +powx3611 power 38.71210232488775 -66.58341618227921 -> 1.886855066146495E-106 Inexact Rounded +powx3612 power 0.0000804235229062 -6.715207948992859 -> 3.134757864389333E+27 Inexact Rounded +powx3613 power 0.0000073547092399 -11.27725685719934 -> 7.781428390953695E+57 Inexact Rounded +powx3614 power 52.72181272599316 -186.1422311607435 -> 2.916601998744177E-321 Inexact Rounded +powx3615 power 0.0969519963083306 -280.8220862151369 -> 3.955906885970987E+284 Inexact Rounded +powx3616 power 94.07263302150081 -148.2031146071230 -> 3.361958990752490E-293 Inexact Rounded +powx3617 power 85.80286965053704 -90.21453695813759 -> 3.715602429645798E-175 Inexact Rounded +powx3618 power 03.52699858152259 -492.0414362539196 -> 4.507309220081092E-270 Inexact Rounded +powx3619 power 0.0508278086396068 -181.0871731572167 -> 2.034428013017949E+234 Inexact Rounded +powx3620 power 0.395576740303172 -915.5524507432392 -> 5.706585187437578E+368 Inexact Rounded +powx3621 power 38.06105826789202 -49.75913753435335 -> 2.273188991431738E-79 Inexact Rounded +powx3622 power 0.0003656748910646 -73.28988491310354 -> 7.768936940568763E+251 Inexact Rounded +powx3623 power 0.0000006373551809 -51.30825234200690 -> 7.697618167701985E+317 Inexact Rounded +powx3624 power 82.41729920673856 -35.73319631625699 -> 3.424042354585529E-69 Inexact Rounded +powx3625 power 0.7845821453127670 -971.4982028897663 -> 2.283415527661089E+102 Inexact Rounded +powx3626 power 4.840983673433497 -182.3730452370515 -> 1.220591407927770E-125 Inexact Rounded +powx3627 power 0.0000006137592139 -2.122139474431484 -> 15231217034839.29 Inexact Rounded +powx3628 power 0.0003657962862984 -35.97993782448099 -> 4.512701319250839E+123 Inexact Rounded +powx3629 power 40.93693004443150 -165.1362408792997 -> 6.044276411057239E-267 Inexact Rounded +powx3630 power 0.2941552583028898 -17.41046264945892 -> 1787833103.503346 Inexact Rounded +powx3631 power 63.99335135369977 -69.92417205168579 -> 5.099359804872509E-127 Inexact Rounded +powx3632 power 0.0000657924467388 -89.14497293588313 -> 6.145878266688521E+372 Inexact Rounded +powx3633 power 11.35071250339147 -323.3705865614542 -> 6.863626248766775E-342 Inexact Rounded +powx3634 power 23.88024718470895 -277.7117513329510 -> 2.006441422612815E-383 Inexact Rounded +powx3635 power 0.0000009111939914 -58.51782946929182 -> 2.954352883996773E+353 Inexact Rounded +powx3636 power 0.0000878179048782 -75.81060420238669 -> 3.306878455207585E+307 Inexact Rounded +powx3637 power 07.39190564273779 -287.5047307244636 -> 1.692080354659805E-250 Inexact Rounded +powx3638 power 0.0000298310819799 -1.844740377759355 -> 222874718.7238888 Inexact Rounded +powx3639 power 0.0000006412929384 -28.24850078229290 -> 8.737164230666529E+174 Inexact Rounded +powx3640 power 0.0000010202965998 -47.17573701956498 -> 4.392845306049341E+282 Inexact Rounded + +-- P=7, within 0-9 -- negative arg2 +Precision: 7 +powx3501 power 0.326324 -71.96509 -> 1.000673E+35 Inexact Rounded +powx3502 power 0.0017635 -0.7186967 -> 95.28419 Inexact Rounded +powx3503 power 8.564155 -253.0899 -> 8.850512E-237 Inexact Rounded +powx3504 power 8.987272 -2.155789 -> 0.008793859 Inexact Rounded +powx3505 power 9.604856 -139.9630 -> 3.073492E-138 Inexact Rounded +powx3506 power 0.8472919 -2539.085 -> 5.372686E+182 Inexact Rounded +powx3507 power 5.312329 -60.32965 -> 1.753121E-44 Inexact Rounded +powx3508 power 0.0338294 -100.5440 -> 7.423939E+147 Inexact Rounded +powx3509 power 0.0017777 -130.8583 -> 7.565629E+359 Inexact Rounded +powx3510 power 8.016154 -405.5689 -> 2.395977E-367 Inexact Rounded +powx3511 power 5.016570 -327.8906 -> 2.203784E-230 Inexact Rounded +powx3512 power 0.8161743 -744.5276 -> 4.786899E+65 Inexact Rounded +powx3513 power 0.0666343 -164.7320 -> 5.951240E+193 Inexact Rounded +powx3514 power 0.0803966 -202.2666 -> 2.715512E+221 Inexact Rounded +powx3515 power 0.0014752 -12.55547 -> 3.518905E+35 Inexact Rounded +powx3516 power 9.737565 -14.69615 -> 2.975672E-15 Inexact Rounded +powx3517 power 0.6634172 -152.7308 -> 1.654458E+27 Inexact Rounded +powx3518 power 0.0009337 -33.32939 -> 9.575039E+100 Inexact Rounded +powx3519 power 8.679922 -224.4194 -> 2.392446E-211 Inexact Rounded +powx3520 power 7.390494 -161.9483 -> 2.088375E-141 Inexact Rounded +powx3521 power 0.4631489 -417.1673 -> 2.821106E+139 Inexact Rounded +powx3522 power 0.0095471 -7.677458 -> 3.231855E+15 Inexact Rounded +powx3523 power 6.566339 -176.1867 -> 9.965633E-145 Inexact Rounded +powx3524 power 2.696128 -26.15501 -> 5.419731E-12 Inexact Rounded +powx3525 power 0.4464366 -852.1893 -> 2.957725E+298 Inexact Rounded +powx3526 power 0.4772006 -921.4111 -> 1.118105E+296 Inexact Rounded +powx3527 power 8.923696 -359.2211 -> 3.501573E-342 Inexact Rounded +powx3528 power 0.0018008 -66.91252 -> 4.402718E+183 Inexact Rounded +powx3529 power 0.0811964 -92.83278 -> 1.701111E+101 Inexact Rounded +powx3530 power 0.0711219 -58.94347 -> 4.644148E+67 Inexact Rounded +powx3531 power 7.958121 -50.66123 -> 2.311161E-46 Inexact Rounded +powx3532 power 6.106466 -81.83610 -> 4.943285E-65 Inexact Rounded +powx3533 power 4.557634 -129.5268 -> 4.737917E-86 Inexact Rounded +powx3534 power 0.0027348 -9.180135 -> 3.383524E+23 Inexact Rounded +powx3535 power 0.0083924 -46.24016 -> 9.996212E+95 Inexact Rounded +powx3536 power 2.138523 -47.25897 -> 2.507009E-16 Inexact Rounded +powx3537 power 1.626728 -1573.830 -> 2.668117E-333 Inexact Rounded +powx3538 power 0.082615 -164.5842 -> 1.717882E+178 Inexact Rounded +powx3539 power 7.636003 -363.6763 -> 8.366174E-322 Inexact Rounded +powx3540 power 0.0021481 -138.0065 -> 1.562505E+368 Inexact Rounded + + +-- Invalid operations due to restrictions +-- [next two probably skipped by most test harnesses] +precision: 100000000 +powx4001 power 1 1.1 -> NaN Invalid_context +precision: 99999999 +powx4002 power 1 1.1 -> NaN Invalid_context + +precision: 9 +maxExponent: 1000000 +minExponent: -999999 +powx4003 power 1 1.1 -> NaN Invalid_context +maxExponent: 999999 +minExponent: -999999 +powx4004 power 1 1.1 -> 1.00000000 Inexact Rounded +maxExponent: 999999 +minExponent: -1000000 +powx4005 power 1 1.1 -> NaN Invalid_context +maxExponent: 999999 +minExponent: -999998 +powx4006 power 1 1.1 -> 1.00000000 Inexact Rounded + +-- operand range violations +powx4007 power 1 1.1E+999999 -> 1 +powx4008 power 1 1.1E+1000000 -> NaN Invalid_operation +powx4009 power 1.1E+999999 1.1 -> Infinity Overflow Inexact Rounded +powx4010 power 1.1E+1000000 1.1 -> NaN Invalid_operation +powx4011 power 1 1.1E-1999997 -> 1.00000000 Inexact Rounded +powx4012 power 1 1.1E-1999998 -> NaN Invalid_operation +powx4013 power 1.1E-1999997 1.1 -> 0E-1000006 Underflow Inexact Rounded Clamped Subnormal +powx4014 power 1.1E-1999998 1.1 -> NaN Invalid_operation + +-- rounding modes -- power is sensitive +precision: 7 +maxExponent: 99 +minExponent: -99 + +-- 0.7 ** 3.3 => 0.30819354053418943822 +-- 0.7 ** 3.4 => 0.29739477638272533854 +-- -1.2 ** 17 => -22.18611106740436992 +-- -1.3 ** 17 => -86.50415919381337933 +-- 0.5 ** 11 => 0.00048828125 +-- 3.15 ** 3 => 31.255875 + +rounding: up +powx4100 power 0.7 3.3 -> 0.3081936 Inexact Rounded +powx4101 power 0.7 3.4 -> 0.2973948 Inexact Rounded +powx4102 power -1.2 17 -> -22.18612 Inexact Rounded +powx4103 power -1.3 17 -> -86.50416 Inexact Rounded +powx4104 power 17 81.27115 -> 9.999974E+99 Inexact Rounded +powx4105 power 17 81.27116 -> Infinity Overflow Inexact Rounded + +rounding: down +powx4120 power 0.7 3.3 -> 0.3081935 Inexact Rounded +powx4121 power 0.7 3.4 -> 0.2973947 Inexact Rounded +powx4122 power -1.2 17 -> -22.18611 Inexact Rounded +powx4123 power -1.3 17 -> -86.50415 Inexact Rounded +powx4124 power 17 81.27115 -> 9.999973E+99 Inexact Rounded +powx4125 power 17 81.27116 -> 9.999999E+99 Overflow Inexact Rounded + +rounding: floor +powx4140 power 0.7 3.3 -> 0.3081935 Inexact Rounded +powx4141 power 0.7 3.4 -> 0.2973947 Inexact Rounded +powx4142 power -1.2 17 -> -22.18612 Inexact Rounded +powx4143 power -1.3 17 -> -86.50416 Inexact Rounded +powx4144 power 17 81.27115 -> 9.999973E+99 Inexact Rounded +powx4145 power 17 81.27116 -> 9.999999E+99 Overflow Inexact Rounded + +rounding: ceiling +powx4160 power 0.7 3.3 -> 0.3081936 Inexact Rounded +powx4161 power 0.7 3.4 -> 0.2973948 Inexact Rounded +powx4162 power -1.2 17 -> -22.18611 Inexact Rounded +powx4163 power -1.3 17 -> -86.50415 Inexact Rounded +powx4164 power 17 81.27115 -> 9.999974E+99 Inexact Rounded +powx4165 power 17 81.27116 -> Infinity Overflow Inexact Rounded + +rounding: half_up +powx4180 power 0.7 3.3 -> 0.3081935 Inexact Rounded +powx4181 power 0.7 3.4 -> 0.2973948 Inexact Rounded +powx4182 power -1.2 17 -> -22.18611 Inexact Rounded +powx4183 power -1.3 17 -> -86.50416 Inexact Rounded +powx4184 power 0.5 11 -> 0.0004882813 Inexact Rounded +powx4185 power 3.15 3 -> 31.25588 Inexact Rounded +powx4186 power 17 81.27115 -> 9.999974E+99 Inexact Rounded +powx4187 power 17 81.27116 -> Infinity Overflow Inexact Rounded + +rounding: half_even +powx4200 power 0.7 3.3 -> 0.3081935 Inexact Rounded +powx4201 power 0.7 3.4 -> 0.2973948 Inexact Rounded +powx4202 power -1.2 17 -> -22.18611 Inexact Rounded +powx4203 power -1.3 17 -> -86.50416 Inexact Rounded +powx4204 power 0.5 11 -> 0.0004882812 Inexact Rounded +powx4205 power 3.15 3 -> 31.25588 Inexact Rounded +powx4206 power 17 81.27115 -> 9.999974E+99 Inexact Rounded +powx4207 power 17 81.27116 -> Infinity Overflow Inexact Rounded + +rounding: half_down +powx4220 power 0.7 3.3 -> 0.3081935 Inexact Rounded +powx4221 power 0.7 3.4 -> 0.2973948 Inexact Rounded +powx4222 power -1.2 17 -> -22.18611 Inexact Rounded +powx4223 power -1.3 17 -> -86.50416 Inexact Rounded +powx4224 power 0.5 11 -> 0.0004882812 Inexact Rounded +powx4225 power 3.15 3 -> 31.25587 Inexact Rounded +powx4226 power -3.15 3 -> -31.25587 Inexact Rounded +powx4227 power 17 81.27115 -> 9.999974E+99 Inexact Rounded +powx4228 power 17 81.27116 -> Infinity Overflow Inexact Rounded + + +-- more rounding tests as per Ilan Nehama's suggestions & analysis +-- these are likely to show > 0.5 ulp error for very small powers +precision: 7 +maxExponent: 96 +minExponent: -95 + +-- For x=nextfp(1)=1.00..001 (where the number of 0s is precision-2) +-- power(x,y)=x when the rounding is up (e.g., toward_pos_inf or +-- ceil) for any y in (0,1]. +rounding: ceiling +powx4301 power 1.000001 0 -> 1 +-- The next test should be skipped for decNumber +powx4302 power 1.000001 1e-101 -> 1.000001 Inexact Rounded +-- The next test should be skipped for decNumber +powx4303 power 1.000001 1e-95 -> 1.000001 Inexact Rounded +powx4304 power 1.000001 1e-10 -> 1.000001 Inexact Rounded +powx4305 power 1.000001 0.1 -> 1.000001 Inexact Rounded +powx4306 power 1.000001 0.1234567 -> 1.000001 Inexact Rounded +powx4307 power 1.000001 0.7 -> 1.000001 Inexact Rounded +powx4308 power 1.000001 0.9999999 -> 1.000001 Inexact Rounded +powx4309 power 1.000001 1.000000 -> 1.000001 +-- power(x,y)=1 when the rounding is down (e.g. toward_zero or +-- floor) for any y in [0,1). +rounding: floor +powx4321 power 1.000001 0 -> 1 +powx4322 power 1.000001 1e-101 -> 1.000000 Inexact Rounded +powx4323 power 1.000001 1e-95 -> 1.000000 Inexact Rounded +powx4324 power 1.000001 1e-10 -> 1.000000 Inexact Rounded +powx4325 power 1.000001 0.1 -> 1.000000 Inexact Rounded +powx4326 power 1.000001 0.1234567 -> 1.000000 Inexact Rounded +powx4327 power 1.000001 0.7 -> 1.000000 Inexact Rounded +powx4328 power 1.000001 0.9999999 -> 1.000000 Inexact Rounded +powx4329 power 1.000001 1.000000 -> 1.000001 + +-- For x=prevfp(1)=0.99..99 (where the number of 9s is precision) +-- power(x,y)=x when the rounding is down for any y in (0,1]. +rounding: floor +powx4341 power 0.9999999 0 -> 1 +-- The next test should be skipped for decNumber +powx4342 power 0.9999999 1e-101 -> 0.9999999 Inexact Rounded +-- The next test should be skipped for decNumber +powx4343 power 0.9999999 1e-95 -> 0.9999999 Inexact Rounded +powx4344 power 0.9999999 1e-10 -> 0.9999999 Inexact Rounded +powx4345 power 0.9999999 0.1 -> 0.9999999 Inexact Rounded +powx4346 power 0.9999999 0.1234567 -> 0.9999999 Inexact Rounded +powx4347 power 0.9999999 0.7 -> 0.9999999 Inexact Rounded +powx4348 power 0.9999999 0.9999999 -> 0.9999999 Inexact Rounded +powx4349 power 0.9999999 1.000000 -> 0.9999999 +-- power(x,y)=1 when the rounding is up for any y in (0,1]. +rounding: ceiling +powx4361 power 0.9999999 0 -> 1 +powx4362 power 0.9999999 1e-101 -> 1.000000 Inexact Rounded +powx4363 power 0.9999999 1e-95 -> 1.000000 Inexact Rounded +powx4364 power 0.9999999 1e-10 -> 1.000000 Inexact Rounded +powx4365 power 0.9999999 0.1 -> 1.000000 Inexact Rounded +powx4366 power 0.9999999 0.1234567 -> 1.000000 Inexact Rounded +powx4367 power 0.9999999 0.7 -> 1.000000 Inexact Rounded +powx4368 power 0.9999999 0.9999999 -> 1.000000 Inexact Rounded +powx4369 power 0.9999999 1.000000 -> 0.9999999 + +-- For x=nextfp(0) +-- power(x,y)=0 when the rounding is down for any y larger than 1. +rounding: floor +powx4382 power 1e-101 0 -> 1 +powx4383 power 1e-101 0.9999999 -> 1E-101 Underflow Subnormal Inexact Rounded +powx4384 power 1e-101 1.000000 -> 1E-101 Subnormal +powx4385 power 1e-101 1.000001 -> 0E-101 Underflow Subnormal Inexact Rounded Clamped +powx4386 power 1e-101 2.000000 -> 0E-101 Underflow Subnormal Inexact Rounded Clamped Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/quantize.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/quantize.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/quantize.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- quantize.decTest -- decimal quantize operation -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,11 +17,12 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- Most of the tests here assume a "regular pattern", where the -- sign and coefficient are +1. -- 2004.03.15 Underflow for quantize is suppressed +-- 2005.06.08 More extensive tests for 'does not fit' extended: 1 precision: 9 @@ -123,10 +124,6 @@ quax124 quantize 1.05 1e-3 -> 1.050 quax125 quantize 1.05 1e-2 -> 1.05 quax126 quantize 1.05 1e-1 -> 1.1 Inexact Rounded -quax127 quantize 1.05 1e0 -> 1 Inexact Rounded -quax128 quantize 1.05 1e-3 -> 1.050 -quax129 quantize 1.05 1e-2 -> 1.05 -quax130 quantize 1.05 1e-1 -> 1.1 Inexact Rounded quax131 quantize 1.05 1e0 -> 1 Inexact Rounded quax132 quantize 1.06 1e-3 -> 1.060 quax133 quantize 1.06 1e-2 -> 1.06 @@ -435,6 +432,102 @@ quax472 quantize 9.999E-15 1e0 -> 0 Inexact Rounded quax473 quantize 9.999E-15 1e1 -> 0E+1 Inexact Rounded +precision: 7 +quax900 quantize 9.999E-15 1e-22 -> NaN Invalid_operation +quax901 quantize 9.999E-15 1e-21 -> 9.999000E-15 +quax902 quantize 9.999E-15 1e-20 -> 9.99900E-15 +quax903 quantize 9.999E-15 1e-19 -> 9.9990E-15 +quax904 quantize 9.999E-15 1e-18 -> 9.999E-15 +quax905 quantize 9.999E-15 1e-17 -> 1.000E-14 Inexact Rounded +quax906 quantize 9.999E-15 1e-16 -> 1.00E-14 Inexact Rounded +quax907 quantize 9.999E-15 1e-15 -> 1.0E-14 Inexact Rounded +quax908 quantize 9.999E-15 1e-14 -> 1E-14 Inexact Rounded +quax909 quantize 9.999E-15 1e-13 -> 0E-13 Inexact Rounded +quax910 quantize 9.999E-15 1e-12 -> 0E-12 Inexact Rounded +quax911 quantize 9.999E-15 1e-11 -> 0E-11 Inexact Rounded +quax912 quantize 9.999E-15 1e-10 -> 0E-10 Inexact Rounded +quax913 quantize 9.999E-15 1e-9 -> 0E-9 Inexact Rounded +quax914 quantize 9.999E-15 1e-8 -> 0E-8 Inexact Rounded +quax915 quantize 9.999E-15 1e-7 -> 0E-7 Inexact Rounded +quax916 quantize 9.999E-15 1e-6 -> 0.000000 Inexact Rounded +quax917 quantize 9.999E-15 1e-5 -> 0.00000 Inexact Rounded +quax918 quantize 9.999E-15 1e-4 -> 0.0000 Inexact Rounded +quax919 quantize 9.999E-15 1e-3 -> 0.000 Inexact Rounded +quax920 quantize 9.999E-15 1e-2 -> 0.00 Inexact Rounded +quax921 quantize 9.999E-15 1e-1 -> 0.0 Inexact Rounded +quax922 quantize 9.999E-15 1e0 -> 0 Inexact Rounded +quax923 quantize 9.999E-15 1e1 -> 0E+1 Inexact Rounded + +precision: 6 +quax930 quantize 9.999E-15 1e-22 -> NaN Invalid_operation +quax931 quantize 9.999E-15 1e-21 -> NaN Invalid_operation +quax932 quantize 9.999E-15 1e-20 -> 9.99900E-15 +quax933 quantize 9.999E-15 1e-19 -> 9.9990E-15 +quax934 quantize 9.999E-15 1e-18 -> 9.999E-15 +quax935 quantize 9.999E-15 1e-17 -> 1.000E-14 Inexact Rounded +quax936 quantize 9.999E-15 1e-16 -> 1.00E-14 Inexact Rounded +quax937 quantize 9.999E-15 1e-15 -> 1.0E-14 Inexact Rounded +quax938 quantize 9.999E-15 1e-14 -> 1E-14 Inexact Rounded +quax939 quantize 9.999E-15 1e-13 -> 0E-13 Inexact Rounded +quax940 quantize 9.999E-15 1e-12 -> 0E-12 Inexact Rounded +quax941 quantize 9.999E-15 1e-11 -> 0E-11 Inexact Rounded +quax942 quantize 9.999E-15 1e-10 -> 0E-10 Inexact Rounded +quax943 quantize 9.999E-15 1e-9 -> 0E-9 Inexact Rounded +quax944 quantize 9.999E-15 1e-8 -> 0E-8 Inexact Rounded +quax945 quantize 9.999E-15 1e-7 -> 0E-7 Inexact Rounded +quax946 quantize 9.999E-15 1e-6 -> 0.000000 Inexact Rounded +quax947 quantize 9.999E-15 1e-5 -> 0.00000 Inexact Rounded +quax948 quantize 9.999E-15 1e-4 -> 0.0000 Inexact Rounded +quax949 quantize 9.999E-15 1e-3 -> 0.000 Inexact Rounded +quax950 quantize 9.999E-15 1e-2 -> 0.00 Inexact Rounded +quax951 quantize 9.999E-15 1e-1 -> 0.0 Inexact Rounded +quax952 quantize 9.999E-15 1e0 -> 0 Inexact Rounded +quax953 quantize 9.999E-15 1e1 -> 0E+1 Inexact Rounded + +precision: 3 +quax960 quantize 9.999E-15 1e-22 -> NaN Invalid_operation +quax961 quantize 9.999E-15 1e-21 -> NaN Invalid_operation +quax962 quantize 9.999E-15 1e-20 -> NaN Invalid_operation +quax963 quantize 9.999E-15 1e-19 -> NaN Invalid_operation +quax964 quantize 9.999E-15 1e-18 -> NaN Invalid_operation +quax965 quantize 9.999E-15 1e-17 -> NaN Invalid_operation +quax966 quantize 9.999E-15 1e-16 -> 1.00E-14 Inexact Rounded +quax967 quantize 9.999E-15 1e-15 -> 1.0E-14 Inexact Rounded +quax968 quantize 9.999E-15 1e-14 -> 1E-14 Inexact Rounded +quax969 quantize 9.999E-15 1e-13 -> 0E-13 Inexact Rounded +quax970 quantize 9.999E-15 1e-12 -> 0E-12 Inexact Rounded +quax971 quantize 9.999E-15 1e-11 -> 0E-11 Inexact Rounded +quax972 quantize 9.999E-15 1e-10 -> 0E-10 Inexact Rounded +quax973 quantize 9.999E-15 1e-9 -> 0E-9 Inexact Rounded +quax974 quantize 9.999E-15 1e-8 -> 0E-8 Inexact Rounded +quax975 quantize 9.999E-15 1e-7 -> 0E-7 Inexact Rounded +quax976 quantize 9.999E-15 1e-6 -> 0.000000 Inexact Rounded +quax977 quantize 9.999E-15 1e-5 -> 0.00000 Inexact Rounded +quax978 quantize 9.999E-15 1e-4 -> 0.0000 Inexact Rounded +quax979 quantize 9.999E-15 1e-3 -> 0.000 Inexact Rounded +quax980 quantize 9.999E-15 1e-2 -> 0.00 Inexact Rounded +quax981 quantize 9.999E-15 1e-1 -> 0.0 Inexact Rounded +quax982 quantize 9.999E-15 1e0 -> 0 Inexact Rounded +quax983 quantize 9.999E-15 1e1 -> 0E+1 Inexact Rounded + +-- Fung Lee's case & similar +precision: 3 +quax1001 quantize 0.000 0.001 -> 0.000 +quax1002 quantize 0.001 0.001 -> 0.001 +quax1003 quantize 0.0012 0.001 -> 0.001 Inexact Rounded +quax1004 quantize 0.0018 0.001 -> 0.002 Inexact Rounded +quax1005 quantize 0.501 0.001 -> 0.501 +quax1006 quantize 0.5012 0.001 -> 0.501 Inexact Rounded +quax1007 quantize 0.5018 0.001 -> 0.502 Inexact Rounded +quax1008 quantize 0.999 0.001 -> 0.999 +quax1009 quantize 0.9992 0.001 -> 0.999 Inexact Rounded +quax1010 quantize 0.9998 0.001 -> NaN Invalid_operation +quax1011 quantize 1.0001 0.001 -> NaN Invalid_operation +quax1012 quantize 1.0051 0.001 -> NaN Invalid_operation +quax1013 quantize 1.0551 0.001 -> NaN Invalid_operation +quax1014 quantize 1.5551 0.001 -> NaN Invalid_operation +quax1015 quantize 1.9999 0.001 -> NaN Invalid_operation + -- long operand checks [rhs checks removed] maxexponent: 999 minexponent: -999 @@ -775,6 +868,81 @@ quax865 quantize 1 1e-2147483648 -> NaN Invalid_operation quax866 quantize 1 1e-2147483649 -> NaN Invalid_operation +-- More from Fung Lee +precision: 16 +rounding: half_up +maxExponent: 384 +minExponent: -383 +quax1021 quantize 8.666666666666000E+384 1.000000000000000E+384 -> 8.666666666666000E+384 +quax1022 quantize 64#8.666666666666000E+384 64#1.000000000000000E+384 -> 8.666666666666000E+384 +quax1023 quantize 64#8.666666666666000E+384 128#1.000000000000000E+384 -> 8.666666666666000E+384 +quax1024 quantize 64#8.666666666666000E+384 64#1E+384 -> 8.666666666666000E+384 +quax1025 quantize 64#8.666666666666000E+384 64#1E+384 -> 64#8.666666666666000E+384 +quax1026 quantize 64#8.666666666666000E+384 128#1E+384 -> 64#9E+384 Inexact Rounded Clamped +quax1027 quantize 64#8.666666666666000E+323 64#1E+31 -> NaN Invalid_operation +quax1028 quantize 64#8.666666666666000E+323 128#1E+31 -> NaN Invalid_operation +quax1029 quantize 64#8.66666666E+3 128#1E+10 -> 64#0E10 Inexact Rounded +quax1030 quantize 8.66666666E+3 1E+3 -> 9E+3 Inexact Rounded + +-- Int and uInt32 edge values for testing conversions +quax1040 quantize -2147483646 0 -> -2147483646 +quax1041 quantize -2147483647 0 -> -2147483647 +quax1042 quantize -2147483648 0 -> -2147483648 +quax1043 quantize -2147483649 0 -> -2147483649 +quax1044 quantize 2147483646 0 -> 2147483646 +quax1045 quantize 2147483647 0 -> 2147483647 +quax1046 quantize 2147483648 0 -> 2147483648 +quax1047 quantize 2147483649 0 -> 2147483649 +quax1048 quantize 4294967294 0 -> 4294967294 +quax1049 quantize 4294967295 0 -> 4294967295 +quax1050 quantize 4294967296 0 -> 4294967296 +quax1051 quantize 4294967297 0 -> 4294967297 +-- and powers of ten for same +quax1101 quantize 5000000000 0 -> 5000000000 +quax1102 quantize 4000000000 0 -> 4000000000 +quax1103 quantize 2000000000 0 -> 2000000000 +quax1104 quantize 1000000000 0 -> 1000000000 +quax1105 quantize 0100000000 0 -> 100000000 +quax1106 quantize 0010000000 0 -> 10000000 +quax1107 quantize 0001000000 0 -> 1000000 +quax1108 quantize 0000100000 0 -> 100000 +quax1109 quantize 0000010000 0 -> 10000 +quax1110 quantize 0000001000 0 -> 1000 +quax1111 quantize 0000000100 0 -> 100 +quax1112 quantize 0000000010 0 -> 10 +quax1113 quantize 0000000001 0 -> 1 +quax1114 quantize 0000000000 0 -> 0 +-- and powers of ten for same +quax1121 quantize -5000000000 0 -> -5000000000 +quax1122 quantize -4000000000 0 -> -4000000000 +quax1123 quantize -2000000000 0 -> -2000000000 +quax1124 quantize -1000000000 0 -> -1000000000 +quax1125 quantize -0100000000 0 -> -100000000 +quax1126 quantize -0010000000 0 -> -10000000 +quax1127 quantize -0001000000 0 -> -1000000 +quax1128 quantize -0000100000 0 -> -100000 +quax1129 quantize -0000010000 0 -> -10000 +quax1130 quantize -0000001000 0 -> -1000 +quax1131 quantize -0000000100 0 -> -100 +quax1132 quantize -0000000010 0 -> -10 +quax1133 quantize -0000000001 0 -> -1 +quax1134 quantize -0000000000 0 -> -0 + +-- Some miscellany +precision: 34 +rounding: half_up +maxExponent: 6144 +minExponent: -6143 +-- 1 2 3 +-- 1 234567890123456789012345678901234 +quax0a1 quantize 8.555555555555555555555555555555555E+6143 1E+6143 -> 9E+6143 Inexact Rounded +quax0a2 quantize 128#8.555555555555555555555555555555555E+6143 128#1E+6143 -> 8.55555555555555555555555555555556E+6143 Rounded Inexact +quax0a3 quantize 128#8.555555555555555555555555555555555E+6144 128#1E+6144 -> 8.555555555555555555555555555555555E+6144 + +-- payload decapitate +precision: 5 +quax62100 quantize 11 -sNaN1234567890 -> -NaN67890 Invalid_operation + -- Null tests -quax900 quantize 10 # -> NaN Invalid_operation -quax901 quantize # 1e10 -> NaN Invalid_operation +quax998 quantize 10 # -> NaN Invalid_operation +quax999 quantize # 1e10 -> NaN Invalid_operation Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/randomBound32.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/randomBound32.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/randomBound32.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- randomBound32.decTest -- decimal testcases -- boundaries near 32 -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.55 -- These testcases test calculations at precisions 31, 32, and 33, to -- exercise the boundaries around 2**5 @@ -90,7 +90,7 @@ divx3008 divide 75353574493.84484153484918212042 -8684111695095849922263044191221 -> -8.677177026223536475531592432118E-21 Inexact Rounded dvix3008 divideint 75353574493.84484153484918212042 -8684111695095849922263044191221 -> -0 mulx3008 multiply 75353574493.84484153484918212042 -8684111695095849922263044191221 -> -6.543788575292743281456830701127E+41 Inexact Rounded -powx3008 power 75353574493.84484153484918212042 -9 -> 1.276630670287906925570645490708E-98 Inexact Rounded +powx3008 power 75353574493.84484153484918212042 -9 -> 1.276630670287906925570645490707E-98 Inexact Rounded remx3008 remainder 75353574493.84484153484918212042 -8684111695095849922263044191221 -> 75353574493.84484153484918212042 subx3008 subtract 75353574493.84484153484918212042 -8684111695095849922263044191221 -> 8684111695095849922338397765715 Inexact Rounded addx3009 add 6907058.216435355874729592373011 2.857005446917670515662398741545 -> 6907061.073440802792400108035410 Inexact Rounded @@ -1040,7 +1040,7 @@ divx3226 divide 47.525676459351505682005359699680E+704 -58631943508436657383369760970210 -> -8.1057651538555854520994438038537E+673 Inexact Rounded dvix3226 divideint 47.525676459351505682005359699680E+704 -58631943508436657383369760970210 -> NaN Division_impossible mulx3226 multiply 47.525676459351505682005359699680E+704 -58631943508436657383369760970210 -> -2.7865227773649353769876975366506E+737 Inexact Rounded -powx3226 power 47.525676459351505682005359699680E+704 -6 -> 8.6782100393941226535150385475463E-4235 Inexact Rounded +powx3226 power 47.525676459351505682005359699680E+704 -6 -> 8.6782100393941226535150385475464E-4235 Inexact Rounded remx3226 remainder 47.525676459351505682005359699680E+704 -58631943508436657383369760970210 -> NaN Division_impossible subx3226 subtract 47.525676459351505682005359699680E+704 -58631943508436657383369760970210 -> 4.7525676459351505682005359699680E+705 Inexact Rounded addx3227 add -74396862273800.625679130772935550 -115616605.52826981284183992013157 -> -74396977890406.153948943614775470 Inexact Rounded Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/randoms.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/randoms.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/randoms.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- randoms.decTest -- decimal random testcases -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 maxexponent: 999999999 @@ -264,7 +264,7 @@ xdiv030 divide -225094.28 -88.7723542 -> 2535.63491 Inexact Rounded xdvi030 divideint -225094.28 -88.7723542 -> 2535 xmul030 multiply -225094.28 -88.7723542 -> 19982149.2 Inexact Rounded -xpow030 power -225094.28 -89 -> -4.36076964E-477 Inexact Rounded +xpow030 power -225094.28 -89 -> -4.36076965E-477 Inexact Rounded xrem030 remainder -225094.28 -88.7723542 -> -56.3621030 xsub030 subtract -225094.28 -88.7723542 -> -225005.508 Inexact Rounded xadd031 add 50.4442340 82.7952169E+880120759 -> 8.27952169E+880120760 Inexact Rounded @@ -295,7 +295,7 @@ xcom034 compare 592.142173E-419941416 -3.46079109E-844011845 -> 1 xdiv034 divide 592.142173E-419941416 -3.46079109E-844011845 -> -1.71100236E+424070431 Inexact Rounded xdvi034 divideint 592.142173E-419941416 -3.46079109E-844011845 -> NaN Division_impossible -xmul034 multiply 592.142173E-419941416 -3.46079109E-844011845 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul034 multiply 592.142173E-419941416 -3.46079109E-844011845 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow034 power 592.142173E-419941416 -3 -> Infinity Overflow Inexact Rounded xrem034 remainder 592.142173E-419941416 -3.46079109E-844011845 -> NaN Division_impossible xsub034 subtract 592.142173E-419941416 -3.46079109E-844011845 -> 5.92142173E-419941414 Inexact Rounded @@ -487,7 +487,7 @@ xcom058 compare 151795163E-371727182 -488.09788E-738852245 -> 1 xdiv058 divide 151795163E-371727182 -488.09788E-738852245 -> -3.10993285E+367125068 Inexact Rounded xdvi058 divideint 151795163E-371727182 -488.09788E-738852245 -> NaN Division_impossible -xmul058 multiply 151795163E-371727182 -488.09788E-738852245 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul058 multiply 151795163E-371727182 -488.09788E-738852245 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow058 power 151795163E-371727182 -5 -> Infinity Overflow Inexact Rounded xrem058 remainder 151795163E-371727182 -488.09788E-738852245 -> NaN Division_impossible xsub058 subtract 151795163E-371727182 -488.09788E-738852245 -> 1.51795163E-371727174 Inexact Rounded @@ -568,7 +568,7 @@ xdiv068 divide -12393257.2 76803689E+949125770 -> -1.61362786E-949125771 Inexact Rounded xdvi068 divideint -12393257.2 76803689E+949125770 -> -0 xmul068 multiply -12393257.2 76803689E+949125770 -> -9.51847872E+949125784 Inexact Rounded -xpow068 power -12393257.2 8 -> 5.56523750E+56 Inexact Rounded +xpow068 power -12393257.2 8 -> 5.56523749E+56 Inexact Rounded xrem068 remainder -12393257.2 76803689E+949125770 -> -12393257.2 xsub068 subtract -12393257.2 76803689E+949125770 -> -7.68036890E+949125777 Inexact Rounded xadd069 add -754771634.E+716555026 -292336.311 -> -7.54771634E+716555034 Inexact Rounded @@ -775,7 +775,7 @@ xcom094 compare -671.507198E-908587890 3057429.32E-555230623 -> -1 xdiv094 divide -671.507198E-908587890 3057429.32E-555230623 -> -2.19631307E-353357271 Inexact Rounded xdvi094 divideint -671.507198E-908587890 3057429.32E-555230623 -> -0 -xmul094 multiply -671.507198E-908587890 3057429.32E-555230623 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul094 multiply -671.507198E-908587890 3057429.32E-555230623 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow094 power -671.507198E-908587890 3 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xrem094 remainder -671.507198E-908587890 3057429.32E-555230623 -> -6.71507198E-908587888 xsub094 subtract -671.507198E-908587890 3057429.32E-555230623 -> -3.05742932E-555230617 Inexact Rounded @@ -856,7 +856,7 @@ xdiv104 divide 553527296. -7924.40185 -> -69850.9877 Inexact Rounded xdvi104 divideint 553527296. -7924.40185 -> -69850 xmul104 multiply 553527296. -7924.40185 -> -4.38637273E+12 Inexact Rounded -xpow104 power 553527296. -7924 -> 2.32397213E-69281 Inexact Rounded +xpow104 power 553527296. -7924 -> 2.32397214E-69281 Inexact Rounded xrem104 remainder 553527296. -7924.40185 -> 7826.77750 xsub104 subtract 553527296. -7924.40185 -> 553535220 Inexact Rounded xadd105 add -38.7465207 64936.2942 -> 64897.5477 Inexact Rounded @@ -919,7 +919,7 @@ xcom112 compare -51.1632090E-753968082 8.96207471E-585797887 -> -1 xdiv112 divide -51.1632090E-753968082 8.96207471E-585797887 -> -5.70885768E-168170195 Inexact Rounded xdvi112 divideint -51.1632090E-753968082 8.96207471E-585797887 -> -0 -xmul112 multiply -51.1632090E-753968082 8.96207471E-585797887 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul112 multiply -51.1632090E-753968082 8.96207471E-585797887 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow112 power -51.1632090E-753968082 9 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xrem112 remainder -51.1632090E-753968082 8.96207471E-585797887 -> -5.11632090E-753968081 xsub112 subtract -51.1632090E-753968082 8.96207471E-585797887 -> -8.96207471E-585797887 Inexact Rounded @@ -989,7 +989,7 @@ xsub120 subtract 14239029. -36527.2221 -> 14275556.2 Inexact Rounded xadd121 add 72333.2654E-544425548 -690.664836E+662155120 -> -6.90664836E+662155122 Inexact Rounded xcom121 compare 72333.2654E-544425548 -690.664836E+662155120 -> 1 -xdiv121 divide 72333.2654E-544425548 -690.664836E+662155120 -> -0E-1000000007 Inexact Rounded Underflow Subnormal +xdiv121 divide 72333.2654E-544425548 -690.664836E+662155120 -> -0E-1000000007 Inexact Rounded Underflow Subnormal Clamped xdvi121 divideint 72333.2654E-544425548 -690.664836E+662155120 -> -0 xmul121 multiply 72333.2654E-544425548 -690.664836E+662155120 -> -4.99580429E+117729579 Inexact Rounded xpow121 power 72333.2654E-544425548 -7 -> Infinity Overflow Inexact Rounded @@ -1005,7 +1005,7 @@ xsub122 subtract -37721.1567E-115787341 -828949864E-76251747 -> 8.28949864E-76251739 Inexact Rounded xadd123 add -2078852.83E-647080089 -119779858.E+734665461 -> -1.19779858E+734665469 Inexact Rounded xcom123 compare -2078852.83E-647080089 -119779858.E+734665461 -> 1 -xdiv123 divide -2078852.83E-647080089 -119779858.E+734665461 -> 0E-1000000007 Inexact Rounded Underflow Subnormal +xdiv123 divide -2078852.83E-647080089 -119779858.E+734665461 -> 0E-1000000007 Inexact Rounded Underflow Subnormal Clamped xdvi123 divideint -2078852.83E-647080089 -119779858.E+734665461 -> 0 xmul123 multiply -2078852.83E-647080089 -119779858.E+734665461 -> 2.49004697E+87585386 Inexact Rounded xpow123 power -2078852.83E-647080089 -1 -> -4.81034533E+647080082 Inexact Rounded @@ -1183,7 +1183,7 @@ xcom145 compare -477067757.E-961684940 7.70122608E-741072245 -> -1 xdiv145 divide -477067757.E-961684940 7.70122608E-741072245 -> -6.19469877E-220612688 Inexact Rounded xdvi145 divideint -477067757.E-961684940 7.70122608E-741072245 -> -0 -xmul145 multiply -477067757.E-961684940 7.70122608E-741072245 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul145 multiply -477067757.E-961684940 7.70122608E-741072245 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow145 power -477067757.E-961684940 8 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xrem145 remainder -477067757.E-961684940 7.70122608E-741072245 -> -4.77067757E-961684932 xsub145 subtract -477067757.E-961684940 7.70122608E-741072245 -> -7.70122608E-741072245 Inexact Rounded @@ -1296,7 +1296,7 @@ xdiv159 divide -18861647. 99794586.7 -> -0.189004711 Inexact Rounded xdvi159 divideint -18861647. 99794586.7 -> -0 xmul159 multiply -18861647. 99794586.7 -> -1.88229027E+15 Inexact Rounded -xpow159 power -18861647. 99794587 -> -4.28957460E+726063462 Inexact Rounded +xpow159 power -18861647. 99794587 -> -4.28957459E+726063462 Inexact Rounded xrem159 remainder -18861647. 99794586.7 -> -18861647.0 xsub159 subtract -18861647. 99794586.7 -> -118656234 Inexact Rounded xadd160 add 322192.407 461.67044 -> 322654.077 Inexact Rounded @@ -1519,7 +1519,7 @@ xcom187 compare -29.356551E-282816139 37141748E-903397821 -> -1 xdiv187 divide -29.356551E-282816139 37141748E-903397821 -> -7.90392283E+620581675 Inexact Rounded xdvi187 divideint -29.356551E-282816139 37141748E-903397821 -> NaN Division_impossible -xmul187 multiply -29.356551E-282816139 37141748E-903397821 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul187 multiply -29.356551E-282816139 37141748E-903397821 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow187 power -29.356551E-282816139 4 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xrem187 remainder -29.356551E-282816139 37141748E-903397821 -> NaN Division_impossible xsub187 subtract -29.356551E-282816139 37141748E-903397821 -> -2.93565510E-282816138 Inexact Rounded @@ -1760,7 +1760,7 @@ xdiv217 divide 7428219.97 667.326760 -> 11131.3084 Inexact Rounded xdvi217 divideint 7428219.97 667.326760 -> 11131 xmul217 multiply 7428219.97 667.326760 -> 4.95704997E+9 Inexact Rounded -xpow217 power 7428219.97 667 -> 7.58808510E+4582 Inexact Rounded +xpow217 power 7428219.97 667 -> 7.58808509E+4582 Inexact Rounded xrem217 remainder 7428219.97 667.326760 -> 205.804440 xsub217 subtract 7428219.97 667.326760 -> 7427552.64 Inexact Rounded xadd218 add -7291.19212 209.64966E-588526476 -> -7291.19212 Inexact Rounded @@ -2200,7 +2200,7 @@ xdiv272 divide 513115529. 27775075.6E+217133352 -> 1.84739562E-217133351 Inexact Rounded xdvi272 divideint 513115529. 27775075.6E+217133352 -> 0 xmul272 multiply 513115529. 27775075.6E+217133352 -> 1.42518226E+217133368 Inexact Rounded -xpow272 power 513115529. 3 -> 1.35096929E+26 Inexact Rounded +xpow272 power 513115529. 3 -> 1.35096928E+26 Inexact Rounded xrem272 remainder 513115529. 27775075.6E+217133352 -> 513115529 xsub272 subtract 513115529. 27775075.6E+217133352 -> -2.77750756E+217133359 Inexact Rounded xadd273 add -247157.208 -532990.453 -> -780147.661 @@ -2327,7 +2327,7 @@ xcom288 compare -4.18074650E-858746879 571035.277E-279409165 -> -1 xdiv288 divide -4.18074650E-858746879 571035.277E-279409165 -> -7.32134540E-579337720 Inexact Rounded xdvi288 divideint -4.18074650E-858746879 571035.277E-279409165 -> -0 -xmul288 multiply -4.18074650E-858746879 571035.277E-279409165 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul288 multiply -4.18074650E-858746879 571035.277E-279409165 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow288 power -4.18074650E-858746879 6 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xrem288 remainder -4.18074650E-858746879 571035.277E-279409165 -> -4.18074650E-858746879 xsub288 subtract -4.18074650E-858746879 571035.277E-279409165 -> -5.71035277E-279409160 Inexact Rounded @@ -2599,7 +2599,7 @@ xcom322 compare 82.4185291E-321919303 -215747737.E-995147400 -> 1 xdiv322 divide 82.4185291E-321919303 -215747737.E-995147400 -> -3.82013412E+673228090 Inexact Rounded xdvi322 divideint 82.4185291E-321919303 -215747737.E-995147400 -> NaN Division_impossible -xmul322 multiply 82.4185291E-321919303 -215747737.E-995147400 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul322 multiply 82.4185291E-321919303 -215747737.E-995147400 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow322 power 82.4185291E-321919303 -2 -> 1.47214396E+643838602 Inexact Rounded xrem322 remainder 82.4185291E-321919303 -215747737.E-995147400 -> NaN Division_impossible xsub322 subtract 82.4185291E-321919303 -215747737.E-995147400 -> 8.24185291E-321919302 Inexact Rounded @@ -2640,7 +2640,7 @@ xdiv327 divide 2512953.3 -3769170.35E-993621645 -> -6.66712583E+993621644 Inexact Rounded xdvi327 divideint 2512953.3 -3769170.35E-993621645 -> NaN Division_impossible xmul327 multiply 2512953.3 -3769170.35E-993621645 -> -9.47174907E-993621633 Inexact Rounded -xpow327 power 2512953.3 -4 -> 2.50762349E-26 Inexact Rounded +xpow327 power 2512953.3 -4 -> 2.50762348E-26 Inexact Rounded xrem327 remainder 2512953.3 -3769170.35E-993621645 -> NaN Division_impossible xsub327 subtract 2512953.3 -3769170.35E-993621645 -> 2512953.30 Inexact Rounded xadd328 add -682.796370 71131.0224 -> 70448.2260 Inexact Rounded @@ -2656,7 +2656,7 @@ xdiv329 divide 89.9997490 -4993.69831 -> -0.0180226644 Inexact Rounded xdvi329 divideint 89.9997490 -4993.69831 -> -0 xmul329 multiply 89.9997490 -4993.69831 -> -449431.594 Inexact Rounded -xpow329 power 89.9997490 -4994 -> 3.30336526E-9760 Inexact Rounded +xpow329 power 89.9997490 -4994 -> 3.30336525E-9760 Inexact Rounded xrem329 remainder 89.9997490 -4993.69831 -> 89.9997490 xsub329 subtract 89.9997490 -4993.69831 -> 5083.69806 Inexact Rounded xadd330 add 76563354.6E-112338836 278271.585E-511481095 -> 7.65633546E-112338829 Inexact Rounded @@ -2821,7 +2821,7 @@ xsub349 subtract -4037911.02E+641367645 29.5713010 -> -4.03791102E+641367651 Inexact Rounded xadd350 add -688755561.E-95301699 978.275312E+913812609 -> 9.78275312E+913812611 Inexact Rounded xcom350 compare -688755561.E-95301699 978.275312E+913812609 -> -1 -xdiv350 divide -688755561.E-95301699 978.275312E+913812609 -> -0E-1000000007 Inexact Rounded Underflow Subnormal +xdiv350 divide -688755561.E-95301699 978.275312E+913812609 -> -0E-1000000007 Inexact Rounded Underflow Subnormal Clamped xdvi350 divideint -688755561.E-95301699 978.275312E+913812609 -> -0 xmul350 multiply -688755561.E-95301699 978.275312E+913812609 -> -6.73792561E+818510921 Inexact Rounded xpow350 power -688755561.E-95301699 10 -> 2.40243244E-953016902 Inexact Rounded @@ -3024,7 +3024,7 @@ xdiv375 divide -5549320.1 -93580684.1 -> 0.0592998454 Inexact Rounded xdvi375 divideint -5549320.1 -93580684.1 -> 0 xmul375 multiply -5549320.1 -93580684.1 -> 5.19309171E+14 Inexact Rounded -xpow375 power -5549320.1 -93580684 -> 4.20662080E-631130572 Inexact Rounded +xpow375 power -5549320.1 -93580684 -> 4.20662079E-631130572 Inexact Rounded xrem375 remainder -5549320.1 -93580684.1 -> -5549320.1 xsub375 subtract -5549320.1 -93580684.1 -> 88031364.0 xadd376 add -14677053.1 -25784.7358 -> -14702837.8 Inexact Rounded @@ -3191,7 +3191,7 @@ xcom396 compare 4880.06442E-382222621 -115627239E-912834031 -> 1 xdiv396 divide 4880.06442E-382222621 -115627239E-912834031 -> -4.22051453E+530611405 Inexact Rounded xdvi396 divideint 4880.06442E-382222621 -115627239E-912834031 -> NaN Division_impossible -xmul396 multiply 4880.06442E-382222621 -115627239E-912834031 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul396 multiply 4880.06442E-382222621 -115627239E-912834031 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow396 power 4880.06442E-382222621 -1 -> 2.04915328E+382222617 Inexact Rounded xrem396 remainder 4880.06442E-382222621 -115627239E-912834031 -> NaN Division_impossible xsub396 subtract 4880.06442E-382222621 -115627239E-912834031 -> 4.88006442E-382222618 Inexact Rounded @@ -3295,7 +3295,7 @@ xcom409 compare -54.3684171E-807210192 1.04592973E-984041807 -> -1 xdiv409 divide -54.3684171E-807210192 1.04592973E-984041807 -> -5.19809463E+176831616 Inexact Rounded xdvi409 divideint -54.3684171E-807210192 1.04592973E-984041807 -> NaN Division_impossible -xmul409 multiply -54.3684171E-807210192 1.04592973E-984041807 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul409 multiply -54.3684171E-807210192 1.04592973E-984041807 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow409 power -54.3684171E-807210192 1 -> -5.43684171E-807210191 xrem409 remainder -54.3684171E-807210192 1.04592973E-984041807 -> NaN Division_impossible xsub409 subtract -54.3684171E-807210192 1.04592973E-984041807 -> -5.43684171E-807210191 Inexact Rounded @@ -3391,7 +3391,7 @@ xcom421 compare -4.09492571E-301749490 434.20199E-749390952 -> -1 xdiv421 divide -4.09492571E-301749490 434.20199E-749390952 -> -9.43092341E+447641459 Inexact Rounded xdvi421 divideint -4.09492571E-301749490 434.20199E-749390952 -> NaN Division_impossible -xmul421 multiply -4.09492571E-301749490 434.20199E-749390952 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul421 multiply -4.09492571E-301749490 434.20199E-749390952 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow421 power -4.09492571E-301749490 4 -> 0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xrem421 remainder -4.09492571E-301749490 434.20199E-749390952 -> NaN Division_impossible xsub421 subtract -4.09492571E-301749490 434.20199E-749390952 -> -4.09492571E-301749490 Inexact Rounded @@ -3423,7 +3423,7 @@ xcom425 compare 6.88891136E-935467395 -785049.562E-741671442 -> 1 xdiv425 divide 6.88891136E-935467395 -785049.562E-741671442 -> -8.77512923E-193795959 Inexact Rounded xdvi425 divideint 6.88891136E-935467395 -785049.562E-741671442 -> -0 -xmul425 multiply 6.88891136E-935467395 -785049.562E-741671442 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul425 multiply 6.88891136E-935467395 -785049.562E-741671442 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow425 power 6.88891136E-935467395 -8 -> Infinity Overflow Inexact Rounded xrem425 remainder 6.88891136E-935467395 -785049.562E-741671442 -> 6.88891136E-935467395 xsub425 subtract 6.88891136E-935467395 -785049.562E-741671442 -> 7.85049562E-741671437 Inexact Rounded @@ -3535,7 +3535,7 @@ xcom439 compare 971113.655E-695540249 -419351120E-977743823 -> 1 xdiv439 divide 971113.655E-695540249 -419351120E-977743823 -> -2.31575310E+282203571 Inexact Rounded xdvi439 divideint 971113.655E-695540249 -419351120E-977743823 -> NaN Division_impossible -xmul439 multiply 971113.655E-695540249 -419351120E-977743823 -> -0E-1000000007 Underflow Subnormal Inexact Rounded +xmul439 multiply 971113.655E-695540249 -419351120E-977743823 -> -0E-1000000007 Underflow Subnormal Inexact Rounded Clamped xpow439 power 971113.655E-695540249 -4 -> Infinity Overflow Inexact Rounded xrem439 remainder 971113.655E-695540249 -419351120E-977743823 -> NaN Division_impossible xsub439 subtract 971113.655E-695540249 -419351120E-977743823 -> 9.71113655E-695540244 Inexact Rounded @@ -3600,7 +3600,7 @@ xdiv447 divide -9.95836312 -866466703 -> 1.14930707E-8 Inexact Rounded xdvi447 divideint -9.95836312 -866466703 -> 0 xmul447 multiply -9.95836312 -866466703 -> 8.62859006E+9 Inexact Rounded -xpow447 power -9.95836312 -866466703 -> -6.71744368E-864896630 Inexact Rounded +xpow447 power -9.95836312 -866466703 -> -6.71744369E-864896630 Inexact Rounded xrem447 remainder -9.95836312 -866466703 -> -9.95836312 xsub447 subtract -9.95836312 -866466703 -> 866466693 Inexact Rounded xadd448 add 80919339.2E-967231586 219.824266 -> 219.824266 Inexact Rounded @@ -3616,7 +3616,7 @@ xdiv449 divide 159579.444 -89827.5229 -> -1.77650946 Inexact Rounded xdvi449 divideint 159579.444 -89827.5229 -> -1 xmul449 multiply 159579.444 -89827.5229 -> -1.43346262E+10 Inexact Rounded -xpow449 power 159579.444 -89828 -> 9.69955849E-467374 Inexact Rounded +xpow449 power 159579.444 -89828 -> 9.69955850E-467374 Inexact Rounded xrem449 remainder 159579.444 -89827.5229 -> 69751.9211 xsub449 subtract 159579.444 -89827.5229 -> 249406.967 Inexact Rounded xadd450 add -4.54000153 6966333.74 -> 6966329.20 Inexact Rounded @@ -3640,7 +3640,7 @@ xdiv452 divide -361382575. -7976.15286E+898491169 -> 4.53078798E-898491165 Inexact Rounded xdvi452 divideint -361382575. -7976.15286E+898491169 -> 0 xmul452 multiply -361382575. -7976.15286E+898491169 -> 2.88244266E+898491181 Inexact Rounded -xpow452 power -361382575. -8 -> 3.43765536E-69 Inexact Rounded +xpow452 power -361382575. -8 -> 3.43765537E-69 Inexact Rounded xrem452 remainder -361382575. -7976.15286E+898491169 -> -361382575 xsub452 subtract -361382575. -7976.15286E+898491169 -> 7.97615286E+898491172 Inexact Rounded xadd453 add 7021805.61 1222952.83 -> 8244758.44 @@ -3720,7 +3720,7 @@ xdiv462 divide -51592.2698 -713885.741 -> 0.0722696460 Inexact Rounded xdvi462 divideint -51592.2698 -713885.741 -> 0 xmul462 multiply -51592.2698 -713885.741 -> 3.68309858E+10 Inexact Rounded -xpow462 power -51592.2698 -713886 -> 6.38576921E-3364249 Inexact Rounded +xpow462 power -51592.2698 -713886 -> 6.38576920E-3364249 Inexact Rounded xrem462 remainder -51592.2698 -713885.741 -> -51592.2698 xsub462 subtract -51592.2698 -713885.741 -> 662293.471 Inexact Rounded xadd463 add 51.2279848E+80439745 207.55925E+865165070 -> 2.07559250E+865165072 Inexact Rounded @@ -3768,7 +3768,7 @@ xdiv468 divide -5.32711606 -8447286.21 -> 6.30630468E-7 Inexact Rounded xdvi468 divideint -5.32711606 -8447286.21 -> 0 xmul468 multiply -5.32711606 -8447286.21 -> 44999674.0 Inexact Rounded -xpow468 power -5.32711606 -8447286 -> 9.09138729E-6136888 Inexact Rounded +xpow468 power -5.32711606 -8447286 -> 9.09138728E-6136888 Inexact Rounded xrem468 remainder -5.32711606 -8447286.21 -> -5.32711606 xsub468 subtract -5.32711606 -8447286.21 -> 8447280.88 Inexact Rounded xadd469 add -82272171.8 -776.238587E-372690416 -> -82272171.8 Inexact Rounded @@ -4027,3 +4027,4 @@ xpow500 power -525445087.E+231529167 188227460 -> Infinity Overflow Inexact Rounded xrem500 remainder -525445087.E+231529167 188227460 -> NaN Division_impossible xsub500 subtract -525445087.E+231529167 188227460 -> -5.25445087E+231529175 Inexact Rounded + Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/remainder.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/remainder.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/remainder.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- remainder.decTest -- decimal remainder -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -351,6 +351,17 @@ remx408 remainder 0.55555555 1 -> 0.55555555 remx409 remainder 0.555555555 1 -> 0.555555555 +-- zero signs +remx650 remainder 1 1 -> 0 +remx651 remainder -1 1 -> -0 +remx652 remainder 1 -1 -> 0 +remx653 remainder -1 -1 -> -0 +remx654 remainder 0 1 -> 0 +remx655 remainder -0 1 -> -0 +remx656 remainder 0 -1 -> 0 +remx657 remainder -0 -1 -> -0 +remx658 remainder 0.00 1 -> 0.00 +remx659 remainder -0.00 1 -> -0.00 -- Specials remx680 remainder Inf -Inf -> NaN Invalid_operation Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/remainderNear.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/remainderNear.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/remainderNear.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- remainderNear.decTest -- decimal remainder-near (IEEE remainder) -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.55 extended: 1 precision: 9 Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/rescale.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/rescale.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/rescale.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- rescale.decTest -- decimal rescale operation -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- [obsolete] Quantize.decTest has the improved version @@ -379,7 +379,7 @@ resx446 rescale 0.000999 1 -> 0E+1 Inexact Rounded precision: 8 -resx449 rescale 9.999E-15 -23 -> NaN Invalid_operation +resx449 rescale 9.999E-15 -23 -> NaN Invalid_operation resx450 rescale 9.999E-15 -22 -> 9.9990000E-15 resx451 rescale 9.999E-15 -21 -> 9.999000E-15 resx452 rescale 9.999E-15 -20 -> 9.99900E-15 @@ -405,6 +405,12 @@ resx472 rescale 9.999E-15 0 -> 0 Inexact Rounded resx473 rescale 9.999E-15 1 -> 0E+1 Inexact Rounded +-- [additional tests for "don't fit" edge cases are in +-- quantize.decTest. Here's a critical one.] +precision: 3 +resx480 rescale 0.9999 -3 -> NaN Invalid_operation + + -- long operand checks [rhs checks removed] maxexponent: 999 minexponent: -999 Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/rounding.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/rounding.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/rounding.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- rounding.decTest -- decimal rounding modes testcases -- --- Copyright (c) IBM Corporation, 1981, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- These tests require that implementations take account of residues in -- order to get correct results for some rounding modes. Rather than @@ -26,8 +26,11 @@ -- is rounding of negatives (if the latter works for addition, assume it -- works for the others, too).] -- --- Underflow Subnormal and overflow behaviours are tested under the individual --- operators. +-- Round-for-reround (05UP) is tested as a separate block, mostly for +-- 'historical' reasons. +-- +-- Underflow Subnormal and overflow behaviours are tested under the +-- individual operators. extended: 1 precision: 5 -- for easier visual inspection @@ -980,8 +983,8 @@ rounding: down rovx100 multiply 10 9E+999999999 -> 9.9999E+999999999 Overflow Inexact Rounded rovx101 multiply -10 9E+999999999 -> -9.9999E+999999999 Overflow Inexact Rounded -rovx102 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded -rovx104 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded +rovx102 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded Clamped +rovx104 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded Clamped rounding: up rovx110 multiply 10 9E+999999999 -> Infinity Overflow Inexact Rounded @@ -993,31 +996,31 @@ rovx120 multiply 10 9E+999999999 -> Infinity Overflow Inexact Rounded rovx121 multiply -10 9E+999999999 -> -9.9999E+999999999 Overflow Inexact Rounded rovx122 divide 1E-9 9E+999999999 -> 1E-1000000003 Underflow Subnormal Inexact Rounded -rovx124 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded +rovx124 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded Clamped rounding: floor rovx130 multiply 10 9E+999999999 -> 9.9999E+999999999 Overflow Inexact Rounded rovx131 multiply -10 9E+999999999 -> -Infinity Overflow Inexact Rounded -rovx132 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded +rovx132 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded Clamped rovx134 divide -1E-9 9E+999999999 -> -1E-1000000003 Underflow Subnormal Inexact Rounded rounding: half_up rovx140 multiply 10 9E+999999999 -> Infinity Overflow Inexact Rounded rovx141 multiply -10 9E+999999999 -> -Infinity Overflow Inexact Rounded -rovx142 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded -rovx144 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded +rovx142 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded Clamped +rovx144 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded Clamped rounding: half_even rovx150 multiply 10 9E+999999999 -> Infinity Overflow Inexact Rounded rovx151 multiply -10 9E+999999999 -> -Infinity Overflow Inexact Rounded -rovx152 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded -rovx154 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded +rovx152 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded Clamped +rovx154 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded Clamped rounding: half_down rovx160 multiply 10 9E+999999999 -> Infinity Overflow Inexact Rounded rovx161 multiply -10 9E+999999999 -> -Infinity Overflow Inexact Rounded -rovx162 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded -rovx164 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded +rovx162 divide 1E-9 9E+999999999 -> 0E-1000000003 Underflow Subnormal Inexact Rounded Clamped +rovx164 divide -1E-9 9E+999999999 -> -0E-1000000003 Underflow Subnormal Inexact Rounded Clamped -- check maximum finite value over a range of precisions rounding: down @@ -1077,3 +1080,224 @@ rmex412 multiply -9.999E+999999999 10 -> -9.99999999E+999999999 Overflow Inexact Rounded rmex413 multiply 9.999E+999999999 10 -> 9.99999999E+999999999 Overflow Inexact Rounded +----- Round-for-reround ----- +rounding: 05up +precision: 5 -- for easier visual inspection +maxExponent: 999 +minexponent: -999 + +-- basic rounding; really is just 0 and 5 up +r05up001 add 12340 0.001 -> 12341 Inexact Rounded +r05up002 add 12341 0.001 -> 12341 Inexact Rounded +r05up003 add 12342 0.001 -> 12342 Inexact Rounded +r05up004 add 12343 0.001 -> 12343 Inexact Rounded +r05up005 add 12344 0.001 -> 12344 Inexact Rounded +r05up006 add 12345 0.001 -> 12346 Inexact Rounded +r05up007 add 12346 0.001 -> 12346 Inexact Rounded +r05up008 add 12347 0.001 -> 12347 Inexact Rounded +r05up009 add 12348 0.001 -> 12348 Inexact Rounded +r05up010 add 12349 0.001 -> 12349 Inexact Rounded + +r05up011 add 12340 0.000 -> 12340 Rounded +r05up012 add 12341 0.000 -> 12341 Rounded +r05up013 add 12342 0.000 -> 12342 Rounded +r05up014 add 12343 0.000 -> 12343 Rounded +r05up015 add 12344 0.000 -> 12344 Rounded +r05up016 add 12345 0.000 -> 12345 Rounded +r05up017 add 12346 0.000 -> 12346 Rounded +r05up018 add 12347 0.000 -> 12347 Rounded +r05up019 add 12348 0.000 -> 12348 Rounded +r05up020 add 12349 0.000 -> 12349 Rounded + +r05up021 add 12340 0.901 -> 12341 Inexact Rounded +r05up022 add 12341 0.901 -> 12341 Inexact Rounded +r05up023 add 12342 0.901 -> 12342 Inexact Rounded +r05up024 add 12343 0.901 -> 12343 Inexact Rounded +r05up025 add 12344 0.901 -> 12344 Inexact Rounded +r05up026 add 12345 0.901 -> 12346 Inexact Rounded +r05up027 add 12346 0.901 -> 12346 Inexact Rounded +r05up028 add 12347 0.901 -> 12347 Inexact Rounded +r05up029 add 12348 0.901 -> 12348 Inexact Rounded +r05up030 add 12349 0.901 -> 12349 Inexact Rounded + +r05up031 add -12340 -0.001 -> -12341 Inexact Rounded +r05up032 add -12341 -0.001 -> -12341 Inexact Rounded +r05up033 add -12342 -0.001 -> -12342 Inexact Rounded +r05up034 add -12343 -0.001 -> -12343 Inexact Rounded +r05up035 add -12344 -0.001 -> -12344 Inexact Rounded +r05up036 add -12345 -0.001 -> -12346 Inexact Rounded +r05up037 add -12346 -0.001 -> -12346 Inexact Rounded +r05up038 add -12347 -0.001 -> -12347 Inexact Rounded +r05up039 add -12348 -0.001 -> -12348 Inexact Rounded +r05up040 add -12349 -0.001 -> -12349 Inexact Rounded + +r05up041 add -12340 0.001 -> -12339 Inexact Rounded +r05up042 add -12341 0.001 -> -12341 Inexact Rounded +r05up043 add -12342 0.001 -> -12341 Inexact Rounded +r05up044 add -12343 0.001 -> -12342 Inexact Rounded +r05up045 add -12344 0.001 -> -12343 Inexact Rounded +r05up046 add -12345 0.001 -> -12344 Inexact Rounded +r05up047 add -12346 0.001 -> -12346 Inexact Rounded +r05up048 add -12347 0.001 -> -12346 Inexact Rounded +r05up049 add -12348 0.001 -> -12347 Inexact Rounded +r05up050 add -12349 0.001 -> -12348 Inexact Rounded + +-- Addition operators ------------------------------------------------- +-- [The first few of these check negative residue possibilities; these +-- cases may be implemented as a negative residue in fastpaths] + +r0adx100 add 12345 -0.1 -> 12344 Inexact Rounded +r0adx101 add 12345 -0.01 -> 12344 Inexact Rounded +r0adx102 add 12345 -0.001 -> 12344 Inexact Rounded +r0adx103 add 12345 -0.00001 -> 12344 Inexact Rounded +r0adx104 add 12345 -0.000001 -> 12344 Inexact Rounded +r0adx105 add 12345 -0.0000001 -> 12344 Inexact Rounded +r0adx106 add 12345 0 -> 12345 +r0adx107 add 12345 0.0000001 -> 12346 Inexact Rounded +r0adx108 add 12345 0.000001 -> 12346 Inexact Rounded +r0adx109 add 12345 0.00001 -> 12346 Inexact Rounded +r0adx110 add 12345 0.0001 -> 12346 Inexact Rounded +r0adx111 add 12345 0.001 -> 12346 Inexact Rounded +r0adx112 add 12345 0.01 -> 12346 Inexact Rounded +r0adx113 add 12345 0.1 -> 12346 Inexact Rounded + +r0adx115 add 12346 0.49999 -> 12346 Inexact Rounded +r0adx116 add 12346 0.5 -> 12346 Inexact Rounded +r0adx117 add 12346 0.50001 -> 12346 Inexact Rounded + +r0adx120 add 12345 0.4 -> 12346 Inexact Rounded +r0adx121 add 12345 0.49 -> 12346 Inexact Rounded +r0adx122 add 12345 0.499 -> 12346 Inexact Rounded +r0adx123 add 12345 0.49999 -> 12346 Inexact Rounded +r0adx124 add 12345 0.5 -> 12346 Inexact Rounded +r0adx125 add 12345 0.50001 -> 12346 Inexact Rounded +r0adx126 add 12345 0.5001 -> 12346 Inexact Rounded +r0adx127 add 12345 0.501 -> 12346 Inexact Rounded +r0adx128 add 12345 0.51 -> 12346 Inexact Rounded +r0adx129 add 12345 0.6 -> 12346 Inexact Rounded + +-- negatives... + +r0sux100 add -12345 -0.1 -> -12346 Inexact Rounded +r0sux101 add -12345 -0.01 -> -12346 Inexact Rounded +r0sux102 add -12345 -0.001 -> -12346 Inexact Rounded +r0sux103 add -12345 -0.00001 -> -12346 Inexact Rounded +r0sux104 add -12345 -0.000001 -> -12346 Inexact Rounded +r0sux105 add -12345 -0.0000001 -> -12346 Inexact Rounded +r0sux106 add -12345 0 -> -12345 +r0sux107 add -12345 0.0000001 -> -12344 Inexact Rounded +r0sux108 add -12345 0.000001 -> -12344 Inexact Rounded +r0sux109 add -12345 0.00001 -> -12344 Inexact Rounded +r0sux110 add -12345 0.0001 -> -12344 Inexact Rounded +r0sux111 add -12345 0.001 -> -12344 Inexact Rounded +r0sux112 add -12345 0.01 -> -12344 Inexact Rounded +r0sux113 add -12345 0.1 -> -12344 Inexact Rounded + +r0sux115 add -12346 0.49999 -> -12346 Inexact Rounded +r0sux116 add -12346 0.5 -> -12346 Inexact Rounded +r0sux117 add -12346 0.50001 -> -12346 Inexact Rounded + +r0sux120 add -12345 0.4 -> -12344 Inexact Rounded +r0sux121 add -12345 0.49 -> -12344 Inexact Rounded +r0sux122 add -12345 0.499 -> -12344 Inexact Rounded +r0sux123 add -12345 0.49999 -> -12344 Inexact Rounded +r0sux124 add -12345 0.5 -> -12344 Inexact Rounded +r0sux125 add -12345 0.50001 -> -12344 Inexact Rounded +r0sux126 add -12345 0.5001 -> -12344 Inexact Rounded +r0sux127 add -12345 0.501 -> -12344 Inexact Rounded +r0sux128 add -12345 0.51 -> -12344 Inexact Rounded +r0sux129 add -12345 0.6 -> -12344 Inexact Rounded + +-- Check cancellation subtractions +-- (The IEEE 854 'curious rule' in $6.3) + +r0zex001 add 0 0 -> 0 +r0zex002 add 0 -0 -> 0 +r0zex003 add -0 0 -> 0 +r0zex004 add -0 -0 -> -0 +r0zex005 add 1 -1 -> 0 +r0zex006 add -1 1 -> 0 +r0zex007 add 1.5 -1.5 -> 0.0 +r0zex008 add -1.5 1.5 -> 0.0 +r0zex009 add 2 -2 -> 0 +r0zex010 add -2 2 -> 0 + + +-- Division operators ------------------------------------------------- + +r0dvx101 divide 12345 1 -> 12345 +r0dvx102 divide 12345 1.0001 -> 12343 Inexact Rounded +r0dvx103 divide 12345 1.001 -> 12332 Inexact Rounded +r0dvx104 divide 12345 1.01 -> 12222 Inexact Rounded +r0dvx105 divide 12345 1.1 -> 11222 Inexact Rounded +r0dvx106 divide 12355 4 -> 3088.7 Inexact Rounded +r0dvx107 divide 12345 4 -> 3086.2 Inexact Rounded +r0dvx108 divide 12355 4.0001 -> 3088.6 Inexact Rounded +r0dvx109 divide 12345 4.0001 -> 3086.1 Inexact Rounded +r0dvx110 divide 12345 4.9 -> 2519.3 Inexact Rounded +r0dvx111 divide 12345 4.99 -> 2473.9 Inexact Rounded +r0dvx112 divide 12345 4.999 -> 2469.4 Inexact Rounded +r0dvx113 divide 12345 4.9999 -> 2469.1 Inexact Rounded +r0dvx114 divide 12345 5 -> 2469 +r0dvx115 divide 12345 5.0001 -> 2468.9 Inexact Rounded +r0dvx116 divide 12345 5.001 -> 2468.6 Inexact Rounded +r0dvx117 divide 12345 5.01 -> 2464.1 Inexact Rounded +r0dvx118 divide 12345 5.1 -> 2420.6 Inexact Rounded + +-- [divideInteger and remainder unaffected] + +-- Multiplication operator -------------------------------------------- + +r0mux101 multiply 12345 1 -> 12345 +r0mux102 multiply 12345 1.0001 -> 12346 Inexact Rounded +r0mux103 multiply 12345 1.001 -> 12357 Inexact Rounded +r0mux104 multiply 12345 1.01 -> 12468 Inexact Rounded +r0mux105 multiply 12345 1.1 -> 13579 Inexact Rounded +r0mux106 multiply 12345 4 -> 49380 +r0mux107 multiply 12345 4.0001 -> 49381 Inexact Rounded +r0mux108 multiply 12345 4.9 -> 60491 Inexact Rounded +r0mux109 multiply 12345 4.99 -> 61601 Inexact Rounded +r0mux110 multiply 12345 4.999 -> 61712 Inexact Rounded +r0mux111 multiply 12345 4.9999 -> 61723 Inexact Rounded +r0mux112 multiply 12345 5 -> 61725 +r0mux113 multiply 12345 5.0001 -> 61726 Inexact Rounded +r0mux114 multiply 12345 5.001 -> 61737 Inexact Rounded +r0mux115 multiply 12345 5.01 -> 61848 Inexact Rounded +r0mux116 multiply 12345 12 -> 1.4814E+5 Rounded +r0mux117 multiply 12345 13 -> 1.6048E+5 Inexact Rounded +r0mux118 multiply 12355 12 -> 1.4826E+5 Rounded +r0mux119 multiply 12355 13 -> 1.6061E+5 Inexact Rounded + + +-- Power operator ----------------------------------------------------- + +r0pox101 power 12345 -5 -> 3.4877E-21 Inexact Rounded +r0pox102 power 12345 -4 -> 4.3056E-17 Inexact Rounded +r0pox103 power 12345 -3 -> 5.3152E-13 Inexact Rounded +r0pox104 power 12345 -2 -> 6.5617E-9 Inexact Rounded +r0pox105 power 12345 -1 -> 0.000081004 Inexact Rounded +r0pox106 power 12345 0 -> 1 +r0pox107 power 12345 1 -> 12345 +r0pox108 power 12345 2 -> 1.5239E+8 Inexact Rounded +r0pox109 power 12345 3 -> 1.8813E+12 Inexact Rounded +r0pox110 power 12345 4 -> 2.3226E+16 Inexact Rounded +r0pox111 power 12345 5 -> 2.8671E+20 Inexact Rounded +r0pox112 power 415 2 -> 1.7222E+5 Inexact Rounded +r0pox113 power 75 3 -> 4.2187E+5 Inexact Rounded + + +-- Underflow Subnormal and overflow values vary with rounding mode and sign +maxexponent: 999999999 +minexponent: -999999999 +-- [round down gives Nmax on first two and .0E... on the next two] +r0ovx100 multiply 10 9E+999999999 -> 9.9999E+999999999 Overflow Inexact Rounded +r0ovx101 multiply -10 9E+999999999 -> -9.9999E+999999999 Overflow Inexact Rounded +r0ovx102 divide 1E-9 9E+999999999 -> 1E-1000000003 Underflow Subnormal Inexact Rounded +r0ovx104 divide -1E-9 9E+999999999 -> -1E-1000000003 Underflow Subnormal Inexact Rounded + +-- reprise rounding mode effect (using multiplies so precision directive used) +precision: 9 +maxexponent: 999999999 +r0mex412 multiply -9.999E+999999999 10 -> -9.99999999E+999999999 Overflow Inexact Rounded +r0mex413 multiply 9.999E+999999999 10 -> 9.99999999E+999999999 Overflow Inexact Rounded + Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/samequantum.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/samequantum.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/samequantum.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- samequantum.decTest -- check quantums match -- --- Copyright (c) IBM Corporation, 2001, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 2001, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -64,8 +64,44 @@ samq048 samequantum -0E-17 -0.0E-16 -> 1 samq049 samequantum -0E-17 -0.0E-17 -> 0 --- specials & combinations +-- Nmax, Nmin, Ntiny +samq051 samequantum 9.99999999E+999 9.99999999E+999 -> 1 +samq052 samequantum 1E-999 1E-999 -> 1 +samq053 samequantum 1.00000000E-999 1.00000000E-999 -> 1 +samq054 samequantum 1E-1007 1E-1007 -> 1 +samq055 samequantum 9.99999999E+999 9.99999999E+999 -> 1 +samq056 samequantum 1E-999 1E-999 -> 1 +samq057 samequantum 1.00000000E-999 1.00000000E-999 -> 1 +samq058 samequantum 1E-1007 1E-1007 -> 1 + +samq061 samequantum -1E-1007 -1E-1007 -> 1 +samq062 samequantum -1.00000000E-999 -1.00000000E-999 -> 1 +samq063 samequantum -1E-999 -1E-999 -> 1 +samq064 samequantum -9.99999999E+999 -9.99999999E+999 -> 1 +samq065 samequantum -1E-1007 -1E-1007 -> 1 +samq066 samequantum -1.00000000E-999 -1.00000000E-999 -> 1 +samq067 samequantum -1E-999 -1E-999 -> 1 +samq068 samequantum -9.99999999E+999 -9.99999999E+999 -> 1 + +samq071 samequantum -4E-1007 -1E-1007 -> 1 +samq072 samequantum -4.00000000E-999 -1.00004000E-999 -> 1 +samq073 samequantum -4E-999 -1E-999 -> 1 +samq074 samequantum -4.99999999E+999 -9.99949999E+999 -> 1 +samq075 samequantum -4E-1007 -1E-1007 -> 1 +samq076 samequantum -4.00000000E-999 -1.00400000E-999 -> 1 +samq077 samequantum -4E-999 -1E-999 -> 1 +samq078 samequantum -4.99999999E+999 -9.94999999E+999 -> 1 + +samq081 samequantum -4E-1006 -1E-1007 -> 0 +samq082 samequantum -4.00000000E-999 -1.00004000E-996 -> 0 +samq083 samequantum -4E-996 -1E-999 -> 0 +samq084 samequantum -4.99999999E+999 -9.99949999E+996 -> 0 +samq085 samequantum -4E-1006 -1E-1007 -> 0 +samq086 samequantum -4.00000000E-999 -1.00400000E-996 -> 0 +samq087 samequantum -4E-996 -1E-999 -> 0 +samq088 samequantum -4.99999999E+999 -9.94999999E+996 -> 0 +-- specials & combinations samq0110 samequantum -Inf -Inf -> 1 samq0111 samequantum -Inf Inf -> 1 samq0112 samequantum -Inf NaN -> 0 Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/squareroot.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/squareroot.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/squareroot.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- squareroot.decTest -- decimal square root -- --- Copyright (c) IBM Corporation, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 2003, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -102,6 +102,8 @@ sqtx075 squareroot -100.00 -> NaN Invalid_operation sqtx076 squareroot -1.1000E+3 -> NaN Invalid_operation sqtx077 squareroot -1.10000E+3 -> NaN Invalid_operation +sqtx078 squareroot 1.000 -> 1.00 +sqtx079 squareroot 1.0000 -> 1.00 -- famous squares sqtx080 squareroot 1 -> 1 @@ -2926,19 +2928,26 @@ precision: 11 -- Etiny=-19 sqtx804 squareroot 1E-19 -> 3.162277660E-10 Underflow Subnormal Inexact Rounded -sqtx805 squareroot 10E-19 -> 1.0E-9 +sqtx805 squareroot 10E-19 -> 1.0E-9 -- exact precision: 12 -- Etiny=-20 sqtx806 squareroot 10E-20 -> 3.1622776602E-10 Underflow Subnormal Inexact Rounded -sqtx807 squareroot 1E-20 -> 1E-10 Subnormal -- Exact Subnormal case +sqtx807 squareroot 1E-20 -> 1E-10 Subnormal -- exact Subnormal case precision: 13 -- Etiny=-21 sqtx808 squareroot 1E-21 -> 3.1622776602E-11 Underflow Subnormal Inexact Rounded -sqtx809 squareroot 10E-21 -> 1.0E-10 Subnormal +sqtx809 squareroot 10E-21 -> 1.0E-10 Subnormal -- exact Subnormal case precision: 14 -- Etiny=-22 sqtx810 squareroot 1E-21 -> 3.16227766017E-11 Underflow Subnormal Inexact Rounded sqtx811 squareroot 10E-22 -> 3.16227766017E-11 Underflow Subnormal Inexact Rounded -sqtx812 squareroot 1E-22 -> 1E-11 Subnormal -- Exact Subnormal case +sqtx812 squareroot 1E-22 -> 1E-11 Subnormal -- exact Subnormal case +-- Not enough digits? +precision: 16 +maxExponent: 384 +minExponent: -383 +rounding: half_even +sqtx815 squareroot 1.0000000001000000E-78 -> 1.000000000050000E-39 Inexact Rounded +-- 1 234567890123456 -- special values maxexponent: 999 @@ -2954,5 +2963,842 @@ sqtx827 squareroot -NaN654 -> -NaN654 sqtx828 squareroot NaN1 -> NaN1 +-- payload decapitate +precision: 5 +sqtx840 squareroot -sNaN1234567890 -> -NaN67890 Invalid_operation + +------------------------------------------------------------------------ +-- +-- Special thanks to Mark Dickinson for tests in the range 8000-8999. +-- +-- Extra tests for the square root function, dealing with a variety of +-- corner cases. In particular, these tests concentrate on +-- (1) cases where the input precision exceeds the context precision, and +-- (2) cases where the input exponent is outside the current context, +-- and in particular when the result is subnormal +-- +-- maxexponent and minexponent are set to 9 and -9 for most of these +-- cases; only the precision changes. The rounding also does not +-- change, because it is ignored for this operation. +maxexponent: 9 +minexponent: -9 + +-- exact results, input precision > context precision +precision: 1 +sqtx8000 squareroot 0 -> 0 +sqtx8001 squareroot 1 -> 1 +sqtx8002 squareroot 4 -> 2 +sqtx8003 squareroot 9 -> 3 +sqtx8004 squareroot 16 -> 4 +sqtx8005 squareroot 25 -> 5 +sqtx8006 squareroot 36 -> 6 +sqtx8007 squareroot 49 -> 7 +sqtx8008 squareroot 64 -> 8 +sqtx8009 squareroot 81 -> 9 +sqtx8010 squareroot 100 -> 1E+1 Rounded +sqtx8011 squareroot 121 -> 1E+1 Inexact Rounded + +precision: 2 +sqtx8012 squareroot 0 -> 0 +sqtx8013 squareroot 1 -> 1 +sqtx8014 squareroot 4 -> 2 +sqtx8015 squareroot 9 -> 3 +sqtx8016 squareroot 16 -> 4 +sqtx8017 squareroot 25 -> 5 +sqtx8018 squareroot 36 -> 6 +sqtx8019 squareroot 49 -> 7 +sqtx8020 squareroot 64 -> 8 +sqtx8021 squareroot 81 -> 9 +sqtx8022 squareroot 100 -> 10 +sqtx8023 squareroot 121 -> 11 +sqtx8024 squareroot 144 -> 12 +sqtx8025 squareroot 169 -> 13 +sqtx8026 squareroot 196 -> 14 +sqtx8027 squareroot 225 -> 15 +sqtx8028 squareroot 256 -> 16 +sqtx8029 squareroot 289 -> 17 +sqtx8030 squareroot 324 -> 18 +sqtx8031 squareroot 361 -> 19 +sqtx8032 squareroot 400 -> 20 +sqtx8033 squareroot 441 -> 21 +sqtx8034 squareroot 484 -> 22 +sqtx8035 squareroot 529 -> 23 +sqtx8036 squareroot 576 -> 24 +sqtx8037 squareroot 625 -> 25 +sqtx8038 squareroot 676 -> 26 +sqtx8039 squareroot 729 -> 27 +sqtx8040 squareroot 784 -> 28 +sqtx8041 squareroot 841 -> 29 +sqtx8042 squareroot 900 -> 30 +sqtx8043 squareroot 961 -> 31 +sqtx8044 squareroot 1024 -> 32 +sqtx8045 squareroot 1089 -> 33 +sqtx8046 squareroot 1156 -> 34 +sqtx8047 squareroot 1225 -> 35 +sqtx8048 squareroot 1296 -> 36 +sqtx8049 squareroot 1369 -> 37 +sqtx8050 squareroot 1444 -> 38 +sqtx8051 squareroot 1521 -> 39 +sqtx8052 squareroot 1600 -> 40 +sqtx8053 squareroot 1681 -> 41 +sqtx8054 squareroot 1764 -> 42 +sqtx8055 squareroot 1849 -> 43 +sqtx8056 squareroot 1936 -> 44 +sqtx8057 squareroot 2025 -> 45 +sqtx8058 squareroot 2116 -> 46 +sqtx8059 squareroot 2209 -> 47 +sqtx8060 squareroot 2304 -> 48 +sqtx8061 squareroot 2401 -> 49 +sqtx8062 squareroot 2500 -> 50 +sqtx8063 squareroot 2601 -> 51 +sqtx8064 squareroot 2704 -> 52 +sqtx8065 squareroot 2809 -> 53 +sqtx8066 squareroot 2916 -> 54 +sqtx8067 squareroot 3025 -> 55 +sqtx8068 squareroot 3136 -> 56 +sqtx8069 squareroot 3249 -> 57 +sqtx8070 squareroot 3364 -> 58 +sqtx8071 squareroot 3481 -> 59 +sqtx8072 squareroot 3600 -> 60 +sqtx8073 squareroot 3721 -> 61 +sqtx8074 squareroot 3844 -> 62 +sqtx8075 squareroot 3969 -> 63 +sqtx8076 squareroot 4096 -> 64 +sqtx8077 squareroot 4225 -> 65 +sqtx8078 squareroot 4356 -> 66 +sqtx8079 squareroot 4489 -> 67 +sqtx8080 squareroot 4624 -> 68 +sqtx8081 squareroot 4761 -> 69 +sqtx8082 squareroot 4900 -> 70 +sqtx8083 squareroot 5041 -> 71 +sqtx8084 squareroot 5184 -> 72 +sqtx8085 squareroot 5329 -> 73 +sqtx8086 squareroot 5476 -> 74 +sqtx8087 squareroot 5625 -> 75 +sqtx8088 squareroot 5776 -> 76 +sqtx8089 squareroot 5929 -> 77 +sqtx8090 squareroot 6084 -> 78 +sqtx8091 squareroot 6241 -> 79 +sqtx8092 squareroot 6400 -> 80 +sqtx8093 squareroot 6561 -> 81 +sqtx8094 squareroot 6724 -> 82 +sqtx8095 squareroot 6889 -> 83 +sqtx8096 squareroot 7056 -> 84 +sqtx8097 squareroot 7225 -> 85 +sqtx8098 squareroot 7396 -> 86 +sqtx8099 squareroot 7569 -> 87 +sqtx8100 squareroot 7744 -> 88 +sqtx8101 squareroot 7921 -> 89 +sqtx8102 squareroot 8100 -> 90 +sqtx8103 squareroot 8281 -> 91 +sqtx8104 squareroot 8464 -> 92 +sqtx8105 squareroot 8649 -> 93 +sqtx8106 squareroot 8836 -> 94 +sqtx8107 squareroot 9025 -> 95 +sqtx8108 squareroot 9216 -> 96 +sqtx8109 squareroot 9409 -> 97 +sqtx8110 squareroot 9604 -> 98 +sqtx8111 squareroot 9801 -> 99 +sqtx8112 squareroot 10000 -> 1.0E+2 Rounded +sqtx8113 squareroot 10201 -> 1.0E+2 Inexact Rounded + +precision: 3 +sqtx8114 squareroot 841 -> 29 +sqtx8115 squareroot 1600 -> 40 +sqtx8116 squareroot 2209 -> 47 +sqtx8117 squareroot 9604 -> 98 +sqtx8118 squareroot 21316 -> 146 +sqtx8119 squareroot 52441 -> 229 +sqtx8120 squareroot 68644 -> 262 +sqtx8121 squareroot 69696 -> 264 +sqtx8122 squareroot 70225 -> 265 +sqtx8123 squareroot 76729 -> 277 +sqtx8124 squareroot 130321 -> 361 +sqtx8125 squareroot 171396 -> 414 +sqtx8126 squareroot 270400 -> 520 +sqtx8127 squareroot 279841 -> 529 +sqtx8128 squareroot 407044 -> 638 +sqtx8129 squareroot 408321 -> 639 +sqtx8130 squareroot 480249 -> 693 +sqtx8131 squareroot 516961 -> 719 +sqtx8132 squareroot 692224 -> 832 +sqtx8133 squareroot 829921 -> 911 + +-- selection of random exact results +precision: 6 +sqtx8134 squareroot 2.25E-12 -> 0.0000015 +sqtx8135 squareroot 8.41E-14 -> 2.9E-7 +sqtx8136 squareroot 6.241E-15 -> 7.9E-8 +sqtx8137 squareroot 5.041E+13 -> 7.1E+6 +sqtx8138 squareroot 4761 -> 69 +sqtx8139 squareroot 1.369E+17 -> 3.7E+8 +sqtx8140 squareroot 0.00002116 -> 0.0046 +sqtx8141 squareroot 7.29E+4 -> 2.7E+2 +sqtx8142 squareroot 4.624E-13 -> 6.8E-7 +sqtx8143 squareroot 3.969E+5 -> 6.3E+2 +sqtx8144 squareroot 3.73321E-11 -> 0.00000611 +sqtx8145 squareroot 5.61001E+17 -> 7.49E+8 +sqtx8146 squareroot 2.30400E-11 -> 0.00000480 +sqtx8147 squareroot 4.30336E+17 -> 6.56E+8 +sqtx8148 squareroot 0.057121 -> 0.239 +sqtx8149 squareroot 7.225E+17 -> 8.5E+8 +sqtx8150 squareroot 3.14721E+13 -> 5.61E+6 +sqtx8151 squareroot 4.61041E+17 -> 6.79E+8 +sqtx8152 squareroot 1.39876E-15 -> 3.74E-8 +sqtx8153 squareroot 6.19369E-9 -> 0.0000787 +sqtx8154 squareroot 1.620529E-10 -> 0.00001273 +sqtx8155 squareroot 1177.1761 -> 34.31 +sqtx8156 squareroot 67043344 -> 8188 +sqtx8157 squareroot 4.84E+6 -> 2.2E+3 +sqtx8158 squareroot 1.23904E+11 -> 3.52E+5 +sqtx8159 squareroot 32604100 -> 5710 +sqtx8160 squareroot 2.9757025E-11 -> 0.000005455 +sqtx8161 squareroot 6.3760225E-9 -> 0.00007985 +sqtx8162 squareroot 4.5198729E-11 -> 0.000006723 +sqtx8163 squareroot 1.4745600E-11 -> 0.000003840 +sqtx8164 squareroot 18964283.04 -> 4354.8 +sqtx8165 squareroot 3.308895529E+13 -> 5.7523E+6 +sqtx8166 squareroot 0.0028590409 -> 0.05347 +sqtx8167 squareroot 3572.213824 -> 59.768 +sqtx8168 squareroot 4.274021376E+15 -> 6.5376E+7 +sqtx8169 squareroot 4455476.64 -> 2110.8 +sqtx8170 squareroot 38.44 -> 6.2 +sqtx8171 squareroot 68.558400 -> 8.280 +sqtx8172 squareroot 715402009 -> 26747 +sqtx8173 squareroot 93.373569 -> 9.663 +sqtx8174 squareroot 2.62144000000E+15 -> 5.12000E+7 +sqtx8175 squareroot 7.48225000000E+15 -> 8.65000E+7 +sqtx8176 squareroot 3.38724000000E-9 -> 0.0000582000 +sqtx8177 squareroot 5.64001000000E-13 -> 7.51000E-7 +sqtx8178 squareroot 5.06944000000E-15 -> 7.12000E-8 +sqtx8179 squareroot 4.95616000000E+17 -> 7.04000E+8 +sqtx8180 squareroot 0.0000242064000000 -> 0.00492000 +sqtx8181 squareroot 1.48996000000E-15 -> 3.86000E-8 +sqtx8182 squareroot 9.37024000000E+17 -> 9.68000E+8 +sqtx8183 squareroot 7128900.0000 -> 2670.00 +sqtx8184 squareroot 8.2311610000E-10 -> 0.0000286900 +sqtx8185 squareroot 482747040000 -> 694800 +sqtx8186 squareroot 4.14478440000E+17 -> 6.43800E+8 +sqtx8187 squareroot 5.10510250000E-7 -> 0.000714500 +sqtx8188 squareroot 355096.810000 -> 595.900 +sqtx8189 squareroot 14288400.0000 -> 3780.00 +sqtx8190 squareroot 3.36168040000E-15 -> 5.79800E-8 +sqtx8191 squareroot 1.70899560000E-13 -> 4.13400E-7 +sqtx8192 squareroot 0.0000378348010000 -> 0.00615100 +sqtx8193 squareroot 2.00972890000E-13 -> 4.48300E-7 +sqtx8194 squareroot 4.07222659600E-13 -> 6.38140E-7 +sqtx8195 squareroot 131486012100 -> 362610 +sqtx8196 squareroot 818192611600 -> 904540 +sqtx8197 squareroot 9.8558323600E+16 -> 3.13940E+8 +sqtx8198 squareroot 5641.06144900 -> 75.1070 +sqtx8199 squareroot 4.58789475600E+17 -> 6.77340E+8 +sqtx8200 squareroot 3.21386948100E-9 -> 0.0000566910 +sqtx8201 squareroot 3.9441960000E-8 -> 0.000198600 +sqtx8202 squareroot 242723.728900 -> 492.670 +sqtx8203 squareroot 1874.89000000 -> 43.3000 +sqtx8204 squareroot 2.56722595684E+15 -> 5.06678E+7 +sqtx8205 squareroot 3.96437714689E-17 -> 6.29633E-9 +sqtx8206 squareroot 3.80106774784E-17 -> 6.16528E-9 +sqtx8207 squareroot 1.42403588496E-13 -> 3.77364E-7 +sqtx8208 squareroot 4604.84388100 -> 67.8590 +sqtx8209 squareroot 2157100869.16 -> 46444.6 +sqtx8210 squareroot 355288570.81 -> 18849.1 +sqtx8211 squareroot 4.69775901604E-11 -> 0.00000685402 +sqtx8212 squareroot 8.22115770436E+17 -> 9.06706E+8 +sqtx8213 squareroot 7.16443744900E+15 -> 8.46430E+7 +sqtx8214 squareroot 9.48995498896E+15 -> 9.74164E+7 +sqtx8215 squareroot 0.0000419091801129 -> 0.00647373 +sqtx8216 squareroot 5862627996.84 -> 76567.8 +sqtx8217 squareroot 9369537.3409 -> 3060.97 +sqtx8218 squareroot 7.74792529729E+17 -> 8.80223E+8 +sqtx8219 squareroot 1.08626931396E+17 -> 3.29586E+8 +sqtx8220 squareroot 8.89584739684E-7 -> 0.000943178 +sqtx8221 squareroot 4.0266040896E-18 -> 2.00664E-9 +sqtx8222 squareroot 9.27669480336E-7 -> 0.000963156 +sqtx8223 squareroot 0.00225497717956 -> 0.0474866 + +-- test use of round-half-even for ties +precision: 1 +sqtx8224 squareroot 225 -> 2E+1 Inexact Rounded +sqtx8225 squareroot 625 -> 2E+1 Inexact Rounded +sqtx8226 squareroot 1225 -> 4E+1 Inexact Rounded +sqtx8227 squareroot 2025 -> 4E+1 Inexact Rounded +sqtx8228 squareroot 3025 -> 6E+1 Inexact Rounded +sqtx8229 squareroot 4225 -> 6E+1 Inexact Rounded +sqtx8230 squareroot 5625 -> 8E+1 Inexact Rounded +sqtx8231 squareroot 7225 -> 8E+1 Inexact Rounded +sqtx8232 squareroot 9025 -> 1E+2 Inexact Rounded + +precision: 2 +sqtx8233 squareroot 11025 -> 1.0E+2 Inexact Rounded +sqtx8234 squareroot 13225 -> 1.2E+2 Inexact Rounded +sqtx8235 squareroot 15625 -> 1.2E+2 Inexact Rounded +sqtx8236 squareroot 18225 -> 1.4E+2 Inexact Rounded +sqtx8237 squareroot 21025 -> 1.4E+2 Inexact Rounded +sqtx8238 squareroot 24025 -> 1.6E+2 Inexact Rounded +sqtx8239 squareroot 27225 -> 1.6E+2 Inexact Rounded +sqtx8240 squareroot 30625 -> 1.8E+2 Inexact Rounded +sqtx8241 squareroot 34225 -> 1.8E+2 Inexact Rounded +sqtx8242 squareroot 38025 -> 2.0E+2 Inexact Rounded +sqtx8243 squareroot 42025 -> 2.0E+2 Inexact Rounded +sqtx8244 squareroot 46225 -> 2.2E+2 Inexact Rounded +sqtx8245 squareroot 50625 -> 2.2E+2 Inexact Rounded +sqtx8246 squareroot 55225 -> 2.4E+2 Inexact Rounded +sqtx8247 squareroot 60025 -> 2.4E+2 Inexact Rounded +sqtx8248 squareroot 65025 -> 2.6E+2 Inexact Rounded +sqtx8249 squareroot 70225 -> 2.6E+2 Inexact Rounded +sqtx8250 squareroot 75625 -> 2.8E+2 Inexact Rounded +sqtx8251 squareroot 81225 -> 2.8E+2 Inexact Rounded +sqtx8252 squareroot 87025 -> 3.0E+2 Inexact Rounded +sqtx8253 squareroot 93025 -> 3.0E+2 Inexact Rounded +sqtx8254 squareroot 99225 -> 3.2E+2 Inexact Rounded +sqtx8255 squareroot 105625 -> 3.2E+2 Inexact Rounded +sqtx8256 squareroot 112225 -> 3.4E+2 Inexact Rounded +sqtx8257 squareroot 119025 -> 3.4E+2 Inexact Rounded +sqtx8258 squareroot 126025 -> 3.6E+2 Inexact Rounded +sqtx8259 squareroot 133225 -> 3.6E+2 Inexact Rounded +sqtx8260 squareroot 140625 -> 3.8E+2 Inexact Rounded +sqtx8261 squareroot 148225 -> 3.8E+2 Inexact Rounded +sqtx8262 squareroot 156025 -> 4.0E+2 Inexact Rounded +sqtx8263 squareroot 164025 -> 4.0E+2 Inexact Rounded +sqtx8264 squareroot 172225 -> 4.2E+2 Inexact Rounded +sqtx8265 squareroot 180625 -> 4.2E+2 Inexact Rounded +sqtx8266 squareroot 189225 -> 4.4E+2 Inexact Rounded +sqtx8267 squareroot 198025 -> 4.4E+2 Inexact Rounded +sqtx8268 squareroot 207025 -> 4.6E+2 Inexact Rounded +sqtx8269 squareroot 216225 -> 4.6E+2 Inexact Rounded +sqtx8270 squareroot 225625 -> 4.8E+2 Inexact Rounded +sqtx8271 squareroot 235225 -> 4.8E+2 Inexact Rounded +sqtx8272 squareroot 245025 -> 5.0E+2 Inexact Rounded +sqtx8273 squareroot 255025 -> 5.0E+2 Inexact Rounded +sqtx8274 squareroot 265225 -> 5.2E+2 Inexact Rounded +sqtx8275 squareroot 275625 -> 5.2E+2 Inexact Rounded +sqtx8276 squareroot 286225 -> 5.4E+2 Inexact Rounded +sqtx8277 squareroot 297025 -> 5.4E+2 Inexact Rounded +sqtx8278 squareroot 308025 -> 5.6E+2 Inexact Rounded +sqtx8279 squareroot 319225 -> 5.6E+2 Inexact Rounded +sqtx8280 squareroot 330625 -> 5.8E+2 Inexact Rounded +sqtx8281 squareroot 342225 -> 5.8E+2 Inexact Rounded +sqtx8282 squareroot 354025 -> 6.0E+2 Inexact Rounded +sqtx8283 squareroot 366025 -> 6.0E+2 Inexact Rounded +sqtx8284 squareroot 378225 -> 6.2E+2 Inexact Rounded +sqtx8285 squareroot 390625 -> 6.2E+2 Inexact Rounded +sqtx8286 squareroot 403225 -> 6.4E+2 Inexact Rounded +sqtx8287 squareroot 416025 -> 6.4E+2 Inexact Rounded +sqtx8288 squareroot 429025 -> 6.6E+2 Inexact Rounded +sqtx8289 squareroot 442225 -> 6.6E+2 Inexact Rounded +sqtx8290 squareroot 455625 -> 6.8E+2 Inexact Rounded +sqtx8291 squareroot 469225 -> 6.8E+2 Inexact Rounded +sqtx8292 squareroot 483025 -> 7.0E+2 Inexact Rounded +sqtx8293 squareroot 497025 -> 7.0E+2 Inexact Rounded +sqtx8294 squareroot 511225 -> 7.2E+2 Inexact Rounded +sqtx8295 squareroot 525625 -> 7.2E+2 Inexact Rounded +sqtx8296 squareroot 540225 -> 7.4E+2 Inexact Rounded +sqtx8297 squareroot 555025 -> 7.4E+2 Inexact Rounded +sqtx8298 squareroot 570025 -> 7.6E+2 Inexact Rounded +sqtx8299 squareroot 585225 -> 7.6E+2 Inexact Rounded +sqtx8300 squareroot 600625 -> 7.8E+2 Inexact Rounded +sqtx8301 squareroot 616225 -> 7.8E+2 Inexact Rounded +sqtx8302 squareroot 632025 -> 8.0E+2 Inexact Rounded +sqtx8303 squareroot 648025 -> 8.0E+2 Inexact Rounded +sqtx8304 squareroot 664225 -> 8.2E+2 Inexact Rounded +sqtx8305 squareroot 680625 -> 8.2E+2 Inexact Rounded +sqtx8306 squareroot 697225 -> 8.4E+2 Inexact Rounded +sqtx8307 squareroot 714025 -> 8.4E+2 Inexact Rounded +sqtx8308 squareroot 731025 -> 8.6E+2 Inexact Rounded +sqtx8309 squareroot 748225 -> 8.6E+2 Inexact Rounded +sqtx8310 squareroot 765625 -> 8.8E+2 Inexact Rounded +sqtx8311 squareroot 783225 -> 8.8E+2 Inexact Rounded +sqtx8312 squareroot 801025 -> 9.0E+2 Inexact Rounded +sqtx8313 squareroot 819025 -> 9.0E+2 Inexact Rounded +sqtx8314 squareroot 837225 -> 9.2E+2 Inexact Rounded +sqtx8315 squareroot 855625 -> 9.2E+2 Inexact Rounded +sqtx8316 squareroot 874225 -> 9.4E+2 Inexact Rounded +sqtx8317 squareroot 893025 -> 9.4E+2 Inexact Rounded +sqtx8318 squareroot 912025 -> 9.6E+2 Inexact Rounded +sqtx8319 squareroot 931225 -> 9.6E+2 Inexact Rounded +sqtx8320 squareroot 950625 -> 9.8E+2 Inexact Rounded +sqtx8321 squareroot 970225 -> 9.8E+2 Inexact Rounded +sqtx8322 squareroot 990025 -> 1.0E+3 Inexact Rounded + +precision: 6 +sqtx8323 squareroot 88975734963025 -> 9.43270E+6 Inexact Rounded +sqtx8324 squareroot 71085555000625 -> 8.43122E+6 Inexact Rounded +sqtx8325 squareroot 39994304.051025 -> 6324.10 Inexact Rounded +sqtx8326 squareroot 0.000007327172265625 -> 0.00270688 Inexact Rounded +sqtx8327 squareroot 1.0258600439025E-13 -> 3.20290E-7 Inexact Rounded +sqtx8328 squareroot 0.0034580574275625 -> 0.0588052 Inexact Rounded +sqtx8329 squareroot 7.6842317700625E-7 -> 0.000876598 Inexact Rounded +sqtx8330 squareroot 1263834495.2025 -> 35550.4 Inexact Rounded +sqtx8331 squareroot 433970666460.25 -> 658764 Inexact Rounded +sqtx8332 squareroot 4.5879286230625E-7 -> 0.000677342 Inexact Rounded +sqtx8333 squareroot 0.0029305603306225 -> 0.0541346 Inexact Rounded +sqtx8334 squareroot 70218282.733225 -> 8379.64 Inexact Rounded +sqtx8335 squareroot 11942519.082025 -> 3455.80 Inexact Rounded +sqtx8336 squareroot 0.0021230668905625 -> 0.0460768 Inexact Rounded +sqtx8337 squareroot 0.90081833411025 -> 0.949114 Inexact Rounded +sqtx8338 squareroot 5.5104120936225E-17 -> 7.42322E-9 Inexact Rounded +sqtx8339 squareroot 0.10530446854225 -> 0.324506 Inexact Rounded +sqtx8340 squareroot 8.706069866025E-14 -> 2.95060E-7 Inexact Rounded +sqtx8341 squareroot 23838.58800625 -> 154.398 Inexact Rounded +sqtx8342 squareroot 0.0013426911275625 -> 0.0366428 Inexact Rounded + +-- test use of round-half-even in underflow situations + +-- precisions 2; all cases where result is both subnormal and a tie +precision: 2 +sqtx8343 squareroot 2.5E-21 -> 0E-10 Underflow Subnormal Inexact Rounded Clamped +sqtx8344 squareroot 2.25E-20 -> 2E-10 Underflow Subnormal Inexact Rounded +sqtx8345 squareroot 6.25E-20 -> 2E-10 Underflow Subnormal Inexact Rounded +sqtx8346 squareroot 1.225E-19 -> 4E-10 Underflow Subnormal Inexact Rounded +sqtx8347 squareroot 2.025E-19 -> 4E-10 Underflow Subnormal Inexact Rounded +sqtx8348 squareroot 3.025E-19 -> 6E-10 Underflow Subnormal Inexact Rounded +sqtx8349 squareroot 4.225E-19 -> 6E-10 Underflow Subnormal Inexact Rounded +sqtx8350 squareroot 5.625E-19 -> 8E-10 Underflow Subnormal Inexact Rounded +sqtx8351 squareroot 7.225E-19 -> 8E-10 Underflow Subnormal Inexact Rounded +sqtx8352 squareroot 9.025E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded + +-- precision 3, input precision <= 5 +precision: 3 +sqtx8353 squareroot 2.5E-23 -> 0E-11 Underflow Subnormal Inexact Rounded Clamped +sqtx8354 squareroot 2.25E-22 -> 2E-11 Underflow Subnormal Inexact Rounded +sqtx8355 squareroot 6.25E-22 -> 2E-11 Underflow Subnormal Inexact Rounded +sqtx8356 squareroot 1.225E-21 -> 4E-11 Underflow Subnormal Inexact Rounded +sqtx8357 squareroot 2.025E-21 -> 4E-11 Underflow Subnormal Inexact Rounded +sqtx8358 squareroot 3.025E-21 -> 6E-11 Underflow Subnormal Inexact Rounded +sqtx8359 squareroot 4.225E-21 -> 6E-11 Underflow Subnormal Inexact Rounded +sqtx8360 squareroot 5.625E-21 -> 8E-11 Underflow Subnormal Inexact Rounded +sqtx8361 squareroot 7.225E-21 -> 8E-11 Underflow Subnormal Inexact Rounded +sqtx8362 squareroot 9.025E-21 -> 1.0E-10 Underflow Subnormal Inexact Rounded +sqtx8363 squareroot 1.1025E-20 -> 1.0E-10 Underflow Subnormal Inexact Rounded +sqtx8364 squareroot 1.3225E-20 -> 1.2E-10 Underflow Subnormal Inexact Rounded +sqtx8365 squareroot 1.5625E-20 -> 1.2E-10 Underflow Subnormal Inexact Rounded +sqtx8366 squareroot 1.8225E-20 -> 1.4E-10 Underflow Subnormal Inexact Rounded +sqtx8367 squareroot 2.1025E-20 -> 1.4E-10 Underflow Subnormal Inexact Rounded +sqtx8368 squareroot 2.4025E-20 -> 1.6E-10 Underflow Subnormal Inexact Rounded +sqtx8369 squareroot 2.7225E-20 -> 1.6E-10 Underflow Subnormal Inexact Rounded +sqtx8370 squareroot 3.0625E-20 -> 1.8E-10 Underflow Subnormal Inexact Rounded +sqtx8371 squareroot 3.4225E-20 -> 1.8E-10 Underflow Subnormal Inexact Rounded +sqtx8372 squareroot 3.8025E-20 -> 2.0E-10 Underflow Subnormal Inexact Rounded +sqtx8373 squareroot 4.2025E-20 -> 2.0E-10 Underflow Subnormal Inexact Rounded +sqtx8374 squareroot 4.6225E-20 -> 2.2E-10 Underflow Subnormal Inexact Rounded +sqtx8375 squareroot 5.0625E-20 -> 2.2E-10 Underflow Subnormal Inexact Rounded +sqtx8376 squareroot 5.5225E-20 -> 2.4E-10 Underflow Subnormal Inexact Rounded +sqtx8377 squareroot 6.0025E-20 -> 2.4E-10 Underflow Subnormal Inexact Rounded +sqtx8378 squareroot 6.5025E-20 -> 2.6E-10 Underflow Subnormal Inexact Rounded +sqtx8379 squareroot 7.0225E-20 -> 2.6E-10 Underflow Subnormal Inexact Rounded +sqtx8380 squareroot 7.5625E-20 -> 2.8E-10 Underflow Subnormal Inexact Rounded +sqtx8381 squareroot 8.1225E-20 -> 2.8E-10 Underflow Subnormal Inexact Rounded +sqtx8382 squareroot 8.7025E-20 -> 3.0E-10 Underflow Subnormal Inexact Rounded +sqtx8383 squareroot 9.3025E-20 -> 3.0E-10 Underflow Subnormal Inexact Rounded +sqtx8384 squareroot 9.9225E-20 -> 3.2E-10 Underflow Subnormal Inexact Rounded + +--precision 4, input precision <= 4 +precision: 4 +sqtx8385 squareroot 2.5E-25 -> 0E-12 Underflow Subnormal Inexact Rounded Clamped +sqtx8386 squareroot 2.25E-24 -> 2E-12 Underflow Subnormal Inexact Rounded +sqtx8387 squareroot 6.25E-24 -> 2E-12 Underflow Subnormal Inexact Rounded +sqtx8388 squareroot 1.225E-23 -> 4E-12 Underflow Subnormal Inexact Rounded +sqtx8389 squareroot 2.025E-23 -> 4E-12 Underflow Subnormal Inexact Rounded +sqtx8390 squareroot 3.025E-23 -> 6E-12 Underflow Subnormal Inexact Rounded +sqtx8391 squareroot 4.225E-23 -> 6E-12 Underflow Subnormal Inexact Rounded +sqtx8392 squareroot 5.625E-23 -> 8E-12 Underflow Subnormal Inexact Rounded +sqtx8393 squareroot 7.225E-23 -> 8E-12 Underflow Subnormal Inexact Rounded +sqtx8394 squareroot 9.025E-23 -> 1.0E-11 Underflow Subnormal Inexact Rounded + +--precision 5, input precision <= 5 +precision: 5 +sqtx8395 squareroot 2.5E-27 -> 0E-13 Underflow Subnormal Inexact Rounded Clamped +sqtx8396 squareroot 2.25E-26 -> 2E-13 Underflow Subnormal Inexact Rounded +sqtx8397 squareroot 6.25E-26 -> 2E-13 Underflow Subnormal Inexact Rounded +sqtx8398 squareroot 1.225E-25 -> 4E-13 Underflow Subnormal Inexact Rounded +sqtx8399 squareroot 2.025E-25 -> 4E-13 Underflow Subnormal Inexact Rounded +sqtx8400 squareroot 3.025E-25 -> 6E-13 Underflow Subnormal Inexact Rounded +sqtx8401 squareroot 4.225E-25 -> 6E-13 Underflow Subnormal Inexact Rounded +sqtx8402 squareroot 5.625E-25 -> 8E-13 Underflow Subnormal Inexact Rounded +sqtx8403 squareroot 7.225E-25 -> 8E-13 Underflow Subnormal Inexact Rounded +sqtx8404 squareroot 9.025E-25 -> 1.0E-12 Underflow Subnormal Inexact Rounded +sqtx8405 squareroot 1.1025E-24 -> 1.0E-12 Underflow Subnormal Inexact Rounded +sqtx8406 squareroot 1.3225E-24 -> 1.2E-12 Underflow Subnormal Inexact Rounded +sqtx8407 squareroot 1.5625E-24 -> 1.2E-12 Underflow Subnormal Inexact Rounded +sqtx8408 squareroot 1.8225E-24 -> 1.4E-12 Underflow Subnormal Inexact Rounded +sqtx8409 squareroot 2.1025E-24 -> 1.4E-12 Underflow Subnormal Inexact Rounded +sqtx8410 squareroot 2.4025E-24 -> 1.6E-12 Underflow Subnormal Inexact Rounded +sqtx8411 squareroot 2.7225E-24 -> 1.6E-12 Underflow Subnormal Inexact Rounded +sqtx8412 squareroot 3.0625E-24 -> 1.8E-12 Underflow Subnormal Inexact Rounded +sqtx8413 squareroot 3.4225E-24 -> 1.8E-12 Underflow Subnormal Inexact Rounded +sqtx8414 squareroot 3.8025E-24 -> 2.0E-12 Underflow Subnormal Inexact Rounded +sqtx8415 squareroot 4.2025E-24 -> 2.0E-12 Underflow Subnormal Inexact Rounded +sqtx8416 squareroot 4.6225E-24 -> 2.2E-12 Underflow Subnormal Inexact Rounded +sqtx8417 squareroot 5.0625E-24 -> 2.2E-12 Underflow Subnormal Inexact Rounded +sqtx8418 squareroot 5.5225E-24 -> 2.4E-12 Underflow Subnormal Inexact Rounded +sqtx8419 squareroot 6.0025E-24 -> 2.4E-12 Underflow Subnormal Inexact Rounded +sqtx8420 squareroot 6.5025E-24 -> 2.6E-12 Underflow Subnormal Inexact Rounded +sqtx8421 squareroot 7.0225E-24 -> 2.6E-12 Underflow Subnormal Inexact Rounded +sqtx8422 squareroot 7.5625E-24 -> 2.8E-12 Underflow Subnormal Inexact Rounded +sqtx8423 squareroot 8.1225E-24 -> 2.8E-12 Underflow Subnormal Inexact Rounded +sqtx8424 squareroot 8.7025E-24 -> 3.0E-12 Underflow Subnormal Inexact Rounded +sqtx8425 squareroot 9.3025E-24 -> 3.0E-12 Underflow Subnormal Inexact Rounded +sqtx8426 squareroot 9.9225E-24 -> 3.2E-12 Underflow Subnormal Inexact Rounded + +-- a random selection of values that Python2.5.1 rounds incorrectly +precision: 1 +sqtx8427 squareroot 227 -> 2E+1 Inexact Rounded +sqtx8428 squareroot 625 -> 2E+1 Inexact Rounded +sqtx8429 squareroot 1215 -> 3E+1 Inexact Rounded +sqtx8430 squareroot 2008 -> 4E+1 Inexact Rounded +sqtx8431 squareroot 2020 -> 4E+1 Inexact Rounded +sqtx8432 squareroot 2026 -> 5E+1 Inexact Rounded +sqtx8433 squareroot 2027 -> 5E+1 Inexact Rounded +sqtx8434 squareroot 2065 -> 5E+1 Inexact Rounded +sqtx8435 squareroot 2075 -> 5E+1 Inexact Rounded +sqtx8436 squareroot 2088 -> 5E+1 Inexact Rounded +sqtx8437 squareroot 3049 -> 6E+1 Inexact Rounded +sqtx8438 squareroot 3057 -> 6E+1 Inexact Rounded +sqtx8439 squareroot 3061 -> 6E+1 Inexact Rounded +sqtx8440 squareroot 3092 -> 6E+1 Inexact Rounded +sqtx8441 squareroot 4222 -> 6E+1 Inexact Rounded +sqtx8442 squareroot 5676 -> 8E+1 Inexact Rounded +sqtx8443 squareroot 5686 -> 8E+1 Inexact Rounded +sqtx8444 squareroot 7215 -> 8E+1 Inexact Rounded +sqtx8445 squareroot 9086 -> 1E+2 Inexact Rounded +sqtx8446 squareroot 9095 -> 1E+2 Inexact Rounded + +precision: 2 +sqtx8447 squareroot 1266 -> 36 Inexact Rounded +sqtx8448 squareroot 2552 -> 51 Inexact Rounded +sqtx8449 squareroot 5554 -> 75 Inexact Rounded +sqtx8450 squareroot 7832 -> 88 Inexact Rounded +sqtx8451 squareroot 13201 -> 1.1E+2 Inexact Rounded +sqtx8452 squareroot 15695 -> 1.3E+2 Inexact Rounded +sqtx8453 squareroot 18272 -> 1.4E+2 Inexact Rounded +sqtx8454 squareroot 21026 -> 1.5E+2 Inexact Rounded +sqtx8455 squareroot 24069 -> 1.6E+2 Inexact Rounded +sqtx8456 squareroot 34277 -> 1.9E+2 Inexact Rounded +sqtx8457 squareroot 46233 -> 2.2E+2 Inexact Rounded +sqtx8458 squareroot 46251 -> 2.2E+2 Inexact Rounded +sqtx8459 squareroot 46276 -> 2.2E+2 Inexact Rounded +sqtx8460 squareroot 70214 -> 2.6E+2 Inexact Rounded +sqtx8461 squareroot 81249 -> 2.9E+2 Inexact Rounded +sqtx8462 squareroot 81266 -> 2.9E+2 Inexact Rounded +sqtx8463 squareroot 93065 -> 3.1E+2 Inexact Rounded +sqtx8464 squareroot 93083 -> 3.1E+2 Inexact Rounded +sqtx8465 squareroot 99230 -> 3.2E+2 Inexact Rounded +sqtx8466 squareroot 99271 -> 3.2E+2 Inexact Rounded + +precision: 3 +sqtx8467 squareroot 11349 -> 107 Inexact Rounded +sqtx8468 squareroot 26738 -> 164 Inexact Rounded +sqtx8469 squareroot 31508 -> 178 Inexact Rounded +sqtx8470 squareroot 44734 -> 212 Inexact Rounded +sqtx8471 squareroot 44738 -> 212 Inexact Rounded +sqtx8472 squareroot 51307 -> 227 Inexact Rounded +sqtx8473 squareroot 62259 -> 250 Inexact Rounded +sqtx8474 squareroot 75901 -> 276 Inexact Rounded +sqtx8475 squareroot 76457 -> 277 Inexact Rounded +sqtx8476 squareroot 180287 -> 425 Inexact Rounded +sqtx8477 squareroot 202053 -> 450 Inexact Rounded +sqtx8478 squareroot 235747 -> 486 Inexact Rounded +sqtx8479 squareroot 256537 -> 506 Inexact Rounded +sqtx8480 squareroot 299772 -> 548 Inexact Rounded +sqtx8481 squareroot 415337 -> 644 Inexact Rounded +sqtx8482 squareroot 617067 -> 786 Inexact Rounded +sqtx8483 squareroot 628022 -> 792 Inexact Rounded +sqtx8484 squareroot 645629 -> 804 Inexact Rounded +sqtx8485 squareroot 785836 -> 886 Inexact Rounded +sqtx8486 squareroot 993066 -> 997 Inexact Rounded + +precision: 6 +sqtx8487 squareroot 14917781 -> 3862.35 Inexact Rounded +sqtx8488 squareroot 17237238 -> 4151.78 Inexact Rounded +sqtx8489 squareroot 18054463 -> 4249.05 Inexact Rounded +sqtx8490 squareroot 19990694 -> 4471.10 Inexact Rounded +sqtx8491 squareroot 29061855 -> 5390.90 Inexact Rounded +sqtx8492 squareroot 49166257 -> 7011.87 Inexact Rounded +sqtx8493 squareroot 53082086 -> 7285.75 Inexact Rounded +sqtx8494 squareroot 56787909 -> 7535.78 Inexact Rounded +sqtx8495 squareroot 81140019 -> 9007.78 Inexact Rounded +sqtx8496 squareroot 87977554 -> 9379.64 Inexact Rounded +sqtx8497 squareroot 93624683 -> 9675.98 Inexact Rounded +sqtx8498 squareroot 98732747 -> 9936.44 Inexact Rounded +sqtx8499 squareroot 99222813 -> 9961.06 Inexact Rounded +sqtx8500 squareroot 143883626 -> 11995.2 Inexact Rounded +sqtx8501 squareroot 180433301 -> 13432.5 Inexact Rounded +sqtx8502 squareroot 227034020 -> 15067.6 Inexact Rounded +sqtx8503 squareroot 283253992 -> 16830.2 Inexact Rounded +sqtx8504 squareroot 617047954 -> 24840.4 Inexact Rounded +sqtx8505 squareroot 736870094 -> 27145.4 Inexact Rounded +sqtx8506 squareroot 897322915 -> 29955.3 Inexact Rounded + +-- results close to minimum normal +precision: 1 +sqtx8507 squareroot 1E-20 -> 0E-9 Underflow Subnormal Inexact Rounded Clamped +sqtx8508 squareroot 1E-19 -> 0E-9 Underflow Subnormal Inexact Rounded Clamped +sqtx8509 squareroot 1E-18 -> 1E-9 + +precision: 2 +sqtx8510 squareroot 8.1E-19 -> 9E-10 Subnormal +sqtx8511 squareroot 8.10E-19 -> 9E-10 Subnormal Rounded +sqtx8512 squareroot 9.0E-19 -> 9E-10 Underflow Subnormal Inexact Rounded +sqtx8513 squareroot 9.02E-19 -> 9E-10 Underflow Subnormal Inexact Rounded +sqtx8514 squareroot 9.03E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8515 squareroot 9.1E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8516 squareroot 9.9E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8517 squareroot 9.91E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8518 squareroot 9.92E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8519 squareroot 9.95E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8520 squareroot 9.98E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8521 squareroot 9.99E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +sqtx8522 squareroot 1E-18 -> 1E-9 +sqtx8523 squareroot 1.0E-18 -> 1.0E-9 +sqtx8524 squareroot 1.00E-18 -> 1.0E-9 +sqtx8525 squareroot 1.000E-18 -> 1.0E-9 Rounded +sqtx8526 squareroot 1.0000E-18 -> 1.0E-9 Rounded +sqtx8527 squareroot 1.01E-18 -> 1.0E-9 Inexact Rounded +sqtx8528 squareroot 1.02E-18 -> 1.0E-9 Inexact Rounded +sqtx8529 squareroot 1.1E-18 -> 1.0E-9 Inexact Rounded + +precision: 3 +sqtx8530 squareroot 8.1E-19 -> 9E-10 Subnormal +sqtx8531 squareroot 8.10E-19 -> 9.0E-10 Subnormal +sqtx8532 squareroot 8.100E-19 -> 9.0E-10 Subnormal +sqtx8533 squareroot 8.1000E-19 -> 9.0E-10 Subnormal Rounded +sqtx8534 squareroot 9.9E-19 -> 9.9E-10 Underflow Subnormal Inexact Rounded +sqtx8535 squareroot 9.91E-19 -> 1.00E-9 Underflow Subnormal Inexact Rounded +sqtx8536 squareroot 9.99E-19 -> 1.00E-9 Underflow Subnormal Inexact Rounded +sqtx8537 squareroot 9.998E-19 -> 1.00E-9 Underflow Subnormal Inexact Rounded +sqtx8538 squareroot 1E-18 -> 1E-9 +sqtx8539 squareroot 1.0E-18 -> 1.0E-9 +sqtx8540 squareroot 1.00E-18 -> 1.0E-9 +sqtx8541 squareroot 1.000E-18 -> 1.00E-9 +sqtx8542 squareroot 1.0000E-18 -> 1.00E-9 +sqtx8543 squareroot 1.00000E-18 -> 1.00E-9 Rounded +sqtx8544 squareroot 1.000000E-18 -> 1.00E-9 Rounded +sqtx8545 squareroot 1.01E-18 -> 1.00E-9 Inexact Rounded +sqtx8546 squareroot 1.02E-18 -> 1.01E-9 Inexact Rounded + +-- result exactly representable with precision p, but not necessarily +-- exactly representable as a subnormal; check the correct flags are raised +precision: 2 +sqtx8547 squareroot 1.21E-20 -> 1E-10 Underflow Subnormal Inexact Rounded +sqtx8548 squareroot 1.44E-20 -> 1E-10 Underflow Subnormal Inexact Rounded +sqtx8549 squareroot 9.61E-20 -> 3E-10 Underflow Subnormal Inexact Rounded +sqtx8550 squareroot 8.836E-19 -> 9E-10 Underflow Subnormal Inexact Rounded +sqtx8551 squareroot 9.216E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded + +precision: 3 +sqtx8552 squareroot 1.21E-22 -> 1E-11 Underflow Subnormal Inexact Rounded +sqtx8553 squareroot 1.21E-20 -> 1.1E-10 Subnormal +sqtx8554 squareroot 1.96E-22 -> 1E-11 Underflow Subnormal Inexact Rounded +sqtx8555 squareroot 1.96E-20 -> 1.4E-10 Subnormal +sqtx8556 squareroot 2.56E-22 -> 2E-11 Underflow Subnormal Inexact Rounded +sqtx8557 squareroot 4.00E-22 -> 2E-11 Subnormal Rounded +sqtx8558 squareroot 7.84E-22 -> 3E-11 Underflow Subnormal Inexact Rounded +sqtx8559 squareroot 9.801E-21 -> 1.0E-10 Underflow Subnormal Inexact Rounded +sqtx8560 squareroot 9.801E-19 -> 9.9E-10 Subnormal +sqtx8561 squareroot 1.0201E-20 -> 1.0E-10 Underflow Subnormal Inexact Rounded +sqtx8562 squareroot 1.1025E-20 -> 1.0E-10 Underflow Subnormal Inexact Rounded +sqtx8563 squareroot 1.1236E-20 -> 1.1E-10 Underflow Subnormal Inexact Rounded +sqtx8564 squareroot 1.2996E-20 -> 1.1E-10 Underflow Subnormal Inexact Rounded +sqtx8565 squareroot 1.3225E-20 -> 1.2E-10 Underflow Subnormal Inexact Rounded + +-- A selection of subnormal results prone to double rounding errors +precision: 2 +sqtx8566 squareroot 2.3E-21 -> 0E-10 Underflow Subnormal Inexact Rounded Clamped +sqtx8567 squareroot 2.4E-21 -> 0E-10 Underflow Subnormal Inexact Rounded Clamped +sqtx8568 squareroot 2.5E-21 -> 0E-10 Underflow Subnormal Inexact Rounded Clamped +sqtx8569 squareroot 2.6E-21 -> 1E-10 Underflow Subnormal Inexact Rounded +sqtx8570 squareroot 2.7E-21 -> 1E-10 Underflow Subnormal Inexact Rounded +sqtx8571 squareroot 2.8E-21 -> 1E-10 Underflow Subnormal Inexact Rounded +sqtx8572 squareroot 2.2E-20 -> 1E-10 Underflow Subnormal Inexact Rounded +sqtx8573 squareroot 2.3E-20 -> 2E-10 Underflow Subnormal Inexact Rounded +sqtx8574 squareroot 2.4E-20 -> 2E-10 Underflow Subnormal Inexact Rounded +sqtx8575 squareroot 6.2E-20 -> 2E-10 Underflow Subnormal Inexact Rounded +sqtx8576 squareroot 6.3E-20 -> 3E-10 Underflow Subnormal Inexact Rounded +sqtx8577 squareroot 6.4E-20 -> 3E-10 Underflow Subnormal Inexact Rounded +sqtx8578 squareroot 6.5E-20 -> 3E-10 Underflow Subnormal Inexact Rounded +sqtx8579 squareroot 1.2E-19 -> 3E-10 Underflow Subnormal Inexact Rounded +sqtx8580 squareroot 2.0E-19 -> 4E-10 Underflow Subnormal Inexact Rounded +sqtx8581 squareroot 4.2E-19 -> 6E-10 Underflow Subnormal Inexact Rounded +sqtx8582 squareroot 5.6E-19 -> 7E-10 Underflow Subnormal Inexact Rounded +sqtx8583 squareroot 5.7E-19 -> 8E-10 Underflow Subnormal Inexact Rounded +sqtx8584 squareroot 9.0E-19 -> 9E-10 Underflow Subnormal Inexact Rounded +sqtx8585 squareroot 9.1E-19 -> 1.0E-9 Underflow Subnormal Inexact Rounded +precision: 3 +sqtx8586 squareroot 2.6E-23 -> 1E-11 Underflow Subnormal Inexact Rounded +sqtx8587 squareroot 2.22E-22 -> 1E-11 Underflow Subnormal Inexact Rounded +sqtx8588 squareroot 6.07E-22 -> 2E-11 Underflow Subnormal Inexact Rounded +sqtx8589 squareroot 6.25E-22 -> 2E-11 Underflow Subnormal Inexact Rounded +sqtx8590 squareroot 6.45E-22 -> 3E-11 Underflow Subnormal Inexact Rounded +sqtx8591 squareroot 6.50E-22 -> 3E-11 Underflow Subnormal Inexact Rounded +sqtx8592 squareroot 1.22E-21 -> 3E-11 Underflow Subnormal Inexact Rounded +sqtx8593 squareroot 1.24E-21 -> 4E-11 Underflow Subnormal Inexact Rounded +sqtx8594 squareroot 4.18E-21 -> 6E-11 Underflow Subnormal Inexact Rounded +sqtx8595 squareroot 7.19E-21 -> 8E-11 Underflow Subnormal Inexact Rounded +sqtx8596 squareroot 8.94E-21 -> 9E-11 Underflow Subnormal Inexact Rounded +sqtx8597 squareroot 1.81E-20 -> 1.3E-10 Underflow Subnormal Inexact Rounded +sqtx8598 squareroot 4.64E-20 -> 2.2E-10 Underflow Subnormal Inexact Rounded +sqtx8599 squareroot 5.06E-20 -> 2.2E-10 Underflow Subnormal Inexact Rounded +sqtx8600 squareroot 5.08E-20 -> 2.3E-10 Underflow Subnormal Inexact Rounded +sqtx8601 squareroot 7.00E-20 -> 2.6E-10 Underflow Subnormal Inexact Rounded +sqtx8602 squareroot 1.81E-19 -> 4.3E-10 Underflow Subnormal Inexact Rounded +sqtx8603 squareroot 6.64E-19 -> 8.1E-10 Underflow Subnormal Inexact Rounded +sqtx8604 squareroot 7.48E-19 -> 8.6E-10 Underflow Subnormal Inexact Rounded +sqtx8605 squareroot 9.91E-19 -> 1.00E-9 Underflow Subnormal Inexact Rounded +precision: 4 +sqtx8606 squareroot 6.24E-24 -> 2E-12 Underflow Subnormal Inexact Rounded +sqtx8607 squareroot 7.162E-23 -> 8E-12 Underflow Subnormal Inexact Rounded +sqtx8608 squareroot 7.243E-23 -> 9E-12 Underflow Subnormal Inexact Rounded +sqtx8609 squareroot 8.961E-23 -> 9E-12 Underflow Subnormal Inexact Rounded +sqtx8610 squareroot 9.029E-23 -> 1.0E-11 Underflow Subnormal Inexact Rounded +sqtx8611 squareroot 4.624E-22 -> 2.2E-11 Underflow Subnormal Inexact Rounded +sqtx8612 squareroot 5.980E-22 -> 2.4E-11 Underflow Subnormal Inexact Rounded +sqtx8613 squareroot 6.507E-22 -> 2.6E-11 Underflow Subnormal Inexact Rounded +sqtx8614 squareroot 1.483E-21 -> 3.9E-11 Underflow Subnormal Inexact Rounded +sqtx8615 squareroot 3.903E-21 -> 6.2E-11 Underflow Subnormal Inexact Rounded +sqtx8616 squareroot 8.733E-21 -> 9.3E-11 Underflow Subnormal Inexact Rounded +sqtx8617 squareroot 1.781E-20 -> 1.33E-10 Underflow Subnormal Inexact Rounded +sqtx8618 squareroot 6.426E-20 -> 2.53E-10 Underflow Subnormal Inexact Rounded +sqtx8619 squareroot 7.102E-20 -> 2.66E-10 Underflow Subnormal Inexact Rounded +sqtx8620 squareroot 7.535E-20 -> 2.74E-10 Underflow Subnormal Inexact Rounded +sqtx8621 squareroot 9.892E-20 -> 3.15E-10 Underflow Subnormal Inexact Rounded +sqtx8622 squareroot 1.612E-19 -> 4.01E-10 Underflow Subnormal Inexact Rounded +sqtx8623 squareroot 1.726E-19 -> 4.15E-10 Underflow Subnormal Inexact Rounded +sqtx8624 squareroot 1.853E-19 -> 4.30E-10 Underflow Subnormal Inexact Rounded +sqtx8625 squareroot 4.245E-19 -> 6.52E-10 Underflow Subnormal Inexact Rounded + +-- clamping and overflow for large exponents +precision: 1 +sqtx8626 squareroot 1E+18 -> 1E+9 +sqtx8627 squareroot 1E+19 -> 3E+9 Inexact Rounded +sqtx8628 squareroot 9E+19 -> 9E+9 Inexact Rounded +sqtx8629 squareroot 9.1E+19 -> Infinity Overflow Inexact Rounded +sqtx8630 squareroot 1E+20 -> Infinity Overflow Inexact Rounded + +precision: 2 +sqtx8631 squareroot 1E+18 -> 1E+9 +sqtx8632 squareroot 1.0E+18 -> 1.0E+9 +sqtx8633 squareroot 1.00E+18 -> 1.0E+9 +sqtx8634 squareroot 1.000E+18 -> 1.0E+9 Rounded +sqtx8635 squareroot 1E+20 -> Infinity Overflow Inexact Rounded +clamp: 1 +sqtx8636 squareroot 1E+18 -> 1.0E+9 Clamped +sqtx8637 squareroot 1.0E+18 -> 1.0E+9 +sqtx8638 squareroot 1E+20 -> Infinity Overflow Inexact Rounded +clamp: 0 + +precision: 6 +sqtx8639 squareroot 1E+18 -> 1E+9 +sqtx8640 squareroot 1.0000000000E+18 -> 1.00000E+9 +sqtx8641 squareroot 1.00000000000E+18 -> 1.00000E+9 Rounded +sqtx8642 squareroot 1E+20 -> Infinity Overflow Inexact Rounded +clamp: 1 +sqtx8643 squareroot 1E+8 -> 1E+4 +sqtx8644 squareroot 1E+10 -> 1.0E+5 Clamped +sqtx8645 squareroot 1.0E+10 -> 1.0E+5 +sqtx8646 squareroot 1E+12 -> 1.00E+6 Clamped +sqtx8647 squareroot 1.0E+12 -> 1.00E+6 Clamped +sqtx8648 squareroot 1.00E+12 -> 1.00E+6 Clamped +sqtx8649 squareroot 1.000E+12 -> 1.00E+6 +sqtx8650 squareroot 1E+18 -> 1.00000E+9 Clamped +sqtx8651 squareroot 1.00000000E+18 -> 1.00000E+9 Clamped +sqtx8652 squareroot 1.000000000E+18 -> 1.00000E+9 +sqtx8653 squareroot 1E+20 -> Infinity Overflow Inexact Rounded +clamp: 0 + +-- The following example causes a TypeError in Python 2.5.1 +precision: 3 +maxexponent: 9 +minexponent: -9 +sqtx8654 squareroot 10000000000 -> 1.00E+5 Rounded + +-- Additional tricky cases of underflown subnormals +rounding: half_even +precision: 5 +maxexponent: 999 +minexponent: -999 +sqtx8700 squareroot 2.8073E-2000 -> 1.675E-1000 Underflow Subnormal Inexact Rounded +sqtx8701 squareroot 2.8883E-2000 -> 1.699E-1000 Underflow Subnormal Inexact Rounded +sqtx8702 squareroot 3.1524E-2000 -> 1.775E-1000 Underflow Subnormal Inexact Rounded +sqtx8703 squareroot 3.2382E-2000 -> 1.799E-1000 Underflow Subnormal Inexact Rounded +sqtx8704 squareroot 3.5175E-2000 -> 1.875E-1000 Underflow Subnormal Inexact Rounded +sqtx8705 squareroot 3.6081E-2000 -> 1.899E-1000 Underflow Subnormal Inexact Rounded +sqtx8706 squareroot 3.9026E-2000 -> 1.975E-1000 Underflow Subnormal Inexact Rounded +sqtx8707 squareroot 3.9980E-2000 -> 1.999E-1000 Underflow Subnormal Inexact Rounded +sqtx8708 squareroot 4.3077E-2000 -> 2.075E-1000 Underflow Subnormal Inexact Rounded +sqtx8709 squareroot 4.4079E-2000 -> 2.099E-1000 Underflow Subnormal Inexact Rounded +sqtx8710 squareroot 4.7328E-2000 -> 2.175E-1000 Underflow Subnormal Inexact Rounded +sqtx8711 squareroot 4.8378E-2000 -> 2.199E-1000 Underflow Subnormal Inexact Rounded +sqtx8712 squareroot 5.1779E-2000 -> 2.275E-1000 Underflow Subnormal Inexact Rounded +sqtx8713 squareroot 5.2877E-2000 -> 2.299E-1000 Underflow Subnormal Inexact Rounded +sqtx8714 squareroot 5.6430E-2000 -> 2.375E-1000 Underflow Subnormal Inexact Rounded +sqtx8715 squareroot 5.7576E-2000 -> 2.399E-1000 Underflow Subnormal Inexact Rounded +sqtx8716 squareroot 6.1281E-2000 -> 2.475E-1000 Underflow Subnormal Inexact Rounded +sqtx8717 squareroot 6.2475E-2000 -> 2.499E-1000 Underflow Subnormal Inexact Rounded +sqtx8718 squareroot 6.6332E-2000 -> 2.575E-1000 Underflow Subnormal Inexact Rounded +sqtx8719 squareroot 6.7574E-2000 -> 2.599E-1000 Underflow Subnormal Inexact Rounded +sqtx8720 squareroot 7.1583E-2000 -> 2.675E-1000 Underflow Subnormal Inexact Rounded +sqtx8721 squareroot 7.2873E-2000 -> 2.699E-1000 Underflow Subnormal Inexact Rounded +sqtx8722 squareroot 7.7034E-2000 -> 2.775E-1000 Underflow Subnormal Inexact Rounded +sqtx8723 squareroot 7.8372E-2000 -> 2.799E-1000 Underflow Subnormal Inexact Rounded +sqtx8724 squareroot 8.2685E-2000 -> 2.875E-1000 Underflow Subnormal Inexact Rounded +sqtx8725 squareroot 8.4071E-2000 -> 2.899E-1000 Underflow Subnormal Inexact Rounded +sqtx8726 squareroot 8.8536E-2000 -> 2.975E-1000 Underflow Subnormal Inexact Rounded +sqtx8727 squareroot 8.9970E-2000 -> 2.999E-1000 Underflow Subnormal Inexact Rounded +sqtx8728 squareroot 9.4587E-2000 -> 3.075E-1000 Underflow Subnormal Inexact Rounded +sqtx8729 squareroot 9.6069E-2000 -> 3.099E-1000 Underflow Subnormal Inexact Rounded +-- (End of Mark Dickinson's testcases.) + + +-- Some additional edge cases +maxexponent: 9 +minexponent: -9 +precision: 2 +sqtx9000 squareroot 9980.01 -> 1.0E+2 Inexact Rounded +precision: 3 +sqtx9001 squareroot 9980.01 -> 99.9 +precision: 4 +sqtx9002 squareroot 9980.01 -> 99.9 + +-- Exact from over-precise +precision: 4 +sqtx9003 squareroot 11025 -> 105 +precision: 3 +sqtx9004 squareroot 11025 -> 105 +precision: 2 +sqtx9005 squareroot 11025 -> 1.0E+2 Inexact Rounded +precision: 1 +sqtx9006 squareroot 11025 -> 1E+2 Inexact Rounded + +-- Out-of-bounds zeros +precision: 4 +sqtx9010 squareroot 0E-9 -> 0.00000 +sqtx9011 squareroot 0E-10 -> 0.00000 +sqtx9012 squareroot 0E-11 -> 0.000000 +sqtx9013 squareroot 0E-12 -> 0.000000 +sqtx9014 squareroot 0E-13 -> 0E-7 +sqtx9015 squareroot 0E-14 -> 0E-7 +sqtx9020 squareroot 0E-17 -> 0E-9 +sqtx9021 squareroot 0E-20 -> 0E-10 +sqtx9022 squareroot 0E-22 -> 0E-11 +sqtx9023 squareroot 0E-24 -> 0E-12 +sqtx9024 squareroot 0E-25 -> 0E-12 Clamped +sqtx9025 squareroot 0E-26 -> 0E-12 Clamped +sqtx9026 squareroot 0E-27 -> 0E-12 Clamped +sqtx9027 squareroot 0E-28 -> 0E-12 Clamped + +sqtx9030 squareroot 0E+8 -> 0E+4 +sqtx9031 squareroot 0E+10 -> 0E+5 +sqtx9032 squareroot 0E+12 -> 0E+6 +sqtx9033 squareroot 0E+14 -> 0E+7 +sqtx9034 squareroot 0E+15 -> 0E+7 +sqtx9035 squareroot 0E+16 -> 0E+8 +sqtx9036 squareroot 0E+18 -> 0E+9 +sqtx9037 squareroot 0E+19 -> 0E+9 +sqtx9038 squareroot 0E+20 -> 0E+9 Clamped +sqtx9039 squareroot 0E+21 -> 0E+9 Clamped +sqtx9040 squareroot 0E+22 -> 0E+9 Clamped + + -- Null test -sqtx900 squareroot # -> NaN Invalid_operation +sqtx9900 squareroot # -> NaN Invalid_operation Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/subtract.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/subtract.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/subtract.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- subtract.decTest -- decimal subtraction -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 extended: 1 precision: 9 @@ -805,9 +805,9 @@ subx1015 subtract 0 0.999E-999 -> -1.00E-999 Inexact Rounded Subnormal Underflow subx1016 subtract 0 0.099E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow subx1017 subtract 0 0.009E-999 -> -1E-1001 Inexact Rounded Subnormal Underflow -subx1018 subtract 0 0.001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow -subx1019 subtract 0 0.0009E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow -subx1020 subtract 0 0.0001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow +subx1018 subtract 0 0.001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +subx1019 subtract 0 0.0009E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped +subx1020 subtract 0 0.0001E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped subx1030 subtract 0 -1.00E-999 -> 1.00E-999 subx1031 subtract 0 -0.1E-999 -> 1E-1000 Subnormal @@ -818,9 +818,9 @@ subx1035 subtract 0 -0.999E-999 -> 1.00E-999 Inexact Rounded Subnormal Underflow subx1036 subtract 0 -0.099E-999 -> 1.0E-1000 Inexact Rounded Subnormal Underflow subx1037 subtract 0 -0.009E-999 -> 1E-1001 Inexact Rounded Subnormal Underflow -subx1038 subtract 0 -0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -subx1039 subtract 0 -0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow -subx1040 subtract 0 -0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow +subx1038 subtract 0 -0.001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +subx1039 subtract 0 -0.0009E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped +subx1040 subtract 0 -0.0001E-999 -> 0E-1001 Inexact Rounded Subnormal Underflow Clamped -- some non-zero subnormal subtracts -- subx1056 is a tricky case @@ -831,7 +831,7 @@ subx1053 subtract 0.100E-999 0.1E-999 -> 0E-1001 Clamped subx1054 subtract 0.01E-999 0.1E-999 -> -9E-1001 Subnormal subx1055 subtract 0.999E-999 0.1E-999 -> 9.0E-1000 Inexact Rounded Subnormal Underflow -subx1056 subtract 0.099E-999 0.1E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow +subx1056 subtract 0.099E-999 0.1E-999 -> -0E-1001 Inexact Rounded Subnormal Underflow Clamped subx1057 subtract 0.009E-999 0.1E-999 -> -9E-1001 Inexact Rounded Subnormal Underflow subx1058 subtract 0.001E-999 0.1E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow subx1059 subtract 0.0009E-999 0.1E-999 -> -1.0E-1000 Inexact Rounded Subnormal Underflow @@ -849,15 +849,25 @@ subx1105 subtract 1.52445E-80 0 -> 1.524E-80 Inexact Rounded Subnormal Underflow subx1106 subtract 1.52446E-80 0 -> 1.524E-80 Inexact Rounded Subnormal Underflow -subx1111 subtract 1.2345678E-80 1.2345671E-80 -> 0E-83 Inexact Rounded Subnormal Underflow -subx1112 subtract 1.2345678E-80 1.2345618E-80 -> 0E-83 Inexact Rounded Subnormal Underflow -subx1113 subtract 1.2345678E-80 1.2345178E-80 -> 0E-83 Inexact Rounded Subnormal Underflow -subx1114 subtract 1.2345678E-80 1.2341678E-80 -> 0E-83 Inexact Rounded Subnormal Underflow +subx1111 subtract 1.2345678E-80 1.2345671E-80 -> 0E-83 Inexact Rounded Subnormal Underflow Clamped +subx1112 subtract 1.2345678E-80 1.2345618E-80 -> 0E-83 Inexact Rounded Subnormal Underflow Clamped +subx1113 subtract 1.2345678E-80 1.2345178E-80 -> 0E-83 Inexact Rounded Subnormal Underflow Clamped +subx1114 subtract 1.2345678E-80 1.2341678E-80 -> 0E-83 Inexact Rounded Subnormal Underflow Clamped subx1115 subtract 1.2345678E-80 1.2315678E-80 -> 3E-83 Rounded Subnormal subx1116 subtract 1.2345678E-80 1.2145678E-80 -> 2.0E-82 Rounded Subnormal subx1117 subtract 1.2345678E-80 1.1345678E-80 -> 1.00E-81 Rounded Subnormal subx1118 subtract 1.2345678E-80 0.2345678E-80 -> 1.000E-80 Rounded Subnormal +precision: 34 +rounding: half_up +maxExponent: 6144 +minExponent: -6143 +-- Examples from SQL proposal (Krishna Kulkarni) +subx1125 subtract 130E-2 120E-2 -> 0.10 +subx1126 subtract 130E-2 12E-1 -> 0.10 +subx1127 subtract 130E-2 1E0 -> 0.30 +subx1128 subtract 1E2 1E4 -> -9.9E+3 + -- Null tests subx9990 subtract 10 # -> NaN Invalid_operation subx9991 subtract # 10 -> NaN Invalid_operation Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/testall.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/testall.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/testall.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- testall.decTest -- run all general decimal arithmetic testcases -- --- Copyright (c) IBM Corporation, 1981, 2004. All rights reserved. -- +-- Copyright (c) IBM Corporation, 1981, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,41 +17,70 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- core tests (using Extended: 1) -------------------------------------- dectest: base + dectest: abs dectest: add +dectest: and dectest: clamp +dectest: class dectest: compare +dectest: comparesig +dectest: comparetotal +dectest: comparetotmag +dectest: copy +dectest: copyabs +dectest: copynegate +dectest: copysign dectest: divide dectest: divideint +dectest: exp +dectest: fma dectest: inexact +dectest: invert +dectest: ln +dectest: logb +dectest: log10 dectest: max +dectest: maxmag dectest: min +dectest: minmag dectest: minus dectest: multiply -dectest: normalize +dectest: nextminus +dectest: nextplus +dectest: nexttoward +dectest: or dectest: plus dectest: power +dectest: powersqrt dectest: quantize dectest: randoms +dectest: reduce -- [was called normalize] dectest: remainder dectest: remaindernear dectest: rescale -- [obsolete] +dectest: rotate dectest: rounding dectest: samequantum +dectest: scaleb +dectest: shift dectest: squareroot dectest: subtract dectest: tointegral +dectest: tointegralx dectest: trim +dectest: xor --- The next are for the Strawman 4d concrete representations -dectest: decimal32 -dectest: decimal64 -dectest: decimal128 - +-- The next are for the Strawman 4d concrete representations and +-- tests at those sizes [including dsEncode, ddEncode, and dqEncode, +-- which replace decimal32, decimal64, and decimal128] +dectest: decSingle +dectest: decDouble +dectest: decQuad -- General 31->33-digit boundary tests dectest: randombound32 Modified: python/branches/py3k-importlib/Lib/test/decimaltestdata/tointegral.decTest ============================================================================== --- python/branches/py3k-importlib/Lib/test/decimaltestdata/tointegral.decTest (original) +++ python/branches/py3k-importlib/Lib/test/decimaltestdata/tointegral.decTest Fri Sep 21 03:17:09 2007 @@ -1,6 +1,6 @@ ------------------------------------------------------------------------ -- tointegral.decTest -- round decimal to integral value -- --- Copyright (c) IBM Corporation, 2001, 2003. All rights reserved. -- +-- Copyright (c) IBM Corporation, 2001, 2007. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- @@ -17,7 +17,7 @@ -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc at uk.ibm.com -- ------------------------------------------------------------------------ -version: 2.39 +version: 2.56 -- This set of tests tests the extended specification 'round-to-integral -- value' operation (from IEEE 854, later modified in 754r). @@ -174,3 +174,68 @@ intx206 tointegral 7.89E+77 -> 7.89E+77 intx207 tointegral -Inf -> -Infinity + +-- all rounding modes +rounding: half_even + +intx210 tointegral 55.5 -> 56 +intx211 tointegral 56.5 -> 56 +intx212 tointegral 57.5 -> 58 +intx213 tointegral -55.5 -> -56 +intx214 tointegral -56.5 -> -56 +intx215 tointegral -57.5 -> -58 + +rounding: half_up + +intx220 tointegral 55.5 -> 56 +intx221 tointegral 56.5 -> 57 +intx222 tointegral 57.5 -> 58 +intx223 tointegral -55.5 -> -56 +intx224 tointegral -56.5 -> -57 +intx225 tointegral -57.5 -> -58 + +rounding: half_down + +intx230 tointegral 55.5 -> 55 +intx231 tointegral 56.5 -> 56 +intx232 tointegral 57.5 -> 57 +intx233 tointegral -55.5 -> -55 +intx234 tointegral -56.5 -> -56 +intx235 tointegral -57.5 -> -57 + +rounding: up + +intx240 tointegral 55.3 -> 56 +intx241 tointegral 56.3 -> 57 +intx242 tointegral 57.3 -> 58 +intx243 tointegral -55.3 -> -56 +intx244 tointegral -56.3 -> -57 +intx245 tointegral -57.3 -> -58 + +rounding: down + +intx250 tointegral 55.7 -> 55 +intx251 tointegral 56.7 -> 56 +intx252 tointegral 57.7 -> 57 +intx253 tointegral -55.7 -> -55 +intx254 tointegral -56.7 -> -56 +intx255 tointegral -57.7 -> -57 + +rounding: ceiling + +intx260 tointegral 55.3 -> 56 +intx261 tointegral 56.3 -> 57 +intx262 tointegral 57.3 -> 58 +intx263 tointegral -55.3 -> -55 +intx264 tointegral -56.3 -> -56 +intx265 tointegral -57.3 -> -57 + +rounding: floor + +intx270 tointegral 55.7 -> 55 +intx271 tointegral 56.7 -> 56 +intx272 tointegral 57.7 -> 57 +intx273 tointegral -55.7 -> -56 +intx274 tointegral -56.7 -> -57 +intx275 tointegral -57.7 -> -58 + Modified: python/branches/py3k-importlib/Lib/test/list_tests.py ============================================================================== --- python/branches/py3k-importlib/Lib/test/list_tests.py (original) +++ python/branches/py3k-importlib/Lib/test/list_tests.py Fri Sep 21 03:17:09 2007 @@ -46,6 +46,11 @@ self.assertEqual(str(a2), "[0, 1, 2, [...], 3]") self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]") + l0 = [] + for i in range(sys.getrecursionlimit() + 100): + l0 = [l0] + self.assertRaises(RuntimeError, repr, l0) + def test_print(self): d = self.type2test(range(200)) d.append(d) Modified: python/branches/py3k-importlib/Lib/test/regrtest.py ============================================================================== --- python/branches/py3k-importlib/Lib/test/regrtest.py (original) +++ python/branches/py3k-importlib/Lib/test/regrtest.py Fri Sep 21 03:17:09 2007 @@ -1108,7 +1108,6 @@ class _ExpectedSkips: def __init__(self): import os.path - from test import test_socket_ssl from test import test_timeout self.valid = False @@ -1120,8 +1119,13 @@ if not os.path.supports_unicode_filenames: self.expected.add('test_pep277') - if test_socket_ssl.skip_expected: - self.expected.add('test_socket_ssl') + try: + from test import test_socket_ssl + except ImportError: + pass + else: + if test_socket_ssl.skip_expected: + self.expected.add('test_socket_ssl') if test_timeout.skip_expected: self.expected.add('test_timeout') Modified: python/branches/py3k-importlib/Lib/test/test_cmd_line.py ============================================================================== --- python/branches/py3k-importlib/Lib/test/test_cmd_line.py (original) +++ python/branches/py3k-importlib/Lib/test/test_cmd_line.py Fri Sep 21 03:17:09 2007 @@ -4,7 +4,7 @@ import subprocess def _spawn_python(*args): - cmd_line = [sys.executable] + cmd_line = [sys.executable, '-E'] cmd_line.extend(args) return subprocess.Popen(cmd_line, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) @@ -24,7 +24,7 @@ return _kill_python(p) def exit_code(self, *args): - cmd_line = [sys.executable] + cmd_line = [sys.executable, '-E'] cmd_line.extend(args) return subprocess.call(cmd_line, stdout=subprocess.PIPE, stderr=subprocess.PIPE) @@ -38,9 +38,6 @@ self.assertTrue(data == b'' or data.endswith(b'\n')) self.assertTrue(b'Traceback' not in data) - def test_environment(self): - self.verify_valid_flag('-E') - def test_optimize(self): self.verify_valid_flag('-O') self.verify_valid_flag('-OO') Modified: python/branches/py3k-importlib/Lib/test/test_collections.py ============================================================================== --- python/branches/py3k-importlib/Lib/test/test_collections.py (original) +++ python/branches/py3k-importlib/Lib/test/test_collections.py Fri Sep 21 03:17:09 2007 @@ -38,6 +38,13 @@ self.assertEqual(repr(p), 'Point(x=11, y=22)') self.assert_('__dict__' not in dir(p)) # verify instance has no dict self.assert_('__weakref__' not in dir(p)) + self.assertEqual(p.__fields__, ('x', 'y')) # test __fields__ attribute + self.assertEqual(p.__replace__('x', 1), (1, 22)) # test __replace__ method + + # verify that field string can have commas + Point = NamedTuple('Point', 'x, y') + p = Point(x=11, y=22) + self.assertEqual(repr(p), 'Point(x=11, y=22)') def test_tupleness(self): Point = NamedTuple('Point', 'x y') @@ -58,6 +65,12 @@ self.assertEqual(p.y, y) self.assertRaises(AttributeError, eval, 'p.z', locals()) + def test_odd_sizes(self): + Zero = NamedTuple('Zero', '') + self.assertEqual(Zero(), ()) + Dot = NamedTuple('Dot', 'd') + self.assertEqual(Dot(1), (1,)) + class TestOneTrickPonyABCs(unittest.TestCase): Modified: python/branches/py3k-importlib/Lib/test/test_decimal.py ============================================================================== --- python/branches/py3k-importlib/Lib/test/test_decimal.py (original) +++ python/branches/py3k-importlib/Lib/test/test_decimal.py Fri Sep 21 03:17:09 2007 @@ -65,9 +65,7 @@ # Slower, since it runs some things several times. EXTENDEDERRORTEST = False - #Map the test cases' error names to the actual errors - ErrorNames = {'clamped' : Clamped, 'conversion_syntax' : InvalidOperation, 'division_by_zero' : DivisionByZero, @@ -92,20 +90,62 @@ 'half_down' : ROUND_HALF_DOWN, 'half_even' : ROUND_HALF_EVEN, 'half_up' : ROUND_HALF_UP, - 'up' : ROUND_UP} + 'up' : ROUND_UP, + '05up' : ROUND_05UP} # Name adapter to be able to change the Decimal and Context # interface without changing the test files from Cowlishaw nameAdapter = {'toeng':'to_eng_string', 'tosci':'to_sci_string', 'samequantum':'same_quantum', - 'tointegral':'to_integral', + 'tointegral':'to_integral_value', + 'tointegralx':'to_integral_exact', 'remaindernear':'remainder_near', 'divideint':'divide_int', 'squareroot':'sqrt', 'apply':'_apply', + 'class':'number_class', + 'comparesig':'compare_signal', + 'comparetotal':'compare_total', + 'comparetotmag':'compare_total_mag', + 'copyabs':'copy_abs', + 'copy':'copy_decimal', + 'copynegate':'copy_negate', + 'copysign':'copy_sign', + 'and':'logical_and', + 'or':'logical_or', + 'xor':'logical_xor', + 'invert':'logical_invert', + 'maxmag':'max_mag', + 'minmag':'min_mag', + 'nextminus':'next_minus', + 'nextplus':'next_plus', + 'nexttoward':'next_toward', + 'reduce':'normalize', } +# For some operations (currently exp, ln, log10, power), the decNumber +# reference implementation imposes additional restrictions on the +# context and operands. These restrictions are not part of the +# specification; however, the effect of these restrictions does show +# up in some of the testcases. We skip testcases that violate these +# restrictions, since Decimal behaves differently from decNumber for +# these testcases so these testcases would otherwise fail. + +decNumberRestricted = ('power', 'ln', 'log10', 'exp') +DEC_MAX_MATH = 999999 +def outside_decNumber_bounds(v, context): + if (context.prec > DEC_MAX_MATH or + context.Emax > DEC_MAX_MATH or + -context.Emin > DEC_MAX_MATH): + return True + if not v._is_special and v and ( + len(v._int) > DEC_MAX_MATH or + v.adjusted() > DEC_MAX_MATH or + v.adjusted() < 1-2*DEC_MAX_MATH): + return True + return False + class DecimalTest(unittest.TestCase): """Class which tests the Decimal class against the test cases. @@ -142,10 +182,6 @@ #print line try: t = self.eval_line(line) - except InvalidOperation: - print('Error in test cases:') - print(line) - continue except DecimalException as exception: #Exception raised where there shoudn't have been one. self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line) @@ -194,7 +230,8 @@ Sides = s.split('->') L = Sides[0].strip().split() id = L[0] -# print id, + if DEBUG: + print("Test ", id, end=" ") funct = L[1].lower() valstemp = L[2:] L = Sides[1].strip().split() @@ -246,11 +283,27 @@ self.context.traps[error] = 0 v = self.context.create_decimal(v) else: - v = Decimal(v) + v = Decimal(v, self.context) vals.append(v) ans = FixQuotes(ans) + # skip tests that are related to bounds imposed in the decNumber + # reference implementation + if fname in decNumberRestricted: + if fname == 'power': + if not (vals[1]._isinteger() and + -1999999997 <= vals[1] <= 999999999): + if outside_decNumber_bounds(vals[0], self.context) or \ + outside_decNumber_bounds(vals[1], self.context): + #print "Skipping test %s" % s + return + else: + if outside_decNumber_bounds(vals[0], self.context): + #print "Skipping test %s" % s + return + + if EXTENDEDERRORTEST and fname not in ('to_sci_string', 'to_eng_string'): for error in theirexceptions: self.context.traps[error] = 1 @@ -264,6 +317,8 @@ else: self.fail("Did not raise %s in %s" % (error, s)) self.context.traps[error] = 0 + if DEBUG: + print("--", self.context) try: result = str(funct(*vals)) if fname == 'same_quantum': @@ -283,8 +338,7 @@ self.assertEqual(result, ans, 'Incorrect answer for ' + s + ' -- got ' + result) self.assertEqual(myexceptions, theirexceptions, - 'Incorrect flags set in ' + s + ' -- got ' \ - + str(myexceptions)) + 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions)) return def getexceptions(self): @@ -301,17 +355,6 @@ def change_clamp(self, clamp): self.context._clamp = clamp -# Dynamically build custom test definition for each file in the test -# directory and add the definitions to the DecimalTest class. This -# procedure insures that new files do not get skipped. -for filename in os.listdir(directory): - if '.decTest' not in filename: - continue - head, tail = filename.split('.') - tester = lambda self, f=filename: self.eval_file(directory + f) - setattr(DecimalTest, 'test_' + head, tester) - del filename, head, tail, tester - # The following classes test the behaviour of Decimal according to PEP 327 @@ -798,7 +841,7 @@ th2.start() self.finish1.wait() - self.finish1.wait() + self.finish2.wait() return if threading is None: @@ -858,6 +901,38 @@ def test_hash_method(self): #just that it's hashable hash(Decimal(23)) + + test_values = [Decimal(sign*(2**m + n)) + for m in [0, 14, 15, 16, 17, 30, 31, + 32, 33, 62, 63, 64, 65, 66] + for n in range(-10, 10) + for sign in [-1, 1]] + test_values.extend([ + Decimal("-0"), # zeros + Decimal("0.00"), + Decimal("-0.000"), + Decimal("0E10"), + Decimal("-0E12"), + Decimal("10.0"), # negative exponent + Decimal("-23.00000"), + Decimal("1230E100"), # positive exponent + Decimal("-4.5678E50"), + # a value for which hash(n) != hash(n % (2**64-1)) + # in Python pre-2.6 + Decimal(2**64 + 2**32 - 1), + # selection of values which fail with the old (before + # version 2.6) long.__hash__ + Decimal("1.634E100"), + Decimal("90.697E100"), + Decimal("188.83E100"), + Decimal("1652.9E100"), + Decimal("56531E100"), + ]) + + # check that hash(d) == hash(int(d)) for integral values + for value in test_values: + self.assertEqual(hash(value), hash(int(value))) + #the same hash that to an int self.assertEqual(hash(Decimal(23)), hash(23)) self.assertRaises(TypeError, hash, Decimal('NaN')) @@ -955,8 +1030,8 @@ d1 = Decimal('-25e55') b1 = Decimal('-25e55') - d2 = Decimal('33e-33') - b2 = Decimal('33e-33') + d2 = Decimal('33e+33') + b2 = Decimal('33e+33') def checkSameDec(operation, useOther=False): if useOther: @@ -987,7 +1062,6 @@ checkSameDec("__floordiv__", True) checkSameDec("__hash__") checkSameDec("__int__") - checkSameDec("__long__") checkSameDec("__mod__", True) checkSameDec("__mul__", True) checkSameDec("__neg__") @@ -1018,6 +1092,21 @@ checkSameDec("to_eng_string") checkSameDec("to_integral") + def test_subclassing(self): + # Different behaviours when subclassing Decimal + + class MyDecimal(Decimal): + pass + + d1 = MyDecimal(1) + d2 = MyDecimal(2) + d = d1 + d2 + self.assertTrue(type(d) is Decimal) + + d = d1.max(d2) + self.assertTrue(type(d) is Decimal) + + class DecimalPythonAPItests(unittest.TestCase): def test_pickle(self): @@ -1084,7 +1173,59 @@ self.assert_(new_ctx is not set_ctx, 'did not copy the context') self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context') -def test_main(arith=False, verbose=None): +class ContextFlags(unittest.TestCase): + def test_flags_irrelevant(self): + # check that the result (numeric result + flags raised) of an + # arithmetic operation doesn't depend on the current flags + + context = Context(prec=9, Emin = -999999999, Emax = 999999999, + rounding=ROUND_HALF_EVEN, traps=[], flags=[]) + + # operations that raise various flags, in the form (function, arglist) + operations = [ + (context._apply, [Decimal("100E-1000000009")]), + (context.sqrt, [Decimal(2)]), + (context.add, [Decimal("1.23456789"), Decimal("9.87654321")]), + (context.multiply, [Decimal("1.23456789"), Decimal("9.87654321")]), + (context.subtract, [Decimal("1.23456789"), Decimal("9.87654321")]), + ] + + # try various flags individually, then a whole lot at once + flagsets = [[Inexact], [Rounded], [Underflow], [Clamped], [Subnormal], + [Inexact, Rounded, Underflow, Clamped, Subnormal]] + + for fn, args in operations: + # find answer and flags raised using a clean context + context.clear_flags() + ans = fn(*args) + flags = [k for k, v in context.flags.items() if v] + + for extra_flags in flagsets: + # set flags, before calling operation + context.clear_flags() + for flag in extra_flags: + context._raise_error(flag) + new_ans = fn(*args) + + # flags that we expect to be set after the operation + expected_flags = list(flags) + for flag in extra_flags: + if flag not in expected_flags: + expected_flags.append(flag) + expected_flags.sort(key=id) + + # flags we actually got + new_flags = [k for k,v in context.flags.items() if v] + new_flags.sort(key=id) + + self.assertEqual(ans, new_ans, + "operation produces different answers depending on flags set: " + + "expected %s, got %s." % (ans, new_ans)) + self.assertEqual(new_flags, expected_flags, + "operation raises different flags depending on flags set: " + + "expected %s, got %s" % (expected_flags, new_flags)) + +def test_main(arith=False, verbose=None, todo_tests=None, debug=None): """ Execute the tests. Runs all arithmetic tests if arith is True or if the "decimal" resource @@ -1092,35 +1233,58 @@ """ init() - global TEST_ALL + global TEST_ALL, DEBUG TEST_ALL = arith or is_resource_enabled('decimal') + DEBUG = debug + + if todo_tests is None: + test_classes = [ + DecimalExplicitConstructionTest, + DecimalImplicitConstructionTest, + DecimalArithmeticOperatorsTest, + DecimalUseOfContextTest, + DecimalUsabilityTest, + DecimalPythonAPItests, + ContextAPItests, + DecimalTest, + WithStatementTest, + ContextFlags + ] + else: + test_classes = [DecimalTest] + + # Dynamically build custom test definition for each file in the test + # directory and add the definitions to the DecimalTest class. This + # procedure insures that new files do not get skipped. + for filename in os.listdir(directory): + if '.decTest' not in filename or filename.startswith("."): + continue + head, tail = filename.split('.') + if todo_tests is not None and head not in todo_tests: + continue + tester = lambda self, f=filename: self.eval_file(directory + f) + setattr(DecimalTest, 'test_' + head, tester) + del filename, head, tail, tester - test_classes = [ - DecimalExplicitConstructionTest, - DecimalImplicitConstructionTest, - DecimalArithmeticOperatorsTest, - DecimalUseOfContextTest, - DecimalUsabilityTest, - DecimalPythonAPItests, - ContextAPItests, - DecimalTest, - WithStatementTest, - ] try: run_unittest(*test_classes) - import decimal as DecimalModule - run_doctest(DecimalModule, verbose) + if todo_tests is None: + import decimal as DecimalModule + run_doctest(DecimalModule, verbose) finally: setcontext(ORIGINAL_CONTEXT) if __name__ == '__main__': - # Calling with no arguments runs all tests. - # Calling with "Skip" will skip over 90% of the arithmetic tests. - if len(sys.argv) == 1: - test_main(arith=True, verbose=True) - elif len(sys.argv) == 2: - arith = sys.argv[1].lower() != 'skip' - test_main(arith=arith, verbose=True) + import optparse + p = optparse.OptionParser("test_decimal.py [--debug] [{--skip | test1 [test2 [...]]}]") + p.add_option('--debug', '-d', action='store_true', help='shows the test number and context before each test') + p.add_option('--skip', '-s', action='store_true', help='skip over 90% of the arithmetic tests') + (opt, args) = p.parse_args() + + if opt.skip: + test_main(arith=False, verbose=True) + elif args: + test_main(arith=True, verbose=True, todo_tests=args, debug=opt.debug) else: - raise ValueError("test called with wrong arguments, use test_Decimal [Skip]") + test_main(arith=True, verbose=True) Modified: python/branches/py3k-importlib/Lib/test/test_hash.py ============================================================================== --- python/branches/py3k-importlib/Lib/test/test_hash.py (original) +++ python/branches/py3k-importlib/Lib/test/test_hash.py Fri Sep 21 03:17:09 2007 @@ -18,10 +18,19 @@ def test_numeric_literals(self): self.same_hash(1, 1, 1.0, 1.0+0.0j) + self.same_hash(0, 0.0, 0.0+0.0j) + self.same_hash(-1, -1.0, -1.0+0.0j) + self.same_hash(-2, -2.0, -2.0+0.0j) def test_coerced_integers(self): self.same_hash(int(1), int(1), float(1), complex(1), int('1'), float('1.0')) + self.same_hash(int(-2**31), float(-2**31)) + self.same_hash(int(1-2**31), float(1-2**31)) + self.same_hash(int(2**31-1), float(2**31-1)) + # for 64-bit platforms + self.same_hash(int(2**31), float(2**31)) + self.same_hash(int(-2**63), float(-2**63)) def test_coerced_floats(self): self.same_hash(int(1.23e300), float(1.23e300)) Modified: python/branches/py3k-importlib/Lib/test/test_re.py ============================================================================== --- python/branches/py3k-importlib/Lib/test/test_re.py (original) +++ python/branches/py3k-importlib/Lib/test/test_re.py Fri Sep 21 03:17:09 2007 @@ -83,6 +83,34 @@ self.assertEqual(re.sub('\r\n', '\n', 'abc\r\ndef\r\n'), 'abc\ndef\n') +# This test makes no sense until re supports bytes, and should then probably +# test for the *in*ability to mix bytes and str this way :) +# +# def test_bug_1140(self): +# # re.sub(x, y, b'') should return b'', not '', and +# # re.sub(x, y, '') should return '', not b''. +# # Also: +# # re.sub(x, y, str(x)) should return str(y), and +# # re.sub(x, y, bytes(x)) should return +# # str(y) if isinstance(y, str) else unicode(y). +# for x in 'x', u'x': +# for y in 'y', u'y': +# z = re.sub(x, y, u'') +# self.assertEqual(z, u'') +# self.assertEqual(type(z), unicode) +# # +# z = re.sub(x, y, '') +# self.assertEqual(z, '') +# self.assertEqual(type(z), str) +# # +# z = re.sub(x, y, unicode(x)) +# self.assertEqual(z, y) +# self.assertEqual(type(z), unicode) +# # +# z = re.sub(x, y, str(x)) +# self.assertEqual(z, y) +# self.assertEqual(type(z), type(y)) + def test_sub_template_numeric_escape(self): # bug 776311 and friends self.assertEqual(re.sub('x', r'\0', 'x'), '\0') Modified: python/branches/py3k-importlib/Lib/test/test_repr.py ============================================================================== --- python/branches/py3k-importlib/Lib/test/test_repr.py (original) +++ python/branches/py3k-importlib/Lib/test/test_repr.py Fri Sep 21 03:17:09 2007 @@ -188,6 +188,16 @@ x = classmethod(C.foo) self.failUnless(repr(x).startswith('> received; expected <<%s>>\n" % (data, indata.lower())) - c1.close() + print("didn't raise TypeError") + ssl.RAND_add("this is a random string", 75.0) - def testReadCert(self): + def testParseCert(self): + # note that this uses an 'unofficial' function in _ssl.c, + # provided solely for this test, to exercise the certificate + # parsing code + p = ssl._ssl._test_decode_cert(CERTFILE, False) + if test_support.verbose: + sys.stdout.write("\n" + pprint.pformat(p) + "\n") - s2 = socket.socket() + def testDERtoPEM(self): + + pem = open(SVN_PYTHON_ORG_ROOT_CERT, 'r').read() + d1 = ssl.PEM_cert_to_DER_cert(pem) + p2 = ssl.DER_cert_to_PEM_cert(d1) + d2 = ssl.PEM_cert_to_DER_cert(p2) + if (d1 != d2): + raise test_support.TestFailed("PEM-to-DER or DER-to-PEM translation failed") + + +class NetworkTests(unittest.TestCase): + + def testConnect(self): + import os + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_NONE) + s.connect(("svn.python.org", 443)) + c = s.getpeercert() + if c: + raise test_support.TestFailed("Peer cert %s shouldn't be here!") + s.close() + + # this should fail because we have no verification certs + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED) try: - s2.connect(('127.0.0.1', 10024)) - except: - handle_error("connection failure:\n") - raise test_support.TestFailed("Can't connect to test server") + s.connect(("svn.python.org", 443)) + except ssl.SSLError: + pass + finally: + s.close() + + # this should succeed because we specify the root cert + s = ssl.wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_REQUIRED, + ca_certs=SVN_PYTHON_ORG_ROOT_CERT) + try: + s.connect(("svn.python.org", 443)) + except ssl.SSLError as x: + raise test_support.TestFailed("Unexpected exception %s" % x) + finally: + s.close() + + def testFetchServerCert(self): + + pem = ssl.get_server_certificate(("svn.python.org", 443)) + if not pem: + raise test_support.TestFailed("No server certificate on svn.python.org:443!") + + try: + pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=CERTFILE) + except ssl.SSLError: + #should fail + pass else: - try: - c2 = ssl.sslsocket(s2, ssl_version=ssl.PROTOCOL_TLSv1, - cert_reqs=ssl.CERT_REQUIRED, ca_certs=CERTFILE) - except: - handle_error("SSL handshake failure:\n") - raise test_support.TestFailed("Can't SSL-handshake with test server") - else: - if not c2: - raise test_support.TestFailed("Can't SSL-handshake with test server") - cert = c2.getpeercert() - if not cert: - raise test_support.TestFailed("Can't get peer certificate.") - if test_support.verbose: - sys.stdout.write(pprint.pformat(cert) + '\n') - if not cert.has_key('subject'): - raise test_support.TestFailed( - "No subject field in certificate: %s." % - pprint.pformat(cert)) - if not ('organizationName', 'Python Software Foundation') in cert['subject']: - raise test_support.TestFailed( - "Missing or invalid 'organizationName' field in certificate subject; " - "should be 'Python Software Foundation'."); - c2.close() + raise test_support.TestFailed("Got server certificate %s for svn.python.org!" % pem) + pem = ssl.get_server_certificate(("svn.python.org", 443), ca_certs=SVN_PYTHON_ORG_ROOT_CERT) + if not pem: + raise test_support.TestFailed("No server certificate on svn.python.org:443!") + if test_support.verbose: + sys.stdout.write("\nVerified certificate for svn.python.org:443 is\n%s\n" % pem) -class ThreadedEchoServer(threading.Thread): - class ConnectionHandler(threading.Thread): +try: + import threading +except ImportError: + _have_threads = False +else: - def __init__(self, server, connsock): - self.server = server - self.running = False - self.sock = connsock - threading.Thread.__init__(self) - self.setDaemon(True) + _have_threads = True - def run (self): - self.running = True - try: - sslconn = ssl.sslsocket(self.sock, server_side=True, - certfile=self.server.certificate, - ssl_version=self.server.protocol, - cert_reqs=self.server.certreqs) - except: - # here, we want to stop the server, because this shouldn't - # happen in the context of our test case - handle_error("Test server failure:\n") + class ThreadedEchoServer(threading.Thread): + + class ConnectionHandler(threading.Thread): + + """A mildly complicated class, because we want it to work both + with and without the SSL wrapper around the socket connection, so + that we can test the STARTTLS functionality.""" + + def __init__(self, server, connsock): + self.server = server self.running = False - # normally, we'd just stop here, but for the test - # harness, we want to stop the server - self.server.stop() - return + self.sock = connsock + self.sock.setblocking(1) + self.sslconn = None + threading.Thread.__init__(self) + self.setDaemon(True) - while self.running: + def wrap_conn (self): try: - msg = sslconn.read() - if not msg: - # eof, so quit this handler + self.sslconn = ssl.wrap_socket(self.sock, server_side=True, + certfile=self.server.certificate, + ssl_version=self.server.protocol, + ca_certs=self.server.cacerts, + cert_reqs=self.server.certreqs) + except: + if self.server.chatty: + handle_error("\n server: bad connection attempt from " + + str(self.sock.getpeername()) + ":\n") + if not self.server.expect_bad_connects: + # here, we want to stop the server, because this shouldn't + # happen in the context of our test case self.running = False - sslconn.close() - elif msg.strip() == 'over': - sslconn.close() + # normally, we'd just stop here, but for the test + # harness, we want to stop the server self.server.stop() + return False + + else: + if self.server.certreqs == ssl.CERT_REQUIRED: + cert = self.sslconn.getpeercert() + if test_support.verbose and self.server.chatty: + sys.stdout.write(" client cert is " + pprint.pformat(cert) + "\n") + cert_binary = self.sslconn.getpeercert(True) + if test_support.verbose and self.server.chatty: + sys.stdout.write(" cert binary is " + str(len(cert_binary)) + " bytes\n") + cipher = self.sslconn.cipher() + if test_support.verbose and self.server.chatty: + sys.stdout.write(" server: connection cipher is now " + str(cipher) + "\n") + return True + + def read(self): + if self.sslconn: + return self.sslconn.read() + else: + return self.sock.recv(1024) + + def write(self, bytes): + if self.sslconn: + return self.sslconn.write(bytes) + else: + return self.sock.send(bytes) + + def close(self): + if self.sslconn: + self.sslconn.close() + else: + self.sock.close() + + def run (self): + self.running = True + if not self.server.starttls_server: + if not self.wrap_conn(): + return + while self.running: + try: + msg = self.read() + if not msg: + # eof, so quit this handler + self.running = False + self.close() + elif msg.strip() == 'over': + if test_support.verbose and self.server.connectionchatty: + sys.stdout.write(" server: client closed connection\n") + self.close() + return + elif self.server.starttls_server and msg.strip() == 'STARTTLS': + if test_support.verbose and self.server.connectionchatty: + sys.stdout.write(" server: read STARTTLS from client, sending OK...\n") + self.write("OK\n") + if not self.wrap_conn(): + return + else: + if (test_support.verbose and + self.server.connectionchatty): + ctype = (self.sslconn and "encrypted") or "unencrypted" + sys.stdout.write(" server: read %s (%s), sending back %s (%s)...\n" + % (repr(msg), ctype, repr(msg.lower()), ctype)) + self.write(msg.lower()) + except ssl.SSLError: + if self.server.chatty: + handle_error("Test server failure:\n") + self.close() self.running = False - else: - if test_support.verbose: - sys.stdout.write("\nserver: %s\n" % msg.strip().lower()) - sslconn.write(msg.lower()) - except ssl.sslerror: - handle_error("Test server failure:\n") - sslconn.close() - self.running = False - # normally, we'd just stop here, but for the test - # harness, we want to stop the server - self.server.stop() + # normally, we'd just stop here, but for the test + # harness, we want to stop the server + self.server.stop() + except: + handle_error('') + + def __init__(self, port, certificate, ssl_version=None, + certreqs=None, cacerts=None, expect_bad_connects=False, + chatty=True, connectionchatty=False, starttls_server=False): + if ssl_version is None: + ssl_version = ssl.PROTOCOL_TLSv1 + if certreqs is None: + certreqs = ssl.CERT_NONE + self.certificate = certificate + self.protocol = ssl_version + self.certreqs = certreqs + self.cacerts = cacerts + self.expect_bad_connects = expect_bad_connects + self.chatty = chatty + self.connectionchatty = connectionchatty + self.starttls_server = starttls_server + self.sock = socket.socket() + self.flag = None + if hasattr(socket, 'SO_REUSEADDR'): + self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, 'SO_REUSEPORT'): + self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + self.sock.bind(('127.0.0.1', port)) + self.active = False + threading.Thread.__init__(self) + self.setDaemon(False) + + def start (self, flag=None): + self.flag = flag + threading.Thread.start(self) + + def run (self): + self.sock.settimeout(0.5) + self.sock.listen(5) + self.active = True + if self.flag: + # signal an event + self.flag.set() + while self.active: + try: + newconn, connaddr = self.sock.accept() + if test_support.verbose and self.chatty: + sys.stdout.write(' server: new connection from ' + + str(connaddr) + '\n') + handler = self.ConnectionHandler(self, newconn) + handler.start() + except socket.timeout: + pass + except KeyboardInterrupt: + self.stop() except: - handle_error('') + if self.chatty: + handle_error("Test server failure:\n") + + def stop (self): + self.active = False + self.sock.close() + + + class AsyncoreHTTPSServer(threading.Thread): + + class HTTPSServer(HTTPServer): + + def __init__(self, server_address, RequestHandlerClass, certfile): + + HTTPServer.__init__(self, server_address, RequestHandlerClass) + # we assume the certfile contains both private key and certificate + self.certfile = certfile + self.active = False + self.allow_reuse_address = True + + def get_request (self): + # override this to wrap socket with SSL + sock, addr = self.socket.accept() + sslconn = ssl.wrap_socket(sock, server_side=True, + certfile=self.certfile) + return sslconn, addr + + # The methods overridden below this are mainly so that we + # can run it in a thread and be able to stop it from another + # You probably wouldn't need them in other uses. + + def server_activate(self): + # We want to run this in a thread for testing purposes, + # so we override this to set timeout, so that we get + # a chance to stop the server + self.socket.settimeout(0.5) + HTTPServer.server_activate(self) + + def serve_forever(self): + # We want this to run in a thread, so we use a slightly + # modified version of "forever". + self.active = True + while self.active: + try: + self.handle_request() + except socket.timeout: + pass + except KeyboardInterrupt: + self.server_close() + return + except: + sys.stdout.write(''.join(traceback.format_exception(*sys.exc_info()))); + + def server_close(self): + # Again, we want this to run in a thread, so we need to override + # close to clear the "active" flag, so that serve_forever() will + # terminate. + HTTPServer.server_close(self) + self.active = False + + class RootedHTTPRequestHandler(SimpleHTTPRequestHandler): + + # need to override translate_path to get a known root, + # instead of using os.curdir, since the test could be + # run from anywhere + + server_version = "TestHTTPS/1.0" + + root = None + + def translate_path(self, path): + """Translate a /-separated PATH to the local filename syntax. + + Components that mean special things to the local file system + (e.g. drive or directory names) are ignored. (XXX They should + probably be diagnosed.) + + """ + # abandon query parameters + path = urlparse.urlparse(path)[2] + path = os.path.normpath(urllib.unquote(path)) + words = path.split('/') + words = filter(None, words) + path = self.root + for word in words: + drive, word = os.path.splitdrive(word) + head, word = os.path.split(word) + if word in self.root: continue + path = os.path.join(path, word) + return path + + def log_message(self, format, *args): + + # we override this to suppress logging unless "verbose" + + if test_support.verbose: + sys.stdout.write(" server (%s, %d, %s):\n [%s] %s\n" % + (self.server.server_name, + self.server.server_port, + self.request.cipher(), + self.log_date_time_string(), + format%args)) + + + def __init__(self, port, certfile): + self.flag = None + self.active = False + self.RootedHTTPRequestHandler.root = os.path.split(CERTFILE)[0] + self.server = self.HTTPSServer( + ('', port), self.RootedHTTPRequestHandler, certfile) + threading.Thread.__init__(self) + self.setDaemon(True) - def __init__(self, port, certificate, ssl_version=None, - certreqs=None, cacerts=None): - if ssl_version is None: - ssl_version = ssl.PROTOCOL_TLSv1 - if certreqs is None: - certreqs = ssl.CERT_NONE - self.certificate = certificate - self.protocol = ssl_version - self.certreqs = certreqs - self.cacerts = cacerts - self.sock = socket.socket() - self.flag = None - if hasattr(socket, 'SO_REUSEADDR'): - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - if hasattr(socket, 'SO_REUSEPORT'): - self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) - self.sock.bind(('127.0.0.1', port)) - self.active = False - threading.Thread.__init__(self) - self.setDaemon(False) - - def start (self, flag=None): - self.flag = flag - threading.Thread.start(self) - - def run (self): - self.sock.settimeout(0.5) - self.sock.listen(5) - self.active = True - if self.flag: - # signal an event - self.flag.set() - while self.active: + def __str__(self): + return '<%s %s:%d>' % (self.__class__.__name__, + self.server.server_name, + self.server.server_port) + + def start (self, flag=None): + self.flag = flag + threading.Thread.start(self) + + def run (self): + self.active = True + if self.flag: + self.flag.set() + self.server.serve_forever() + self.active = False + + def stop (self): + self.active = False + self.server.server_close() + + + def badCertTest (certfile): + server = ThreadedEchoServer(TESTPORT, CERTFILE, + certreqs=ssl.CERT_REQUIRED, + cacerts=CERTFILE, chatty=False) + flag = threading.Event() + server.start(flag) + # wait for it to start + flag.wait() + # try to connect + try: try: - newconn, connaddr = self.sock.accept() + s = ssl.wrap_socket(socket.socket(), + certfile=certfile, + ssl_version=ssl.PROTOCOL_TLSv1) + s.connect(('127.0.0.1', TESTPORT)) + except ssl.SSLError as x: if test_support.verbose: - sys.stdout.write('\nserver: new connection from ' + str(connaddr) + '\n') - handler = self.ConnectionHandler(self, newconn) - handler.start() - except socket.timeout: - pass - except KeyboardInterrupt: - self.stop() - except: - handle_error("Test server failure:\n") + sys.stdout.write("\nSSLError is %s\n" % x[1]) + else: + raise test_support.TestFailed( + "Use of invalid cert should have failed!") + finally: + server.stop() + server.join() + + def serverParamsTest (certfile, protocol, certreqs, cacertsfile, + client_certfile, client_protocol=None, indata="FOO\n", + chatty=True, connectionchatty=False): + + server = ThreadedEchoServer(TESTPORT, certfile, + certreqs=certreqs, + ssl_version=protocol, + cacerts=cacertsfile, + chatty=chatty, + connectionchatty=connectionchatty) + flag = threading.Event() + server.start(flag) + # wait for it to start + flag.wait() + # try to connect + if client_protocol is None: + client_protocol = protocol + try: + try: + s = ssl.wrap_socket(socket.socket(), + certfile=client_certfile, + ca_certs=cacertsfile, + cert_reqs=certreqs, + ssl_version=client_protocol) + s.connect(('127.0.0.1', TESTPORT)) + except ssl.SSLError as x: + raise test_support.TestFailed("Unexpected SSL error: " + str(x)) + except Exception as x: + raise test_support.TestFailed("Unexpected exception: " + str(x)) + else: + if connectionchatty: + if test_support.verbose: + sys.stdout.write( + " client: sending %s...\n" % (repr(indata))) + s.write(indata) + outdata = s.read() + if connectionchatty: + if test_support.verbose: + sys.stdout.write(" client: read %s\n" % repr(outdata)) + if outdata != indata.lower(): + raise test_support.TestFailed( + "bad data <<%s>> (%d) received; expected <<%s>> (%d)\n" + % (outdata[:min(len(outdata),20)], len(outdata), + indata[:min(len(indata),20)].lower(), len(indata))) + s.write("over\n") + if connectionchatty: + if test_support.verbose: + sys.stdout.write(" client: closing connection.\n") + s.close() + finally: + server.stop() + server.join() - def stop (self): - self.active = False - self.sock.close() - -CERTFILE_CONFIG_TEMPLATE = """ -# create RSA certs - Server - -[ req ] -default_bits = 1024 -encrypt_key = yes -distinguished_name = req_dn -x509_extensions = cert_type - -[ req_dn ] -countryName = Country Name (2 letter code) -countryName_default = US -countryName_min = 2 -countryName_max = 2 - -stateOrProvinceName = State or Province Name (full name) -stateOrProvinceName_default = %(state)s - -localityName = Locality Name (eg, city) -localityName_default = %(city)s - -0.organizationName = Organization Name (eg, company) -0.organizationName_default = %(organization)s - -organizationalUnitName = Organizational Unit Name (eg, section) -organizationalUnitName_default = %(unit)s - -0.commonName = Common Name (FQDN of your server) -0.commonName_default = %(common-name)s - -# To create a certificate for more than one name uncomment: -# 1.commonName = DNS alias of your server -# 2.commonName = DNS alias of your server -# ... -# See http://home.netscape.com/eng/security/ssl_2.0_certificate.html -# to see how Netscape understands commonName. - -[ cert_type ] -nsCertType = server -""" - -def create_cert_files(hostname=None): - - """This is the routine that was run to create the certificate - and private key contained in keycert.pem.""" - - import tempfile, socket, os - d = tempfile.mkdtemp() - # now create a configuration file for the CA signing cert - fqdn = hostname or socket.getfqdn() - crtfile = os.path.join(d, "cert.pem") - conffile = os.path.join(d, "ca.conf") - fp = open(conffile, "w") - fp.write(CERTFILE_CONFIG_TEMPLATE % - {'state': "Delaware", - 'city': "Wilmington", - 'organization': "Python Software Foundation", - 'unit': "SSL", - 'common-name': fqdn, - }) - fp.close() - error = os.system( - "openssl req -batch -new -x509 -days 2000 -nodes -config %s " - "-keyout \"%s\" -out \"%s\" > /dev/null < /dev/null 2>&1" % - (conffile, crtfile, crtfile)) - # now we have a self-signed server cert in crtfile - os.unlink(conffile) - if (os.WEXITSTATUS(error) or - not os.path.exists(crtfile) or os.path.getsize(crtfile) == 0): + def tryProtocolCombo (server_protocol, + client_protocol, + expectedToWork, + certsreqs=None): + + if certsreqs == None: + certsreqs = ssl.CERT_NONE + + if certsreqs == ssl.CERT_NONE: + certtype = "CERT_NONE" + elif certsreqs == ssl.CERT_OPTIONAL: + certtype = "CERT_OPTIONAL" + elif certsreqs == ssl.CERT_REQUIRED: + certtype = "CERT_REQUIRED" if test_support.verbose: - sys.stdout.write("Unable to create certificate for test, " - + "error status %d\n" % (error >> 8)) - crtfile = None - elif test_support.verbose: - sys.stdout.write(open(crtfile, 'r').read() + '\n') - return d, crtfile + formatstr = (expectedToWork and " %s->%s %s\n") or " {%s->%s} %s\n" + sys.stdout.write(formatstr % + (ssl.get_protocol_name(client_protocol), + ssl.get_protocol_name(server_protocol), + certtype)) + try: + serverParamsTest(CERTFILE, server_protocol, certsreqs, + CERTFILE, CERTFILE, client_protocol, chatty=False) + except test_support.TestFailed: + if expectedToWork: + raise + else: + if not expectedToWork: + raise test_support.TestFailed( + "Client protocol %s succeeded with server protocol %s!" + % (ssl.get_protocol_name(client_protocol), + ssl.get_protocol_name(server_protocol))) + + + class ConnectedTests(unittest.TestCase): + + def testRudeShutdown(self): + + listener_ready = threading.Event() + listener_gone = threading.Event() + + # `listener` runs in a thread. It opens a socket listening on + # PORT, and sits in an accept() until the main thread connects. + # Then it rudely closes the socket, and sets Event `listener_gone` + # to let the main thread know the socket is gone. + def listener(): + s = socket.socket() + if hasattr(socket, 'SO_REUSEADDR'): + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, 'SO_REUSEPORT'): + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + s.bind(('127.0.0.1', TESTPORT)) + s.listen(5) + listener_ready.set() + s.accept() + s = None # reclaim the socket object, which also closes it + listener_gone.set() + + def connector(): + listener_ready.wait() + s = socket.socket() + s.connect(('127.0.0.1', TESTPORT)) + listener_gone.wait() + try: + ssl_sock = ssl.wrap_socket(s) + except socket.sslerror: + pass + else: + raise test_support.TestFailed( + 'connecting to closed SSL socket should have failed') + + t = threading.Thread(target=listener) + t.start() + connector() + t.join() + + def testEcho (self): + + if test_support.verbose: + sys.stdout.write("\n") + serverParamsTest(CERTFILE, ssl.PROTOCOL_TLSv1, ssl.CERT_NONE, + CERTFILE, CERTFILE, ssl.PROTOCOL_TLSv1, + chatty=True, connectionchatty=True) + + def testReadCert(self): + + if test_support.verbose: + sys.stdout.write("\n") + s2 = socket.socket() + server = ThreadedEchoServer(TESTPORT, CERTFILE, + certreqs=ssl.CERT_NONE, + ssl_version=ssl.PROTOCOL_SSLv23, + cacerts=CERTFILE, + chatty=False) + flag = threading.Event() + server.start(flag) + # wait for it to start + flag.wait() + # try to connect + try: + try: + s = ssl.wrap_socket(socket.socket(), + certfile=CERTFILE, + ca_certs=CERTFILE, + cert_reqs=ssl.CERT_REQUIRED, + ssl_version=ssl.PROTOCOL_SSLv23) + s.connect(('127.0.0.1', TESTPORT)) + except ssl.SSLError as x: + raise test_support.TestFailed( + "Unexpected SSL error: " + str(x)) + except Exception as x: + raise test_support.TestFailed( + "Unexpected exception: " + str(x)) + else: + if not s: + raise test_support.TestFailed( + "Can't SSL-handshake with test server") + cert = s.getpeercert() + if not cert: + raise test_support.TestFailed( + "Can't get peer certificate.") + cipher = s.cipher() + if test_support.verbose: + sys.stdout.write(pprint.pformat(cert) + '\n') + sys.stdout.write("Connection cipher is " + str(cipher) + '.\n') + if not cert.has_key('subject'): + raise test_support.TestFailed( + "No subject field in certificate: %s." % + pprint.pformat(cert)) + if ((('organizationName', 'Python Software Foundation'),) + not in cert['subject']): + raise test_support.TestFailed( + "Missing or invalid 'organizationName' field in certificate subject; " + "should be 'Python Software Foundation'."); + s.close() + finally: + server.stop() + server.join() + + def testNULLcert(self): + badCertTest(os.path.join(os.path.dirname(__file__) or os.curdir, + "nullcert.pem")) + def testMalformedCert(self): + badCertTest(os.path.join(os.path.dirname(__file__) or os.curdir, + "badcert.pem")) + def testMalformedKey(self): + badCertTest(os.path.join(os.path.dirname(__file__) or os.curdir, + "badkey.pem")) + + def testProtocolSSL2(self): + if test_support.verbose: + sys.stdout.write("\n") + tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True) + tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_OPTIONAL) + tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv2, True, ssl.CERT_REQUIRED) + tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv23, True) + tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_SSLv3, False) + tryProtocolCombo(ssl.PROTOCOL_SSLv2, ssl.PROTOCOL_TLSv1, False) + + def testProtocolSSL23(self): + if test_support.verbose: + sys.stdout.write("\n") + try: + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv2, True) + except test_support.TestFailed as x: + # this fails on some older versions of OpenSSL (0.9.7l, for instance) + if test_support.verbose: + sys.stdout.write( + " SSL2 client to SSL23 server test unexpectedly failed:\n %s\n" + % str(x)) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True) + + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_OPTIONAL) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) + + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_SSLv23, True, ssl.CERT_REQUIRED) + tryProtocolCombo(ssl.PROTOCOL_SSLv23, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) + + def testProtocolSSL3(self): + if test_support.verbose: + sys.stdout.write("\n") + tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True) + tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_OPTIONAL) + tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv3, True, ssl.CERT_REQUIRED) + tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv2, False) + tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_SSLv23, False) + tryProtocolCombo(ssl.PROTOCOL_SSLv3, ssl.PROTOCOL_TLSv1, False) + + def testProtocolTLS1(self): + if test_support.verbose: + sys.stdout.write("\n") + tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True) + tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_OPTIONAL) + tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1, True, ssl.CERT_REQUIRED) + tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv2, False) + tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv3, False) + tryProtocolCombo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_SSLv23, False) + + def testSTARTTLS (self): + + msgs = ("msg 1", "MSG 2", "STARTTLS", "MSG 3", "msg 4") + + server = ThreadedEchoServer(TESTPORT, CERTFILE, + ssl_version=ssl.PROTOCOL_TLSv1, + starttls_server=True, + chatty=True, + connectionchatty=True) + flag = threading.Event() + server.start(flag) + # wait for it to start + flag.wait() + # try to connect + wrapped = False + try: + try: + s = socket.socket() + s.setblocking(1) + s.connect(('127.0.0.1', TESTPORT)) + except Exception as x: + raise test_support.TestFailed("Unexpected exception: " + str(x)) + else: + if test_support.verbose: + sys.stdout.write("\n") + for indata in msgs: + if test_support.verbose: + sys.stdout.write( + " client: sending %s...\n" % repr(indata)) + if wrapped: + conn.write(indata) + outdata = conn.read() + else: + s.send(indata) + outdata = s.recv(1024) + if (indata == "STARTTLS" and + outdata.strip().lower().startswith("ok")): + if test_support.verbose: + sys.stdout.write( + " client: read %s from server, starting TLS...\n" + % repr(outdata)) + conn = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1) + + wrapped = True + else: + if test_support.verbose: + sys.stdout.write( + " client: read %s from server\n" % repr(outdata)) + if test_support.verbose: + sys.stdout.write(" client: closing connection.\n") + if wrapped: + conn.write("over\n") + else: + s.send("over\n") + s.close() + finally: + server.stop() + server.join() + + def testAsyncore(self): + + server = AsyncoreHTTPSServer(TESTPORT, CERTFILE) + flag = threading.Event() + server.start(flag) + # wait for it to start + flag.wait() + # try to connect + try: + if test_support.verbose: + sys.stdout.write('\n') + d1 = open(CERTFILE, 'rb').read() + d2 = '' + # now fetch the same data from the HTTPS server + url = 'https://127.0.0.1:%d/%s' % ( + TESTPORT, os.path.split(CERTFILE)[1]) + f = urllib.urlopen(url) + dlen = f.info().getheader("content-length") + if dlen and (int(dlen) > 0): + d2 = f.read(int(dlen)) + if test_support.verbose: + sys.stdout.write( + " client: read %d bytes from remote server '%s'\n" + % (len(d2), server)) + f.close() + except: + msg = ''.join(traceback.format_exception(*sys.exc_info())) + if test_support.verbose: + sys.stdout.write('\n' + msg) + raise test_support.TestFailed(msg) + else: + if not (d1 == d2): + raise test_support.TestFailed( + "Couldn't fetch data from HTTPS server") + finally: + server.stop() + server.join() + + +def findtestsocket(start, end): + def testbind(i): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + s.bind(("127.0.0.1", i)) + except: + return 0 + else: + return 1 + finally: + s.close() + + for i in range(start, end): + if testbind(i) and testbind(i+1): + return i + return 0 def test_main(verbose=False): if skip_expected: raise test_support.TestSkipped("No SSL support") - global CERTFILE + global CERTFILE, TESTPORT, SVN_PYTHON_ORG_ROOT_CERT CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir, "keycert.pem") - if not CERTFILE: - sys.__stdout__.write("Skipping test_ssl ConnectedTests; " - "couldn't create a certificate.\n") + SVN_PYTHON_ORG_ROOT_CERT = os.path.join( + os.path.dirname(__file__) or os.curdir, + "https_svn_python_org_root.pem") + + if (not os.path.exists(CERTFILE) or + not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT)): + raise test_support.TestFailed("Can't read certificate files!") + TESTPORT = findtestsocket(10025, 12000) + if not TESTPORT: + raise test_support.TestFailed("Can't find open port to test servers on!") tests = [BasicTests] - server = None - if CERTFILE and test_support.is_resource_enabled('network'): - server = ThreadedEchoServer(10024, CERTFILE) - flag = threading.Event() - server.start(flag) - # wait for it to start - flag.wait() - tests.append(ConnectedTests) + if test_support.is_resource_enabled('network'): + tests.append(NetworkTests) - thread_info = test_support.threading_setup() + if _have_threads: + thread_info = test_support.threading_setup() + if thread_info and test_support.is_resource_enabled('network'): + tests.append(ConnectedTests) - try: - test_support.run_unittest(*tests) - finally: - if server is not None and server.active: - server.stop() - # wait for it to stop - server.join() + test_support.run_unittest(*tests) - test_support.threading_cleanup(*thread_info) + if _have_threads: + test_support.threading_cleanup(*thread_info) if __name__ == "__main__": test_main() Modified: python/branches/py3k-importlib/Lib/urllib.py ============================================================================== --- python/branches/py3k-importlib/Lib/urllib.py (original) +++ python/branches/py3k-importlib/Lib/urllib.py Fri Sep 21 03:17:09 2007 @@ -357,7 +357,9 @@ raise IOError('http protocol error', 0, 'got a bad status line', None) - if response.status == 200: + # According to RFC 2616, "2xx" code indicates that the client's + # request was successfully received, understood, and accepted. + if not (200 <= response.status < 300): return addinfourl(response.fp, response.msg, "http:" + url) else: return self.http_error( Modified: python/branches/py3k-importlib/Mac/Modules/cf/_CFmodule.c ============================================================================== --- python/branches/py3k-importlib/Mac/Modules/cf/_CFmodule.c (original) +++ python/branches/py3k-importlib/Mac/Modules/cf/_CFmodule.c Fri Sep 21 03:17:09 2007 @@ -1821,6 +1821,7 @@ if (!PyArg_Parse(v, "es", "ascii", &cStr)) return 0; *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII); + PyMem_Free(cStr); return 1; } if (PyUnicode_Check(v)) { Modified: python/branches/py3k-importlib/Mac/Modules/cf/cfsupport.py ============================================================================== --- python/branches/py3k-importlib/Mac/Modules/cf/cfsupport.py (original) +++ python/branches/py3k-importlib/Mac/Modules/cf/cfsupport.py Fri Sep 21 03:17:09 2007 @@ -429,6 +429,7 @@ if (!PyArg_Parse(v, "es", "ascii", &cStr)) return NULL; *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII); + PyMem_Free(cStr); return 1; } if (PyUnicode_Check(v)) { Modified: python/branches/py3k-importlib/Mac/Modules/cf/pycfbridge.c ============================================================================== --- python/branches/py3k-importlib/Mac/Modules/cf/pycfbridge.c (original) +++ python/branches/py3k-importlib/Mac/Modules/cf/pycfbridge.c Fri Sep 21 03:17:09 2007 @@ -285,6 +285,7 @@ if (!PyArg_Parse(src, "es", "ascii", &chars)) return 0; /* This error is more descriptive than the general one below */ *dst = CFStringCreateWithCString((CFAllocatorRef)NULL, chars, kCFStringEncodingASCII); + PyMem_Free(chars); return 1; } if (PyUnicode_Check(src)) { Modified: python/branches/py3k-importlib/Modules/_sre.c ============================================================================== --- python/branches/py3k-importlib/Modules/_sre.c (original) +++ python/branches/py3k-importlib/Modules/_sre.c Fri Sep 21 03:17:09 2007 @@ -1969,7 +1969,7 @@ #endif static PyObject* -join_list(PyObject* list, PyObject* pattern) +join_list(PyObject* list, PyObject* string) { /* join list elements */ @@ -1980,24 +1980,15 @@ #endif PyObject* result; - switch (PyList_GET_SIZE(list)) { - case 0: - Py_DECREF(list); - return PySequence_GetSlice(pattern, 0, 0); - case 1: - result = PyList_GET_ITEM(list, 0); - Py_INCREF(result); - Py_DECREF(list); - return result; - } - - /* two or more elements: slice out a suitable separator from the - first member, and use that to join the entire list */ - - joiner = PySequence_GetSlice(pattern, 0, 0); + joiner = PySequence_GetSlice(string, 0, 0); if (!joiner) return NULL; + if (PyList_GET_SIZE(list) == 0) { + Py_DECREF(list); + return joiner; + } + #if PY_VERSION_HEX >= 0x01060000 function = PyObject_GetAttrString(joiner, "join"); if (!function) { @@ -2433,7 +2424,7 @@ Py_DECREF(filter); /* convert list to single string (also removes list) */ - item = join_list(list, self->pattern); + item = join_list(list, string); if (!item) return NULL; Modified: python/branches/py3k-importlib/Modules/_ssl.c ============================================================================== --- python/branches/py3k-importlib/Modules/_ssl.c (original) +++ python/branches/py3k-importlib/Modules/_ssl.c Fri Sep 21 03:17:09 2007 @@ -1,14 +1,38 @@ /* SSL socket module SSL support based on patches by Brian E Gallew and Laszlo Kovacs. + Re-worked a bit by Bill Janssen to add server-side support and + certificate decoding. - This module is imported by socket.py. It should *not* be used + This module is imported by ssl.py. It should *not* be used directly. + XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE? + + XXX what about SSL_MODE_AUTO_RETRY */ #include "Python.h" +#ifdef WITH_THREAD +#include "pythread.h" +#define PySSL_BEGIN_ALLOW_THREADS { \ + PyThreadState *_save; \ + if (_ssl_locks_count>0) {_save = PyEval_SaveThread();} +#define PySSL_BLOCK_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save)}; +#define PySSL_UNBLOCK_THREADS if (_ssl_locks_count>0){_save = PyEval_SaveThread()}; +#define PySSL_END_ALLOW_THREADS if (_ssl_locks_count>0){PyEval_RestoreThread(_save);} \ + } + +#else /* no WITH_THREAD */ + +#define PySSL_BEGIN_ALLOW_THREADS +#define PySSL_BLOCK_THREADS +#define PySSL_UNBLOCK_THREADS +#define PySSL_END_ALLOW_THREADS + +#endif + enum py_ssl_error { /* these mirror ssl.h */ PY_SSL_ERROR_NONE, @@ -55,6 +79,7 @@ #include "openssl/rsa.h" #include "openssl/crypto.h" #include "openssl/x509.h" +#include "openssl/x509v3.h" #include "openssl/pem.h" #include "openssl/ssl.h" #include "openssl/err.h" @@ -63,6 +88,15 @@ /* SSL error object */ static PyObject *PySSLErrorObject; +#ifdef WITH_THREAD + +/* serves as a flag to see whether we've initialized the SSL thread support. */ +/* 0 means no, greater than 0 means yes */ + +static unsigned int _ssl_locks_count = 0; + +#endif /* def WITH_THREAD */ + /* SSL socket object */ #define X509_NAME_MAXLEN 256 @@ -90,8 +124,8 @@ static PyObject *PySSL_SSLread(PySSLObject *self, PyObject *args); static int check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing); -static PyObject *PySSL_peercert(PySSLObject *self); - +static PyObject *PySSL_peercert(PySSLObject *self, PyObject *args); +static PyObject *PySSL_cipher(PySSLObject *self); #define PySSLObject_Check(v) (Py_Type(v) == &PySSL_Type) @@ -126,7 +160,7 @@ assert(ret <= 0); - if ((obj != NULL) && (obj->ssl != NULL)) { + if (obj->ssl != NULL) { err = SSL_get_error(obj->ssl, ret); switch (err) { @@ -202,6 +236,25 @@ return NULL; } +static PyObject * +_setSSLError (char *errstr, int errcode, char *filename, int lineno) { + + char buf[2048]; + PyObject *v; + + if (errstr == NULL) { + errcode = ERR_peek_last_error(); + errstr = ERR_error_string(errcode, NULL); + } + PyOS_snprintf(buf, sizeof(buf), "_ssl.c:%d: %s", lineno, errstr); + v = Py_BuildValue("(is)", errcode, buf); + if (v != NULL) { + PyErr_SetObject(PySSLErrorObject, v); + Py_DECREF(v); + } + return NULL; +} + static PySSLObject * newPySSLObject(PySocketSockObject *Sock, char *key_file, char *cert_file, enum py_ssl_server_or_client socket_type, @@ -226,6 +279,10 @@ self->ctx = NULL; self->Socket = NULL; + /* Make sure the SSL error state is initialized */ + (void) ERR_get_state(); + ERR_clear_error(); + if ((key_file && !cert_file) || (!key_file && cert_file)) { errstr = ERRSTR("Both the key & certificate files " "must be specified"); @@ -239,16 +296,16 @@ goto fail; } - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS if (proto_version == PY_SSL_VERSION_TLS1) self->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */ else if (proto_version == PY_SSL_VERSION_SSL3) self->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */ else if (proto_version == PY_SSL_VERSION_SSL2) self->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */ - else + else if (proto_version == PY_SSL_VERSION_SSL23) self->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */ - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if (self->ctx == NULL) { errstr = ERRSTR("Invalid SSL protocol variant specified."); @@ -261,39 +318,46 @@ "verification of other-side certificates."); goto fail; } else { - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS ret = SSL_CTX_load_verify_locations(self->ctx, cacerts_file, NULL); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if (ret != 1) { - PySSL_SetError(NULL, 0, __FILE__, __LINE__); + _setSSLError(NULL, 0, __FILE__, __LINE__); goto fail; } } } if (key_file) { - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS ret = SSL_CTX_use_PrivateKey_file(self->ctx, key_file, SSL_FILETYPE_PEM); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if (ret != 1) { - PySSL_SetError(NULL, 0, __FILE__, __LINE__); + _setSSLError(NULL, ret, __FILE__, __LINE__); goto fail; } - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS ret = SSL_CTX_use_certificate_chain_file(self->ctx, - cert_file); - Py_END_ALLOW_THREADS + cert_file); + PySSL_END_ALLOW_THREADS if (ret != 1) { - PySSL_SetError(NULL, 0, __FILE__, __LINE__); - goto fail; + /* + fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n", + ret, ERR_peek_error(), ERR_peek_last_error(), cert_file); + */ + if (ERR_peek_last_error() != 0) { + _setSSLError(NULL, ret, __FILE__, __LINE__); + goto fail; + } } - /* ssl compatibility */ - SSL_CTX_set_options(self->ctx, SSL_OP_ALL); } + /* ssl compatibility */ + SSL_CTX_set_options(self->ctx, SSL_OP_ALL); + verification_mode = SSL_VERIFY_NONE; if (certreq == PY_SSL_CERT_OPTIONAL) verification_mode = SSL_VERIFY_PEER; @@ -303,9 +367,9 @@ SSL_CTX_set_verify(self->ctx, verification_mode, NULL); /* set verify lvl */ - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS self->ssl = SSL_new(self->ctx); /* New ssl struct */ - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS SSL_set_fd(self->ssl, Sock->sock_fd); /* Set the socket for SSL */ /* If the socket is in non-blocking mode or timeout mode, set the BIO @@ -317,24 +381,24 @@ BIO_set_nbio(SSL_get_wbio(self->ssl), 1); } - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS if (socket_type == PY_SSL_CLIENT) SSL_set_connect_state(self->ssl); else SSL_set_accept_state(self->ssl); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS /* Actually negotiate SSL connection */ /* XXX If SSL_connect() returns 0, it's also a failure. */ sockstate = 0; do { - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS if (socket_type == PY_SSL_CLIENT) ret = SSL_connect(self->ssl); else ret = SSL_accept(self->ssl); err = SSL_get_error(self->ssl, ret); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if(PyErr_CheckSignals()) { goto fail; } @@ -367,14 +431,14 @@ } self->ssl->debug = 1; - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS if ((self->peer_cert = SSL_get_peer_certificate(self->ssl))) { X509_NAME_oneline(X509_get_subject_name(self->peer_cert), self->server, X509_NAME_MAXLEN); X509_NAME_oneline(X509_get_issuer_name(self->peer_cert), self->issuer, X509_NAME_MAXLEN); } - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS self->Socket = Sock; Py_INCREF(self->Socket); return self; @@ -437,96 +501,313 @@ } static PyObject * +_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) { + + char namebuf[X509_NAME_MAXLEN]; + int buflen; + PyObject *name_obj; + PyObject *value_obj; + PyObject *attr; + unsigned char *valuebuf = NULL; + + buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + name_obj = PyString_FromStringAndSize(namebuf, buflen); + if (name_obj == NULL) + goto fail; + + buflen = ASN1_STRING_to_UTF8(&valuebuf, value); + if (buflen < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + Py_DECREF(name_obj); + goto fail; + } + value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, + buflen, "strict"); + OPENSSL_free(valuebuf); + if (value_obj == NULL) { + Py_DECREF(name_obj); + goto fail; + } + attr = PyTuple_New(2); + if (attr == NULL) { + Py_DECREF(name_obj); + Py_DECREF(value_obj); + goto fail; + } + PyTuple_SET_ITEM(attr, 0, name_obj); + PyTuple_SET_ITEM(attr, 1, value_obj); + return attr; + + fail: + return NULL; +} + +static PyObject * _create_tuple_for_X509_NAME (X509_NAME *xname) { - PyObject *pt = NULL; - PyObject *entry_tuple = NULL; + PyObject *dn = NULL; /* tuple which represents the "distinguished name" */ + PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */ + PyObject *rdnt; + PyObject *attr = NULL; /* tuple to hold an attribute */ int entry_count = X509_NAME_entry_count(xname); + X509_NAME_ENTRY *entry; + ASN1_OBJECT *name; + ASN1_STRING *value; int index_counter; + int rdn_level = -1; + int retcode; - pt = PyTuple_New(entry_count); - if (pt == NULL) + dn = PyList_New(0); + if (dn == NULL) return NULL; + /* now create another tuple to hold the top-level RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; for (index_counter = 0; - index_counter < X509_NAME_entry_count(xname); + index_counter < entry_count; index_counter++) { - char namebuf[X509_NAME_MAXLEN]; - int buflen; - PyObject *name_obj; - ASN1_STRING *value; - PyObject *value_obj; - unsigned char *valuebuf = NULL; - - X509_NAME_ENTRY *entry = X509_NAME_get_entry(xname, - index_counter); - - ASN1_OBJECT *name = X509_NAME_ENTRY_get_object(entry); - buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0); - if (buflen < 0) - goto fail0; - name_obj = PyString_FromStringAndSize(namebuf, buflen); - if (name_obj == NULL) - goto fail0; + entry = X509_NAME_get_entry(xname, index_counter); + /* check to see if we've gotten to a new RDN */ + if (rdn_level >= 0) { + if (rdn_level != entry->set) { + /* yes, new RDN */ + /* add old RDN to DN */ + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) + goto fail0; + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) + goto fail0; + /* create new RDN */ + rdn = PyList_New(0); + if (rdn == NULL) + goto fail0; + } + } + rdn_level = entry->set; + + /* now add this attribute to the current RDN */ + name = X509_NAME_ENTRY_get_object(entry); value = X509_NAME_ENTRY_get_data(entry); - buflen = ASN1_STRING_to_UTF8(&valuebuf, value); - if (buflen < 0) { - Py_DECREF(name_obj); + attr = _create_tuple_for_attribute(name, value); + /* + fprintf(stderr, "RDN level %d, attribute %s: %s\n", + entry->set, + PyString_AS_STRING(PyTuple_GET_ITEM(attr, 0)), + PyString_AS_STRING(PyTuple_GET_ITEM(attr, 1))); + */ + if (attr == NULL) + goto fail1; + retcode = PyList_Append(rdn, attr); + Py_DECREF(attr); + if (retcode < 0) + goto fail1; + } + /* now, there's typically a dangling RDN */ + if ((rdn != NULL) && (PyList_Size(rdn) > 0)) { + rdnt = PyList_AsTuple(rdn); + Py_DECREF(rdn); + if (rdnt == NULL) goto fail0; - } - value_obj = PyUnicode_DecodeUTF8((char *) valuebuf, - buflen, "strict"); - OPENSSL_free(valuebuf); - if (value_obj == NULL) { - Py_DECREF(name_obj); + retcode = PyList_Append(dn, rdnt); + Py_DECREF(rdnt); + if (retcode < 0) goto fail0; + } + + /* convert list to tuple */ + rdnt = PyList_AsTuple(dn); + Py_DECREF(dn); + if (rdnt == NULL) + return NULL; + return rdnt; + + fail1: + Py_XDECREF(rdn); + + fail0: + Py_XDECREF(dn); + return NULL; +} + +static PyObject * +_get_peer_alt_names (X509 *certificate) { + + /* this code follows the procedure outlined in + OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print() + function to extract the STACK_OF(GENERAL_NAME), + then iterates through the stack to add the + names. */ + + int i, j; + PyObject *peer_alt_names = Py_None; + PyObject *v, *t; + X509_EXTENSION *ext = NULL; + GENERAL_NAMES *names = NULL; + GENERAL_NAME *name; + X509V3_EXT_METHOD *method; + BIO *biobuf = NULL; + char buf[2048]; + char *vptr; + int len; + unsigned char *p; + + if (certificate == NULL) + return peer_alt_names; + + /* get a memory buffer */ + biobuf = BIO_new(BIO_s_mem()); + + i = 0; + while ((i = X509_get_ext_by_NID( + certificate, NID_subject_alt_name, i)) >= 0) { + + if (peer_alt_names == Py_None) { + peer_alt_names = PyList_New(0); + if (peer_alt_names == NULL) + goto fail; } - entry_tuple = PyTuple_New(2); - if (entry_tuple == NULL) { - Py_DECREF(name_obj); - Py_DECREF(value_obj); - goto fail0; + + /* now decode the altName */ + ext = X509_get_ext(certificate, i); + if(!(method = X509V3_EXT_get(ext))) { + PyErr_SetString(PySSLErrorObject, + ERRSTR("No method for internalizing subjectAltName!")); + goto fail; + } + + p = ext->value->data; + if(method->it) + names = (GENERAL_NAMES*) (ASN1_item_d2i(NULL, + &p, + ext->value->length, + ASN1_ITEM_ptr(method->it))); + else + names = (GENERAL_NAMES*) (method->d2i(NULL, + &p, + ext->value->length)); + + for(j = 0; j < sk_GENERAL_NAME_num(names); j++) { + + /* get a rendering of each name in the set of names */ + + name = sk_GENERAL_NAME_value(names, j); + if (name->type == GEN_DIRNAME) { + + /* we special-case DirName as a tuple of tuples of attributes */ + + t = PyTuple_New(2); + if (t == NULL) { + goto fail; + } + + v = PyString_FromString("DirName"); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + + v = _create_tuple_for_X509_NAME (name->d.dirn); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + + } else { + + /* for everything else, we use the OpenSSL print form */ + + (void) BIO_reset(biobuf); + GENERAL_NAME_print(biobuf, name); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail; + } + vptr = strchr(buf, ':'); + if (vptr == NULL) + goto fail; + t = PyTuple_New(2); + if (t == NULL) + goto fail; + v = PyString_FromStringAndSize(buf, (vptr - buf)); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 0, v); + v = PyString_FromStringAndSize((vptr + 1), (len - (vptr - buf + 1))); + if (v == NULL) { + Py_DECREF(t); + goto fail; + } + PyTuple_SET_ITEM(t, 1, v); + } + + /* and add that rendering to the list */ + + if (PyList_Append(peer_alt_names, t) < 0) { + Py_DECREF(t); + goto fail; + } + Py_DECREF(t); } - PyTuple_SET_ITEM(entry_tuple, 0, name_obj); - PyTuple_SET_ITEM(entry_tuple, 1, value_obj); - PyTuple_SET_ITEM(pt, index_counter, entry_tuple); } - return pt; + BIO_free(biobuf); + if (peer_alt_names != Py_None) { + v = PyList_AsTuple(peer_alt_names); + Py_DECREF(peer_alt_names); + return v; + } else { + return peer_alt_names; + } + + + fail: + if (biobuf != NULL) + BIO_free(biobuf); + + if (peer_alt_names != Py_None) { + Py_XDECREF(peer_alt_names); + } - fail0: - Py_XDECREF(pt); return NULL; } static PyObject * -PySSL_peercert(PySSLObject *self) -{ +_decode_certificate (X509 *certificate, int verbose) { + PyObject *retval = NULL; BIO *biobuf = NULL; PyObject *peer; + PyObject *peer_alt_names = NULL; PyObject *issuer; PyObject *version; + PyObject *sn_obj; + ASN1_INTEGER *serialNumber; char buf[2048]; int len; ASN1_TIME *notBefore, *notAfter; PyObject *pnotBefore, *pnotAfter; - int verification; - - if (!self->peer_cert) - Py_RETURN_NONE; retval = PyDict_New(); if (retval == NULL) return NULL; - verification = SSL_CTX_get_verify_mode(self->ctx); - if ((verification & SSL_VERIFY_PEER) == 0) - return retval; - peer = _create_tuple_for_X509_NAME( - X509_get_subject_name(self->peer_cert)); + X509_get_subject_name(certificate)); if (peer == NULL) goto fail0; if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) { @@ -535,51 +816,98 @@ } Py_DECREF(peer); - issuer = _create_tuple_for_X509_NAME( - X509_get_issuer_name(self->peer_cert)); - if (issuer == NULL) - goto fail0; - if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { + if (verbose) { + issuer = _create_tuple_for_X509_NAME( + X509_get_issuer_name(certificate)); + if (issuer == NULL) + goto fail0; + if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) { + Py_DECREF(issuer); + goto fail0; + } Py_DECREF(issuer); - goto fail0; - } - Py_DECREF(issuer); - - version = PyInt_FromLong(X509_get_version(self->peer_cert)); - if (PyDict_SetItemString(retval, "version", version) < 0) { + + version = PyInt_FromLong(X509_get_version(certificate) + 1); + if (PyDict_SetItemString(retval, "version", version) < 0) { + Py_DECREF(version); + goto fail0; + } Py_DECREF(version); - goto fail0; } - Py_DECREF(version); - + /* get a memory buffer */ biobuf = BIO_new(BIO_s_mem()); + + if (verbose) { - notBefore = X509_get_notBefore(self->peer_cert); - ASN1_TIME_print(biobuf, notBefore); - len = BIO_gets(biobuf, buf, sizeof(buf)-1); - pnotBefore = PyString_FromStringAndSize(buf, len); - if (pnotBefore == NULL) - goto fail1; - if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { + (void) BIO_reset(biobuf); + serialNumber = X509_get_serialNumber(certificate); + /* should not exceed 20 octets, 160 bits, so buf is big enough */ + i2a_ASN1_INTEGER(biobuf, serialNumber); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + sn_obj = PyString_FromStringAndSize(buf, len); + if (sn_obj == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) { + Py_DECREF(sn_obj); + goto fail1; + } + Py_DECREF(sn_obj); + + (void) BIO_reset(biobuf); + notBefore = X509_get_notBefore(certificate); + ASN1_TIME_print(biobuf, notBefore); + len = BIO_gets(biobuf, buf, sizeof(buf)-1); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } + pnotBefore = PyString_FromStringAndSize(buf, len); + if (pnotBefore == NULL) + goto fail1; + if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) { + Py_DECREF(pnotBefore); + goto fail1; + } Py_DECREF(pnotBefore); - goto fail1; } - Py_DECREF(pnotBefore); (void) BIO_reset(biobuf); - notAfter = X509_get_notAfter(self->peer_cert); + notAfter = X509_get_notAfter(certificate); ASN1_TIME_print(biobuf, notAfter); len = BIO_gets(biobuf, buf, sizeof(buf)-1); - BIO_free(biobuf); + if (len < 0) { + _setSSLError(NULL, 0, __FILE__, __LINE__); + goto fail1; + } pnotAfter = PyString_FromStringAndSize(buf, len); if (pnotAfter == NULL) - goto fail0; + goto fail1; if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) { Py_DECREF(pnotAfter); - goto fail0; + goto fail1; } Py_DECREF(pnotAfter); + + /* Now look for subjectAltName */ + + peer_alt_names = _get_peer_alt_names(certificate); + if (peer_alt_names == NULL) + goto fail1; + else if (peer_alt_names != Py_None) { + if (PyDict_SetItemString(retval, "subjectAltName", + peer_alt_names) < 0) { + Py_DECREF(peer_alt_names); + goto fail1; + } + Py_DECREF(peer_alt_names); + } + + BIO_free(biobuf); return retval; fail1: @@ -590,6 +918,141 @@ return NULL; } + +static PyObject * +PySSL_test_decode_certificate (PyObject *mod, PyObject *args) { + + PyObject *retval = NULL; + char *filename = NULL; + X509 *x=NULL; + BIO *cert; + int verbose = 1; + + if (!PyArg_ParseTuple(args, "s|i:test_decode_certificate", &filename, &verbose)) + return NULL; + + if ((cert=BIO_new(BIO_s_file())) == NULL) { + PyErr_SetString(PySSLErrorObject, "Can't malloc memory to read file"); + goto fail0; + } + + if (BIO_read_filename(cert,filename) <= 0) { + PyErr_SetString(PySSLErrorObject, "Can't open file"); + goto fail0; + } + + x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL); + if (x == NULL) { + PyErr_SetString(PySSLErrorObject, "Error decoding PEM-encoded file"); + goto fail0; + } + + retval = _decode_certificate(x, verbose); + + fail0: + + if (cert != NULL) BIO_free(cert); + return retval; +} + + +static PyObject * +PySSL_peercert(PySSLObject *self, PyObject *args) +{ + PyObject *retval = NULL; + int len; + int verification; + PyObject *binary_mode = Py_None; + + if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode)) + return NULL; + + if (!self->peer_cert) + Py_RETURN_NONE; + + if (PyObject_IsTrue(binary_mode)) { + /* return cert in DER-encoded format */ + + unsigned char *bytes_buf = NULL; + + bytes_buf = NULL; + len = i2d_X509(self->peer_cert, &bytes_buf); + if (len < 0) { + PySSL_SetError(self, len, __FILE__, __LINE__); + return NULL; + } + retval = PyString_FromStringAndSize((const char *) bytes_buf, len); + OPENSSL_free(bytes_buf); + return retval; + + } else { + + verification = SSL_CTX_get_verify_mode(self->ctx); + if ((verification & SSL_VERIFY_PEER) == 0) + return PyDict_New(); + else + return _decode_certificate (self->peer_cert, 0); + } +} + +PyDoc_STRVAR(PySSL_peercert_doc, +"peer_certificate([der=False]) -> certificate\n\ +\n\ +Returns the certificate for the peer. If no certificate was provided,\n\ +returns None. If a certificate was provided, but not validated, returns\n\ +an empty dictionary. Otherwise returns a dict containing information\n\ +about the peer certificate.\n\ +\n\ +If the optional argument is True, returns a DER-encoded copy of the\n\ +peer certificate, or None if no certificate was provided. This will\n\ +return the certificate even if it wasn't validated."); + +static PyObject *PySSL_cipher (PySSLObject *self) { + + PyObject *retval, *v; + SSL_CIPHER *current; + char *cipher_name; + char *cipher_protocol; + + if (self->ssl == NULL) + return Py_None; + current = SSL_get_current_cipher(self->ssl); + if (current == NULL) + return Py_None; + + retval = PyTuple_New(3); + if (retval == NULL) + return NULL; + + cipher_name = (char *) SSL_CIPHER_get_name(current); + if (cipher_name == NULL) { + PyTuple_SET_ITEM(retval, 0, Py_None); + } else { + v = PyString_FromString(cipher_name); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 0, v); + } + cipher_protocol = SSL_CIPHER_get_version(current); + if (cipher_protocol == NULL) { + PyTuple_SET_ITEM(retval, 1, Py_None); + } else { + v = PyString_FromString(cipher_protocol); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 1, v); + } + v = PyInt_FromLong(SSL_CIPHER_get_bits(current, NULL)); + if (v == NULL) + goto fail0; + PyTuple_SET_ITEM(retval, 2, v); + return retval; + + fail0: + Py_DECREF(retval); + return NULL; +} + static void PySSL_dealloc(PySSLObject *self) { if (self->peer_cert) /* Possible not to have one? */ @@ -636,9 +1099,9 @@ /* s->sock_timeout is in seconds, timeout in ms */ timeout = (int)(s->sock_timeout * 1000 + 0.5); - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS rc = poll(&pollfd, 1, timeout); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS goto normal_return; } @@ -657,12 +1120,12 @@ FD_SET(s->sock_fd, &fds); /* See if the socket is ready */ - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS if (writing) rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv); else rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS normal_return: /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise @@ -697,10 +1160,10 @@ } do { err = 0; - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS len = SSL_write(self->ssl, data, count); err = SSL_get_error(self->ssl, len); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if(PyErr_CheckSignals()) { return NULL; } @@ -752,9 +1215,9 @@ return NULL; /* first check if there are bytes ready to be read */ - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS count = SSL_pending(self->ssl); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if (!count) { sockstate = check_socket_and_wait_for_timeout(self->Socket, 0); @@ -769,26 +1232,17 @@ Py_DECREF(buf); return NULL; } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) { - if (SSL_get_shutdown(self->ssl) != - SSL_RECEIVED_SHUTDOWN) - { - Py_DECREF(buf); - PyErr_SetString(PySSLErrorObject, - "Socket closed without SSL shutdown handshake"); - return NULL; - } else { - /* should contain a zero-length string */ - _PyString_Resize(&buf, 0); - return buf; - } + /* should contain a zero-length string */ + _PyString_Resize(&buf, 0); + return buf; } } do { err = 0; - Py_BEGIN_ALLOW_THREADS + PySSL_BEGIN_ALLOW_THREADS count = SSL_read(self->ssl, PyBytes_AS_STRING(buf), len); err = SSL_get_error(self->ssl, count); - Py_END_ALLOW_THREADS + PySSL_END_ALLOW_THREADS if(PyErr_CheckSignals()) { Py_DECREF(buf); return NULL; @@ -834,49 +1288,16 @@ \n\ Read up to len bytes from the SSL socket."); -static PyObject *PySSL_SSLshutdown(PySSLObject *self, PyObject *args) -{ - int err; - - /* Guard against closed socket */ - if (self->Socket->sock_fd < 0) { - PyErr_SetString(PySSLErrorObject, - "Underlying socket has been closed."); - return NULL; - } - - Py_BEGIN_ALLOW_THREADS - err = SSL_shutdown(self->ssl); - if (err == 0) { - /* we need to call it again to finish the shutdown */ - err = SSL_shutdown(self->ssl); - } - Py_END_ALLOW_THREADS - - if (err < 0) - return PySSL_SetError(self, err, __FILE__, __LINE__); - else { - Py_INCREF(self->Socket); - return (PyObject *) (self->Socket); - } -} - -PyDoc_STRVAR(PySSL_SSLshutdown_doc, -"shutdown(s) -> socket\n\ -\n\ -Does the SSL shutdown handshake with the remote end, and returns\n\ -the underlying socket object."); - static PyMethodDef PySSLMethods[] = { {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS, - PySSL_SSLwrite_doc}, + PySSL_SSLwrite_doc}, {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS, - PySSL_SSLread_doc}, + PySSL_SSLread_doc}, {"server", (PyCFunction)PySSL_server, METH_NOARGS}, {"issuer", (PyCFunction)PySSL_issuer, METH_NOARGS}, - {"peer_certificate", (PyCFunction)PySSL_peercert, METH_NOARGS}, - {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS, - PySSL_SSLshutdown_doc}, + {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS, + PySSL_peercert_doc}, + {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS}, {NULL, NULL} }; @@ -924,7 +1345,7 @@ "RAND_add(string, entropy)\n\ \n\ Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\ -bound on the entropy contained in string."); +bound on the entropy contained in string. See RFC 1750."); static PyObject * PySSL_RAND_status(PyObject *self) @@ -961,9 +1382,9 @@ PyDoc_STRVAR(PySSL_RAND_egd_doc, "RAND_egd(path) -> bytes\n\ \n\ -Queries the entropy gather daemon (EGD) on socket path. Returns number\n\ -of bytes read. Raises ssl.sslerror if connection to EGD fails or\n\ -if it does provide enough data to seed PRNG."); +Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\ +Returns number of bytes read. Raises SSLError if connection to EGD\n\ +fails or if it does provide enough data to seed PRNG."); #endif @@ -972,6 +1393,8 @@ static PyMethodDef PySSL_methods[] = { {"sslwrap", PySSL_sslwrap, METH_VARARGS, ssl_doc}, + {"_test_decode_cert", PySSL_test_decode_certificate, + METH_VARARGS}, #ifdef HAVE_OPENSSL_RAND {"RAND_add", PySSL_RAND_add, METH_VARARGS, PySSL_RAND_add_doc}, @@ -984,6 +1407,73 @@ }; +#ifdef WITH_THREAD + +/* an implementation of OpenSSL threading operations in terms + of the Python C thread library */ + +static PyThread_type_lock *_ssl_locks = NULL; + +static unsigned long _ssl_thread_id_function (void) { + return PyThread_get_thread_ident(); +} + +static void _ssl_thread_locking_function (int mode, int n, const char *file, int line) { + /* this function is needed to perform locking on shared data + structures. (Note that OpenSSL uses a number of global data + structures that will be implicitly shared whenever multiple threads + use OpenSSL.) Multi-threaded applications will crash at random if + it is not set. + + locking_function() must be able to handle up to CRYPTO_num_locks() + different mutex locks. It sets the n-th lock if mode & CRYPTO_LOCK, and + releases it otherwise. + + file and line are the file number of the function setting the + lock. They can be useful for debugging. + */ + + if ((_ssl_locks == NULL) || + (n < 0) || (n >= _ssl_locks_count)) + return; + + if (mode & CRYPTO_LOCK) { + PyThread_acquire_lock(_ssl_locks[n], 1); + } else { + PyThread_release_lock(_ssl_locks[n]); + } +} + +static int _setup_ssl_threads(void) { + + int i; + + if (_ssl_locks == NULL) { + _ssl_locks_count = CRYPTO_num_locks(); + _ssl_locks = (PyThread_type_lock *) + malloc(sizeof(PyThread_type_lock) * _ssl_locks_count); + if (_ssl_locks == NULL) + return 0; + memset(_ssl_locks, 0, sizeof(PyThread_type_lock) * _ssl_locks_count); + for (i = 0; i < _ssl_locks_count; i++) { + _ssl_locks[i] = PyThread_allocate_lock(); + if (_ssl_locks[i] == NULL) { + int j; + for (j = 0; j < i; j++) { + PyThread_free_lock(_ssl_locks[j]); + } + free(_ssl_locks); + return 0; + } + } + CRYPTO_set_locking_callback(_ssl_thread_locking_function); + CRYPTO_set_id_callback(_ssl_thread_id_function); + } + return 1; +} + +#endif /* def HAVE_THREAD */ + PyDoc_STRVAR(module_doc, "Implementation module for SSL socket operations. See the socket module\n\ for documentation."); @@ -1006,15 +1496,21 @@ /* Init OpenSSL */ SSL_load_error_strings(); +#ifdef WITH_THREAD + /* note that this will start threading if not already started */ + if (!_setup_ssl_threads()) { + return; + } +#endif SSLeay_add_ssl_algorithms(); /* Add symbols to module dict */ - PySSLErrorObject = PyErr_NewException("ssl.sslerror", + PySSLErrorObject = PyErr_NewException("ssl.SSLError", PySocketModule.error, NULL); if (PySSLErrorObject == NULL) return; - if (PyDict_SetItemString(d, "sslerror", PySSLErrorObject) != 0) + if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0) return; if (PyDict_SetItemString(d, "SSLType", (PyObject *)&PySSL_Type) != 0) Modified: python/branches/py3k-importlib/Modules/bz2module.c ============================================================================== --- python/branches/py3k-importlib/Modules/bz2module.c (original) +++ python/branches/py3k-importlib/Modules/bz2module.c Fri Sep 21 03:17:09 2007 @@ -229,6 +229,7 @@ size_t increment; /* amount to increment the buffer */ PyObject *v; int bzerror; + int bytes_read; total_v_size = n > 0 ? n : 100; v = PyBytes_FromStringAndSize((char *)NULL, total_v_size); @@ -241,8 +242,10 @@ for (;;) { Py_BEGIN_ALLOW_THREADS do { - BZ2_bzRead(&bzerror, f->fp, &c, 1); + bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1); f->pos++; + if (bytes_read == 0) + break; *buf++ = c; } while (bzerror == BZ_OK && c != '\n' && buf != end); Py_END_ALLOW_THREADS Modified: python/branches/py3k-importlib/Objects/dictobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/dictobject.c (original) +++ python/branches/py3k-importlib/Objects/dictobject.c Fri Sep 21 03:17:09 2007 @@ -149,7 +149,7 @@ /* forward declarations */ static dictentry * -lookdict_string(dictobject *mp, PyObject *key, long hash); +lookdict_unicode(dictobject *mp, PyObject *key, long hash); #ifdef SHOW_CONVERSION_COUNTS static long created = 0L; @@ -218,7 +218,7 @@ return NULL; EMPTY_TO_MINSIZE(mp); } - mp->ma_lookup = lookdict_string; + mp->ma_lookup = lookdict_unicode; #ifdef SHOW_CONVERSION_COUNTS ++created; #endif @@ -243,7 +243,7 @@ lookdict() is general-purpose, and may return NULL if (and only if) a comparison raises an exception (this was new in Python 2.5). -lookdict_string() below is specialized to string keys, comparison of which can +lookdict_unicode() below is specialized to string keys, comparison of which can never raise an exception; that function can never return NULL. For both, when the key isn't found a dictentry* is returned for which the me_value field is NULL; this is the slot in the dict at which the key would have been found, and @@ -325,17 +325,37 @@ return 0; } +/* Return 1 if two unicode objects are equal, 0 if not. */ +static int +unicode_eq(PyObject *aa, PyObject *bb) +{ + PyUnicodeObject *a = (PyUnicodeObject *)aa; + PyUnicodeObject *b = (PyUnicodeObject *)bb; + + if (a->length != b->length) + return 0; + if (a->length == 0) + return 1; + if (a->str[0] != b->str[0]) + return 0; + if (a->length == 1) + return 1; + return memcmp(a->str, b->str, a->length * sizeof(Py_UNICODE)) == 0; +} + + /* - * Hacked up version of lookdict which can assume keys are always strings; - * this assumption allows testing for errors during PyObject_RichCompareBool() - * to be dropped; string-string comparisons never raise exceptions. This also - * means we don't need to go through PyObject_RichCompareBool(); we can always - * use _PyString_Eq() directly. + * Hacked up version of lookdict which can assume keys are always + * unicodes; this assumption allows testing for errors during + * PyObject_RichCompareBool() to be dropped; unicode-unicode + * comparisons never raise exceptions. This also means we don't need + * to go through PyObject_RichCompareBool(); we can always use + * unicode_eq() directly. * - * This is valuable because dicts with only string keys are very common. + * This is valuable because dicts with only unicode keys are very common. */ static dictentry * -lookdict_string(dictobject *mp, PyObject *key, register long hash) +lookdict_unicode(dictobject *mp, PyObject *key, register long hash) { register size_t i; register size_t perturb; @@ -344,11 +364,11 @@ dictentry *ep0 = mp->ma_table; register dictentry *ep; - /* Make sure this function doesn't have to handle non-string keys, + /* Make sure this function doesn't have to handle non-unicode keys, including subclasses of str; e.g., one reason to subclass - strings is to override __eq__, and for speed we don't cater to + unicodes is to override __eq__, and for speed we don't cater to that here. */ - if (!PyString_CheckExact(key)) { + if (!PyUnicode_CheckExact(key)) { #ifdef SHOW_CONVERSION_COUNTS ++converted; #endif @@ -362,7 +382,7 @@ if (ep->me_key == dummy) freeslot = ep; else { - if (ep->me_hash == hash && _PyString_Eq(ep->me_key, key)) + if (ep->me_hash == hash && unicode_eq(ep->me_key, key)) return ep; freeslot = NULL; } @@ -377,7 +397,7 @@ if (ep->me_key == key || (ep->me_hash == hash && ep->me_key != dummy - && _PyString_Eq(ep->me_key, key))) + && unicode_eq(ep->me_key, key))) return ep; if (ep->me_key == dummy && freeslot == NULL) freeslot = ep; @@ -615,8 +635,8 @@ PyErr_BadInternalCall(); return NULL; } - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) { @@ -695,8 +715,8 @@ return -1; } assert(key); - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return -1; @@ -975,8 +995,8 @@ long hash; dictentry *ep; assert(mp->ma_table != NULL); - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; @@ -1547,8 +1567,8 @@ long hash; dictentry *ep; - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; @@ -1571,8 +1591,8 @@ if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj)) return NULL; - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; @@ -1600,8 +1620,8 @@ if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj)) return NULL; - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; @@ -1646,8 +1666,8 @@ "pop(): dictionary is empty"); return NULL; } - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return NULL; @@ -1842,8 +1862,8 @@ dictobject *mp = (dictobject *)op; dictentry *ep; - if (!PyString_CheckExact(key) || - (hash = ((PyStringObject *) key)->ob_shash) == -1) { + if (!PyUnicode_CheckExact(key) || + (hash = ((PyUnicodeObject *) key)->hash) == -1) { hash = PyObject_Hash(key); if (hash == -1) return -1; @@ -1889,7 +1909,7 @@ /* It's guaranteed that tp->alloc zeroed out the struct. */ assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0); INIT_NONZERO_DICT_SLOTS(d); - d->ma_lookup = lookdict_string; + d->ma_lookup = lookdict_unicode; #ifdef SHOW_CONVERSION_COUNTS ++created; #endif Modified: python/branches/py3k-importlib/Objects/genobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/genobject.c (original) +++ python/branches/py3k-importlib/Objects/genobject.c Fri Sep 21 03:17:09 2007 @@ -252,7 +252,6 @@ Py_INCREF(typ); } } - else { /* Not something you can raise. throw() fails. */ PyErr_Format(PyExc_TypeError, Modified: python/branches/py3k-importlib/Objects/listobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/listobject.c (original) +++ python/branches/py3k-importlib/Objects/listobject.c Fri Sep 21 03:17:09 2007 @@ -297,7 +297,10 @@ so must refetch the list size on each iteration. */ for (i = 0; i < Py_Size(v); ++i) { int status; + if (Py_EnterRecursiveCall(" while getting the repr of a list")) + goto Done; s = PyObject_Repr(v->ob_item[i]); + Py_LeaveRecursiveCall(); if (s == NULL) goto Done; status = PyList_Append(pieces, s); Modified: python/branches/py3k-importlib/Objects/longobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/longobject.c (original) +++ python/branches/py3k-importlib/Objects/longobject.c Fri Sep 21 03:17:09 2007 @@ -2197,10 +2197,18 @@ i = -(i); } #define LONG_BIT_PyLong_SHIFT (8*sizeof(long) - PyLong_SHIFT) + /* The following loop produces a C long x such that (unsigned long)x + is congruent to the absolute value of v modulo ULONG_MAX. The + resulting x is nonzero if and only if v is. */ while (--i >= 0) { /* Force a native long #-bits (32 or 64) circular shift */ x = ((x << PyLong_SHIFT) & ~PyLong_MASK) | ((x >> LONG_BIT_PyLong_SHIFT) & PyLong_MASK); x += v->ob_digit[i]; + /* If the addition above overflowed (thinking of x as + unsigned), we compensate by incrementing. This preserves + the value modulo ULONG_MAX. */ + if ((unsigned long)x < v->ob_digit[i]) + x++; } #undef LONG_BIT_PyLong_SHIFT x = x * sign; Modified: python/branches/py3k-importlib/Objects/object.c ============================================================================== --- python/branches/py3k-importlib/Objects/object.c (original) +++ python/branches/py3k-importlib/Objects/object.c Fri Sep 21 03:17:09 2007 @@ -271,14 +271,18 @@ #endif clearerr(fp); /* Clear any previous error condition */ if (op == NULL) { + Py_BEGIN_ALLOW_THREADS fprintf(fp, ""); + Py_END_ALLOW_THREADS } else { if (op->ob_refcnt <= 0) /* XXX(twouters) cast refcount to long until %zd is universally available */ + Py_BEGIN_ALLOW_THREADS fprintf(fp, "", (long)op->ob_refcnt, op); + Py_END_ALLOW_THREADS else { PyObject *s; if (flags & Py_PRINT_RAW) Modified: python/branches/py3k-importlib/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/unicodeobject.c (original) +++ python/branches/py3k-importlib/Objects/unicodeobject.c Fri Sep 21 03:17:09 2007 @@ -6587,21 +6587,27 @@ return (PyObject*) PyUnicode_FromUnicode(&self->str[index], 1); } +/* Believe it or not, this produces the same value for ASCII strings + as string_hash(). */ static long unicode_hash(PyUnicodeObject *self) { - if (self->hash != -1) { - return self->hash; - } - else { - /* Since Unicode objects compare equal to their UTF-8 string - counterparts, we hash the UTF-8 string. */ - PyObject *v = _PyUnicode_AsDefaultEncodedString((PyObject*)self, NULL); - if (v == NULL) - return -1; - assert(PyString_CheckExact(v)); - return self->hash = v->ob_type->tp_hash(v); - } + Py_ssize_t len; + Py_UNICODE *p; + long x; + + if (self->hash != -1) + return self->hash; + len = Py_Size(self); + p = self->str; + x = *p << 7; + while (--len >= 0) + x = (1000003*x) ^ *p++; + x ^= Py_Size(self); + if (x == -1) + x = -2; + self->hash = x; + return x; } PyDoc_STRVAR(index__doc__, Modified: python/branches/py3k-importlib/Python/ceval.c ============================================================================== --- python/branches/py3k-importlib/Python/ceval.c (original) +++ python/branches/py3k-importlib/Python/ceval.c Fri Sep 21 03:17:09 2007 @@ -28,8 +28,9 @@ typedef unsigned long long uint64; #if defined(__ppc__) /* <- Don't know if this is the correct symbol; this - section should work for GCC on any PowerPC platform, - irrespective of OS. POWER? Who knows :-) */ + section should work for GCC on any PowerPC + platform, irrespective of OS. + POWER? Who knows :-) */ #define READ_TIMESTAMP(var) ppc_getcounter(&var) @@ -93,7 +94,8 @@ static PyObject * fast_function(PyObject *, PyObject ***, int, int, int); static PyObject * do_call(PyObject *, PyObject ***, int, int); static PyObject * ext_do_call(PyObject *, PyObject ***, int, int, int); -static PyObject * update_keyword_args(PyObject *, int, PyObject ***,PyObject *); +static PyObject * update_keyword_args(PyObject *, int, PyObject ***, + PyObject *); static PyObject * update_star_args(int, int, PyObject *, PyObject ***); static PyObject * load_args(PyObject ***, int); #define CALL_FLAG_VAR 1 @@ -431,7 +433,7 @@ Py_SetRecursionLimit(int new_limit) { recursion_limit = new_limit; - _Py_CheckRecursionLimit = recursion_limit; + _Py_CheckRecursionLimit = recursion_limit; } /* the macro Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall() @@ -469,7 +471,7 @@ where); return -1; } - _Py_CheckRecursionLimit = recursion_limit; + _Py_CheckRecursionLimit = recursion_limit; return 0; } @@ -509,7 +511,8 @@ PyObject * PyEval_EvalFrame(PyFrameObject *f) { /* This is for backward compatibility with extension modules that - used this API; core interpreter code should call PyEval_EvalFrameEx() */ + used this API; core interpreter code should call + PyEval_EvalFrameEx() */ return PyEval_EvalFrameEx(f, 0); } @@ -519,7 +522,7 @@ #ifdef DXPAIRS int lastopcode = 0; #endif - register PyObject **stack_pointer; /* Next free slot in value stack */ + register PyObject **stack_pointer; /* Next free slot in value stack */ register unsigned char *next_instr; register int opcode; /* Current opcode */ register int oparg; /* Current opcode argument, if any */ @@ -610,10 +613,10 @@ #define JUMPBY(x) (next_instr += (x)) /* OpCode prediction macros - Some opcodes tend to come in pairs thus making it possible to predict - the second code when the first is run. For example, COMPARE_OP is often - followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, those opcodes are often - followed by a POP_TOP. + Some opcodes tend to come in pairs thus making it possible to + predict the second code when the first is run. For example, + COMPARE_OP is often followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, + those opcodes are often followed by a POP_TOP. Verifying the prediction costs a single high-speed test of register variable against a constant. If the pairing was good, then the @@ -660,11 +663,13 @@ #define PUSH(v) { (void)(BASIC_PUSH(v), \ lltrace && prtrace(TOP(), "push")); \ assert(STACK_LEVEL() <= co->co_stacksize); } -#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), BASIC_POP()) +#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \ + BASIC_POP()) #define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \ lltrace && prtrace(TOP(), "stackadj")); \ assert(STACK_LEVEL() <= co->co_stacksize); } -#define EXT_POP(STACK_POINTER) (lltrace && prtrace((STACK_POINTER)[-1], "ext_pop"), *--(STACK_POINTER)) +#define EXT_POP(STACK_POINTER) (lltrace && prtrace((STACK_POINTER)[-1], \ + "ext_pop"), *--(STACK_POINTER)) #else #define PUSH(v) BASIC_PUSH(v) #define POP() BASIC_POP() @@ -805,11 +810,11 @@ Py_MakePendingCalls() above. */ if (--_Py_Ticker < 0) { - if (*next_instr == SETUP_FINALLY) { - /* Make the last opcode before - a try: finally: block uninterruptable. */ - goto fast_next_opcode; - } + if (*next_instr == SETUP_FINALLY) { + /* Make the last opcode before + a try: finally: block uninterruptable. */ + goto fast_next_opcode; + } _Py_Ticker = _Py_CheckInterval; tstate->tick_counter++; #ifdef WITH_TSC @@ -1467,8 +1472,8 @@ case RAISE_VARARGS: v = w = NULL; switch (oparg) { - case 2: - v = POP(); /* cause */ + case 2: + v = POP(); /* cause */ case 1: w = POP(); /* exc */ case 0: /* Fallthrough */ @@ -1568,7 +1573,8 @@ if ((x = f->f_locals) != NULL) { if ((err = PyObject_DelItem(x, w)) != 0) format_exc_check_arg(PyExc_NameError, - NAME_ERROR_MSG ,w); + NAME_ERROR_MSG, + w); break; } PyErr_Format(PyExc_SystemError, @@ -1579,8 +1585,10 @@ PREDICTED_WITH_ARG(UNPACK_SEQUENCE); case UNPACK_SEQUENCE: v = POP(); - if (PyTuple_CheckExact(v) && PyTuple_GET_SIZE(v) == oparg) { - PyObject **items = ((PyTupleObject *)v)->ob_item; + if (PyTuple_CheckExact(v) && + PyTuple_GET_SIZE(v) == oparg) { + PyObject **items = \ + ((PyTupleObject *)v)->ob_item; while (oparg--) { w = items[oparg]; Py_INCREF(w); @@ -1588,15 +1596,17 @@ } Py_DECREF(v); continue; - } else if (PyList_CheckExact(v) && PyList_GET_SIZE(v) == oparg) { - PyObject **items = ((PyListObject *)v)->ob_item; + } else if (PyList_CheckExact(v) && + PyList_GET_SIZE(v) == oparg) { + PyObject **items = \ + ((PyListObject *)v)->ob_item; while (oparg--) { w = items[oparg]; Py_INCREF(w); PUSH(w); } } else if (unpack_iterable(v, oparg, -1, - stack_pointer + oparg)) { + stack_pointer + oparg)) { stack_pointer += oparg; } else { /* unpack_iterable() raised an exception */ @@ -1669,7 +1679,8 @@ else { x = PyObject_GetItem(v, w); if (x == NULL && PyErr_Occurred()) { - if (!PyErr_ExceptionMatches(PyExc_KeyError)) + if (!PyErr_ExceptionMatches( + PyExc_KeyError)) break; PyErr_Clear(); } @@ -1681,7 +1692,7 @@ if (x == NULL) { format_exc_check_arg( PyExc_NameError, - NAME_ERROR_MSG ,w); + NAME_ERROR_MSG, w); break; } } @@ -1782,13 +1793,10 @@ UNBOUNDLOCAL_ERROR_MSG, v); } else { - v = PyTuple_GET_ITEM( - co->co_freevars, - oparg - PyTuple_GET_SIZE(co->co_cellvars)); - format_exc_check_arg( - PyExc_NameError, - UNBOUNDFREE_ERROR_MSG, - v); + v = PyTuple_GET_ITEM(co->co_freevars, oparg - + PyTuple_GET_SIZE(co->co_cellvars)); + format_exc_check_arg(PyExc_NameError, + UNBOUNDFREE_ERROR_MSG, v); } break; @@ -2046,7 +2054,8 @@ continue; } if (PyErr_Occurred()) { - if (!PyErr_ExceptionMatches(PyExc_StopIteration)) + if (!PyErr_ExceptionMatches( + PyExc_StopIteration)) break; PyErr_Clear(); } @@ -2072,9 +2081,10 @@ case SETUP_LOOP: case SETUP_EXCEPT: case SETUP_FINALLY: - /* NOTE: If you add any new block-setup opcodes that are - not try/except/finally handlers, you may need to - update the PyGen_NeedsFinalizing() function. */ + /* NOTE: If you add any new block-setup opcodes that + are not try/except/finally handlers, you may need + to update the PyGen_NeedsFinalizing() function. + */ PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg, STACK_LEVEL()); @@ -2500,7 +2510,7 @@ } /* pop frame */ - exit_eval_frame: +exit_eval_frame: Py_LeaveRecursiveCall(); tstate->frame = f->f_back; @@ -2761,9 +2771,9 @@ return PyGen_New(f); } - retval = PyEval_EvalFrameEx(f,0); + retval = PyEval_EvalFrameEx(f,0); - fail: /* Jump here from prelude on failure */ +fail: /* Jump here from prelude on failure */ /* decref'ing the frame can cause __del__ methods to get invoked, which can call back into Python. While we're done with the @@ -2772,7 +2782,7 @@ */ assert(tstate != NULL); ++tstate->recursion_depth; - Py_DECREF(f); + Py_DECREF(f); --tstate->recursion_depth; return retval; } @@ -2876,7 +2886,7 @@ tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; - PyException_SetTraceback(value, tb); + PyException_SetTraceback(value, tb); Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); @@ -2927,7 +2937,7 @@ static enum why_code do_raise(PyObject *exc, PyObject *cause) { - PyObject *type = NULL, *value = NULL, *tb = NULL; + PyObject *type = NULL, *value = NULL, *tb = NULL; if (exc == NULL) { /* Reraise */ @@ -2935,16 +2945,16 @@ type = tstate->exc_type; value = tstate->exc_value; tb = tstate->exc_traceback; - if (type == Py_None) { - PyErr_SetString(PyExc_RuntimeError, - "No active exception to reraise"); - return WHY_EXCEPTION; - } - Py_XINCREF(type); + if (type == Py_None) { + PyErr_SetString(PyExc_RuntimeError, + "No active exception to reraise"); + return WHY_EXCEPTION; + } + Py_XINCREF(type); Py_XINCREF(value); Py_XINCREF(tb); - PyErr_Restore(type, value, tb); - return WHY_RERAISE; + PyErr_Restore(type, value, tb); + return WHY_RERAISE; } /* We support the following forms of raise: @@ -2953,11 +2963,11 @@ raise */ if (PyExceptionClass_Check(exc)) { - type = exc; - value = PyObject_CallObject(exc, NULL); + type = exc; + value = PyObject_CallObject(exc, NULL); if (value == NULL) - goto raise_error; - } + goto raise_error; + } else if (PyExceptionInstance_Check(exc)) { value = exc; type = PyExceptionInstance_Class(exc); @@ -2966,31 +2976,32 @@ else { /* Not something you can raise. You get an exception anyway, just not what you specified :-) */ - Py_DECREF(exc); + Py_DECREF(exc); PyErr_SetString(PyExc_TypeError, - "exceptions must derive from BaseException"); + "exceptions must derive from BaseException"); goto raise_error; } - tb = PyException_GetTraceback(value); - if (cause) { - PyObject *fixed_cause; - if (PyExceptionClass_Check(cause)) { - fixed_cause = PyObject_CallObject(cause, NULL); - if (fixed_cause == NULL) - goto raise_error; - Py_DECREF(cause); - } - else if (PyExceptionInstance_Check(cause)) { - fixed_cause = cause; - } - else { - PyErr_SetString(PyExc_TypeError, - "exception causes must derive from BaseException"); - goto raise_error; - } - PyException_SetCause(value, fixed_cause); - } + tb = PyException_GetTraceback(value); + if (cause) { + PyObject *fixed_cause; + if (PyExceptionClass_Check(cause)) { + fixed_cause = PyObject_CallObject(cause, NULL); + if (fixed_cause == NULL) + goto raise_error; + Py_DECREF(cause); + } + else if (PyExceptionInstance_Check(cause)) { + fixed_cause = cause; + } + else { + PyErr_SetString(PyExc_TypeError, + "exception causes must derive from " + "BaseException"); + goto raise_error; + } + PyException_SetCause(value, fixed_cause); + } PyErr_Restore(type, value, tb); return WHY_EXCEPTION; @@ -3186,18 +3197,18 @@ represents a jump backwards, call the trace function. */ if ((frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub)) { - int line; - PyAddrPair bounds; + int line; + PyAddrPair bounds; - line = PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, - &bounds); - if (line >= 0) { + line = PyCode_CheckLineNumber(frame->f_code, frame->f_lasti, + &bounds); + if (line >= 0) { frame->f_lineno = line; result = call_trace(func, obj, frame, PyTrace_LINE, Py_None); - } - *instr_lb = bounds.ap_lower; - *instr_ub = bounds.ap_upper; + } + *instr_lb = bounds.ap_lower; + *instr_ub = bounds.ap_upper; } else if (frame->f_lasti <= *instr_prev) { result = call_trace(func, obj, frame, PyTrace_LINE, Py_None); @@ -3583,9 +3594,9 @@ PyObject *value = EXT_POP(*pp_stack); PyObject *key = EXT_POP(*pp_stack); if (PyDict_GetItem(kwdict, key) != NULL) { - PyErr_Format(PyExc_TypeError, - "%.200s%s got multiple values " - "for keyword argument '%.200s'", + PyErr_Format(PyExc_TypeError, + "%.200s%s got multiple values " + "for keyword argument '%.200s'", PyEval_GetFuncName(func), PyEval_GetFuncDesc(func), PyUnicode_AsString(key)); @@ -3675,7 +3686,7 @@ PCALL(PCALL_OTHER); #endif result = PyObject_Call(func, callargs, kwdict); - call_fail: +call_fail: Py_XDECREF(callargs); Py_XDECREF(kwdict); return result; @@ -3763,7 +3774,7 @@ PCALL(PCALL_OTHER); #endif result = PyObject_Call(func, callargs, kwdict); - ext_call_fail: +ext_call_fail: Py_XDECREF(callargs); Py_XDECREF(kwdict); Py_XDECREF(stararg); @@ -3967,8 +3978,9 @@ if (v->ob_refcnt == 2) { /* In the common case, there are 2 references to the value * stored in 'variable' when the += is performed: one on the - * value stack (in 'v') and one still stored in the 'variable'. - * We try to delete the variable now to reduce the refcnt to 1. + * value stack (in 'v') and one still stored in the + * 'variable'. We try to delete the variable now to reduce + * the refcnt to 1. */ switch (*next_instr) { case STORE_FAST: @@ -3981,7 +3993,8 @@ } case STORE_DEREF: { - PyObject **freevars = f->f_localsplus + f->f_code->co_nlocals; + PyObject **freevars = (f->f_localsplus + + f->f_code->co_nlocals); PyObject *c = freevars[PEEKARG()]; if (PyCell_GET(c) == v) PyCell_Set(c, NULL); @@ -4009,10 +4022,10 @@ */ if (_PyString_Resize(&v, new_len) != 0) { /* XXX if _PyString_Resize() fails, 'v' has been - * deallocated so it cannot be put back into 'variable'. - * The MemoryError is raised when there is no value in - * 'variable', which might (very remotely) be a cause - * of incompatibilities. + * deallocated so it cannot be put back into + * 'variable'. The MemoryError is raised when there + * is no value in 'variable', which might (very + * remotely) be a cause of incompatibilities. */ return NULL; } Modified: python/branches/py3k-importlib/Python/compile.c ============================================================================== --- python/branches/py3k-importlib/Python/compile.c (original) +++ python/branches/py3k-importlib/Python/compile.c Fri Sep 21 03:17:09 2007 @@ -1428,7 +1428,7 @@ st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0); docstring = compiler_isdocstring(st); - if (docstring) + if (docstring && Py_OptimizeFlag < 2) first_const = st->v.Expr.value->v.Str.s; if (compiler_add_o(c, c->u->u_consts, first_const) < 0) { compiler_exit_scope(c); From python-3000-checkins at python.org Fri Sep 21 03:38:18 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 21 Sep 2007 03:38:18 +0200 (CEST) Subject: [Python-3000-checkins] r58224 - in python/branches/py3k-importlib: Include/pythonrun.h Modules/getpath.c NEWS Message-ID: <20070921013818.3D5081E400A@bag.python.org> Author: brett.cannon Date: Fri Sep 21 03:38:17 2007 New Revision: 58224 Modified: python/branches/py3k-importlib/Include/pythonrun.h python/branches/py3k-importlib/Modules/getpath.c python/branches/py3k-importlib/NEWS Log: Added Py_GetImportlibPath() in order to get the path to _importlib easily. Modified: python/branches/py3k-importlib/Include/pythonrun.h ============================================================================== --- python/branches/py3k-importlib/Include/pythonrun.h (original) +++ python/branches/py3k-importlib/Include/pythonrun.h Fri Sep 21 03:38:17 2007 @@ -106,6 +106,7 @@ PyAPI_FUNC(char *) Py_GetProgramFullPath(void); PyAPI_FUNC(char *) Py_GetPrefix(void); PyAPI_FUNC(char *) Py_GetExecPrefix(void); +PyAPI_FUNC(char *) Py_GetImportlibPath(void); PyAPI_FUNC(char *) Py_GetPath(void); /* In their own files */ Modified: python/branches/py3k-importlib/Modules/getpath.c ============================================================================== --- python/branches/py3k-importlib/Modules/getpath.c (original) +++ python/branches/py3k-importlib/Modules/getpath.c Fri Sep 21 03:38:17 2007 @@ -127,6 +127,7 @@ static char prefix[MAXPATHLEN+1]; static char exec_prefix[MAXPATHLEN+1]; +static char importlib_path[MAXPATHLEN+1]; static char progpath[MAXPATHLEN+1]; static char *module_search_path = NULL; static char lib_python[] = "lib/python" VERSION; @@ -269,6 +270,10 @@ *delim = '\0'; joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); + if (ismodule(prefix)) + strcpy(importlib_path, prefix); + else + importlib_path[0] = '\0'; return 1; } @@ -282,8 +287,10 @@ joinpath(prefix, vpath); joinpath(prefix, "Lib"); joinpath(prefix, LANDMARK); - if (ismodule(prefix)) + if (ismodule(prefix)) { + strcpy(importlib_path, prefix); return -1; + } } /* Search from argv0_path, until root is found */ @@ -292,8 +299,10 @@ n = strlen(prefix); joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); - if (ismodule(prefix)) + if (ismodule(prefix)) { + strcpy(importlib_path, prefix); return 1; + } prefix[n] = '\0'; reduce(prefix); } while (prefix[0]); @@ -302,10 +311,13 @@ strncpy(prefix, PREFIX, MAXPATHLEN); joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); - if (ismodule(prefix)) + if (ismodule(prefix)) { + strcpy(importlib_path, prefix); return 1; + } /* Fail */ + importlib_path[0] = '\0'; return 0; } @@ -680,6 +692,14 @@ } char * +Py_GetImportlibPath(void) +{ + if (!module_search_path) + calculate_path(); + return importlib_path; +} + +char * Py_GetProgramFullPath(void) { if (!module_search_path) Modified: python/branches/py3k-importlib/NEWS ============================================================================== --- python/branches/py3k-importlib/NEWS (original) +++ python/branches/py3k-importlib/NEWS Fri Sep 21 03:38:17 2007 @@ -1,2 +1,4 @@ +* Add Py_GetImportlibPath() as a way to get the path to _importlib. + * Have Modules/getpath.c use _importlib.py instead of os.py when searching for Python's stdlib directory. From python-3000-checkins at python.org Fri Sep 21 22:19:23 2007 From: python-3000-checkins at python.org (neil.schemenauer) Date: Fri, 21 Sep 2007 22:19:23 +0200 (CEST) Subject: [Python-3000-checkins] r58226 - in python/branches/py3k: Demo/classes/Rat.py Demo/classes/bitvec.py Doc/c-api/newtypes.rst Doc/glossary.rst Doc/library/decimal.rst Include/object.h Modules/datetimemodule.c Objects/boolobject.c Objects/complexobject.c Objects/floatobject.c Objects/longobject.c Objects/setobject.c Objects/weakrefobject.c PC/_winreg.c Tools/modulator/Templates/object_tp_as_number Message-ID: <20070921201923.F2BB51E400D@bag.python.org> Author: neil.schemenauer Date: Fri Sep 21 22:19:23 2007 New Revision: 58226 Modified: python/branches/py3k/Demo/classes/Rat.py python/branches/py3k/Demo/classes/bitvec.py python/branches/py3k/Doc/c-api/newtypes.rst python/branches/py3k/Doc/glossary.rst python/branches/py3k/Doc/library/decimal.rst python/branches/py3k/Include/object.h python/branches/py3k/Modules/datetimemodule.c python/branches/py3k/Objects/boolobject.c python/branches/py3k/Objects/complexobject.c python/branches/py3k/Objects/floatobject.c python/branches/py3k/Objects/longobject.c python/branches/py3k/Objects/setobject.c python/branches/py3k/Objects/weakrefobject.c python/branches/py3k/PC/_winreg.c python/branches/py3k/Tools/modulator/Templates/object_tp_as_number Log: Remove more cruft leftover from nb_coerce. Rename nb_coerce to nb_reserved. Modified: python/branches/py3k/Demo/classes/Rat.py ============================================================================== --- python/branches/py3k/Demo/classes/Rat.py (original) +++ python/branches/py3k/Demo/classes/Rat.py Fri Sep 21 22:19:23 2007 @@ -226,10 +226,6 @@ def __bool__(a): return a.__num != 0 - # coercion - def __coerce__(a, b): - return a, Rat(b) - def test(): '''\ Test function for rat module. Modified: python/branches/py3k/Demo/classes/bitvec.py ============================================================================== --- python/branches/py3k/Demo/classes/bitvec.py (original) +++ python/branches/py3k/Demo/classes/bitvec.py Fri Sep 21 22:19:23 2007 @@ -311,13 +311,6 @@ return BitVec(~self._data & ((1 << self._len) - 1), \ self._len) - def __coerce__(self, otherseq, *rest): - #needed for *some* of the arithmetic operations - #rprt('%r.__coerce__%r\n' % (self, (otherseq,) + rest)) - if type(otherseq) != type(self): - otherseq = bitvec(otherseq, *rest) - return self, otherseq - def __int__(self): return int(self._data) Modified: python/branches/py3k/Doc/c-api/newtypes.rst ============================================================================== --- python/branches/py3k/Doc/c-api/newtypes.rst (original) +++ python/branches/py3k/Doc/c-api/newtypes.rst Fri Sep 21 22:19:23 2007 @@ -330,7 +330,7 @@ section. The fields will be described in the order in which they occur in the structure. -Typedefs: unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc, +Typedefs: unaryfunc, binaryfunc, ternaryfunc, inquiry, intargfunc, intintargfunc, intobjargproc, intintobjargproc, objobjargproc, destructor, freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc, setattrofunc, cmpfunc, reprfunc, hashfunc @@ -751,19 +751,6 @@ :attr:`sq_inplace_repeat`. - .. data:: Py_TPFLAGS_CHECKTYPES - - If this bit is set, the binary and ternary operations in the - :ctype:`PyNumberMethods` structure referenced by :attr:`tp_as_number` accept - arguments of arbitrary object types, and do their own type conversions if - needed. If this bit is clear, those operations require that all arguments have - the current type as their type, and the caller is supposed to perform a coercion - operation first. This applies to :attr:`nb_add`, :attr:`nb_subtract`, - :attr:`nb_multiply`, :attr:`nb_divide`, :attr:`nb_remainder`, :attr:`nb_divmod`, - :attr:`nb_power`, :attr:`nb_lshift`, :attr:`nb_rshift`, :attr:`nb_and`, - :attr:`nb_xor`, and :attr:`nb_or`. - - .. data:: Py_TPFLAGS_HAVE_RICHCOMPARE If this bit is set, the type object has the :attr:`tp_richcompare` field, as Modified: python/branches/py3k/Doc/glossary.rst ============================================================================== --- python/branches/py3k/Doc/glossary.rst (original) +++ python/branches/py3k/Doc/glossary.rst Fri Sep 21 22:19:23 2007 @@ -32,19 +32,6 @@ One of the two flavors of classes in earlier Python versions. Since Python 3.0, there are no classic classes anymore. - coercion - The implicit conversion of an instance of one type to another during an - operation which involves two arguments of the same type. For example, - ``int(3.15)`` converts the floating point number to the integer ``3``, but - in ``3+4.5``, each argument is of a different type (one int, one float), - and both must be converted to the same type before they can be added or it - will raise a ``TypeError``. Coercion between two operands can be - performed with the ``coerce`` builtin function; thus, ``3+4.5`` is - equivalent to calling ``operator.add(*coerce(3, 4.5))`` and results in - ``operator.add(3.0, 4.5)``. Without coercion, all arguments of even - compatible types would have to be normalized to the same value by the - programmer, e.g., ``float(3)+4.5`` rather than just ``3+4.5``. - complex number An extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part. Imaginary @@ -168,14 +155,14 @@ integer division Mathematical division discarding any remainder. For example, the expression ``11/4`` currently evaluates to ``2`` in contrast to the - ``2.75`` returned by float division. Also called *floor division*. - When dividing two integers the outcome will always be another integer - (having the floor function applied to it). However, if one of the operands - is another numeric type (such as a :class:`float`), the result will be - coerced (see :term:`coercion`) to a common type. For example, an integer - divided by a float will result in a float value, possibly with a decimal - fraction. Integer division can be forced by using the ``//`` operator - instead of the ``/`` operator. See also :term:`__future__`. + ``2.75`` returned by float division. Also called *floor division*. When + dividing two integers the outcome will always be another integer (having + the floor function applied to it). However, if the operands types are + different, one of them will be converted to the other's type. For + example, an integer divided by a float will result in a float value, + possibly with a decimal fraction. Integer division can be forced by using + the ``//`` operator instead of the ``/`` operator. See also + :term:`__future__`. interactive Python has an interactive interpreter which means that you can try out Modified: python/branches/py3k/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k/Doc/library/decimal.rst (original) +++ python/branches/py3k/Doc/library/decimal.rst Fri Sep 21 22:19:23 2007 @@ -312,7 +312,7 @@ numeric types such as :class:`float` and :class:`int`. All of the usual math operations and special methods apply. Likewise, decimal objects can be copied, pickled, printed, used as dictionary keys, used as set elements, compared, -sorted, and coerced to another type (such as :class:`float` or :class:`long`). +sorted, and converted to another type (such as :class:`float` or :class:`int`). In addition to the standard numeric properties, decimal floating point objects also have a number of specialized methods: Modified: python/branches/py3k/Include/object.h ============================================================================== --- python/branches/py3k/Include/object.h (original) +++ python/branches/py3k/Include/object.h Fri Sep 21 22:19:23 2007 @@ -133,7 +133,6 @@ typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *); typedef int (*inquiry)(PyObject *); typedef Py_ssize_t (*lenfunc)(PyObject *); -typedef int (*coercion)(PyObject **, PyObject **); typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t); typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t); typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *); @@ -222,7 +221,7 @@ binaryfunc nb_and; binaryfunc nb_xor; binaryfunc nb_or; - coercion nb_coerce; + int nb_reserved; /* unused, used to be nb_coerce */ unaryfunc nb_int; unaryfunc nb_long; unaryfunc nb_float; Modified: python/branches/py3k/Modules/datetimemodule.c ============================================================================== --- python/branches/py3k/Modules/datetimemodule.c (original) +++ python/branches/py3k/Modules/datetimemodule.c Fri Sep 21 22:19:23 2007 @@ -2082,7 +2082,7 @@ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ - 0, /*nb_coerce*/ + 0, /*nb_reserved*/ 0, /*nb_int*/ 0, /*nb_long*/ 0, /*nb_float*/ Modified: python/branches/py3k/Objects/boolobject.c ============================================================================== --- python/branches/py3k/Objects/boolobject.c (original) +++ python/branches/py3k/Objects/boolobject.c Fri Sep 21 22:19:23 2007 @@ -108,7 +108,7 @@ bool_and, /* nb_and */ bool_xor, /* nb_xor */ bool_or, /* nb_or */ - 0, /* nb_coerce */ + 0, /* nb_reserved */ 0, /* nb_int */ 0, /* nb_long */ 0, /* nb_float */ Modified: python/branches/py3k/Objects/complexobject.c ============================================================================== --- python/branches/py3k/Objects/complexobject.c (original) +++ python/branches/py3k/Objects/complexobject.c Fri Sep 21 22:19:23 2007 @@ -963,7 +963,7 @@ 0, /* nb_and */ 0, /* nb_xor */ 0, /* nb_or */ - (coercion)0, /* nb_coerce */ + 0, /* nb_reserved */ complex_int, /* nb_int */ complex_long, /* nb_long */ complex_float, /* nb_float */ Modified: python/branches/py3k/Objects/floatobject.c ============================================================================== --- python/branches/py3k/Objects/floatobject.c (original) +++ python/branches/py3k/Objects/floatobject.c Fri Sep 21 22:19:23 2007 @@ -235,8 +235,7 @@ } /* Macro and helper that convert PyObject obj to a C double and store - the value in dbl; this replaces the functionality of the coercion - slot function. If conversion to double raises an exception, obj is + the value in dbl. If conversion to double raises an exception, obj is set to NULL, and the function invoking this macro returns NULL. If obj is not of float, int or long type, Py_NotImplemented is incref'ed, stored in obj, and returned from the function invoking this macro. @@ -1069,7 +1068,7 @@ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ - (coercion)0, /*nb_coerce*/ + 0, /*nb_reserved*/ float_trunc, /*nb_int*/ float_trunc, /*nb_long*/ float_float, /*nb_float*/ Modified: python/branches/py3k/Objects/longobject.c ============================================================================== --- python/branches/py3k/Objects/longobject.c (original) +++ python/branches/py3k/Objects/longobject.c Fri Sep 21 22:19:23 2007 @@ -3631,7 +3631,7 @@ long_and, /*nb_and*/ long_xor, /*nb_xor*/ long_or, /*nb_or*/ - 0, /*nb_coerce*/ + 0, /*nb_reserved*/ long_long, /*nb_int*/ long_long, /*nb_long*/ long_float, /*nb_float*/ Modified: python/branches/py3k/Objects/setobject.c ============================================================================== --- python/branches/py3k/Objects/setobject.c (original) +++ python/branches/py3k/Objects/setobject.c Fri Sep 21 22:19:23 2007 @@ -1881,7 +1881,7 @@ (binaryfunc)set_and, /*nb_and*/ (binaryfunc)set_xor, /*nb_xor*/ (binaryfunc)set_or, /*nb_or*/ - 0, /*nb_coerce*/ + 0, /*nb_reserved*/ 0, /*nb_int*/ 0, /*nb_long*/ 0, /*nb_float*/ Modified: python/branches/py3k/Objects/weakrefobject.c ============================================================================== --- python/branches/py3k/Objects/weakrefobject.c (original) +++ python/branches/py3k/Objects/weakrefobject.c Fri Sep 21 22:19:23 2007 @@ -589,7 +589,7 @@ proxy_and, /*nb_and*/ proxy_xor, /*nb_xor*/ proxy_or, /*nb_or*/ - 0, /*nb_coerce*/ + 0, /*nb_reserved*/ proxy_int, /*nb_int*/ proxy_long, /*nb_long*/ proxy_float, /*nb_float*/ Modified: python/branches/py3k/PC/_winreg.c ============================================================================== --- python/branches/py3k/PC/_winreg.c (original) +++ python/branches/py3k/PC/_winreg.c Fri Sep 21 22:19:23 2007 @@ -430,7 +430,7 @@ PyHKEY_binaryFailureFunc, /* nb_and */ PyHKEY_binaryFailureFunc, /* nb_xor */ PyHKEY_binaryFailureFunc, /* nb_or */ - NULL, /* nb_coerce */ + 0, /* nb_reserved */ PyHKEY_intFunc, /* nb_int */ PyHKEY_unaryFailureFunc, /* nb_long */ PyHKEY_unaryFailureFunc, /* nb_float */ Modified: python/branches/py3k/Tools/modulator/Templates/object_tp_as_number ============================================================================== --- python/branches/py3k/Tools/modulator/Templates/object_tp_as_number (original) +++ python/branches/py3k/Tools/modulator/Templates/object_tp_as_number Fri Sep 21 22:19:23 2007 @@ -103,13 +103,6 @@ /* XXXX */ } -static int -$abbrev$_coerce(PyObject **pv, PyObject **pw) -{ - /* XXXX I haven't a clue... */ - return 1; -} - static PyObject * $abbrev$_int($abbrev$object *v) { From python-3000-checkins at python.org Fri Sep 21 22:50:26 2007 From: python-3000-checkins at python.org (neil.schemenauer) Date: Fri, 21 Sep 2007 22:50:26 +0200 (CEST) Subject: [Python-3000-checkins] r58227 - python/branches/py3k/Parser/tokenizer.c python/branches/py3k/Parser/tokenizer.h Message-ID: <20070921205026.8A46D1E4015@bag.python.org> Author: neil.schemenauer Date: Fri Sep 21 22:50:26 2007 New Revision: 58227 Modified: python/branches/py3k/Parser/tokenizer.c python/branches/py3k/Parser/tokenizer.h Log: Use an enum for decoding_state. It makes the code a little more understandable. Modified: python/branches/py3k/Parser/tokenizer.c ============================================================================== --- python/branches/py3k/Parser/tokenizer.c (original) +++ python/branches/py3k/Parser/tokenizer.c Fri Sep 21 22:50:26 2007 @@ -139,7 +139,7 @@ tok->alterror = 1; tok->alttabsize = 1; tok->altindstack[0] = 0; - tok->decoding_state = 0; + tok->decoding_state = STATE_INIT; tok->decoding_erred = 0; tok->read_coding_spec = 0; tok->encoding = NULL; @@ -280,7 +280,7 @@ if (cs != NULL) { tok->read_coding_spec = 1; if (tok->encoding == NULL) { - assert(tok->decoding_state == 1); /* raw */ + assert(tok->decoding_state == STATE_RAW); if (strcmp(cs, "utf-8") == 0 || strcmp(cs, "iso-8859-1") == 0) { tok->encoding = cs; @@ -288,7 +288,7 @@ r = set_readline(tok, cs); if (r) { tok->encoding = cs; - tok->decoding_state = -1; + tok->decoding_state = STATE_NORMAL; } else PyMem_FREE(cs); @@ -318,7 +318,7 @@ struct tok_state *tok) { int ch = get_char(tok); - tok->decoding_state = 1; + tok->decoding_state = STATE_RAW; if (ch == EOF) { return 1; } else if (ch == 0xEF) { @@ -330,11 +330,11 @@ } else if (ch == 0xFE) { ch = get_char(tok); if (ch != 0xFF) goto NON_BOM; if (!set_readline(tok, "utf-16-be")) return 0; - tok->decoding_state = -1; + tok->decoding_state = STATE_NORMAL; } else if (ch == 0xFF) { ch = get_char(tok); if (ch != 0xFE) goto NON_BOM; if (!set_readline(tok, "utf-16-le")) return 0; - tok->decoding_state = -1; + tok->decoding_state = STATE_NORMAL; #endif } else { unget_char(ch, tok); @@ -494,12 +494,12 @@ char *line = NULL; int badchar = 0; for (;;) { - if (tok->decoding_state < 0) { + if (tok->decoding_state == STATE_NORMAL) { /* We already have a codec associated with this input. */ line = fp_readl(s, size, tok); break; - } else if (tok->decoding_state > 0) { + } else if (tok->decoding_state == STATE_RAW) { /* We want a 'raw' read. */ line = Py_UniversalNewlineFgets(s, size, tok->fp, NULL); @@ -510,7 +510,7 @@ reader functions from now on. */ if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok)) return error_ret(tok); - assert(tok->decoding_state != 0); + assert(tok->decoding_state != STATE_INIT); } } if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) { @@ -550,7 +550,7 @@ static int decoding_feof(struct tok_state *tok) { - if (tok->decoding_state >= 0) { + if (tok->decoding_state != STATE_NORMAL) { return feof(tok->fp); } else { PyObject* buf = tok->decoding_buffer; @@ -700,7 +700,7 @@ return NULL; } strcpy(tok->encoding, enc); - tok->decoding_state = -1; + tok->decoding_state = STATE_NORMAL; } return tok; } Modified: python/branches/py3k/Parser/tokenizer.h ============================================================================== --- python/branches/py3k/Parser/tokenizer.h (original) +++ python/branches/py3k/Parser/tokenizer.h Fri Sep 21 22:50:26 2007 @@ -12,6 +12,12 @@ #define MAXINDENT 100 /* Max indentation level */ +enum decoding_state { + STATE_INIT, + STATE_RAW, + STATE_NORMAL, /* have a codec associated with input */ +}; + /* Tokenizer state */ struct tok_state { /* Input state; buf <= cur <= inp <= end */ @@ -40,7 +46,7 @@ int alttabsize; /* Alternate tab spacing */ int altindstack[MAXINDENT]; /* Stack of alternate indents */ /* Stuff for PEP 0263 */ - int decoding_state; /* -1:decoding, 0:init, 1:raw */ + enum decoding_state decoding_state; int decoding_erred; /* whether erred in decoding */ int read_coding_spec; /* whether 'coding:...' has been read */ char *encoding; From python-3000-checkins at python.org Sat Sep 22 05:51:57 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Sat, 22 Sep 2007 05:51:57 +0200 (CEST) Subject: [Python-3000-checkins] r58228 - python/branches/py3k-importlib/Modules/getpath.c Message-ID: <20070922035158.013ED1E400D@bag.python.org> Author: brett.cannon Date: Sat Sep 22 05:51:57 2007 New Revision: 58228 Modified: python/branches/py3k-importlib/Modules/getpath.c Log: For now just look for _importlib as a source file; don't worry about bytecode. Modified: python/branches/py3k-importlib/Modules/getpath.c ============================================================================== --- python/branches/py3k-importlib/Modules/getpath.c (original) +++ python/branches/py3k-importlib/Modules/getpath.c Sat Sep 22 05:51:57 2007 @@ -270,7 +270,7 @@ *delim = '\0'; joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); - if (ismodule(prefix)) + if (isfile(prefix)) strcpy(importlib_path, prefix); else importlib_path[0] = '\0'; @@ -287,7 +287,7 @@ joinpath(prefix, vpath); joinpath(prefix, "Lib"); joinpath(prefix, LANDMARK); - if (ismodule(prefix)) { + if (isfile(prefix)) { strcpy(importlib_path, prefix); return -1; } @@ -299,7 +299,7 @@ n = strlen(prefix); joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); - if (ismodule(prefix)) { + if (isfile(prefix)) { strcpy(importlib_path, prefix); return 1; } @@ -311,7 +311,7 @@ strncpy(prefix, PREFIX, MAXPATHLEN); joinpath(prefix, lib_python); joinpath(prefix, LANDMARK); - if (ismodule(prefix)) { + if (isfile(prefix)) { strcpy(importlib_path, prefix); return 1; } From python-3000-checkins at python.org Sat Sep 22 06:41:13 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Sat, 22 Sep 2007 06:41:13 +0200 (CEST) Subject: [Python-3000-checkins] r58230 - in python/branches/py3k-importlib: Include/pythonrun.h NEWS Python/import.c Python/pythonrun.c Message-ID: <20070922044113.7F8F11E400D@bag.python.org> Author: brett.cannon Date: Sat Sep 22 06:41:13 2007 New Revision: 58230 Modified: python/branches/py3k-importlib/Include/pythonrun.h python/branches/py3k-importlib/NEWS python/branches/py3k-importlib/Python/import.c python/branches/py3k-importlib/Python/pythonrun.c Log: Introduce _PyImport_Importlib() to handle importing _importlib.py during startup. Modified: python/branches/py3k-importlib/Include/pythonrun.h ============================================================================== --- python/branches/py3k-importlib/Include/pythonrun.h (original) +++ python/branches/py3k-importlib/Include/pythonrun.h Sat Sep 22 06:41:13 2007 @@ -123,6 +123,7 @@ PyAPI_FUNC(PyObject *) _PyBuiltin_Init(void); PyAPI_FUNC(PyObject *) _PySys_Init(void); PyAPI_FUNC(void) _PyImport_Init(void); +PyAPI_FUNC(void) _PyImport_Importlib(void); PyAPI_FUNC(void) _PyExc_Init(void); PyAPI_FUNC(void) _PyImportHooks_Init(void); PyAPI_FUNC(int) _PyFrame_Init(void); Modified: python/branches/py3k-importlib/NEWS ============================================================================== --- python/branches/py3k-importlib/NEWS (original) +++ python/branches/py3k-importlib/NEWS Sat Sep 22 06:41:13 2007 @@ -1,3 +1,5 @@ +* Add _PyImport_Importlib() to import _importlib. + * Add Py_GetImportlibPath() as a way to get the path to _importlib. * Have Modules/getpath.c use _importlib.py instead of os.py when searching for Modified: python/branches/py3k-importlib/Python/import.c ============================================================================== --- python/branches/py3k-importlib/Python/import.c (original) +++ python/branches/py3k-importlib/Python/import.c Sat Sep 22 06:41:13 2007 @@ -104,7 +104,9 @@ {0, 0} }; -static PyTypeObject NullImporterType; /* Forward reference */ +/* Forward declarations */ +static PyTypeObject NullImporterType; +static PyCodeObject * parse_source_module(const char *, FILE *); /* Initialize things */ @@ -152,6 +154,7 @@ code created in normal operation mode. */ pyc_magic = MAGIC + 1; } + } void @@ -519,6 +522,34 @@ } +void +_PyImport_Importlib(void) +{ + const char *importlib_path = Py_GetImportlibPath(); + FILE *fp = NULL; + PyCodeObject *code_object = NULL; + PyObject *module = NULL; + + + if (importlib_path[0] == '\0') + Py_FatalError("_importlib.py not found"); + + fp = fopen(importlib_path, "r"); + code_object = parse_source_module(importlib_path, fp); + fclose(fp); + + if (!code_object) + Py_FatalError("unable to parse _importlib"); + + module = PyImport_ExecCodeModuleEx("_importlib", (PyObject *)code_object, + (char *)importlib_path); + if (!module) + Py_FatalError("could not initialize _importlib"); + + Py_DECREF(module); +} + + /* Magic for extension modules (built-in as well as dynamically loaded). To prevent initializing an extension module more than once, we keep a static dictionary 'extensions' keyed by module name Modified: python/branches/py3k-importlib/Python/pythonrun.c ============================================================================== --- python/branches/py3k-importlib/Python/pythonrun.c (original) +++ python/branches/py3k-importlib/Python/pythonrun.c Sat Sep 22 06:41:13 2007 @@ -237,6 +237,8 @@ _PyImportHooks_Init(); + _PyImport_Importlib(); + if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ From python-3000-checkins at python.org Sat Sep 22 23:32:46 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Sat, 22 Sep 2007 23:32:46 +0200 (CEST) Subject: [Python-3000-checkins] r58233 - in python/branches/py3k-importlib: Include/pythonrun.h Modules/posixmodule.c NEWS Python/import.c Message-ID: <20070922213246.114961E400F@bag.python.org> Author: brett.cannon Date: Sat Sep 22 23:32:45 2007 New Revision: 58233 Modified: python/branches/py3k-importlib/Include/pythonrun.h python/branches/py3k-importlib/Modules/posixmodule.c python/branches/py3k-importlib/NEWS python/branches/py3k-importlib/Python/import.c Log: Inject needed modules (sans warnings as it is not a built-in module yet) into _importlib. Still missing required attributes and exposure of certain C functions (see importlib for what is needed). Modified: python/branches/py3k-importlib/Include/pythonrun.h ============================================================================== --- python/branches/py3k-importlib/Include/pythonrun.h (original) +++ python/branches/py3k-importlib/Include/pythonrun.h Sat Sep 22 23:32:45 2007 @@ -152,6 +152,21 @@ PyAPI_DATA(char) *(*PyOS_ReadlineFunctionPointer)(FILE *, FILE *, char *); PyAPI_DATA(PyThreadState*) _PyOS_ReadlineTState; +/* Name and init function for the platform-dependent os module */ +#if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__)) && !defined(__QNX__) +#define PyOS_INITFUNC initnt +#define PyOS_MODNAME "nt" + +#elif defined(PYOS_OS2) +#define PyOS_INITFUNC initos2 +#define PyOS_MODNAME "os2" + +#else +#define PyOS_INITFUNC initposix +#define PyOS_MODNAME "posix" +#endif + + /* Stack size, in "pointers" (so we get extra safety margins on 64-bit platforms). On a 32-bit platform, this translates to a 8k margin. */ Modified: python/branches/py3k-importlib/Modules/posixmodule.c ============================================================================== --- python/branches/py3k-importlib/Modules/posixmodule.c (original) +++ python/branches/py3k-importlib/Modules/posixmodule.c Sat Sep 22 23:32:45 2007 @@ -7239,25 +7239,12 @@ } -#if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__BORLANDC__)) && !defined(__QNX__) -#define INITFUNC initnt -#define MODNAME "nt" - -#elif defined(PYOS_OS2) -#define INITFUNC initos2 -#define MODNAME "os2" - -#else -#define INITFUNC initposix -#define MODNAME "posix" -#endif - PyMODINIT_FUNC -INITFUNC(void) +PyOS_INITFUNC(void) { PyObject *m, *v; - m = Py_InitModule3(MODNAME, + m = Py_InitModule3(PyOS_MODNAME, posix_methods, posix__doc__); if (m == NULL) @@ -7285,7 +7272,7 @@ #endif if (!initialized) { - stat_result_desc.name = MODNAME ".stat_result"; + stat_result_desc.name = PyOS_MODNAME ".stat_result"; stat_result_desc.fields[7].name = PyStructSequence_UnnamedField; stat_result_desc.fields[8].name = PyStructSequence_UnnamedField; stat_result_desc.fields[9].name = PyStructSequence_UnnamedField; @@ -7293,7 +7280,7 @@ structseq_new = StatResultType.tp_new; StatResultType.tp_new = statresult_new; - statvfs_result_desc.name = MODNAME ".statvfs_result"; + statvfs_result_desc.name = PyOS_MODNAME ".statvfs_result"; PyStructSequence_InitType(&StatVFSResultType, &statvfs_result_desc); } Py_INCREF((PyObject*) &StatResultType); Modified: python/branches/py3k-importlib/NEWS ============================================================================== --- python/branches/py3k-importlib/NEWS (original) +++ python/branches/py3k-importlib/NEWS Sat Sep 22 23:32:45 2007 @@ -1,4 +1,6 @@ -* Add _PyImport_Importlib() to import _importlib. +* Add _PyImport_Importlib() to import _importlib. This also involves importing + sys, imp, marshal and _os (which can be either nt, os2, or posix; reason why + PyOS_MODNAME and PyOS_INITFUNC have been added). * Add Py_GetImportlibPath() as a way to get the path to _importlib. Modified: python/branches/py3k-importlib/Python/import.c ============================================================================== --- python/branches/py3k-importlib/Python/import.c (original) +++ python/branches/py3k-importlib/Python/import.c Sat Sep 22 23:32:45 2007 @@ -107,6 +107,8 @@ /* Forward declarations */ static PyTypeObject NullImporterType; static PyCodeObject * parse_source_module(const char *, FILE *); +static int init_builtin(char *); + /* Initialize things */ @@ -528,12 +530,23 @@ const char *importlib_path = Py_GetImportlibPath(); FILE *fp = NULL; PyCodeObject *code_object = NULL; - PyObject *module = NULL; + PyObject *importlib = NULL; + PyObject *modules= NULL; + PyObject *builtin_module = NULL; if (importlib_path[0] == '\0') Py_FatalError("_importlib.py not found"); + if (!init_builtin("sys")) + Py_FatalError("initializiation of sys failed"); + if (!init_builtin("imp")) + Py_FatalError("initialization of imp failed"); + if (!init_builtin("marshal")) + Py_FatalError("initialization of marshal failed"); + if (!init_builtin(PyOS_MODNAME)) + Py_FatalError("initializatino of _os failed"); + fp = fopen(importlib_path, "r"); code_object = parse_source_module(importlib_path, fp); fclose(fp); @@ -541,12 +554,43 @@ if (!code_object) Py_FatalError("unable to parse _importlib"); - module = PyImport_ExecCodeModuleEx("_importlib", (PyObject *)code_object, + importlib = PyImport_ExecCodeModuleEx("_importlib", (PyObject *)code_object, (char *)importlib_path); - if (!module) + if (!importlib) Py_FatalError("could not initialize _importlib"); - Py_DECREF(module); + modules = PyImport_GetModuleDict(); + + builtin_module = PyDict_GetItemString(modules, "sys"); + if (!builtin_module) + Py_FatalError("sys module lost"); + Py_INCREF(builtin_module); + if (PyModule_AddObject(importlib, "sys", builtin_module) < 0) + Py_FatalError("could not add sys to _importlib"); + + builtin_module = PyDict_GetItemString(modules, "imp"); + if (!builtin_module) + Py_FatalError("imp module lost"); + Py_INCREF(builtin_module); + if (PyModule_AddObject(importlib, "imp", builtin_module) < 0) + Py_FatalError("could not add imp to _importlib"); + + builtin_module = PyDict_GetItemString(modules, "marshal"); + if (!builtin_module) + Py_FatalError("mashal module lost"); + Py_INCREF(builtin_module); + if (PyModule_AddObject(importlib, "marshal", builtin_module) < 0) + Py_FatalError("could not add marshal to _importlib"); + + builtin_module = PyDict_GetItemString(modules, PyOS_MODNAME); + if (!builtin_module) + Py_FatalError("_os module lost"); + Py_INCREF(builtin_module); + if (PyModule_AddObject(importlib, "_os", builtin_module) < 0) + Py_FatalError("could not add _os to _importlib"); + + + Py_DECREF(importlib); } @@ -1653,7 +1697,6 @@ #endif /* HAVE_STAT */ -static int init_builtin(char *); /* Forward */ /* Load an external module using the default search path and return its module object WITH INCREMENTED REFERENCE COUNT */ From python-3000-checkins at python.org Sun Sep 23 04:00:14 2007 From: python-3000-checkins at python.org (travis.oliphant) Date: Sun, 23 Sep 2007 04:00:14 +0200 (CEST) Subject: [Python-3000-checkins] r58236 - in python/branches/py3k: Include/abstract.h Include/memoryobject.h Include/object.h Modules/_ctypes/_ctypes.c Modules/_hashopenssl.c Modules/_sre.c Modules/arraymodule.c Modules/mmapmodule.c Objects/abstract.c Objects/bufferobject.c Objects/bytesobject.c Objects/memoryobject.c Objects/stringobject.c Objects/unicodeobject.c Python/getargs.c Python/marshal.c Message-ID: <20070923020014.70F021E4013@bag.python.org> Author: travis.oliphant Date: Sun Sep 23 04:00:13 2007 New Revision: 58236 Modified: python/branches/py3k/Include/abstract.h python/branches/py3k/Include/memoryobject.h python/branches/py3k/Include/object.h python/branches/py3k/Modules/_ctypes/_ctypes.c python/branches/py3k/Modules/_hashopenssl.c python/branches/py3k/Modules/_sre.c python/branches/py3k/Modules/arraymodule.c python/branches/py3k/Modules/mmapmodule.c python/branches/py3k/Objects/abstract.c python/branches/py3k/Objects/bufferobject.c python/branches/py3k/Objects/bytesobject.c python/branches/py3k/Objects/memoryobject.c python/branches/py3k/Objects/stringobject.c python/branches/py3k/Objects/unicodeobject.c python/branches/py3k/Python/getargs.c python/branches/py3k/Python/marshal.c Log: Change PyBuffer to Py_buffer to be consistent with other non-object structures like Py_complex. Add some more functionality to the memoryview object. Modified: python/branches/py3k/Include/abstract.h ============================================================================== --- python/branches/py3k/Include/abstract.h (original) +++ python/branches/py3k/Include/abstract.h Sun Sep 23 04:00:13 2007 @@ -542,7 +542,7 @@ /* Return 1 if the getbuffer function is available, otherwise return 0 */ - PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, PyBuffer *view, + PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags); /* This is a C-API version of the getbuffer function call. It checks @@ -552,7 +552,7 @@ */ - PyAPI_FUNC(void) PyObject_ReleaseBuffer(PyObject *obj, PyBuffer *view); + PyAPI_FUNC(void) PyObject_ReleaseBuffer(PyObject *obj, Py_buffer *view); /* C-API version of the releasebuffer function call. It @@ -570,7 +570,7 @@ buffer */ - PyAPI_FUNC(void *) PyBuffer_GetPointer(PyBuffer *view, Py_ssize_t *indices); + PyAPI_FUNC(void *) PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices); /* Get the memory area pointed to by the indices for the buffer given. Note that view->ndim is the assumed size of indices @@ -583,10 +583,10 @@ - PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, PyBuffer *view, + PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort); - PyAPI_FUNC(int) PyBuffer_FromContiguous(PyBuffer *view, void *buf, + PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort); @@ -611,7 +611,7 @@ /* Copy the data from the src buffer to the buffer of destination */ - PyAPI_FUNC(int) PyBuffer_IsContiguous(PyBuffer *view, char fortran); + PyAPI_FUNC(int) PyBuffer_IsContiguous(Py_buffer *view, char fortran); PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims, @@ -626,7 +626,7 @@ per element. */ - PyAPI_FUNC(int) PyBuffer_FillInfo(PyBuffer *view, void *buf, + PyAPI_FUNC(int) PyBuffer_FillInfo(Py_buffer *view, void *buf, Py_ssize_t len, int readonly, int flags); Modified: python/branches/py3k/Include/memoryobject.h ============================================================================== --- python/branches/py3k/Include/memoryobject.h (original) +++ python/branches/py3k/Include/memoryobject.h Sun Sep 23 04:00:13 2007 @@ -10,7 +10,7 @@ typedef struct { PyObject_HEAD PyObject *base; - PyBuffer view; + Py_buffer view; } PyMemoryViewObject; @@ -57,7 +57,7 @@ PyAPI_FUNC(PyObject *) PyMemoryView_FromObject(PyObject *base); -PyAPI_FUNC(PyObject *) PyMemoryView_FromMemory(PyBuffer *info); +PyAPI_FUNC(PyObject *) PyMemoryView_FromMemory(Py_buffer *info); /* create new if bufptr is NULL will be a new bytesobject in base */ Modified: python/branches/py3k/Include/object.h ============================================================================== --- python/branches/py3k/Include/object.h (original) +++ python/branches/py3k/Include/object.h Sun Sep 23 04:00:13 2007 @@ -153,10 +153,10 @@ Py_ssize_t *strides; Py_ssize_t *suboffsets; void *internal; -} PyBuffer; +} Py_buffer; -typedef int (*getbufferproc)(PyObject *, PyBuffer *, int); -typedef void (*releasebufferproc)(PyObject *, PyBuffer *); +typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); +typedef void (*releasebufferproc)(PyObject *, Py_buffer *); /* Flags for getting buffers */ #define PyBUF_SIMPLE 0 Modified: python/branches/py3k/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/_ctypes.c (original) +++ python/branches/py3k/Modules/_ctypes/_ctypes.c Sun Sep 23 04:00:13 2007 @@ -740,7 +740,7 @@ char *ptr; Py_ssize_t size; int rel = 0; - PyBuffer view; + Py_buffer view; if (PyBuffer_Check(value)) { if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) @@ -2083,7 +2083,7 @@ { NULL }, }; -static int CData_GetBuffer(PyObject *_self, PyBuffer *view, int flags) +static int CData_GetBuffer(PyObject *_self, Py_buffer *view, int flags) { CDataObject *self = (CDataObject *)_self; return PyBuffer_FillInfo(view, self->b_ptr, self->b_size, 0, flags); Modified: python/branches/py3k/Modules/_hashopenssl.c ============================================================================== --- python/branches/py3k/Modules/_hashopenssl.c (original) +++ python/branches/py3k/Modules/_hashopenssl.c Sun Sep 23 04:00:13 2007 @@ -176,7 +176,7 @@ EVP_update(EVPobject *self, PyObject *args) { PyObject *obj; - PyBuffer view; + Py_buffer view; if (!PyArg_ParseTuple(args, "O:update", &obj)) return NULL; @@ -252,7 +252,7 @@ static char *kwlist[] = {"name", "string", NULL}; PyObject *name_obj = NULL; PyObject *data_obj = NULL; - PyBuffer view; + Py_buffer view; char *nameStr; const EVP_MD *digest; @@ -397,7 +397,7 @@ static char *kwlist[] = {"name", "string", NULL}; PyObject *name_obj = NULL; PyObject *data_obj = NULL; - PyBuffer view = { 0 }; + Py_buffer view = { 0 }; PyObject *ret_obj; char *name; const EVP_MD *digest; @@ -437,7 +437,7 @@ EVP_new_ ## NAME (PyObject *self, PyObject *args) \ { \ PyObject *data_obj = NULL; \ - PyBuffer view = { 0 }; \ + Py_buffer view = { 0 }; \ PyObject *ret_obj; \ \ if (!PyArg_ParseTuple(args, "|O:" #NAME , &data_obj)) { \ Modified: python/branches/py3k/Modules/_sre.c ============================================================================== --- python/branches/py3k/Modules/_sre.c (original) +++ python/branches/py3k/Modules/_sre.c Sun Sep 23 04:00:13 2007 @@ -1672,7 +1672,7 @@ Py_ssize_t size, bytes; int charsize; void* ptr; - PyBuffer view; + Py_buffer view; /* get pointer to string buffer */ view.len = -1; Modified: python/branches/py3k/Modules/arraymodule.c ============================================================================== --- python/branches/py3k/Modules/arraymodule.c (original) +++ python/branches/py3k/Modules/arraymodule.c Sun Sep 23 04:00:13 2007 @@ -1784,7 +1784,7 @@ static int -array_buffer_getbuf(arrayobject *self, PyBuffer *view, int flags) +array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags) { if ((flags & PyBUF_CHARACTER)) { PyErr_SetString(PyExc_TypeError, @@ -1825,7 +1825,7 @@ } static void -array_buffer_relbuf(arrayobject *self, PyBuffer *view) +array_buffer_relbuf(arrayobject *self, Py_buffer *view) { self->ob_exports--; } Modified: python/branches/py3k/Modules/mmapmodule.c ============================================================================== --- python/branches/py3k/Modules/mmapmodule.c (original) +++ python/branches/py3k/Modules/mmapmodule.c Sun Sep 23 04:00:13 2007 @@ -601,7 +601,7 @@ /* Functions for treating an mmap'ed file as a buffer */ static int -mmap_buffer_getbuf(mmap_object *self, PyBuffer *view, int flags) +mmap_buffer_getbuf(mmap_object *self, Py_buffer *view, int flags) { CHECK_VALID(-1); if (PyBuffer_FillInfo(view, self->data, self->size, @@ -612,7 +612,7 @@ } static void -mmap_buffer_releasebuf(mmap_object *self, PyBuffer *view) +mmap_buffer_releasebuf(mmap_object *self, Py_buffer *view) { self->exports--; } Modified: python/branches/py3k/Objects/abstract.c ============================================================================== --- python/branches/py3k/Objects/abstract.c (original) +++ python/branches/py3k/Objects/abstract.c Sun Sep 23 04:00:13 2007 @@ -224,7 +224,7 @@ Py_ssize_t *buffer_len) { PyBufferProcs *pb; - PyBuffer view; + Py_buffer view; if (obj == NULL || buffer == NULL || buffer_len == NULL) { null_error(); @@ -267,7 +267,7 @@ Py_ssize_t *buffer_len) { PyBufferProcs *pb; - PyBuffer view; + Py_buffer view; if (obj == NULL || buffer == NULL || buffer_len == NULL) { null_error(); @@ -295,7 +295,7 @@ Py_ssize_t *buffer_len) { PyBufferProcs *pb; - PyBuffer view; + Py_buffer view; if (obj == NULL || buffer == NULL || buffer_len == NULL) { null_error(); @@ -320,7 +320,7 @@ /* Buffer C-API for Python 3.0 */ int -PyObject_GetBuffer(PyObject *obj, PyBuffer *view, int flags) +PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { if (!PyObject_CheckBuffer(obj)) { PyErr_SetString(PyExc_TypeError, @@ -331,7 +331,7 @@ } void -PyObject_ReleaseBuffer(PyObject *obj, PyBuffer *view) +PyObject_ReleaseBuffer(PyObject *obj, Py_buffer *view) { if (obj->ob_type->tp_as_buffer != NULL && obj->ob_type->tp_as_buffer->bf_releasebuffer != NULL) { @@ -341,7 +341,7 @@ static int -_IsFortranContiguous(PyBuffer *view) +_IsFortranContiguous(Py_buffer *view) { Py_ssize_t sd, dim; int i; @@ -362,7 +362,7 @@ } static int -_IsCContiguous(PyBuffer *view) +_IsCContiguous(Py_buffer *view) { Py_ssize_t sd, dim; int i; @@ -383,7 +383,7 @@ } int -PyBuffer_IsContiguous(PyBuffer *view, char fort) +PyBuffer_IsContiguous(Py_buffer *view, char fort) { if (view->suboffsets != NULL) return 0; @@ -399,7 +399,7 @@ void* -PyBuffer_GetPointer(PyBuffer *view, Py_ssize_t *indices) +PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices) { char* pointer; int i; @@ -452,7 +452,7 @@ */ int -PyBuffer_ToContiguous(void *buf, PyBuffer *view, Py_ssize_t len, char fort) +PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort) { int k; void (*addone)(int, Py_ssize_t *, Py_ssize_t *); @@ -503,7 +503,7 @@ } int -PyBuffer_FromContiguous(PyBuffer *view, void *buf, Py_ssize_t len, char fort) +PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort) { int k; void (*addone)(int, Py_ssize_t *, Py_ssize_t *); @@ -556,7 +556,7 @@ int PyObject_CopyData(PyObject *dest, PyObject *src) { - PyBuffer view_dest, view_src; + Py_buffer view_dest, view_src; int k; Py_ssize_t *indices, elements; char *dptr, *sptr; @@ -649,7 +649,7 @@ } int -PyBuffer_FillInfo(PyBuffer *view, void *buf, Py_ssize_t len, +PyBuffer_FillInfo(Py_buffer *view, void *buf, Py_ssize_t len, int readonly, int flags) { if (view == NULL) return 0; Modified: python/branches/py3k/Objects/bufferobject.c ============================================================================== --- python/branches/py3k/Objects/bufferobject.c (original) +++ python/branches/py3k/Objects/bufferobject.c Sun Sep 23 04:00:13 2007 @@ -16,11 +16,12 @@ static int -get_buf(PyBufferObject *self, PyBuffer *view, int flags) +get_buf(PyBufferObject *self, Py_buffer *view, int flags) { if (self->b_base == NULL) { view->buf = self->b_ptr; view->len = self->b_size; + view->readonly = 0; } else { Py_ssize_t count, offset; @@ -46,7 +47,7 @@ static int -buffer_getbuf(PyBufferObject *self, PyBuffer *view, int flags) +buffer_getbuf(PyBufferObject *self, Py_buffer *view, int flags) { if (view == NULL) return 0; if (!get_buf(self, view, flags)) @@ -57,7 +58,7 @@ static void -buffer_releasebuf(PyBufferObject *self, PyBuffer *view) +buffer_releasebuf(PyBufferObject *self, Py_buffer *view) { /* No-op if there is no self->b_base */ if (self->b_base != NULL) { @@ -229,7 +230,7 @@ } static int -get_bufx(PyObject *obj, PyBuffer *view, int flags) +get_bufx(PyObject *obj, Py_buffer *view, int flags) { PyBufferProcs *bp; @@ -256,7 +257,7 @@ void *p1, *p2; Py_ssize_t len1, len2, min_len; int cmp, ok; - PyBuffer v1, v2; + Py_buffer v1, v2; ok = 1; if (!get_bufx(self, &v1, PyBUF_SIMPLE)) @@ -318,7 +319,7 @@ static long buffer_hash(PyBufferObject *self) { - PyBuffer view; + Py_buffer view; register Py_ssize_t len; register unsigned char *p; register long x; @@ -351,7 +352,7 @@ static PyObject * buffer_str(PyBufferObject *self) { - PyBuffer view; + Py_buffer view; PyObject *res; if (!get_buf(self, &view, PyBUF_SIMPLE)) @@ -366,7 +367,7 @@ static Py_ssize_t buffer_length(PyBufferObject *self) { - PyBuffer view; + Py_buffer view; if (!get_buf(self, &view, PyBUF_SIMPLE)) return -1; @@ -380,7 +381,7 @@ PyBufferProcs *pb = other->ob_type->tp_as_buffer; char *p; PyObject *ob; - PyBuffer view, view2; + Py_buffer view, view2; if (pb == NULL || pb->bf_getbuffer == NULL) @@ -426,7 +427,7 @@ { PyObject *ob; register char *p; - PyBuffer view; + Py_buffer view; if (count < 0) count = 0; @@ -450,7 +451,7 @@ static PyObject * buffer_item(PyBufferObject *self, Py_ssize_t idx) { - PyBuffer view; + Py_buffer view; PyObject *ob; if (!get_buf(self, &view, PyBUF_SIMPLE)) @@ -467,7 +468,7 @@ static PyObject * buffer_subscript(PyBufferObject *self, PyObject *item) { - PyBuffer view; + Py_buffer view; PyObject *ob; if (!get_buf(self, &view, PyBUF_SIMPLE)) @@ -537,7 +538,7 @@ buffer_ass_item(PyBufferObject *self, Py_ssize_t idx, PyObject *other) { PyBufferProcs *pb; - PyBuffer view, view2; + Py_buffer view, view2; if (!get_buf(self, &view, PyBUF_SIMPLE)) return -1; @@ -585,7 +586,7 @@ static int buffer_ass_subscript(PyBufferObject *self, PyObject *item, PyObject *value) { - PyBuffer v1; + Py_buffer v1; if (!get_buf(self, &v1, PyBUF_SIMPLE)) return -1; @@ -606,7 +607,7 @@ } else if (PySlice_Check(item)) { Py_ssize_t start, stop, step, slicelength; - PyBuffer v2; + Py_buffer v2; PyBufferProcs *pb; if (PySlice_GetIndicesEx((PySliceObject *)item, v1.len, Modified: python/branches/py3k/Objects/bytesobject.c ============================================================================== --- python/branches/py3k/Objects/bytesobject.c (original) +++ python/branches/py3k/Objects/bytesobject.c Sun Sep 23 04:00:13 2007 @@ -50,7 +50,7 @@ } static int -bytes_getbuffer(PyBytesObject *obj, PyBuffer *view, int flags) +bytes_getbuffer(PyBytesObject *obj, Py_buffer *view, int flags) { int ret; void *ptr; @@ -70,13 +70,13 @@ } static void -bytes_releasebuffer(PyBytesObject *obj, PyBuffer *view) +bytes_releasebuffer(PyBytesObject *obj, Py_buffer *view) { obj->ob_exports--; } static Py_ssize_t -_getbuffer(PyObject *obj, PyBuffer *view) +_getbuffer(PyObject *obj, Py_buffer *view) { PyBufferProcs *buffer = Py_Type(obj)->tp_as_buffer; @@ -213,7 +213,7 @@ PyBytes_Concat(PyObject *a, PyObject *b) { Py_ssize_t size; - PyBuffer va, vb; + Py_buffer va, vb; PyBytesObject *result; va.len = -1; @@ -266,7 +266,7 @@ { Py_ssize_t mysize; Py_ssize_t size; - PyBuffer vo; + Py_buffer vo; if (_getbuffer(other, &vo) < 0) { PyErr_Format(PyExc_TypeError, "can't concat bytes to %.100s", @@ -462,7 +462,7 @@ { Py_ssize_t avail, needed; void *bytes; - PyBuffer vbytes; + Py_buffer vbytes; int res = 0; vbytes.len = -1; @@ -814,7 +814,7 @@ /* Use the modern buffer interface */ if (PyObject_CheckBuffer(arg)) { Py_ssize_t size; - PyBuffer view; + Py_buffer view; if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0) return -1; size = view.len; @@ -954,7 +954,7 @@ bytes_richcompare(PyObject *self, PyObject *other, int op) { Py_ssize_t self_size, other_size; - PyBuffer self_bytes, other_bytes; + Py_buffer self_bytes, other_bytes; PyObject *res; Py_ssize_t minsize; int cmp; @@ -1067,7 +1067,7 @@ bytes_find_internal(PyBytesObject *self, PyObject *args, int dir) { PyObject *subobj; - PyBuffer subbuf; + Py_buffer subbuf; Py_ssize_t start=0, end=PY_SSIZE_T_MAX; Py_ssize_t res; @@ -2033,7 +2033,7 @@ { Py_ssize_t count = -1; PyObject *from, *to, *res; - PyBuffer vfrom, vto; + Py_buffer vfrom, vto; if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count)) return NULL; @@ -2187,7 +2187,7 @@ Py_ssize_t maxsplit = -1, count = 0; const char *s = PyBytes_AS_STRING(self), *sub; PyObject *list, *str, *subobj = Py_None; - PyBuffer vsub; + Py_buffer vsub; #ifdef USE_FAST Py_ssize_t pos; #endif @@ -2396,7 +2396,7 @@ Py_ssize_t maxsplit = -1, count = 0; const char *s = PyBytes_AS_STRING(self), *sub; PyObject *list, *str, *subobj = Py_None; - PyBuffer vsub; + Py_buffer vsub; if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit)) return NULL; @@ -2647,7 +2647,7 @@ Py_ssize_t left, right, mysize, argsize; void *myptr, *argptr; PyObject *arg = Py_None; - PyBuffer varg; + Py_buffer varg; if (!PyArg_ParseTuple(args, "|O:strip", &arg)) return NULL; if (arg == Py_None) { @@ -2683,7 +2683,7 @@ Py_ssize_t left, right, mysize, argsize; void *myptr, *argptr; PyObject *arg = Py_None; - PyBuffer varg; + Py_buffer varg; if (!PyArg_ParseTuple(args, "|O:lstrip", &arg)) return NULL; if (arg == Py_None) { @@ -2716,7 +2716,7 @@ Py_ssize_t left, right, mysize, argsize; void *myptr, *argptr; PyObject *arg = Py_None; - PyBuffer varg; + Py_buffer varg; if (!PyArg_ParseTuple(args, "|O:rstrip", &arg)) return NULL; if (arg == Py_None) { Modified: python/branches/py3k/Objects/memoryobject.c ============================================================================== --- python/branches/py3k/Objects/memoryobject.c (original) +++ python/branches/py3k/Objects/memoryobject.c Sun Sep 23 04:00:13 2007 @@ -4,16 +4,16 @@ #include "Python.h" static int -memory_getbuf(PyMemoryViewObject *self, PyBuffer *view, int flags) +memory_getbuf(PyMemoryViewObject *self, Py_buffer *view, int flags) { if (view != NULL) - memcpy(view, &(self->view), sizeof(PyBuffer)); + *view = self->view; return self->base->ob_type->tp_as_buffer->bf_getbuffer(self->base, NULL, PyBUF_FULL); } static void -memory_releasebuf(PyMemoryViewObject *self, PyBuffer *view) +memory_releasebuf(PyMemoryViewObject *self, Py_buffer *view) { PyObject_ReleaseBuffer(self->base, NULL); } @@ -24,11 +24,16 @@ Create a new memoryview object which references the given object."); PyObject * -PyMemoryView_FromMemory(PyBuffer *info) +PyMemoryView_FromMemory(Py_buffer *info) { - /* XXX(nnorwitz): need to implement something here? */ - PyErr_SetString(PyExc_NotImplementedError, "need to implement"); - return NULL; + PyMemoryViewObject *mview; + + mview = (PyMemoryViewObject *)PyObject_New(PyMemoryViewObject, + &PyMemoryView_Type); + if (mview == NULL) return NULL; + mview->base = NULL; + mview->view = *info; + return (PyObject *)mview; } PyObject * @@ -130,7 +135,7 @@ void _add_one_to_index_C(int nd, Py_ssize_t *index, Py_ssize_t *shape); static int -_indirect_copy_nd(char *dest, PyBuffer *view, char fort) +_indirect_copy_nd(char *dest, Py_buffer *view, char fort) { Py_ssize_t *indices; int k; @@ -196,7 +201,7 @@ { PyMemoryViewObject *mem; PyObject *bytes; - PyBuffer *view; + Py_buffer *view; int flags; char *dest; @@ -264,8 +269,11 @@ /* return a shadowed memory-view object */ view->buf = dest; mem->base = PyTuple_Pack(2, obj, bytes); - /* XXX(nnorwitz): need to verify alloc was successful. */ Py_DECREF(bytes); + if (mem->base == NULL) { + PyObject_ReleaseBuffer(obj, view); + return NULL; + } } else { PyObject_ReleaseBuffer(obj, view); @@ -364,13 +372,15 @@ static PyObject * memory_tobytes(PyMemoryViewObject *mem, PyObject *noargs) { - /* Create new Bytes object for data */ return PyBytes_FromObject((PyObject *)mem); } static PyObject * memory_tolist(PyMemoryViewObject *mem, PyObject *noargs) { + /* This should construct a (nested) list of unpacked objects + possibly using the struct module. + */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -429,7 +439,7 @@ static PyObject * memory_str(PyMemoryViewObject *self) { - PyBuffer view; + Py_buffer view; PyObject *res; if (PyObject_GetBuffer((PyObject *)self, &view, PyBUF_FULL) < 0) @@ -446,7 +456,7 @@ static Py_ssize_t memory_length(PyMemoryViewObject *self) { - PyBuffer view; + Py_buffer view; if (PyObject_GetBuffer((PyObject *)self, &view, PyBUF_FULL) < 0) return -1; @@ -454,9 +464,58 @@ return view.len; } +/* + mem[obj] returns a bytes object holding the data for one element if + obj fully indexes the memory view or another memory-view object + if it does not. + + 0-d memory-view objects can be referenced using ... or () but + not with anything else. + */ static PyObject * memory_subscript(PyMemoryViewObject *self, PyObject *key) { + Py_buffer *view; + view = &(self->view); + + if (view->ndim == 0) { + if (key == Py_Ellipsis || + (PyTuple_Check(key) && PyTuple_GET_SIZE(key)==0)) { + Py_INCREF(self); + return (PyObject *)self; + } + else { + PyErr_SetString(PyExc_IndexError, "invalid indexing of 0-dim memory"); + return NULL; + } + } + if (PyIndex_Check(key)) { + Py_ssize_t result; + result = PyNumber_AsSsize_t(key, NULL); + if (result == -1 && PyErr_Occurred()) + return NULL; + if (view->ndim == 1) { + /* Return a bytes object */ + char *ptr; + ptr = (char *)view->buf; + if (view->strides == NULL) + ptr += view->itemsize * result; + else + ptr += view->strides[0] * result; + if (view->suboffsets != NULL && view->suboffsets[0] >= 0) { + ptr = *((char **)ptr) + view->suboffsets[0]; + } + return PyBytes_FromStringAndSize(ptr, view->itemsize); + } + else { + /* Return a new memory-view object */ + Py_buffer newview; + PyMemoryView_FromMemory(&newview); + } + } + + + Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } Modified: python/branches/py3k/Objects/stringobject.c ============================================================================== --- python/branches/py3k/Objects/stringobject.c (original) +++ python/branches/py3k/Objects/stringobject.c Sun Sep 23 04:00:13 2007 @@ -1160,7 +1160,7 @@ } static int -string_buffer_getbuffer(PyStringObject *self, PyBuffer *view, int flags) +string_buffer_getbuffer(PyStringObject *self, Py_buffer *view, int flags) { return PyBuffer_FillInfo(view, (void *)self->ob_sval, Py_Size(self), 0, flags); } Modified: python/branches/py3k/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k/Objects/unicodeobject.c (original) +++ python/branches/py3k/Objects/unicodeobject.c Sun Sep 23 04:00:13 2007 @@ -8104,7 +8104,7 @@ static int -unicode_buffer_getbuffer(PyUnicodeObject *self, PyBuffer *view, int flags) +unicode_buffer_getbuffer(PyUnicodeObject *self, Py_buffer *view, int flags) { if (flags & PyBUF_CHARACTER) { Modified: python/branches/py3k/Python/getargs.c ============================================================================== --- python/branches/py3k/Python/getargs.c (original) +++ python/branches/py3k/Python/getargs.c Sun Sep 23 04:00:13 2007 @@ -1211,7 +1211,7 @@ PyBufferProcs *pb = arg->ob_type->tp_as_buffer; int count; int temp=-1; - PyBuffer view; + Py_buffer view; if (pb == NULL || pb->bf_getbuffer == NULL || @@ -1242,7 +1242,7 @@ char **p = va_arg(*p_va, char **); PyBufferProcs *pb = arg->ob_type->tp_as_buffer; int count; - PyBuffer view; + Py_buffer view; if (*format++ != '#') return converterr( @@ -1286,7 +1286,7 @@ { PyBufferProcs *pb = arg->ob_type->tp_as_buffer; Py_ssize_t count; - PyBuffer view; + Py_buffer view; *errmsg = NULL; *p = NULL; Modified: python/branches/py3k/Python/marshal.c ============================================================================== --- python/branches/py3k/Python/marshal.c (original) +++ python/branches/py3k/Python/marshal.c Sun Sep 23 04:00:13 2007 @@ -367,7 +367,7 @@ /* Write unknown buffer-style objects as a string */ char *s; PyBufferProcs *pb = v->ob_type->tp_as_buffer; - PyBuffer view; + Py_buffer view; if ((*pb->bf_getbuffer)(v, &view, PyBUF_SIMPLE) != 0) { w_byte(TYPE_UNKNOWN, p); p->error = 1; From python-3000-checkins at python.org Sun Sep 23 04:40:40 2007 From: python-3000-checkins at python.org (travis.oliphant) Date: Sun, 23 Sep 2007 04:40:40 +0200 (CEST) Subject: [Python-3000-checkins] r58237 - python/branches/py3k-buffer Message-ID: <20070923024040.A8ED21E401F@bag.python.org> Author: travis.oliphant Date: Sun Sep 23 04:40:40 2007 New Revision: 58237 Removed: python/branches/py3k-buffer/ Log: Delete py3k-buffer branch which has been merged back to the py3k branch. From python-3000-checkins at python.org Sun Sep 23 15:37:01 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Sun, 23 Sep 2007 15:37:01 +0200 (CEST) Subject: [Python-3000-checkins] r58238 - python/branches/py3k/Lib/lib-tk/turtle.py Message-ID: <20070923133701.0BE621E4002@bag.python.org> Author: georg.brandl Date: Sun Sep 23 15:37:00 2007 New Revision: 58238 Modified: python/branches/py3k/Lib/lib-tk/turtle.py Log: Fix turtle module: None and int are not comparable, map returns an iterator. Modified: python/branches/py3k/Lib/lib-tk/turtle.py ============================================================================== --- python/branches/py3k/Lib/lib-tk/turtle.py (original) +++ python/branches/py3k/Lib/lib-tk/turtle.py Sun Sep 23 15:37:00 2007 @@ -531,7 +531,7 @@ def _goto(self, x1, y1): x0, y0 = self._position - self._position = map(float, (x1, y1)) + self._position = (float(x1), float(y1)) if self._filling: self._path.append(self._position) if self._drawing: @@ -749,25 +749,25 @@ global _width, _height, _startx, _starty width = geometry.get('width',_width) - if width >= 0 or width == None: + if width is None or width >= 0: _width = width else: raise ValueError("width can not be less than 0") height = geometry.get('height',_height) - if height >= 0 or height == None: + if height is None or height >= 0: _height = height else: raise ValueError("height can not be less than 0") startx = geometry.get('startx', _startx) - if startx >= 0 or startx == None: + if startx is None or startx >= 0: _startx = _startx else: raise ValueError("startx can not be less than 0") starty = geometry.get('starty', _starty) - if starty >= 0 or starty == None: + if starty is None or starty >= 0: _starty = starty else: raise ValueError("startx can not be less than 0") From python-3000-checkins at python.org Sun Sep 23 21:49:54 2007 From: python-3000-checkins at python.org (skip.montanaro) Date: Sun, 23 Sep 2007 21:49:54 +0200 (CEST) Subject: [Python-3000-checkins] r58239 - python/branches/py3k/Doc/library/functions.rst Message-ID: <20070923194954.F2EA51E4003@bag.python.org> Author: skip.montanaro Date: Sun Sep 23 21:49:54 2007 New Revision: 58239 Modified: python/branches/py3k/Doc/library/functions.rst Log: Reformat the open function text so it fits within 80 columns in preparation for a bit of rewriting. Separating the reformatting from the rewriting should make it easier for people to review the substantive changes. Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Sun Sep 23 21:49:54 2007 @@ -701,18 +701,20 @@ :func:`open` instead of invoking the :class:`file` constructor directly. The first two arguments are the same as for ``stdio``'s :cfunc:`fopen`: - *filename* is the file name to be opened, and *mode* is a string indicating how - the file is to be opened. + *filename* is the file name to be opened, and *mode* is a string + indicating how the file is to be opened. - The most commonly-used values of *mode* are ``'r'`` for reading, ``'w'`` for - writing (truncating the file if it already exists), and ``'a'`` for appending - (which on *some* Unix systems means that *all* writes append to the end of the - file regardless of the current seek position). If *mode* is omitted, it - defaults to ``'r'``. When opening a binary file, you should append ``'b'`` to - the *mode* value to open the file in binary mode, which will improve - portability. (Appending ``'b'`` is useful even on systems that don't treat - binary and text files differently, where it serves as documentation.) See below - for more possible values of *mode*. + The most commonly-used values of *mode* are ``'r'`` for reading, ``'w'`` + for writing (truncating the file if it already exists), and ``'a'`` for + appending (which on *some* Unix systems means that *all* writes append to + the end of the file regardless of the current seek position). If *mode* + is omitted, it defaults to ``'r'``. + + When opening a binary file, you should append ``'b'`` to the *mode* value + to open the file in binary mode, which will improve portability. + (Appending ``'b'`` is useful even on systems that don't treat binary and + text files differently, where it serves as documentation.) See below for + more possible values of *mode*. .. index:: single: line-buffered I/O @@ -720,31 +722,33 @@ single: buffer size, I/O single: I/O control; buffering - The optional *bufsize* argument specifies the file's desired buffer size: 0 - means unbuffered, 1 means line buffered, any other positive value means use a - buffer of (approximately) that size. A negative *bufsize* means to use the - system default, which is usually line buffered for tty devices and fully - buffered for other files. If omitted, the system default is used. [#]_ - - Modes ``'r+'``, ``'w+'`` and ``'a+'`` open the file for updating (note that - ``'w+'`` truncates the file). Append ``'b'`` to the mode to open the file in - binary mode, on systems that differentiate between binary and text files; on - systems that don't have this distinction, adding the ``'b'`` has no effect. - - In addition to the standard :cfunc:`fopen` values *mode* may be ``'U'`` or - ``'rU'``. Python is usually built with universal newline support; supplying - ``'U'`` opens the file as a text file, but lines may be terminated by any of the - following: the Unix end-of-line convention ``'\n'``, the Macintosh convention - ``'\r'``, or the Windows convention ``'\r\n'``. All of these external - representations are seen as ``'\n'`` by the Python program. If Python is built - without universal newline support a *mode* with ``'U'`` is the same as normal - text mode. Note that file objects so opened also have an attribute called - :attr:`newlines` which has a value of ``None`` (if no newlines have yet been - seen), ``'\n'``, ``'\r'``, ``'\r\n'``, or a tuple containing all the newline - types seen. + The optional *bufsize* argument specifies the file's desired buffer size: + 0 means unbuffered, 1 means line buffered, any other positive value means + use a buffer of (approximately) that size. A negative *bufsize* means to + use the system default, which is usually line buffered for tty devices + and fully buffered for other files. If omitted, the system default is + used. [#]_ + + Modes ``'r+'``, ``'w+'`` and ``'a+'`` open the file for updating (note + that ``'w+'`` truncates the file). Append ``'b'`` to the mode to open + the file in binary mode, on systems that differentiate between binary and + text files; on systems that don't have this distinction, adding the + ``'b'`` has no effect. + + In addition to the standard :cfunc:`fopen` values *mode* may be ``'U'`` + or ``'rU'``. Python is usually built with universal newline support; + supplying ``'U'`` opens the file as a text file, but lines may be + terminated by any of the following: the Unix end-of-line convention + ``'\n'``, the Macintosh convention ``'\r'``, or the Windows convention + ``'\r\n'``. All of these external representations are seen as ``'\n'`` by + the Python program. If Python is built without universal newline support + a *mode* with ``'U'`` is the same as normal text mode. Note that file + objects so opened also have an attribute called :attr:`newlines` which + has a value of ``None`` (if no newlines have yet been seen), ``'\n'``, + ``'\r'``, ``'\r\n'``, or a tuple containing all the newline types seen. - Python enforces that the mode, after stripping ``'U'``, begins with ``'r'``, - ``'w'`` or ``'a'``. + Python enforces that the mode, after stripping ``'U'``, begins with + ``'r'``, ``'w'`` or ``'a'``. See also the :mod:`fileinput` module, the :mod:`os` module, and the :mod:`os.path` module. From python-3000-checkins at python.org Sun Sep 23 23:13:46 2007 From: python-3000-checkins at python.org (skip.montanaro) Date: Sun, 23 Sep 2007 23:13:46 +0200 (CEST) Subject: [Python-3000-checkins] r58240 - python/branches/py3k/Doc/library/functions.rst Message-ID: <20070923211346.31AC01E4003@bag.python.org> Author: skip.montanaro Date: Sun Sep 23 23:13:45 2007 New Revision: 58240 Modified: python/branches/py3k/Doc/library/functions.rst Log: Update the documentation of the open() builtin function a bit. I believe I mostly got the distinction between text and binary modes correct, though someone should proofread my writing. I also sort of guessed at the meaning of the various index:: entries. Modified: python/branches/py3k/Doc/library/functions.rst ============================================================================== --- python/branches/py3k/Doc/library/functions.rst (original) +++ python/branches/py3k/Doc/library/functions.rst Sun Sep 23 23:13:45 2007 @@ -708,19 +708,25 @@ for writing (truncating the file if it already exists), and ``'a'`` for appending (which on *some* Unix systems means that *all* writes append to the end of the file regardless of the current seek position). If *mode* - is omitted, it defaults to ``'r'``. + is omitted, it defaults to ``'r'``. See below for more possible values + of *mode*. - When opening a binary file, you should append ``'b'`` to the *mode* value - to open the file in binary mode, which will improve portability. - (Appending ``'b'`` is useful even on systems that don't treat binary and - text files differently, where it serves as documentation.) See below for - more possible values of *mode*. + Python distinguishes between files opened in binary and text modes, even + when the underlying operating system doesn't. Files opened in binary + mode (appending ``'b'`` to the *mode* argument to :func:``open``) return + contents as bytes objects without any decoding. In text mode (the + default, or when ``'t'`` is appended to the *mode* argument) the contents + of the file are returned as strings, the bytes having been first decoded + using the encoding specified by :func:`sys.getfilesystemencoding`. .. index:: single: line-buffered I/O single: unbuffered I/O single: buffer size, I/O single: I/O control; buffering + single: binary mode + single: text mode + module: sys The optional *bufsize* argument specifies the file's desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means @@ -730,28 +736,20 @@ used. [#]_ Modes ``'r+'``, ``'w+'`` and ``'a+'`` open the file for updating (note - that ``'w+'`` truncates the file). Append ``'b'`` to the mode to open - the file in binary mode, on systems that differentiate between binary and - text files; on systems that don't have this distinction, adding the - ``'b'`` has no effect. - - In addition to the standard :cfunc:`fopen` values *mode* may be ``'U'`` - or ``'rU'``. Python is usually built with universal newline support; - supplying ``'U'`` opens the file as a text file, but lines may be - terminated by any of the following: the Unix end-of-line convention - ``'\n'``, the Macintosh convention ``'\r'``, or the Windows convention - ``'\r\n'``. All of these external representations are seen as ``'\n'`` by - the Python program. If Python is built without universal newline support - a *mode* with ``'U'`` is the same as normal text mode. Note that file - objects so opened also have an attribute called :attr:`newlines` which - has a value of ``None`` (if no newlines have yet been seen), ``'\n'``, - ``'\r'``, ``'\r\n'``, or a tuple containing all the newline types seen. + that ``'w+'`` truncates the file). - Python enforces that the mode, after stripping ``'U'``, begins with - ``'r'``, ``'w'`` or ``'a'``. + When a file is opened in text mode it is also opened in universal + newlines mode. Unlike earlier versions of Python it's no longer + necessary to add a ``'U'`` value to the *mode* argument to enable this + mode. Consequently, in files opened in text mode lines may be terminated + with ``'\n'``, ``'\r'``, or ``'\r\n'``. All three external + representations are seen as ``'\n'`` by the Python program. File objects + opened in text mode also have a :attr:`newlines` attribute which has a + value of ``None`` (if no newlines have been seen yet), ``'\n'``, + ``'\r'``, ``'\r\n'``, or a tuple containing all the newline types seen. - See also the :mod:`fileinput` module, the :mod:`os` module, and the - :mod:`os.path` module. + See also the :mod:`fileinput` module, the file-related functions in the + :mod:`os` module, and the :mod:`os.path` module. .. function:: ord(c) From python-3000-checkins at python.org Mon Sep 24 16:43:56 2007 From: python-3000-checkins at python.org (thomas.heller) Date: Mon, 24 Sep 2007 16:43:56 +0200 (CEST) Subject: [Python-3000-checkins] r58241 - in python/branches/py3k: Modules/_bsddb.c PC/_winreg.c Message-ID: <20070924144356.E67EA1E400C@bag.python.org> Author: thomas.heller Date: Mon Sep 24 16:43:56 2007 New Revision: 58241 Modified: python/branches/py3k/Modules/_bsddb.c python/branches/py3k/PC/_winreg.c Log: Make Modules/_bsddb.c and PC/_winreg.c compile again by renaming PyBuffer into Py_buffer. Modified: python/branches/py3k/Modules/_bsddb.c ============================================================================== --- python/branches/py3k/Modules/_bsddb.c (original) +++ python/branches/py3k/Modules/_bsddb.c Mon Sep 24 16:43:56 2007 @@ -382,7 +382,7 @@ /* Cleanup a Python buffer API view created by make_dbt() */ -static void free_buf_view(PyObject *obj, PyBuffer *view) +static void free_buf_view(PyObject *obj, Py_buffer *view) { if (view) { PyObject_ReleaseBuffer(obj, view); @@ -400,13 +400,13 @@ } while(0); -static PyBuffer * _malloc_view(PyObject *obj) +static Py_buffer * _malloc_view(PyObject *obj) { - PyBuffer *view; + Py_buffer *view; - if (!(view = PyMem_Malloc(sizeof(PyBuffer)))) { + if (!(view = PyMem_Malloc(sizeof(Py_buffer)))) { PyErr_SetString(PyExc_MemoryError, - "PyBuffer malloc failed"); + "Py_buffer malloc failed"); return NULL; } /* XXX(gps): PyBUF_LOCKDATA is desired to prevent other theads from @@ -429,11 +429,11 @@ /* Create a DBT structure (containing key and data values) from Python strings. Returns >= 1 on success, 0 on an error. The returned_view_p - may be filled with a newly allocated PyBuffer view on success. - The caller MUST call free_buf_view() on any returned PyBuffer. */ -static int make_dbt(PyObject* obj, DBT* dbt, PyBuffer** returned_view_p) + may be filled with a newly allocated Py_buffer view on success. + The caller MUST call free_buf_view() on any returned Py_buffer. */ +static int make_dbt(PyObject* obj, DBT* dbt, Py_buffer** returned_view_p) { - PyBuffer *view; + Py_buffer *view; /* simple way to ensure the caller can detect if we've returned a new buffer view or not: require their pointer to start out NULL. */ @@ -464,14 +464,14 @@ what's been given, verifies that it's allowed, and then makes the DBT. Caller MUST call FREE_DBT_VIEW(keydbt, keyobj, key_view) with all - returned DBT and PyBuffer values when done. */ + returned DBT and Py_buffer values when done. */ static int make_key_dbt(DBObject* self, PyObject* keyobj, DBT* key, int* pflags, - PyBuffer** returned_view_p) + Py_buffer** returned_view_p) { db_recno_t recno; int type; - PyBuffer *view; + Py_buffer *view; /* simple way to ensure the caller can detect if we've returned a new buffer view or not: require their pointer to start out NULL. */ @@ -1221,7 +1221,7 @@ { PyObject* txnobj = NULL; PyObject* dataobj; - PyBuffer* data_buf_view = NULL; + Py_buffer* data_buf_view = NULL; db_recno_t recno; DBT key, data; DB_TXN *txn = NULL; @@ -1534,7 +1534,7 @@ PyObject* txnobj = NULL; int flags = 0; PyObject* keyobj; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; DBT key; DB_TXN *txn = NULL; static char* kwnames[] = { "key", "txn", "flags", NULL }; @@ -1585,7 +1585,7 @@ PyObject* keyobj; PyObject* dfltobj = NULL; PyObject* retval = NULL; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; int dlen = -1; int doff = -1; DBT key, data; @@ -1654,7 +1654,7 @@ PyObject* keyobj; PyObject* dfltobj = NULL; PyObject* retval = NULL; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; int dlen = -1; int doff = -1; DBT key, pkey, data; @@ -1758,7 +1758,7 @@ PyObject* txnobj = NULL; PyObject* keyobj; PyObject* retval = NULL; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; DBT key, data; DB_TXN *txn = NULL; static char* kwnames[] = { "key", "txn", NULL }; @@ -1802,8 +1802,8 @@ PyObject* keyobj; PyObject* dataobj; PyObject* retval = NULL; - PyBuffer* data_buf_view = NULL; - PyBuffer* key_buf_view = NULL; + Py_buffer* data_buf_view = NULL; + Py_buffer* key_buf_view = NULL; DBT key, data; void *orig_data; DB_TXN *txn = NULL; @@ -1969,7 +1969,7 @@ int err, flags=0; PyObject* txnobj = NULL; PyObject* keyobj; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; DBT key; DB_TXN *txn = NULL; DB_KEY_RANGE range; @@ -2100,8 +2100,8 @@ int dlen = -1; int doff = -1; PyObject *keyobj, *dataobj, *retval; - PyBuffer *data_buf_view = NULL; - PyBuffer *key_buf_view = NULL; + Py_buffer *data_buf_view = NULL; + Py_buffer *key_buf_view = NULL; DBT key, data; DB_TXN *txn = NULL; static char* kwnames[] = { "key", "data", "txn", "flags", "dlen", @@ -2881,7 +2881,7 @@ { int err; PyObject* retval; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; DBT key; DBT data; @@ -2920,8 +2920,8 @@ DBT key, data; int retval; int flags = 0; - PyBuffer *data_buf_view = NULL; - PyBuffer *key_buf_view = NULL; + Py_buffer *data_buf_view = NULL; + Py_buffer *key_buf_view = NULL; if (self->db == NULL) { PyObject *t = Py_BuildValue("(is)", 0, "DB object has been closed"); @@ -2966,7 +2966,7 @@ { int err; PyObject* keyobj; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; DBT key, data; PyObject* txnobj = NULL; DB_TXN *txn = NULL; @@ -3263,8 +3263,8 @@ PyObject* keyobj = NULL; PyObject* dataobj = NULL; PyObject* retval = NULL; - PyBuffer* data_buf_view = NULL; - PyBuffer* key_buf_view = NULL; + Py_buffer* data_buf_view = NULL; + Py_buffer* key_buf_view = NULL; int dlen = -1; int doff = -1; DBT key, data; @@ -3354,8 +3354,8 @@ PyObject* keyobj = NULL; PyObject* dataobj = NULL; PyObject* retval = NULL; - PyBuffer* data_buf_view = NULL; - PyBuffer* key_buf_view = NULL; + Py_buffer* data_buf_view = NULL; + Py_buffer* key_buf_view = NULL; int dlen = -1; int doff = -1; DBT key, pkey, data; @@ -3517,8 +3517,8 @@ { int err, flags = 0; PyObject *keyobj, *dataobj; - PyBuffer *data_buf_view = NULL; - PyBuffer *key_buf_view = NULL; + Py_buffer *data_buf_view = NULL; + Py_buffer *key_buf_view = NULL; DBT key, data; static char* kwnames[] = { "key", "data", "flags", "dlen", "doff", NULL }; @@ -3558,7 +3558,7 @@ int err, flags = 0; DBT key, data; PyObject *retval, *keyobj; - PyBuffer *key_buf_view = NULL; + Py_buffer *key_buf_view = NULL; static char* kwnames[] = { "key", "flags", "dlen", "doff", NULL }; int dlen = -1; int doff = -1; @@ -3630,7 +3630,7 @@ int err, flags = 0; DBT key, data; PyObject *retval, *keyobj; - PyBuffer *key_buf_view = NULL; + Py_buffer *key_buf_view = NULL; static char* kwnames[] = { "key", "flags", "dlen", "doff", NULL }; int dlen = -1; int doff = -1; @@ -3705,8 +3705,8 @@ int err; DBT key, data; PyObject *retval; - PyBuffer *data_buf_view = NULL; - PyBuffer *key_buf_view = NULL; + Py_buffer *data_buf_view = NULL; + Py_buffer *key_buf_view = NULL; /* the caller did this: CHECK_CURSOR_NOT_CLOSED(self); */ if (!make_key_dbt(self->mydb, keyobj, &key, NULL, &key_buf_view)) @@ -4480,7 +4480,7 @@ int locker, lock_mode; DBT obj; PyObject *objobj, *retval; - PyBuffer *obj_buf_view = NULL; + Py_buffer *obj_buf_view = NULL; if (!PyArg_ParseTuple(args, "iOi|i:lock_get", &locker, &objobj, &lock_mode, &flags)) return NULL; @@ -5057,7 +5057,7 @@ { int err, flags = 0; PyObject *keyobj; - PyBuffer *key_buf_view = NULL; + Py_buffer *key_buf_view = NULL; PyObject *txnobj = NULL; DB_TXN *txn = NULL; DBT key; Modified: python/branches/py3k/PC/_winreg.c ============================================================================== --- python/branches/py3k/PC/_winreg.c (original) +++ python/branches/py3k/PC/_winreg.c Mon Sep 24 16:43:56 2007 @@ -773,7 +773,7 @@ if (value == Py_None) *retDataSize = 0; else { - PyBuffer view; + Py_buffer view; if (!PyObject_CheckBuffer(value)) { PyErr_Format(PyExc_TypeError, From python-3000-checkins at python.org Mon Sep 24 20:05:09 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 24 Sep 2007 20:05:09 +0200 (CEST) Subject: [Python-3000-checkins] r58246 - python/branches/py3k/Doc/c-api/newtypes.rst Message-ID: <20070924180509.526691E4005@bag.python.org> Author: georg.brandl Date: Mon Sep 24 20:05:08 2007 New Revision: 58246 Modified: python/branches/py3k/Doc/c-api/newtypes.rst Log: #1189: documentation for tp_as_* structs. Modified: python/branches/py3k/Doc/c-api/newtypes.rst ============================================================================== --- python/branches/py3k/Doc/c-api/newtypes.rst (original) +++ python/branches/py3k/Doc/c-api/newtypes.rst Mon Sep 24 20:05:08 2007 @@ -592,17 +592,34 @@ This field is inherited by subtypes. -.. cmember:: PyNumberMethods *tp_as_number; +.. cmember:: PyNumberMethods* tp_as_number - XXX + Pointer to an additional structure that contains fields relevant only to + objects which implement the number protocol. These fields are documented in + :ref:`number-structs`. + + The :attr:`tp_as_number` field is not inherited, but the contained fields are + inherited individually. + + +.. cmember:: PySequenceMethods* tp_as_sequence + + Pointer to an additional structure that contains fields relevant only to + objects which implement the sequence protocol. These fields are documented + in :ref:`sequence-structs`. + + The :attr:`tp_as_sequence` field is not inherited, but the contained fields + are inherited individually. -.. cmember:: PySequenceMethods *tp_as_sequence; - XXX +.. cmember:: PyMappingMethods* tp_as_mapping -.. cmember:: PyMappingMethods *tp_as_mapping; + Pointer to an additional structure that contains fields relevant only to + objects which implement the mapping protocol. These fields are documented in + :ref:`mapping-structs`. - XXX + The :attr:`tp_as_mapping` field is not inherited, but the contained fields are + inherited individually. .. cmember:: hashfunc PyTypeObject.tp_hash @@ -1401,28 +1418,106 @@ of the library. +.. _number-structs: + +Number Object Structures +======================== + +.. sectionauthor:: Amaury Forgeot d'Arc + + +.. ctype:: PyNumberMethods + + This structure holds pointers to the functions which an object uses to + implement the number protocol. Each function is used by the function of + similar name documented in the :ref:`number` section. + + Here is the structure definition:: + + typedef struct { + binaryfunc nb_add; + binaryfunc nb_subtract; + binaryfunc nb_multiply; + binaryfunc nb_remainder; + binaryfunc nb_divmod; + ternaryfunc nb_power; + unaryfunc nb_negative; + unaryfunc nb_positive; + unaryfunc nb_absolute; + inquiry nb_bool; + unaryfunc nb_invert; + binaryfunc nb_lshift; + binaryfunc nb_rshift; + binaryfunc nb_and; + binaryfunc nb_xor; + binaryfunc nb_or; + int nb_reserved; /* unused, must be zero */ + unaryfunc nb_int; + unaryfunc nb_long; + unaryfunc nb_float; + + unaryfunc nb_oct; /* not used anymore, must be zero */ + unaryfunc nb_hex; /* not used anymore, must be zero */ + + binaryfunc nb_inplace_add; + binaryfunc nb_inplace_subtract; + binaryfunc nb_inplace_multiply; + binaryfunc nb_inplace_remainder; + ternaryfunc nb_inplace_power; + binaryfunc nb_inplace_lshift; + binaryfunc nb_inplace_rshift; + binaryfunc nb_inplace_and; + binaryfunc nb_inplace_xor; + binaryfunc nb_inplace_or; + + binaryfunc nb_floor_divide; + binaryfunc nb_true_divide; + binaryfunc nb_inplace_floor_divide; + binaryfunc nb_inplace_true_divide; + + unaryfunc nb_index; + } PyNumberMethods; + + .. note:: + + Binary and ternary functions must check the type of all their operands, + and implement the necessary conversions (at least one of the operands is + an instance of the defined type). If the operation is not defined for the + given operands, binary and ternary functions must return + ``Py_NotImplemented``, if another error occurred they must return ``NULL`` + and set an exception. + + .. _mapping-structs: Mapping Object Structures ========================= +.. sectionauthor:: Amaury Forgeot d'Arc + .. ctype:: PyMappingMethods - Structure used to hold pointers to the functions used to implement the mapping - protocol for an extension type. + This structure holds pointers to the functions which an object uses to + implement the mapping protocol. It has three members: +.. cmember:: lenfunc PyMappingMethods.mp_length -.. _number-structs: + This function is used by :cfunc:`PyMapping_Length` and + :cfunc:`PyObject_Size`, and has the same signature. This slot may be set to + *NULL* if the object has no defined length. -Number Object Structures -======================== +.. cmember:: binaryfunc PyMappingMethods.mp_subscript + This function is used by :cfunc:`PyObject_GetItem` and has the same + signature. This slot must be filled for the :cfunc:`PyMapping_Check` + function to return ``1``, it can be *NULL* otherwise. -.. ctype:: PyNumberMethods +.. cmember:: objobjargproc PyMappingMethods.mp_ass_subscript - Structure used to hold pointers to the functions an extension type uses to - implement the number protocol. + This function is used by :cfunc:`PyObject_SetItem` and has the same + signature. If this slot is *NULL*, the object does not support item + assignment. .. _sequence-structs: @@ -1430,12 +1525,68 @@ Sequence Object Structures ========================== +.. sectionauthor:: Amaury Forgeot d'Arc + .. ctype:: PySequenceMethods - Structure used to hold pointers to the functions which an object uses to + This structure holds pointers to the functions which an object uses to implement the sequence protocol. +.. cmember:: lenfunc PySequenceMethods.sq_length + + This function is used by :cfunc:`PySequence_Size` and :cfunc:`PyObject_Size`, + and has the same signature. + +.. cmember:: binaryfunc PySequenceMethods.sq_concat + + This function is used by :cfunc:`PySequence_Concat` and has the same + signature. It is also used by the `+` operator, after trying the numeric + addition via the :attr:`tp_as_number.nb_add` slot. + +.. cmember:: ssizeargfunc PySequenceMethods.sq_repeat + + This function is used by :cfunc:`PySequence_Repeat` and has the same + signature. It is also used by the `*` operator, after trying numeric + multiplication via the :attr:`tp_as_number.nb_mul` slot. + +.. cmember:: ssizeargfunc PySequenceMethods.sq_item + + This function is used by :cfunc:`PySequence_GetItem` and has the same + signature. This slot must be filled for the :cfunc:`PySequence_Check` + function to return ``1``, it can be *NULL* otherwise. + + Negative indexes are handled as follows: if the :attr:`sq_length` slot is + filled, it is called and the sequence length is used to compute a positive + index which is passed to :attr:`sq_item`. If :attr:`sq_length` is *NULL*, + the index is passed as is to the function. + +.. cmember:: ssizeobjargproc PySequenceMethods.sq_ass_item + + This function is used by :cfunc:`PySequence_SetItem` and has the same + signature. This slot may be left to *NULL* if the object does not support + item assignment. + +.. cmember:: objobjproc PySequenceMethods.sq_contains + + This function may be used by :cfunc:`PySequence_Contains` and has the same + signature. This slot may be left to *NULL*, in this case + :cfunc:`PySequence_Contains` simply traverses the sequence until it finds a + match. + +.. cmember:: binaryfunc PySequenceMethods.sq_inplace_concat + + This function is used by :cfunc:`PySequence_InPlaceConcat` and has the same + signature. It should modify its first operand, and return it. + +.. cmember:: ssizeargfunc PySequenceMethods.sq_inplace_repeat + + This function is used by :cfunc:`PySequence_InPlaceRepeat` and has the same + signature. It should modify its first operand, and return it. + +.. XXX need to explain precedence between mapping and sequence +.. XXX explains when to implement the sq_inplace_* slots + .. _buffer-structs: From python-3000-checkins at python.org Tue Sep 25 23:48:10 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 25 Sep 2007 23:48:10 +0200 (CEST) Subject: [Python-3000-checkins] r58253 - python/branches/py3k/Lib/distutils/fancy_getopt.py Message-ID: <20070925214810.260E71E4008@bag.python.org> Author: guido.van.rossum Date: Tue Sep 25 23:48:09 2007 New Revision: 58253 Modified: python/branches/py3k/Lib/distutils/fancy_getopt.py Log: Fix a straggler filter() call. Modified: python/branches/py3k/Lib/distutils/fancy_getopt.py ============================================================================== --- python/branches/py3k/Lib/distutils/fancy_getopt.py (original) +++ python/branches/py3k/Lib/distutils/fancy_getopt.py Tue Sep 25 23:48:09 2007 @@ -388,7 +388,7 @@ text = text.expandtabs() text = text.translate(WS_TRANS) chunks = re.split(r'( +|-+)', text) - chunks = filter(None, chunks) # ' - ' results in empty strings + chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings lines = [] while chunks: From python-3000-checkins at python.org Tue Sep 25 23:51:12 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 25 Sep 2007 23:51:12 +0200 (CEST) Subject: [Python-3000-checkins] r58254 - python/branches/py3k/Modules/_ctypes/_ctypes.c Message-ID: <20070925215112.7F5CB1E4008@bag.python.org> Author: guido.van.rossum Date: Tue Sep 25 23:51:12 2007 New Revision: 58254 Modified: python/branches/py3k/Modules/_ctypes/_ctypes.c Log: Delete now-unused static function Array_ass_slice(). Modified: python/branches/py3k/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/py3k/Modules/_ctypes/_ctypes.c (original) +++ python/branches/py3k/Modules/_ctypes/_ctypes.c Tue Sep 25 23:51:12 2007 @@ -3833,48 +3833,6 @@ } static int -Array_ass_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *value) -{ - CDataObject *self = (CDataObject *)_self; - Py_ssize_t i, len; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Array does not support item deletion"); - return -1; - } - - if (ilow < 0) - ilow = 0; - else if (ilow > self->b_length) - ilow = self->b_length; - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > self->b_length) - ihigh = self->b_length; - - len = PySequence_Length(value); - if (len != ihigh - ilow) { - PyErr_SetString(PyExc_ValueError, - "Can only assign sequence of same size"); - return -1; - } - for (i = 0; i < len; i++) { - PyObject *item = PySequence_GetItem(value, i); - int result; - if (item == NULL) - return -1; - result = Array_ass_item(_self, i+ilow, item); - Py_DECREF(item); - if (result == -1) - return -1; - } - return 0; -} - -static int Array_ass_subscript(PyObject *_self, PyObject *item, PyObject *value) { CDataObject *self = (CDataObject *)_self; From python-3000-checkins at python.org Wed Sep 26 00:10:05 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Wed, 26 Sep 2007 00:10:05 +0200 (CEST) Subject: [Python-3000-checkins] r58255 - python/branches/py3k/Objects/memoryobject.c Message-ID: <20070925221005.D25431E4011@bag.python.org> Author: guido.van.rossum Date: Wed Sep 26 00:10:05 2007 New Revision: 58255 Modified: python/branches/py3k/Objects/memoryobject.c Log: Whitespace and line lengrth cleanup. Modified: python/branches/py3k/Objects/memoryobject.c ============================================================================== --- python/branches/py3k/Objects/memoryobject.c (original) +++ python/branches/py3k/Objects/memoryobject.c Wed Sep 26 00:10:05 2007 @@ -6,14 +6,14 @@ static int memory_getbuf(PyMemoryViewObject *self, Py_buffer *view, int flags) { - if (view != NULL) + if (view != NULL) *view = self->view; - return self->base->ob_type->tp_as_buffer->bf_getbuffer(self->base, - NULL, PyBUF_FULL); + return self->base->ob_type->tp_as_buffer->bf_getbuffer(self->base, NULL, + PyBUF_FULL); } static void -memory_releasebuf(PyMemoryViewObject *self, Py_buffer *view) +memory_releasebuf(PyMemoryViewObject *self, Py_buffer *view) { PyObject_ReleaseBuffer(self->base, NULL); } @@ -42,16 +42,16 @@ PyMemoryViewObject *mview; if (!PyObject_CheckBuffer(base)) { - PyErr_SetString(PyExc_TypeError, - "cannot make memory view because object does "\ + PyErr_SetString(PyExc_TypeError, + "cannot make memory view because object does " "not have the buffer interface"); - return NULL; + return NULL; } - - mview = (PyMemoryViewObject *)PyObject_New(PyMemoryViewObject, + + mview = (PyMemoryViewObject *)PyObject_New(PyMemoryViewObject, &PyMemoryView_Type); if (mview == NULL) return NULL; - + mview->base = NULL; if (PyObject_GetBuffer(base, &(mview->view), PyBUF_FULL) < 0) { Py_DECREF(mview); @@ -69,12 +69,12 @@ PyObject *obj; if (!PyArg_UnpackTuple(args, "memoryview", 1, 1, &obj)) return NULL; - return PyMemoryView_FromObject(obj); + return PyMemoryView_FromObject(obj); } static void -_strided_copy_nd(char *dest, char *src, int nd, Py_ssize_t *shape, +_strided_copy_nd(char *dest, char *src, int nd, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char fort) { int k; @@ -92,23 +92,23 @@ } else { if (fort == 'F') { - /* Copy first dimension first, + /* Copy first dimension first, second dimension second, etc... Set up the recursive loop backwards so that final - dimension is actually copied last. + dimension is actually copied last. */ outstride = itemsize; for (k=1; kndim); if (indices == NULL) { @@ -153,7 +153,7 @@ for (k=0; kndim;k++) { indices[k] = 0; } - + elements = 1; for (k=0; kndim; k++) { elements *= view->shape[k]; @@ -170,26 +170,26 @@ memcpy(dest, ptr, view->itemsize); dest += view->itemsize; } - + PyMem_Free(indices); return 0; } -/* +/* Get a the data from an object as a contiguous chunk of memory (in either 'C' or 'F'ortran order) even if it means copying it into a separate memory area. Returns a new reference to a Memory view object. If no copy is needed, - the memory view object points to the original memory and holds a + the memory view object points to the original memory and holds a lock on the original. If a copy is needed, then the memory view object - points to a brand-new Bytes object (and holds a memory lock on it). + points to a brand-new Bytes object (and holds a memory lock on it). buffertype PyBUF_READ buffer only needs to be read-only PyBUF_WRITE buffer needs to be writable (give error if not contiguous) - PyBUF_SHADOW buffer needs to be writable so shadow it with + PyBUF_SHADOW buffer needs to be writable so shadow it with a contiguous buffer if it is not. The view will point to the shadow buffer which can be written to and then will be copied back into the other buffer when the memory @@ -210,7 +210,7 @@ "object does not have the buffer interface"); return NULL; } - + mem = PyObject_New(PyMemoryViewObject, &PyMemoryView_Type); if (mem == NULL) return NULL; @@ -240,8 +240,8 @@ if (buffertype == PyBUF_WRITE) { PyObject_DEL(mem); PyErr_SetString(PyExc_BufferError, - "writable contiguous buffer requested for a non-contiguous" \ - "object."); + "writable contiguous buffer requested " + "for a non-contiguousobject."); return NULL; } bytes = PyBytes_FromStringAndSize(NULL, view->len); @@ -255,15 +255,15 @@ */ /* strided or in-direct copy */ if (view->suboffsets==NULL) { - _strided_copy_nd(dest, view->buf, view->ndim, view->shape, - view->strides, view->itemsize, fort); + _strided_copy_nd(dest, view->buf, view->ndim, view->shape, + view->strides, view->itemsize, fort); } else { if (_indirect_copy_nd(dest, view, fort) < 0) { Py_DECREF(bytes); PyObject_ReleaseBuffer(obj, view); return NULL; - } + } } if (buffertype == PyBUF_SHADOW) { /* return a shadowed memory-view object */ @@ -356,7 +356,7 @@ return PyInt_FromLong(self->view.ndim); } -static PyGetSetDef memory_getsetlist[] ={ +static PyGetSetDef memory_getsetlist[] ={ {"format", (getter)memory_format_get, NULL, NULL}, {"itemsize", (getter)memory_itemsize_get, NULL, NULL}, {"shape", (getter)memory_shape_get, NULL, NULL}, @@ -379,7 +379,7 @@ memory_tolist(PyMemoryViewObject *mem, PyObject *noargs) { /* This should construct a (nested) list of unpacked objects - possibly using the struct module. + possibly using the struct module. */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; @@ -403,16 +403,16 @@ with buffer interface and the second element is a contiguous "shadow" that must be copied back into the data areay of the first tuple element before - releasing the buffer on the first element. + releasing the buffer on the first element. */ - + PyObject_CopyData(PyTuple_GET_ITEM(self->base,0), PyTuple_GET_ITEM(self->base,1)); /* The view member should have readonly == -1 in this instance indicating that the memory can be "locked" and was locked and will be unlocked - again after this call. + again after this call. */ PyObject_ReleaseBuffer(PyTuple_GET_ITEM(self->base,0), &(self->view)); @@ -444,7 +444,7 @@ if (PyObject_GetBuffer((PyObject *)self, &view, PyBUF_FULL) < 0) return NULL; - + res = PyBytes_FromStringAndSize(NULL, view.len); PyBuffer_ToContiguous(PyBytes_AS_STRING(res), &view, view.len, 'C'); PyObject_ReleaseBuffer((PyObject *)self, &view); @@ -464,13 +464,13 @@ return view.len; } -/* +/* mem[obj] returns a bytes object holding the data for one element if obj fully indexes the memory view or another memory-view object if it does not. - + 0-d memory-view objects can be referenced using ... or () but - not with anything else. + not with anything else. */ static PyObject * memory_subscript(PyMemoryViewObject *self, PyObject *key) @@ -485,7 +485,8 @@ return (PyObject *)self; } else { - PyErr_SetString(PyExc_IndexError, "invalid indexing of 0-dim memory"); + PyErr_SetString(PyExc_IndexError, + "invalid indexing of 0-dim memory"); return NULL; } } @@ -498,23 +499,25 @@ /* Return a bytes object */ char *ptr; ptr = (char *)view->buf; - if (view->strides == NULL) + if (view->strides == NULL) ptr += view->itemsize * result; else ptr += view->strides[0] * result; - if (view->suboffsets != NULL && view->suboffsets[0] >= 0) { + if (view->suboffsets != NULL && + view->suboffsets[0] >= 0) + { ptr = *((char **)ptr) + view->suboffsets[0]; } return PyBytes_FromStringAndSize(ptr, view->itemsize); } else { - /* Return a new memory-view object */ + /* Return a new memory-view object */ Py_buffer newview; PyMemoryView_FromMemory(&newview); } } - - + + Py_INCREF(Py_NotImplemented); return Py_NotImplemented; @@ -570,7 +573,7 @@ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ - memory_methods, /* tp_methods */ + memory_methods, /* tp_methods */ 0, /* tp_members */ memory_getsetlist, /* tp_getset */ 0, /* tp_base */ From python-3000-checkins at python.org Wed Sep 26 03:10:12 2007 From: python-3000-checkins at python.org (skip.montanaro) Date: Wed, 26 Sep 2007 03:10:12 +0200 (CEST) Subject: [Python-3000-checkins] r58256 - python/branches/py3k/Doc/tutorial/inputoutput.rst Message-ID: <20070926011012.E1C691E4008@bag.python.org> Author: skip.montanaro Date: Wed Sep 26 03:10:12 2007 New Revision: 58256 Modified: python/branches/py3k/Doc/tutorial/inputoutput.rst Log: Clarify the difference between text and binary files. I'm not sure the tutorial is the right place to mention a file object's encoding. Modified: python/branches/py3k/Doc/tutorial/inputoutput.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/inputoutput.rst (original) +++ python/branches/py3k/Doc/tutorial/inputoutput.rst Wed Sep 26 03:10:12 2007 @@ -197,14 +197,20 @@ writing. The *mode* argument is optional; ``'r'`` will be assumed if it's omitted. -On Windows and the Macintosh, ``'b'`` appended to the mode opens the file in -binary mode, so there are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. -Windows makes a distinction between text and binary files; the end-of-line -characters in text files are automatically altered slightly when data is read or -written. This behind-the-scenes modification to file data is fine for ASCII -text files, but it'll corrupt binary data like that in :file:`JPEG` or -:file:`EXE` files. Be very careful to use binary mode when reading and writing -such files. +``'b'`` appended to the mode opens the file in binary mode, so there are +also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. Python distinguishes +between text and binary files. Binary files are read and written without +any data transformation. In text mode, platform-specific newline +representations are automatically converted to newlines when read and +newline characters are automatically converted to the proper +platform-specific representation when written. This makes writing portable +code which reads or writes text files easier. In addition, when reading +from or writing to text files, the data are automatically decoded or +encoding, respectively, using the encoding associated with the file. + +This behind-the-scenes modification to file data is fine for text files, but +will corrupt binary data like that in :file:`JPEG` or :file:`EXE` files. Be +very careful to use binary mode when reading and writing such files. .. _tut-filemethods: From python-3000-checkins at python.org Wed Sep 26 22:43:50 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Wed, 26 Sep 2007 22:43:50 +0200 (CEST) Subject: [Python-3000-checkins] r58260 - in python/branches/py3k-importlib: NEWS Python/import.c Message-ID: <20070926204350.ED9C71E400B@bag.python.org> Author: brett.cannon Date: Wed Sep 26 22:43:50 2007 New Revision: 58260 Modified: python/branches/py3k-importlib/NEWS python/branches/py3k-importlib/Python/import.c Log: Add imp._case_ok(). Also refactor PyImport_Importlib() to use less boilerplate. Modified: python/branches/py3k-importlib/NEWS ============================================================================== --- python/branches/py3k-importlib/NEWS (original) +++ python/branches/py3k-importlib/NEWS Wed Sep 26 22:43:50 2007 @@ -1,6 +1,9 @@ +* Add _case_ok() to imp. + * Add _PyImport_Importlib() to import _importlib. This also involves importing - sys, imp, marshal and _os (which can be either nt, os2, or posix; reason why - PyOS_MODNAME and PyOS_INITFUNC have been added). + errno, sys, imp, marshal and _os (which can be either nt, os2, or posix; + reason why PyOS_MODNAME and PyOS_INITFUNC have been added). Also inject SEP + as path_sep into _importlib. * Add Py_GetImportlibPath() as a way to get the path to _importlib. Modified: python/branches/py3k-importlib/Python/import.c ============================================================================== --- python/branches/py3k-importlib/Python/import.c (original) +++ python/branches/py3k-importlib/Python/import.c Wed Sep 26 22:43:50 2007 @@ -531,63 +531,57 @@ FILE *fp = NULL; PyCodeObject *code_object = NULL; PyObject *importlib = NULL; - PyObject *modules= NULL; - PyObject *builtin_module = NULL; + const char *builtin_modules[] = {"sys", "imp", "marshal", "errno", + PyOS_MODNAME, NULL}; + unsigned int x; + PyObject *modules_dict = NULL; + PyObject *attr = NULL; + /* _importlib must have been found. */ if (importlib_path[0] == '\0') Py_FatalError("_importlib.py not found"); - if (!init_builtin("sys")) - Py_FatalError("initializiation of sys failed"); - if (!init_builtin("imp")) - Py_FatalError("initialization of imp failed"); - if (!init_builtin("marshal")) - Py_FatalError("initialization of marshal failed"); - if (!init_builtin(PyOS_MODNAME)) - Py_FatalError("initializatino of _os failed"); - + /* Parse the module. */ fp = fopen(importlib_path, "r"); code_object = parse_source_module(importlib_path, fp); fclose(fp); - if (!code_object) Py_FatalError("unable to parse _importlib"); + /* Create the module object. */ importlib = PyImport_ExecCodeModuleEx("_importlib", (PyObject *)code_object, (char *)importlib_path); if (!importlib) Py_FatalError("could not initialize _importlib"); - modules = PyImport_GetModuleDict(); - - builtin_module = PyDict_GetItemString(modules, "sys"); - if (!builtin_module) - Py_FatalError("sys module lost"); - Py_INCREF(builtin_module); - if (PyModule_AddObject(importlib, "sys", builtin_module) < 0) - Py_FatalError("could not add sys to _importlib"); - - builtin_module = PyDict_GetItemString(modules, "imp"); - if (!builtin_module) - Py_FatalError("imp module lost"); - Py_INCREF(builtin_module); - if (PyModule_AddObject(importlib, "imp", builtin_module) < 0) - Py_FatalError("could not add imp to _importlib"); - - builtin_module = PyDict_GetItemString(modules, "marshal"); - if (!builtin_module) - Py_FatalError("mashal module lost"); - Py_INCREF(builtin_module); - if (PyModule_AddObject(importlib, "marshal", builtin_module) < 0) - Py_FatalError("could not add marshal to _importlib"); - - builtin_module = PyDict_GetItemString(modules, PyOS_MODNAME); - if (!builtin_module) - Py_FatalError("_os module lost"); - Py_INCREF(builtin_module); - if (PyModule_AddObject(importlib, "_os", builtin_module) < 0) - Py_FatalError("could not add _os to _importlib"); + /* Get sys.modules so as to extract needed built-in modules. */ + modules_dict = PyImport_GetModuleDict(); + for (x = 0; builtin_modules[x] != NULL; x += 1) { + PyObject *module; + const char *name = builtin_modules[x]; + + /* Initialize the built-in module. */ + if (!init_builtin((char *)name)) + Py_FatalError("initialization of a built-in module failed"); + /* Get the module from sys.modules. */ + module = PyDict_GetItemString(modules_dict, name); + if (!module) + Py_FatalError("built-in module lost"); + /* Add the module to _importlib's globals. */ + Py_INCREF(module); + if (PyModule_AddObject(importlib, + (strcmp(name, PyOS_MODNAME) ? name : "_os"), + module)) + Py_FatalError("could not add built-in module to _importlib"); + } + + /* Add SEP as path_sep to _importlib's globals. */ + attr = PyString_FromFormat("%c", SEP); + if (!attr) + Py_FatalError("could not create path_sep for _importlib"); + if (PyModule_AddObject(importlib, "path_sep", attr) < 0) + Py_FatalError("could not add path_sep to _importlib"); Py_DECREF(importlib); @@ -2624,6 +2618,27 @@ } static PyObject * +imp_case_ok(PyObject *self, PyObject *args) +{ + const char *path; + Py_ssize_t trimmed_path_len; + const char *module_name; + Py_ssize_t module_name_len; + int ret; + + if (!PyArg_ParseTuple(args, "sns#:imp._case_ok", &path, &trimmed_path_len, + &module_name, &module_name_len)) + return NULL; + + ret = case_ok((char *)path, trimmed_path_len, module_name_len, (char *)module_name); + + if (PyErr_Occurred()) + return NULL; + + return PyBool_FromLong(ret); +} + +static PyObject * call_find_module(char *name, PyObject *path) { extern int fclose(FILE *); @@ -2929,6 +2944,7 @@ {"find_module", imp_find_module, METH_VARARGS, doc_find_module}, {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic}, {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes}, + {"_case_ok", imp_case_ok, METH_VARARGS}, {"load_module", imp_load_module, METH_VARARGS, doc_load_module}, {"new_module", imp_new_module, METH_VARARGS, doc_new_module}, {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held}, From python-3000-checkins at python.org Thu Sep 27 20:01:23 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 27 Sep 2007 20:01:23 +0200 (CEST) Subject: [Python-3000-checkins] r58276 - in python/branches/py3k: Doc/library/stdtypes.rst Lib/test/string_tests.py Lib/test/test_descr.py Lib/test/test_unicode.py Objects/unicodeobject.c Message-ID: <20070927180123.0562A1E4016@bag.python.org> Author: guido.van.rossum Date: Thu Sep 27 20:01:22 2007 New Revision: 58276 Modified: python/branches/py3k/Doc/library/stdtypes.rst python/branches/py3k/Lib/test/string_tests.py python/branches/py3k/Lib/test/test_descr.py python/branches/py3k/Lib/test/test_unicode.py python/branches/py3k/Objects/unicodeobject.c Log: Patch # 1145 by Thomas Lee: str.join(...) now applies str() to the sequence elements if they're not strings alraedy, except for bytes, which still raise TypeError (for the same reasons why ""==b"" raises it). Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Thu Sep 27 20:01:22 2007 @@ -789,8 +789,11 @@ .. method:: str.join(seq) - Return a string which is the concatenation of the strings in the sequence *seq*. - The separator between elements is the string providing this method. + Return a string which is the concatenation of the values in the sequence + *seq*. Non-string values in *seq* will be converted to a string using their + respective ``str()`` value. If there are any :class:`bytes` objects in + *seq*, a :exc:`TypeError` will be raised. The separator between elements is + the string providing this method. .. method:: str.ljust(width[, fillchar]) Modified: python/branches/py3k/Lib/test/string_tests.py ============================================================================== --- python/branches/py3k/Lib/test/string_tests.py (original) +++ python/branches/py3k/Lib/test/string_tests.py Thu Sep 27 20:01:22 2007 @@ -13,6 +13,7 @@ class BadSeq1(Sequence): def __init__(self): self.seq = [7, 'hello', 123] + def __str__(self): return '{0} {1} {2}'.format(*self.seq) class BadSeq2(Sequence): def __init__(self): self.seq = ['a', 'b', 'c'] @@ -987,19 +988,19 @@ self.checkequal('abc', 'a', 'join', ('abc',)) self.checkequal('z', 'a', 'join', UserList(['z'])) self.checkequal('a.b.c', '.', 'join', ['a', 'b', 'c']) - self.checkraises(TypeError, '.', 'join', ['a', 'b', 3]) + self.checkequal('a.b.3', '.', 'join', ['a', 'b', 3]) for i in [5, 25, 125]: self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join', ['a' * i] * i) self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join', ('a' * i,) * i) - self.checkraises(TypeError, ' ', 'join', BadSeq1()) + self.checkequal(str(BadSeq1()), ' ', 'join', BadSeq1()) self.checkequal('a b c', ' ', 'join', BadSeq2()) self.checkraises(TypeError, ' ', 'join') self.checkraises(TypeError, ' ', 'join', 7) - self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123])) + self.checkraises(TypeError, ' ', 'join', [1, 2, bytes()]) try: def f(): yield 4 + "" Modified: python/branches/py3k/Lib/test/test_descr.py ============================================================================== --- python/branches/py3k/Lib/test/test_descr.py (original) +++ python/branches/py3k/Lib/test/test_descr.py Thu Sep 27 20:01:22 2007 @@ -3238,10 +3238,6 @@ except ValueError: pass else: raise TestFailed("''.split('') doesn't raise ValueError") - try: ''.join([0]) - except TypeError: pass - else: raise TestFailed("''.join([0]) doesn't raise TypeError") - try: ''.rindex('5') except ValueError: pass else: raise TestFailed("''.rindex('5') doesn't raise ValueError") Modified: python/branches/py3k/Lib/test/test_unicode.py ============================================================================== --- python/branches/py3k/Lib/test/test_unicode.py (original) +++ python/branches/py3k/Lib/test/test_unicode.py Thu Sep 27 20:01:22 2007 @@ -178,6 +178,10 @@ def test_join(self): string_tests.MixinStrUnicodeUserStringTest.test_join(self) + class MyWrapper: + def __init__(self, sval): self.sval = sval + def __str__(self): return self.sval + # mixed arguments self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd']) self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd')) @@ -186,6 +190,8 @@ self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd']) self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd')) self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz')) + self.checkequalnofix('1 2 foo', ' ', 'join', [1, 2, MyWrapper('foo')]) + self.checkraises(TypeError, ' ', 'join', [1, 2, 3, bytes()]) def test_replace(self): string_tests.CommonTest.test_replace(self) Modified: python/branches/py3k/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k/Objects/unicodeobject.c (original) +++ python/branches/py3k/Objects/unicodeobject.c Thu Sep 27 20:01:22 2007 @@ -5412,14 +5412,20 @@ item = PySequence_Fast_GET_ITEM(fseq, i); /* Convert item to Unicode. */ - if (! PyUnicode_Check(item) && ! PyString_Check(item)) { - PyErr_Format(PyExc_TypeError, - "sequence item %zd: expected string or Unicode," - " %.80s found", - i, Py_Type(item)->tp_name); - goto onError; + if (!PyString_Check(item) && !PyUnicode_Check(item)) + { + if (PyBytes_Check(item)) + { + PyErr_Format(PyExc_TypeError, + "sequence item %d: join() will not operate on " + "bytes objects", i); + goto onError; + } + item = PyObject_Unicode(item); } - item = PyUnicode_FromObject(item); + else + item = PyUnicode_FromObject(item); + if (item == NULL) goto onError; /* We own a reference to item from here on. */ From python-3000-checkins at python.org Thu Sep 27 23:28:21 2007 From: python-3000-checkins at python.org (collin.winter) Date: Thu, 27 Sep 2007 23:28:21 +0200 (CEST) Subject: [Python-3000-checkins] r58278 - python/branches/py3k/Doc/tutorial/errors.rst Message-ID: <20070927212821.45D4E1E400D@bag.python.org> Author: collin.winter Date: Thu Sep 27 23:28:21 2007 New Revision: 58278 Modified: python/branches/py3k/Doc/tutorial/errors.rst Log: Revert r58075 (incorrect docs patch). Modified: python/branches/py3k/Doc/tutorial/errors.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/errors.rst (original) +++ python/branches/py3k/Doc/tutorial/errors.rst Thu Sep 27 23:28:21 2007 @@ -115,9 +115,9 @@ handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same :keyword:`try` statement. An except clause may -name multiple exceptions as a tuple, for example:: +name multiple exceptions as a parenthesized tuple, for example:: - ... except RuntimeError, TypeError, NameError: + ... except (RuntimeError, TypeError, NameError): ... pass The last except clause may omit the exception name(s), to serve as a wildcard. From python-3000-checkins at python.org Fri Sep 28 00:39:13 2007 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 28 Sep 2007 00:39:13 +0200 (CEST) Subject: [Python-3000-checkins] r58279 - python/branches/py3k/Tools/scripts/byext.py Message-ID: <20070927223913.1701D1E400D@bag.python.org> Author: guido.van.rossum Date: Fri Sep 28 00:39:12 2007 New Revision: 58279 Modified: python/branches/py3k/Tools/scripts/byext.py Log: Make byext.py really work. Modified: python/branches/py3k/Tools/scripts/byext.py ============================================================================== --- python/branches/py3k/Tools/scripts/byext.py (original) +++ python/branches/py3k/Tools/scripts/byext.py Fri Sep 28 00:39:12 2007 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3.0 """Show file statistics by extension.""" @@ -60,13 +60,13 @@ data = f.read() f.close() self.addstats(ext, "bytes", len(data)) - if '\0' in data: + if b'\0' in data: self.addstats(ext, "binary", 1) return if not data: self.addstats(ext, "empty", 1) #self.addstats(ext, "chars", len(data)) - lines = data.splitlines() + lines = str(data, "latin-1").splitlines() self.addstats(ext, "lines", len(lines)) del lines words = data.split() @@ -77,14 +77,12 @@ d[key] = d.get(key, 0) + n def report(self): - exts = self.stats.keys() - exts.sort() + exts = sorted(self.stats) # Get the column keys columns = {} for ext in exts: columns.update(self.stats[ext]) - cols = columns.keys() - cols.sort() + cols = sorted(columns) colwidth = {} colwidth["ext"] = max([len(ext) for ext in exts]) minwidth = 6 From python-3000-checkins at python.org Fri Sep 28 15:13:35 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Fri, 28 Sep 2007 15:13:35 +0200 (CEST) Subject: [Python-3000-checkins] r58281 - in python/branches/py3k/Doc: ACKS.txt tutorial/classes.rst tutorial/interpreter.rst tutorial/introduction.rst Message-ID: <20070928131335.D381E1E400D@bag.python.org> Author: georg.brandl Date: Fri Sep 28 15:13:35 2007 New Revision: 58281 Modified: python/branches/py3k/Doc/ACKS.txt python/branches/py3k/Doc/tutorial/classes.rst python/branches/py3k/Doc/tutorial/interpreter.rst python/branches/py3k/Doc/tutorial/introduction.rst Log: #1211, #1212, #1213: py3k fixes to the tutorial. Modified: python/branches/py3k/Doc/ACKS.txt ============================================================================== --- python/branches/py3k/Doc/ACKS.txt (original) +++ python/branches/py3k/Doc/ACKS.txt Fri Sep 28 15:13:35 2007 @@ -65,6 +65,7 @@ * Harald Hanche-Olsen * Manus Hand * Gerhard H?ring +* Peter Harris * Travis B. Hartwell * Tim Hatch * Janko Hauser Modified: python/branches/py3k/Doc/tutorial/classes.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/classes.rst (original) +++ python/branches/py3k/Doc/tutorial/classes.rst Fri Sep 28 15:13:35 2007 @@ -473,8 +473,8 @@ Multiple Inheritance -------------------- -Python supports a limited form of multiple inheritance as well. A class -definition with multiple base classes looks like this:: +Python supports a form of multiple inheritance as well. A class definition with +multiple base classes looks like this:: class DerivedClassName(Base1, Base2, Base3): @@ -483,15 +483,18 @@ . -Formerly, the only rule was depth-first, left-to-right. Thus, if an attribute -was not found in :class:`DerivedClassName`, it was searched in :class:`Base1`, -then (recursively) in the base classes of :class:`Base1`, and only if it was not -found there, it was searched in :class:`Base2`, and so on. - -In the meantime, the method resolution order changes dynamically to support -cooperative calls to :func:`super`. This approach is known in some other -multiple-inheritance languages as call-next-method and is more powerful than the -super call found in single-inheritance languages. +For most purposes, in the simplest cases, you can think of the search for +attributes inherited from a parent class as depth-first, left-to-right, not +searching twice in the same class where there is an overlap in the hierarchy. +Thus, if an attribute is not found in :class:`DerivedClassName`, it is searched +for in :class:`Base1`, then (recursively) in the base classes of :class:`Base1`, +and if it was not found there, it was searched for in :class:`Base2`, and so on. + +In fact, it is slightly more complex than that; the method resolution order +changes dynamically to support cooperative calls to :func:`super`. This +approach is known in some other multiple-inheritance languages as +call-next-method and is more powerful than the super call found in +single-inheritance languages. Dynamic ordering is necessary because all cases of multiple inheritance exhibit one or more diamond relationships (where one at least one of the parent classes Modified: python/branches/py3k/Doc/tutorial/interpreter.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/interpreter.rst (original) +++ python/branches/py3k/Doc/tutorial/interpreter.rst Fri Sep 28 15:13:35 2007 @@ -101,11 +101,14 @@ prints a welcome message stating its version number and a copyright notice before printing the first prompt:: - python - Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5 - Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam + $ python + Python 3.0a1 (py3k, Sep 12 2007, 12:21:02) + [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2 + Type "help", "copyright", "credits" or "license" for more information. >>> +.. XXX update for final release of Python 3.0 + Continuation lines are needed when entering a multi-line construct. As an example, take a look at this :keyword:`if` statement:: @@ -170,44 +173,32 @@ Source Code Encoding -------------------- -.. XXX out of date! - -It is possible to use encodings different than ASCII in Python source files. The -best way to do it is to put one more special comment line right after the ``#!`` -line to define the source file encoding:: +By default, Python source files are treated as encoded in UTF-8. In that +encoding, characters of most languages in the world can be used simultaneously +in string literals, identifiers and comments --- although the standard library +only uses ASCII characters for identifiers, a convention that any portable code +should follow. To display all these characters properly, your editor must +recognize that the file is UTF-8, and it must use a font that supports all the +characters in the file. + +It is also possible to specify a different encoding for source files. In order +to do this, put one more special comment line right after the ``#!`` line to +define the source file encoding:: # -*- coding: encoding -*- - -With that declaration, all characters in the source file will be treated as -having the encoding *encoding*, and it will be possible to directly write -Unicode string literals in the selected encoding. The list of possible -encodings can be found in the Python Library Reference, in the section on -:mod:`codecs`. - -For example, to write Unicode literals including the Euro currency symbol, the -ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value -164. This script will print the value 8364 (the Unicode codepoint corresponding -to the Euro symbol) and then exit:: - - # -*- coding: iso-8859-15 -*- - - currency = u"?" - print(ord(currency)) - -If your editor supports saving files as ``UTF-8`` with a UTF-8 *byte order mark* -(aka BOM), you can use that instead of an encoding declaration. IDLE supports -this capability if ``Options/General/Default Source Encoding/UTF-8`` is set. -Notice that this signature is not understood in older Python releases (2.2 and -earlier), and also not understood by the operating system for script files with -``#!`` lines (only used on Unix systems). - -By using UTF-8 (either through the signature or an encoding declaration), -characters of most languages in the world can be used simultaneously in string -literals and comments. Using non-ASCII characters in identifiers is not -supported. To display all these characters properly, your editor must recognize -that the file is UTF-8, and it must use a font that supports all the characters -in the file. +With that declaration, everything in the source file will be treated as having +the encoding *encoding* instead of UTF-8. The list of possible encodings can be +found in the Python Library Reference, in the section on :mod:`codecs`. + +For example, if your editor of choice does not support UTF-8 encoded files and +insists on using some other encoding, say Windows-1252, you can write:: + + # -*- coding: cp-1252 -*- + +and still use all characters in the Windows-1252 character set in the source +files. The special encoding comment must be in the *first or second* line +within the file. .. _tut-startup: Modified: python/branches/py3k/Doc/tutorial/introduction.rst ============================================================================== --- python/branches/py3k/Doc/tutorial/introduction.rst (original) +++ python/branches/py3k/Doc/tutorial/introduction.rst Fri Sep 28 15:13:35 2007 @@ -131,9 +131,9 @@ 0.5 The conversion functions to floating point and integer (:func:`float`, -:func:`int` and :func:`long`) don't work for complex numbers --- there is no one -correct way to convert a complex number to a real number. Use ``abs(z)`` to get -its magnitude (as a float) or ``z.real`` to get its real part. :: +:func:`int`) don't work for complex numbers --- there is not one correct way to +convert a complex number to a real number. Use ``abs(z)`` to get its magnitude +(as a float) or ``z.real`` to get its real part:: >>> a=3.0+4.0j >>> float(a) From python-3000-checkins at python.org Fri Sep 28 15:39:26 2007 From: python-3000-checkins at python.org (georg.brandl) Date: Fri, 28 Sep 2007 15:39:26 +0200 (CEST) Subject: [Python-3000-checkins] r58282 - python/branches/py3k/Doc/library/stdtypes.rst Message-ID: <20070928133926.1B53D1E400D@bag.python.org> Author: georg.brandl Date: Fri Sep 28 15:39:25 2007 New Revision: 58282 Modified: python/branches/py3k/Doc/library/stdtypes.rst Log: #1219: py3k cleanup in standard types docs. Modified: python/branches/py3k/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k/Doc/library/stdtypes.rst (original) +++ python/branches/py3k/Doc/library/stdtypes.rst Fri Sep 28 15:39:25 2007 @@ -10,13 +10,6 @@ The following sections describe the standard types that are built into the interpreter. -.. note:: - - Historically (until release 2.2), Python's built-in types have differed from - user-defined types because it was not possible to use the built-in types as the - basis for object-oriented inheritance. This limitation no longer - exists. - .. index:: pair: built-in; types The principal built-in types are numerics, sequences, mappings, files, classes, @@ -129,8 +122,8 @@ .. index:: pair: chaining; comparisons -Comparison operations are supported by all objects. They all have the same -priority (which is higher than that of the Boolean operations). Comparisons can +There are eight comparison operations in Python. They all have the same +priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and y <= z``, except that *y* is evaluated only once (but in both cases *z* is not evaluated at all when ``x < y`` is found to be false). @@ -172,24 +165,35 @@ pair: object; numeric pair: objects; comparing -Objects of different types, except different numeric types and different string -types, never compare equal; such objects are ordered consistently but -arbitrarily (so that sorting a heterogeneous array yields a consistent result). +Objects of different types, except different numeric types, never compare equal. Furthermore, some types (for example, file objects) support only a degenerate -notion of comparison where any two objects of that type are unequal. Again, -such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>`` -and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is -a complex number. - -.. index:: single: __cmp__() (instance method) +notion of comparison where any two objects of that type are unequal. The ``<``, +``<=``, ``>`` and ``>=`` operators will raise a :exc:`TypeError` exception when +any operand is a complex number, the objects are of different types that cannot +be compared, or other cases where there is no defined ordering. + +.. index:: + single: __cmp__() (instance method) + single: __eq__() (instance method) + single: __ne__() (instance method) + single: __lt__() (instance method) + single: __le__() (instance method) + single: __gt__() (instance method) + single: __ge__() (instance method) Instances of a class normally compare as non-equal unless the class defines the -:meth:`__cmp__` method. Refer to :ref:`customization`) for information on the -use of this method to effect object comparisons. +:meth:`__eq__` or :meth:`__cmp__` method. -**Implementation note:** Objects of different types except numbers are ordered -by their type names; objects of the same types that don't support proper -comparison are ordered by their address. +Instances of a class cannot be ordered with respect to other instances of the +same class, or other types of object, unless the class defines enough of the +methods :meth:`__cmp__`, :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and +:meth:`__ge__` (in general, either :meth:`__cmp__` or both :meth:`__lt__` and +:meth:`__eq__` are sufficient, if you want the conventional meanings of the +comparison operators). + +The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be +customized; also they can be applied to any two objects and never raise an +exception. .. index:: operator: in @@ -201,27 +205,22 @@ .. _typesnumeric: -Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex` -=============================================================================== +Numeric Types --- :class:`int`, :class:`float`, :class:`complex` +================================================================ .. index:: object: numeric object: Boolean object: integer - object: long integer object: floating point object: complex number pair: C; language -There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long -integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In -addition, Booleans are a subtype of plain integers. Plain integers (also just -called :dfn:`integers`) are implemented using :ctype:`long` in C, which gives -them at least 32 bits of precision (``sys.maxint`` is always set to the maximum -plain integer value for the current platform, the minimum value is -``-sys.maxint - 1``). Long integers have unlimited precision. Floating point -numbers are implemented using :ctype:`double` in C. All bets on their precision -are off unless you happen to know the machine you are working with. +There are three distinct numeric types: :dfn:`integers`, :dfn:`floating point +numbers`, and :dfn:`complex numbers`. In addition, Booleans are a subtype of +plain integers. Integers have unlimited precision. loating point numbers are +implemented using :ctype:`double` in C. All bets on their precision are off +unless you happen to know the machine you are working with. Complex numbers have a real and imaginary part, which are each implemented using :ctype:`double` in C. To extract these parts from a complex number *z*, use @@ -230,21 +229,19 @@ .. index:: pair: numeric; literals pair: integer; literals - triple: long; integer; literals pair: floating point; literals pair: complex number; literals pair: hexadecimal; literals pair: octal; literals + pair: binary: literals Numbers are created by numeric literals or as the result of built-in functions -and operators. Unadorned integer literals (including hex and octal numbers) -yield plain integers unless the value they denote is too large to be represented -as a plain integer, in which case they yield a long integer. Integer literals -with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'`` is preferred -because ``1l`` looks too much like eleven!). Numeric literals containing a -decimal point or an exponent sign yield floating point numbers. Appending -``'j'`` or ``'J'`` to a numeric literal yields a complex number with a zero real -part. A complex numeric literal is the sum of a real and an imaginary part. +and operators. Unadorned integer literals (including hex, octal and binary +numbers) yield integers. Numeric literals containing a decimal point or an +exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a +numeric literal yields an imaginary number (a complex number with a zero real +part) which you can add to an integer or float to get a complex number with real +and imaginary parts. .. index:: single: arithmetic @@ -255,58 +252,55 @@ Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the "narrower" type is -widened to that of the other, where plain integer is narrower than long integer -is narrower than floating point is narrower than complex. Comparisons between -numbers of mixed type use the same rule. [#]_ The constructors :func:`int`, -:func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers -of a specific type. +widened to that of the other, where integer is narrower than floating point, +which is narrower than complex. Comparisons between numbers of mixed type use +the same rule. [#]_ The constructors :func:`int`, :func:`float`, and +:func:`complex` can be used to produce numbers of a specific type. All numeric types (except complex) support the following operations, sorted by ascending priority (operations in the same box have the same priority; all numeric operations have a higher priority than comparison operations): -+--------------------+---------------------------------+--------+ -| Operation | Result | Notes | -+====================+=================================+========+ -| ``x + y`` | sum of *x* and *y* | | -+--------------------+---------------------------------+--------+ -| ``x - y`` | difference of *x* and *y* | | -+--------------------+---------------------------------+--------+ -| ``x * y`` | product of *x* and *y* | | -+--------------------+---------------------------------+--------+ -| ``x / y`` | quotient of *x* and *y* | \(1) | -+--------------------+---------------------------------+--------+ -| ``x // y`` | (floored) quotient of *x* and | \(5) | -| | *y* | | -+--------------------+---------------------------------+--------+ -| ``x % y`` | remainder of ``x / y`` | \(4) | -+--------------------+---------------------------------+--------+ -| ``-x`` | *x* negated | | -+--------------------+---------------------------------+--------+ -| ``+x`` | *x* unchanged | | -+--------------------+---------------------------------+--------+ -| ``abs(x)`` | absolute value or magnitude of | | -| | *x* | | -+--------------------+---------------------------------+--------+ -| ``int(x)`` | *x* converted to integer | \(2) | -+--------------------+---------------------------------+--------+ -| ``long(x)`` | *x* converted to long integer | \(2) | -+--------------------+---------------------------------+--------+ -| ``float(x)`` | *x* converted to floating point | | -+--------------------+---------------------------------+--------+ -| ``complex(re,im)`` | a complex number with real part | | -| | *re*, imaginary part *im*. | | -| | *im* defaults to zero. | | -+--------------------+---------------------------------+--------+ -| ``c.conjugate()`` | conjugate of the complex number | | -| | *c* | | -+--------------------+---------------------------------+--------+ -| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) | -+--------------------+---------------------------------+--------+ -| ``pow(x, y)`` | *x* to the power *y* | | -+--------------------+---------------------------------+--------+ -| ``x ** y`` | *x* to the power *y* | | -+--------------------+---------------------------------+--------+ ++---------------------+---------------------------------+-------+--------------------+ +| Operation | Result | Notes | Full documentation | ++==================== +=================================+=======+====================| +| ``x + y`` | sum of *x* and *y* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``x - y`` | difference of *x* and *y* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``x * y`` | product of *x* and *y* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``x / y`` | quotient of *x* and *y* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``x // y`` | floored quotient of *x* and | \(1) | | +| | *y* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``x % y`` | remainder of ``x / y`` | \(2) | | ++---------------------+---------------------------------+-------+--------------------+ +| ``-x`` | *x* negated | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``+x`` | *x* unchanged | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``abs(x)`` | absolute value or magnitude of | | :func:`abs` | +| | *x* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``int(x)`` | *x* converted to integer | \(3) | :func:`int` | ++---------------------+---------------------------------+-------+--------------------+ +| ``float(x)`` | *x* converted to floating point | | :func:`float` | ++---------------------+---------------------------------+-------+--------------------+ +| ``complex(re, im)`` | a complex number with real part | | :func:`complex` | +| | *re*, imaginary part *im*. | | | +| | *im* defaults to zero. | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``c.conjugate()`` | conjugate of the complex number | | | +| | *c* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` | ++---------------------+---------------------------------+-------+--------------------+ +| ``pow(x, y)`` | *x* to the power *y* | | :func:`pow` | ++---------------------+---------------------------------+-------+--------------------+ +| ``x ** y`` | *x* to the power *y* | | | ++---------------------+---------------------------------+-------+--------------------+ .. index:: triple: operations on; numeric; types @@ -315,16 +309,16 @@ Notes: (1) - .. index:: - pair: integer; division - triple: long; integer; division - - For (plain or long) integer division, the result is an integer. The result is - always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and - (-1)/(-2) is 0. Note that the result is a long integer if either operand is a - long integer, regardless of the numeric value. + Also referred to as integer division. The resultant value is a whole + integer, though the result's type is not necessarily int. The result is + always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is + ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``. (2) + Not for complex numbers. Instead convert to floats using :func:`abs` if + appropriate. + +(3) .. index:: module: math single: floor() (in module math) @@ -336,19 +330,6 @@ as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module for well-defined conversions. -(3) - See :ref:`built-in-funcs` for a full description. - -(4) - Complex floor division operator, modulo operator, and :func:`divmod`. - - .. deprecated:: 2.3 - Instead convert to float using :func:`abs` if appropriate. - -(5) - Also referred to as integer division. The resultant value is a whole integer, - though the result's type is not necessarily int. - .. % XXXJH exceptions: overflow (when? what operations?) zerodivision @@ -359,10 +340,9 @@ .. _bit-string-operations: -Plain and long integer types support additional operations that make sense only -for bit-strings. Negative numbers are treated as their 2's complement value -(for long integers, this assumes a sufficiently large number of bits that no -overflow occurs during the operation). +Integers support additional operations that make sense only for bit-strings. +Negative numbers are treated as their 2's complement value (this assumes a +sufficiently large number of bits that no overflow occurs during the operation). The priorities of the binary bit-wise operations are all lower than the numeric operations and higher than the comparisons; the unary operation ``~`` has the @@ -453,7 +433,7 @@ Python objects in the Python/C API. -.. method:: iterator.next() +.. method:: iterator.__next__() Return the next item from the container. If there are no further items, raise the :exc:`StopIteration` exception. This method corresponds to the @@ -465,11 +445,9 @@ specific types are not important beyond their implementation of the iterator protocol. -The intention of the protocol is that once an iterator's :meth:`__next__` method -raises :exc:`StopIteration`, it will continue to do so on subsequent calls. -Implementations that do not obey this property are deemed broken. (This -constraint was added in Python 2.3; in Python 2.2, various iterators are broken -according to this rule.) +Once an iterator's :meth:`__next__` method raises :exc:`StopIteration`, it must +continue to do so on subsequent calls. Implementations that do not obey this +property are deemed broken. Python's generators provide a convenient way to implement the iterator protocol. If a container object's :meth:`__iter__` method is implemented as a generator, @@ -1140,13 +1118,9 @@ decimal point and defaults to 6. (5) - The ``%r`` conversion was added in Python 2.0. - The precision determines the maximal number of characters used. - The precision determines the maximal number of characters used. - Since Python strings have an explicit length, ``%s`` conversions do not assume that ``'\0'`` is the end of the string. @@ -1164,8 +1138,8 @@ .. _typesseq-range: -XRange Type ------------ +Range Type +---------- .. index:: object: range @@ -1174,7 +1148,7 @@ object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages. -XRange objects have very little behavior: they only support indexing, iteration, +Range objects have very little behavior: they only support indexing, iteration, and the :func:`len` function. From python-3000-checkins at python.org Sat Sep 29 08:53:03 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Sat, 29 Sep 2007 08:53:03 +0200 (CEST) Subject: [Python-3000-checkins] r58285 - in python/branches/py3k-importlib: NEWS Python/marshal.c Message-ID: <20070929065303.5E4471E4002@bag.python.org> Author: brett.cannon Date: Sat Sep 29 08:53:02 2007 New Revision: 58285 Modified: python/branches/py3k-importlib/NEWS python/branches/py3k-importlib/Python/marshal.c Log: Ditch own implementation for _r_long and _w_long for ones that 'marshal' has. Modified: python/branches/py3k-importlib/NEWS ============================================================================== --- python/branches/py3k-importlib/NEWS (original) +++ python/branches/py3k-importlib/NEWS Sat Sep 29 08:53:02 2007 @@ -1,3 +1,5 @@ +* Add _r_long() and _w_long() to marshal. + * Add _case_ok() to imp. * Add _PyImport_Importlib() to import _importlib. This also involves importing Modified: python/branches/py3k-importlib/Python/marshal.c ============================================================================== --- python/branches/py3k-importlib/Python/marshal.c (original) +++ python/branches/py3k-importlib/Python/marshal.c Sat Sep 29 08:53:02 2007 @@ -1230,11 +1230,76 @@ return result; } +static PyObject * +marshal_r_long(PyObject *self, PyObject *obj) +{ + RFILE rf; + PyObject *bytes; + long long_result; + PyObject *obj_result = NULL; /* Almost always used as return value. */ + + /* Get a bytes object. */ + bytes = PyBytes_FromObject(obj); + if (!bytes) + return NULL; + + /* Make sure it is the right length. */ + if (PyBytes_Size(bytes) != 4) { + PyErr_SetString(PyExc_ValueError, + "Expected bytes of length 4"); + goto exit; + } + + /* Set the RFILE to not be used as an fp. */ + rf.fp = NULL; + /* Use the bytes object as a 'char *' directly. */ + rf.ptr = PyBytes_AS_STRING(bytes); + rf.end = rf.ptr + 4; + + long_result = r_long(&rf); + + obj_result = PyInt_FromLong(long_result); + + exit: + Py_DECREF(bytes); + return obj_result; +} + +static PyObject * +marshal_w_long(PyObject *self, PyObject *obj) +{ + WFILE wf; + PyObject *bytes = NULL; + long value; + + /* Get the long value of the argument. */ + value = PyInt_AsLong(obj); + if ((value == -1) && PyErr_Occurred()) + return NULL; + + /* Create a bytes object. */ + bytes = PyBytes_FromStringAndSize("0000", 4); + if (!bytes) + return NULL; + + /* Write the long value into the bytes object. */ + wf.fp = NULL; + wf.ptr = PyBytes_AS_STRING(bytes); + wf.end = wf.ptr + 4; + + w_long(value, &wf); + + return bytes; +} + + static PyMethodDef marshal_methods[] = { {"dump", marshal_dump, METH_VARARGS}, {"load", marshal_load, METH_O}, {"dumps", marshal_dumps, METH_VARARGS}, {"loads", marshal_loads, METH_VARARGS}, + {"_r_long", marshal_r_long, METH_O}, + {"_w_long", marshal_w_long, METH_O}, {NULL, NULL} /* sentinel */ }; From python-3000-checkins at python.org Sat Sep 29 22:20:35 2007 From: python-3000-checkins at python.org (brett.cannon) Date: Sat, 29 Sep 2007 22:20:35 +0200 (CEST) Subject: [Python-3000-checkins] r58287 - in python/branches/py3k-importlib: Demo/classes/Rat.py Demo/classes/bitvec.py Doc/ACKS.txt Doc/c-api/newtypes.rst Doc/glossary.rst Doc/library/decimal.rst Doc/library/functions.rst Doc/library/stdtypes.rst Doc/tutorial/classes.rst Doc/tutorial/errors.rst Doc/tutorial/inputoutput.rst Doc/tutorial/interpreter.rst Doc/tutorial/introduction.rst Include/abstract.h Include/memoryobject.h Include/object.h Lib/distutils/fancy_getopt.py Lib/lib-tk/turtle.py Lib/test/string_tests.py Lib/test/test_descr.py Lib/test/test_unicode.py Modules/_bsddb.c Modules/_ctypes/_ctypes.c Modules/_hashopenssl.c Modules/_sre.c Modules/arraymodule.c Modules/datetimemodule.c Modules/mmapmodule.c Objects/abstract.c Objects/boolobject.c Objects/bufferobject.c Objects/bytesobject.c Objects/complexobject.c Objects/floatobject.c Objects/longobject.c Objects/memoryobject.c Objects/setobject.c Objects/stringobject.c Objects/unicodeobject.c Objects/weakrefobject.c PC/_winreg.c Parser/tokenizer.c Parser/tokenizer.h Python/getargs.c Python/marshal.c Tools/modulator/Templates/object_tp_as_number Tools/scripts/byext.py Message-ID: <20070929202035.8A8971E4005@bag.python.org> Author: brett.cannon Date: Sat Sep 29 22:20:33 2007 New Revision: 58287 Modified: python/branches/py3k-importlib/ (props changed) python/branches/py3k-importlib/Demo/classes/Rat.py python/branches/py3k-importlib/Demo/classes/bitvec.py python/branches/py3k-importlib/Doc/ACKS.txt python/branches/py3k-importlib/Doc/c-api/newtypes.rst python/branches/py3k-importlib/Doc/glossary.rst python/branches/py3k-importlib/Doc/library/decimal.rst python/branches/py3k-importlib/Doc/library/functions.rst python/branches/py3k-importlib/Doc/library/stdtypes.rst python/branches/py3k-importlib/Doc/tutorial/classes.rst python/branches/py3k-importlib/Doc/tutorial/errors.rst python/branches/py3k-importlib/Doc/tutorial/inputoutput.rst python/branches/py3k-importlib/Doc/tutorial/interpreter.rst python/branches/py3k-importlib/Doc/tutorial/introduction.rst python/branches/py3k-importlib/Include/abstract.h python/branches/py3k-importlib/Include/memoryobject.h python/branches/py3k-importlib/Include/object.h python/branches/py3k-importlib/Lib/distutils/fancy_getopt.py python/branches/py3k-importlib/Lib/lib-tk/turtle.py python/branches/py3k-importlib/Lib/test/string_tests.py python/branches/py3k-importlib/Lib/test/test_descr.py python/branches/py3k-importlib/Lib/test/test_unicode.py python/branches/py3k-importlib/Modules/_bsddb.c python/branches/py3k-importlib/Modules/_ctypes/_ctypes.c python/branches/py3k-importlib/Modules/_hashopenssl.c python/branches/py3k-importlib/Modules/_sre.c python/branches/py3k-importlib/Modules/arraymodule.c python/branches/py3k-importlib/Modules/datetimemodule.c python/branches/py3k-importlib/Modules/mmapmodule.c python/branches/py3k-importlib/Objects/abstract.c python/branches/py3k-importlib/Objects/boolobject.c python/branches/py3k-importlib/Objects/bufferobject.c python/branches/py3k-importlib/Objects/bytesobject.c python/branches/py3k-importlib/Objects/complexobject.c python/branches/py3k-importlib/Objects/floatobject.c python/branches/py3k-importlib/Objects/longobject.c python/branches/py3k-importlib/Objects/memoryobject.c python/branches/py3k-importlib/Objects/setobject.c python/branches/py3k-importlib/Objects/stringobject.c python/branches/py3k-importlib/Objects/unicodeobject.c python/branches/py3k-importlib/Objects/weakrefobject.c python/branches/py3k-importlib/PC/_winreg.c python/branches/py3k-importlib/Parser/tokenizer.c python/branches/py3k-importlib/Parser/tokenizer.h python/branches/py3k-importlib/Python/getargs.c python/branches/py3k-importlib/Python/marshal.c python/branches/py3k-importlib/Tools/modulator/Templates/object_tp_as_number python/branches/py3k-importlib/Tools/scripts/byext.py Log: Merged revisions 58223-58286 via svnmerge from svn+ssh://pythondev at svn.python.org/python/branches/py3k Modified: python/branches/py3k-importlib/Demo/classes/Rat.py ============================================================================== --- python/branches/py3k-importlib/Demo/classes/Rat.py (original) +++ python/branches/py3k-importlib/Demo/classes/Rat.py Sat Sep 29 22:20:33 2007 @@ -226,10 +226,6 @@ def __bool__(a): return a.__num != 0 - # coercion - def __coerce__(a, b): - return a, Rat(b) - def test(): '''\ Test function for rat module. Modified: python/branches/py3k-importlib/Demo/classes/bitvec.py ============================================================================== --- python/branches/py3k-importlib/Demo/classes/bitvec.py (original) +++ python/branches/py3k-importlib/Demo/classes/bitvec.py Sat Sep 29 22:20:33 2007 @@ -311,13 +311,6 @@ return BitVec(~self._data & ((1 << self._len) - 1), \ self._len) - def __coerce__(self, otherseq, *rest): - #needed for *some* of the arithmetic operations - #rprt('%r.__coerce__%r\n' % (self, (otherseq,) + rest)) - if type(otherseq) != type(self): - otherseq = bitvec(otherseq, *rest) - return self, otherseq - def __int__(self): return int(self._data) Modified: python/branches/py3k-importlib/Doc/ACKS.txt ============================================================================== --- python/branches/py3k-importlib/Doc/ACKS.txt (original) +++ python/branches/py3k-importlib/Doc/ACKS.txt Sat Sep 29 22:20:33 2007 @@ -65,6 +65,7 @@ * Harald Hanche-Olsen * Manus Hand * Gerhard H?ring +* Peter Harris * Travis B. Hartwell * Tim Hatch * Janko Hauser Modified: python/branches/py3k-importlib/Doc/c-api/newtypes.rst ============================================================================== --- python/branches/py3k-importlib/Doc/c-api/newtypes.rst (original) +++ python/branches/py3k-importlib/Doc/c-api/newtypes.rst Sat Sep 29 22:20:33 2007 @@ -330,7 +330,7 @@ section. The fields will be described in the order in which they occur in the structure. -Typedefs: unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc, +Typedefs: unaryfunc, binaryfunc, ternaryfunc, inquiry, intargfunc, intintargfunc, intobjargproc, intintobjargproc, objobjargproc, destructor, freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc, setattrofunc, cmpfunc, reprfunc, hashfunc @@ -592,17 +592,34 @@ This field is inherited by subtypes. -.. cmember:: PyNumberMethods *tp_as_number; +.. cmember:: PyNumberMethods* tp_as_number - XXX + Pointer to an additional structure that contains fields relevant only to + objects which implement the number protocol. These fields are documented in + :ref:`number-structs`. -.. cmember:: PySequenceMethods *tp_as_sequence; + The :attr:`tp_as_number` field is not inherited, but the contained fields are + inherited individually. + + +.. cmember:: PySequenceMethods* tp_as_sequence + + Pointer to an additional structure that contains fields relevant only to + objects which implement the sequence protocol. These fields are documented + in :ref:`sequence-structs`. - XXX + The :attr:`tp_as_sequence` field is not inherited, but the contained fields + are inherited individually. -.. cmember:: PyMappingMethods *tp_as_mapping; - XXX +.. cmember:: PyMappingMethods* tp_as_mapping + + Pointer to an additional structure that contains fields relevant only to + objects which implement the mapping protocol. These fields are documented in + :ref:`mapping-structs`. + + The :attr:`tp_as_mapping` field is not inherited, but the contained fields are + inherited individually. .. cmember:: hashfunc PyTypeObject.tp_hash @@ -751,19 +768,6 @@ :attr:`sq_inplace_repeat`. - .. data:: Py_TPFLAGS_CHECKTYPES - - If this bit is set, the binary and ternary operations in the - :ctype:`PyNumberMethods` structure referenced by :attr:`tp_as_number` accept - arguments of arbitrary object types, and do their own type conversions if - needed. If this bit is clear, those operations require that all arguments have - the current type as their type, and the caller is supposed to perform a coercion - operation first. This applies to :attr:`nb_add`, :attr:`nb_subtract`, - :attr:`nb_multiply`, :attr:`nb_divide`, :attr:`nb_remainder`, :attr:`nb_divmod`, - :attr:`nb_power`, :attr:`nb_lshift`, :attr:`nb_rshift`, :attr:`nb_and`, - :attr:`nb_xor`, and :attr:`nb_or`. - - .. data:: Py_TPFLAGS_HAVE_RICHCOMPARE If this bit is set, the type object has the :attr:`tp_richcompare` field, as @@ -1414,28 +1418,106 @@ of the library. +.. _number-structs: + +Number Object Structures +======================== + +.. sectionauthor:: Amaury Forgeot d'Arc + + +.. ctype:: PyNumberMethods + + This structure holds pointers to the functions which an object uses to + implement the number protocol. Each function is used by the function of + similar name documented in the :ref:`number` section. + + Here is the structure definition:: + + typedef struct { + binaryfunc nb_add; + binaryfunc nb_subtract; + binaryfunc nb_multiply; + binaryfunc nb_remainder; + binaryfunc nb_divmod; + ternaryfunc nb_power; + unaryfunc nb_negative; + unaryfunc nb_positive; + unaryfunc nb_absolute; + inquiry nb_bool; + unaryfunc nb_invert; + binaryfunc nb_lshift; + binaryfunc nb_rshift; + binaryfunc nb_and; + binaryfunc nb_xor; + binaryfunc nb_or; + int nb_reserved; /* unused, must be zero */ + unaryfunc nb_int; + unaryfunc nb_long; + unaryfunc nb_float; + + unaryfunc nb_oct; /* not used anymore, must be zero */ + unaryfunc nb_hex; /* not used anymore, must be zero */ + + binaryfunc nb_inplace_add; + binaryfunc nb_inplace_subtract; + binaryfunc nb_inplace_multiply; + binaryfunc nb_inplace_remainder; + ternaryfunc nb_inplace_power; + binaryfunc nb_inplace_lshift; + binaryfunc nb_inplace_rshift; + binaryfunc nb_inplace_and; + binaryfunc nb_inplace_xor; + binaryfunc nb_inplace_or; + + binaryfunc nb_floor_divide; + binaryfunc nb_true_divide; + binaryfunc nb_inplace_floor_divide; + binaryfunc nb_inplace_true_divide; + + unaryfunc nb_index; + } PyNumberMethods; + + .. note:: + + Binary and ternary functions must check the type of all their operands, + and implement the necessary conversions (at least one of the operands is + an instance of the defined type). If the operation is not defined for the + given operands, binary and ternary functions must return + ``Py_NotImplemented``, if another error occurred they must return ``NULL`` + and set an exception. + + .. _mapping-structs: Mapping Object Structures ========================= +.. sectionauthor:: Amaury Forgeot d'Arc + .. ctype:: PyMappingMethods - Structure used to hold pointers to the functions used to implement the mapping - protocol for an extension type. + This structure holds pointers to the functions which an object uses to + implement the mapping protocol. It has three members: +.. cmember:: lenfunc PyMappingMethods.mp_length -.. _number-structs: + This function is used by :cfunc:`PyMapping_Length` and + :cfunc:`PyObject_Size`, and has the same signature. This slot may be set to + *NULL* if the object has no defined length. -Number Object Structures -======================== +.. cmember:: binaryfunc PyMappingMethods.mp_subscript + This function is used by :cfunc:`PyObject_GetItem` and has the same + signature. This slot must be filled for the :cfunc:`PyMapping_Check` + function to return ``1``, it can be *NULL* otherwise. -.. ctype:: PyNumberMethods +.. cmember:: objobjargproc PyMappingMethods.mp_ass_subscript - Structure used to hold pointers to the functions an extension type uses to - implement the number protocol. + This function is used by :cfunc:`PyObject_SetItem` and has the same + signature. If this slot is *NULL*, the object does not support item + assignment. .. _sequence-structs: @@ -1443,12 +1525,68 @@ Sequence Object Structures ========================== +.. sectionauthor:: Amaury Forgeot d'Arc + .. ctype:: PySequenceMethods - Structure used to hold pointers to the functions which an object uses to + This structure holds pointers to the functions which an object uses to implement the sequence protocol. +.. cmember:: lenfunc PySequenceMethods.sq_length + + This function is used by :cfunc:`PySequence_Size` and :cfunc:`PyObject_Size`, + and has the same signature. + +.. cmember:: binaryfunc PySequenceMethods.sq_concat + + This function is used by :cfunc:`PySequence_Concat` and has the same + signature. It is also used by the `+` operator, after trying the numeric + addition via the :attr:`tp_as_number.nb_add` slot. + +.. cmember:: ssizeargfunc PySequenceMethods.sq_repeat + + This function is used by :cfunc:`PySequence_Repeat` and has the same + signature. It is also used by the `*` operator, after trying numeric + multiplication via the :attr:`tp_as_number.nb_mul` slot. + +.. cmember:: ssizeargfunc PySequenceMethods.sq_item + + This function is used by :cfunc:`PySequence_GetItem` and has the same + signature. This slot must be filled for the :cfunc:`PySequence_Check` + function to return ``1``, it can be *NULL* otherwise. + + Negative indexes are handled as follows: if the :attr:`sq_length` slot is + filled, it is called and the sequence length is used to compute a positive + index which is passed to :attr:`sq_item`. If :attr:`sq_length` is *NULL*, + the index is passed as is to the function. + +.. cmember:: ssizeobjargproc PySequenceMethods.sq_ass_item + + This function is used by :cfunc:`PySequence_SetItem` and has the same + signature. This slot may be left to *NULL* if the object does not support + item assignment. + +.. cmember:: objobjproc PySequenceMethods.sq_contains + + This function may be used by :cfunc:`PySequence_Contains` and has the same + signature. This slot may be left to *NULL*, in this case + :cfunc:`PySequence_Contains` simply traverses the sequence until it finds a + match. + +.. cmember:: binaryfunc PySequenceMethods.sq_inplace_concat + + This function is used by :cfunc:`PySequence_InPlaceConcat` and has the same + signature. It should modify its first operand, and return it. + +.. cmember:: ssizeargfunc PySequenceMethods.sq_inplace_repeat + + This function is used by :cfunc:`PySequence_InPlaceRepeat` and has the same + signature. It should modify its first operand, and return it. + +.. XXX need to explain precedence between mapping and sequence +.. XXX explains when to implement the sq_inplace_* slots + .. _buffer-structs: Modified: python/branches/py3k-importlib/Doc/glossary.rst ============================================================================== --- python/branches/py3k-importlib/Doc/glossary.rst (original) +++ python/branches/py3k-importlib/Doc/glossary.rst Sat Sep 29 22:20:33 2007 @@ -32,19 +32,6 @@ One of the two flavors of classes in earlier Python versions. Since Python 3.0, there are no classic classes anymore. - coercion - The implicit conversion of an instance of one type to another during an - operation which involves two arguments of the same type. For example, - ``int(3.15)`` converts the floating point number to the integer ``3``, but - in ``3+4.5``, each argument is of a different type (one int, one float), - and both must be converted to the same type before they can be added or it - will raise a ``TypeError``. Coercion between two operands can be - performed with the ``coerce`` builtin function; thus, ``3+4.5`` is - equivalent to calling ``operator.add(*coerce(3, 4.5))`` and results in - ``operator.add(3.0, 4.5)``. Without coercion, all arguments of even - compatible types would have to be normalized to the same value by the - programmer, e.g., ``float(3)+4.5`` rather than just ``3+4.5``. - complex number An extension of the familiar real number system in which all numbers are expressed as a sum of a real part and an imaginary part. Imaginary @@ -168,14 +155,14 @@ integer division Mathematical division discarding any remainder. For example, the expression ``11/4`` currently evaluates to ``2`` in contrast to the - ``2.75`` returned by float division. Also called *floor division*. - When dividing two integers the outcome will always be another integer - (having the floor function applied to it). However, if one of the operands - is another numeric type (such as a :class:`float`), the result will be - coerced (see :term:`coercion`) to a common type. For example, an integer - divided by a float will result in a float value, possibly with a decimal - fraction. Integer division can be forced by using the ``//`` operator - instead of the ``/`` operator. See also :term:`__future__`. + ``2.75`` returned by float division. Also called *floor division*. When + dividing two integers the outcome will always be another integer (having + the floor function applied to it). However, if the operands types are + different, one of them will be converted to the other's type. For + example, an integer divided by a float will result in a float value, + possibly with a decimal fraction. Integer division can be forced by using + the ``//`` operator instead of the ``/`` operator. See also + :term:`__future__`. interactive Python has an interactive interpreter which means that you can try out Modified: python/branches/py3k-importlib/Doc/library/decimal.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/decimal.rst (original) +++ python/branches/py3k-importlib/Doc/library/decimal.rst Sat Sep 29 22:20:33 2007 @@ -312,7 +312,7 @@ numeric types such as :class:`float` and :class:`int`. All of the usual math operations and special methods apply. Likewise, decimal objects can be copied, pickled, printed, used as dictionary keys, used as set elements, compared, -sorted, and coerced to another type (such as :class:`float` or :class:`long`). +sorted, and converted to another type (such as :class:`float` or :class:`int`). In addition to the standard numeric properties, decimal floating point objects also have a number of specialized methods: Modified: python/branches/py3k-importlib/Doc/library/functions.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/functions.rst (original) +++ python/branches/py3k-importlib/Doc/library/functions.rst Sat Sep 29 22:20:33 2007 @@ -701,53 +701,55 @@ :func:`open` instead of invoking the :class:`file` constructor directly. The first two arguments are the same as for ``stdio``'s :cfunc:`fopen`: - *filename* is the file name to be opened, and *mode* is a string indicating how - the file is to be opened. + *filename* is the file name to be opened, and *mode* is a string + indicating how the file is to be opened. - The most commonly-used values of *mode* are ``'r'`` for reading, ``'w'`` for - writing (truncating the file if it already exists), and ``'a'`` for appending - (which on *some* Unix systems means that *all* writes append to the end of the - file regardless of the current seek position). If *mode* is omitted, it - defaults to ``'r'``. When opening a binary file, you should append ``'b'`` to - the *mode* value to open the file in binary mode, which will improve - portability. (Appending ``'b'`` is useful even on systems that don't treat - binary and text files differently, where it serves as documentation.) See below - for more possible values of *mode*. + The most commonly-used values of *mode* are ``'r'`` for reading, ``'w'`` + for writing (truncating the file if it already exists), and ``'a'`` for + appending (which on *some* Unix systems means that *all* writes append to + the end of the file regardless of the current seek position). If *mode* + is omitted, it defaults to ``'r'``. See below for more possible values + of *mode*. + + Python distinguishes between files opened in binary and text modes, even + when the underlying operating system doesn't. Files opened in binary + mode (appending ``'b'`` to the *mode* argument to :func:``open``) return + contents as bytes objects without any decoding. In text mode (the + default, or when ``'t'`` is appended to the *mode* argument) the contents + of the file are returned as strings, the bytes having been first decoded + using the encoding specified by :func:`sys.getfilesystemencoding`. .. index:: single: line-buffered I/O single: unbuffered I/O single: buffer size, I/O single: I/O control; buffering + single: binary mode + single: text mode + module: sys + + The optional *bufsize* argument specifies the file's desired buffer size: + 0 means unbuffered, 1 means line buffered, any other positive value means + use a buffer of (approximately) that size. A negative *bufsize* means to + use the system default, which is usually line buffered for tty devices + and fully buffered for other files. If omitted, the system default is + used. [#]_ + + Modes ``'r+'``, ``'w+'`` and ``'a+'`` open the file for updating (note + that ``'w+'`` truncates the file). + + When a file is opened in text mode it is also opened in universal + newlines mode. Unlike earlier versions of Python it's no longer + necessary to add a ``'U'`` value to the *mode* argument to enable this + mode. Consequently, in files opened in text mode lines may be terminated + with ``'\n'``, ``'\r'``, or ``'\r\n'``. All three external + representations are seen as ``'\n'`` by the Python program. File objects + opened in text mode also have a :attr:`newlines` attribute which has a + value of ``None`` (if no newlines have been seen yet), ``'\n'``, + ``'\r'``, ``'\r\n'``, or a tuple containing all the newline types seen. - The optional *bufsize* argument specifies the file's desired buffer size: 0 - means unbuffered, 1 means line buffered, any other positive value means use a - buffer of (approximately) that size. A negative *bufsize* means to use the - system default, which is usually line buffered for tty devices and fully - buffered for other files. If omitted, the system default is used. [#]_ - - Modes ``'r+'``, ``'w+'`` and ``'a+'`` open the file for updating (note that - ``'w+'`` truncates the file). Append ``'b'`` to the mode to open the file in - binary mode, on systems that differentiate between binary and text files; on - systems that don't have this distinction, adding the ``'b'`` has no effect. - - In addition to the standard :cfunc:`fopen` values *mode* may be ``'U'`` or - ``'rU'``. Python is usually built with universal newline support; supplying - ``'U'`` opens the file as a text file, but lines may be terminated by any of the - following: the Unix end-of-line convention ``'\n'``, the Macintosh convention - ``'\r'``, or the Windows convention ``'\r\n'``. All of these external - representations are seen as ``'\n'`` by the Python program. If Python is built - without universal newline support a *mode* with ``'U'`` is the same as normal - text mode. Note that file objects so opened also have an attribute called - :attr:`newlines` which has a value of ``None`` (if no newlines have yet been - seen), ``'\n'``, ``'\r'``, ``'\r\n'``, or a tuple containing all the newline - types seen. - - Python enforces that the mode, after stripping ``'U'``, begins with ``'r'``, - ``'w'`` or ``'a'``. - - See also the :mod:`fileinput` module, the :mod:`os` module, and the - :mod:`os.path` module. + See also the :mod:`fileinput` module, the file-related functions in the + :mod:`os` module, and the :mod:`os.path` module. .. function:: ord(c) Modified: python/branches/py3k-importlib/Doc/library/stdtypes.rst ============================================================================== --- python/branches/py3k-importlib/Doc/library/stdtypes.rst (original) +++ python/branches/py3k-importlib/Doc/library/stdtypes.rst Sat Sep 29 22:20:33 2007 @@ -10,13 +10,6 @@ The following sections describe the standard types that are built into the interpreter. -.. note:: - - Historically (until release 2.2), Python's built-in types have differed from - user-defined types because it was not possible to use the built-in types as the - basis for object-oriented inheritance. This limitation no longer - exists. - .. index:: pair: built-in; types The principal built-in types are numerics, sequences, mappings, files, classes, @@ -129,8 +122,8 @@ .. index:: pair: chaining; comparisons -Comparison operations are supported by all objects. They all have the same -priority (which is higher than that of the Boolean operations). Comparisons can +There are eight comparison operations in Python. They all have the same +priority (which is higher than that of the Boolean operations). Comparisons can be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and y <= z``, except that *y* is evaluated only once (but in both cases *z* is not evaluated at all when ``x < y`` is found to be false). @@ -172,24 +165,35 @@ pair: object; numeric pair: objects; comparing -Objects of different types, except different numeric types and different string -types, never compare equal; such objects are ordered consistently but -arbitrarily (so that sorting a heterogeneous array yields a consistent result). +Objects of different types, except different numeric types, never compare equal. Furthermore, some types (for example, file objects) support only a degenerate -notion of comparison where any two objects of that type are unequal. Again, -such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>`` -and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is -a complex number. - -.. index:: single: __cmp__() (instance method) +notion of comparison where any two objects of that type are unequal. The ``<``, +``<=``, ``>`` and ``>=`` operators will raise a :exc:`TypeError` exception when +any operand is a complex number, the objects are of different types that cannot +be compared, or other cases where there is no defined ordering. + +.. index:: + single: __cmp__() (instance method) + single: __eq__() (instance method) + single: __ne__() (instance method) + single: __lt__() (instance method) + single: __le__() (instance method) + single: __gt__() (instance method) + single: __ge__() (instance method) Instances of a class normally compare as non-equal unless the class defines the -:meth:`__cmp__` method. Refer to :ref:`customization`) for information on the -use of this method to effect object comparisons. +:meth:`__eq__` or :meth:`__cmp__` method. -**Implementation note:** Objects of different types except numbers are ordered -by their type names; objects of the same types that don't support proper -comparison are ordered by their address. +Instances of a class cannot be ordered with respect to other instances of the +same class, or other types of object, unless the class defines enough of the +methods :meth:`__cmp__`, :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and +:meth:`__ge__` (in general, either :meth:`__cmp__` or both :meth:`__lt__` and +:meth:`__eq__` are sufficient, if you want the conventional meanings of the +comparison operators). + +The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be +customized; also they can be applied to any two objects and never raise an +exception. .. index:: operator: in @@ -201,27 +205,22 @@ .. _typesnumeric: -Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex` -=============================================================================== +Numeric Types --- :class:`int`, :class:`float`, :class:`complex` +================================================================ .. index:: object: numeric object: Boolean object: integer - object: long integer object: floating point object: complex number pair: C; language -There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long -integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In -addition, Booleans are a subtype of plain integers. Plain integers (also just -called :dfn:`integers`) are implemented using :ctype:`long` in C, which gives -them at least 32 bits of precision (``sys.maxint`` is always set to the maximum -plain integer value for the current platform, the minimum value is -``-sys.maxint - 1``). Long integers have unlimited precision. Floating point -numbers are implemented using :ctype:`double` in C. All bets on their precision -are off unless you happen to know the machine you are working with. +There are three distinct numeric types: :dfn:`integers`, :dfn:`floating point +numbers`, and :dfn:`complex numbers`. In addition, Booleans are a subtype of +plain integers. Integers have unlimited precision. loating point numbers are +implemented using :ctype:`double` in C. All bets on their precision are off +unless you happen to know the machine you are working with. Complex numbers have a real and imaginary part, which are each implemented using :ctype:`double` in C. To extract these parts from a complex number *z*, use @@ -230,21 +229,19 @@ .. index:: pair: numeric; literals pair: integer; literals - triple: long; integer; literals pair: floating point; literals pair: complex number; literals pair: hexadecimal; literals pair: octal; literals + pair: binary: literals Numbers are created by numeric literals or as the result of built-in functions -and operators. Unadorned integer literals (including hex and octal numbers) -yield plain integers unless the value they denote is too large to be represented -as a plain integer, in which case they yield a long integer. Integer literals -with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'`` is preferred -because ``1l`` looks too much like eleven!). Numeric literals containing a -decimal point or an exponent sign yield floating point numbers. Appending -``'j'`` or ``'J'`` to a numeric literal yields a complex number with a zero real -part. A complex numeric literal is the sum of a real and an imaginary part. +and operators. Unadorned integer literals (including hex, octal and binary +numbers) yield integers. Numeric literals containing a decimal point or an +exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a +numeric literal yields an imaginary number (a complex number with a zero real +part) which you can add to an integer or float to get a complex number with real +and imaginary parts. .. index:: single: arithmetic @@ -255,58 +252,55 @@ Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the "narrower" type is -widened to that of the other, where plain integer is narrower than long integer -is narrower than floating point is narrower than complex. Comparisons between -numbers of mixed type use the same rule. [#]_ The constructors :func:`int`, -:func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers -of a specific type. +widened to that of the other, where integer is narrower than floating point, +which is narrower than complex. Comparisons between numbers of mixed type use +the same rule. [#]_ The constructors :func:`int`, :func:`float`, and +:func:`complex` can be used to produce numbers of a specific type. All numeric types (except complex) support the following operations, sorted by ascending priority (operations in the same box have the same priority; all numeric operations have a higher priority than comparison operations): -+--------------------+---------------------------------+--------+ -| Operation | Result | Notes | -+====================+=================================+========+ -| ``x + y`` | sum of *x* and *y* | | -+--------------------+---------------------------------+--------+ -| ``x - y`` | difference of *x* and *y* | | -+--------------------+---------------------------------+--------+ -| ``x * y`` | product of *x* and *y* | | -+--------------------+---------------------------------+--------+ -| ``x / y`` | quotient of *x* and *y* | \(1) | -+--------------------+---------------------------------+--------+ -| ``x // y`` | (floored) quotient of *x* and | \(5) | -| | *y* | | -+--------------------+---------------------------------+--------+ -| ``x % y`` | remainder of ``x / y`` | \(4) | -+--------------------+---------------------------------+--------+ -| ``-x`` | *x* negated | | -+--------------------+---------------------------------+--------+ -| ``+x`` | *x* unchanged | | -+--------------------+---------------------------------+--------+ -| ``abs(x)`` | absolute value or magnitude of | | -| | *x* | | -+--------------------+---------------------------------+--------+ -| ``int(x)`` | *x* converted to integer | \(2) | -+--------------------+---------------------------------+--------+ -| ``long(x)`` | *x* converted to long integer | \(2) | -+--------------------+---------------------------------+--------+ -| ``float(x)`` | *x* converted to floating point | | -+--------------------+---------------------------------+--------+ -| ``complex(re,im)`` | a complex number with real part | | -| | *re*, imaginary part *im*. | | -| | *im* defaults to zero. | | -+--------------------+---------------------------------+--------+ -| ``c.conjugate()`` | conjugate of the complex number | | -| | *c* | | -+--------------------+---------------------------------+--------+ -| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | (3)(4) | -+--------------------+---------------------------------+--------+ -| ``pow(x, y)`` | *x* to the power *y* | | -+--------------------+---------------------------------+--------+ -| ``x ** y`` | *x* to the power *y* | | -+--------------------+---------------------------------+--------+ ++---------------------+---------------------------------+-------+--------------------+ +| Operation | Result | Notes | Full documentation | ++==================== +=================================+=======+====================| +| ``x + y`` | sum of *x* and *y* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``x - y`` | difference of *x* and *y* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``x * y`` | product of *x* and *y* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``x / y`` | quotient of *x* and *y* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``x // y`` | floored quotient of *x* and | \(1) | | +| | *y* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``x % y`` | remainder of ``x / y`` | \(2) | | ++---------------------+---------------------------------+-------+--------------------+ +| ``-x`` | *x* negated | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``+x`` | *x* unchanged | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``abs(x)`` | absolute value or magnitude of | | :func:`abs` | +| | *x* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``int(x)`` | *x* converted to integer | \(3) | :func:`int` | ++---------------------+---------------------------------+-------+--------------------+ +| ``float(x)`` | *x* converted to floating point | | :func:`float` | ++---------------------+---------------------------------+-------+--------------------+ +| ``complex(re, im)`` | a complex number with real part | | :func:`complex` | +| | *re*, imaginary part *im*. | | | +| | *im* defaults to zero. | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``c.conjugate()`` | conjugate of the complex number | | | +| | *c* | | | ++---------------------+---------------------------------+-------+--------------------+ +| ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` | ++---------------------+---------------------------------+-------+--------------------+ +| ``pow(x, y)`` | *x* to the power *y* | | :func:`pow` | ++---------------------+---------------------------------+-------+--------------------+ +| ``x ** y`` | *x* to the power *y* | | | ++---------------------+---------------------------------+-------+--------------------+ .. index:: triple: operations on; numeric; types @@ -315,16 +309,16 @@ Notes: (1) - .. index:: - pair: integer; division - triple: long; integer; division - - For (plain or long) integer division, the result is an integer. The result is - always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and - (-1)/(-2) is 0. Note that the result is a long integer if either operand is a - long integer, regardless of the numeric value. + Also referred to as integer division. The resultant value is a whole + integer, though the result's type is not necessarily int. The result is + always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is + ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``. (2) + Not for complex numbers. Instead convert to floats using :func:`abs` if + appropriate. + +(3) .. index:: module: math single: floor() (in module math) @@ -336,19 +330,6 @@ as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module for well-defined conversions. -(3) - See :ref:`built-in-funcs` for a full description. - -(4) - Complex floor division operator, modulo operator, and :func:`divmod`. - - .. deprecated:: 2.3 - Instead convert to float using :func:`abs` if appropriate. - -(5) - Also referred to as integer division. The resultant value is a whole integer, - though the result's type is not necessarily int. - .. % XXXJH exceptions: overflow (when? what operations?) zerodivision @@ -359,10 +340,9 @@ .. _bit-string-operations: -Plain and long integer types support additional operations that make sense only -for bit-strings. Negative numbers are treated as their 2's complement value -(for long integers, this assumes a sufficiently large number of bits that no -overflow occurs during the operation). +Integers support additional operations that make sense only for bit-strings. +Negative numbers are treated as their 2's complement value (this assumes a +sufficiently large number of bits that no overflow occurs during the operation). The priorities of the binary bit-wise operations are all lower than the numeric operations and higher than the comparisons; the unary operation ``~`` has the @@ -453,7 +433,7 @@ Python objects in the Python/C API. -.. method:: iterator.next() +.. method:: iterator.__next__() Return the next item from the container. If there are no further items, raise the :exc:`StopIteration` exception. This method corresponds to the @@ -465,11 +445,9 @@ specific types are not important beyond their implementation of the iterator protocol. -The intention of the protocol is that once an iterator's :meth:`__next__` method -raises :exc:`StopIteration`, it will continue to do so on subsequent calls. -Implementations that do not obey this property are deemed broken. (This -constraint was added in Python 2.3; in Python 2.2, various iterators are broken -according to this rule.) +Once an iterator's :meth:`__next__` method raises :exc:`StopIteration`, it must +continue to do so on subsequent calls. Implementations that do not obey this +property are deemed broken. Python's generators provide a convenient way to implement the iterator protocol. If a container object's :meth:`__iter__` method is implemented as a generator, @@ -789,8 +767,11 @@ .. method:: str.join(seq) - Return a string which is the concatenation of the strings in the sequence *seq*. - The separator between elements is the string providing this method. + Return a string which is the concatenation of the values in the sequence + *seq*. Non-string values in *seq* will be converted to a string using their + respective ``str()`` value. If there are any :class:`bytes` objects in + *seq*, a :exc:`TypeError` will be raised. The separator between elements is + the string providing this method. .. method:: str.ljust(width[, fillchar]) @@ -1137,13 +1118,9 @@ decimal point and defaults to 6. (5) - The ``%r`` conversion was added in Python 2.0. - The precision determines the maximal number of characters used. - The precision determines the maximal number of characters used. - Since Python strings have an explicit length, ``%s`` conversions do not assume that ``'\0'`` is the end of the string. @@ -1161,8 +1138,8 @@ .. _typesseq-range: -XRange Type ------------ +Range Type +---------- .. index:: object: range @@ -1171,7 +1148,7 @@ object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages. -XRange objects have very little behavior: they only support indexing, iteration, +Range objects have very little behavior: they only support indexing, iteration, and the :func:`len` function. Modified: python/branches/py3k-importlib/Doc/tutorial/classes.rst ============================================================================== --- python/branches/py3k-importlib/Doc/tutorial/classes.rst (original) +++ python/branches/py3k-importlib/Doc/tutorial/classes.rst Sat Sep 29 22:20:33 2007 @@ -473,8 +473,8 @@ Multiple Inheritance -------------------- -Python supports a limited form of multiple inheritance as well. A class -definition with multiple base classes looks like this:: +Python supports a form of multiple inheritance as well. A class definition with +multiple base classes looks like this:: class DerivedClassName(Base1, Base2, Base3): @@ -483,15 +483,18 @@ . -Formerly, the only rule was depth-first, left-to-right. Thus, if an attribute -was not found in :class:`DerivedClassName`, it was searched in :class:`Base1`, -then (recursively) in the base classes of :class:`Base1`, and only if it was not -found there, it was searched in :class:`Base2`, and so on. - -In the meantime, the method resolution order changes dynamically to support -cooperative calls to :func:`super`. This approach is known in some other -multiple-inheritance languages as call-next-method and is more powerful than the -super call found in single-inheritance languages. +For most purposes, in the simplest cases, you can think of the search for +attributes inherited from a parent class as depth-first, left-to-right, not +searching twice in the same class where there is an overlap in the hierarchy. +Thus, if an attribute is not found in :class:`DerivedClassName`, it is searched +for in :class:`Base1`, then (recursively) in the base classes of :class:`Base1`, +and if it was not found there, it was searched for in :class:`Base2`, and so on. + +In fact, it is slightly more complex than that; the method resolution order +changes dynamically to support cooperative calls to :func:`super`. This +approach is known in some other multiple-inheritance languages as +call-next-method and is more powerful than the super call found in +single-inheritance languages. Dynamic ordering is necessary because all cases of multiple inheritance exhibit one or more diamond relationships (where one at least one of the parent classes Modified: python/branches/py3k-importlib/Doc/tutorial/errors.rst ============================================================================== --- python/branches/py3k-importlib/Doc/tutorial/errors.rst (original) +++ python/branches/py3k-importlib/Doc/tutorial/errors.rst Sat Sep 29 22:20:33 2007 @@ -115,9 +115,9 @@ handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same :keyword:`try` statement. An except clause may -name multiple exceptions as a tuple, for example:: +name multiple exceptions as a parenthesized tuple, for example:: - ... except RuntimeError, TypeError, NameError: + ... except (RuntimeError, TypeError, NameError): ... pass The last except clause may omit the exception name(s), to serve as a wildcard. Modified: python/branches/py3k-importlib/Doc/tutorial/inputoutput.rst ============================================================================== --- python/branches/py3k-importlib/Doc/tutorial/inputoutput.rst (original) +++ python/branches/py3k-importlib/Doc/tutorial/inputoutput.rst Sat Sep 29 22:20:33 2007 @@ -197,14 +197,20 @@ writing. The *mode* argument is optional; ``'r'`` will be assumed if it's omitted. -On Windows and the Macintosh, ``'b'`` appended to the mode opens the file in -binary mode, so there are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. -Windows makes a distinction between text and binary files; the end-of-line -characters in text files are automatically altered slightly when data is read or -written. This behind-the-scenes modification to file data is fine for ASCII -text files, but it'll corrupt binary data like that in :file:`JPEG` or -:file:`EXE` files. Be very careful to use binary mode when reading and writing -such files. +``'b'`` appended to the mode opens the file in binary mode, so there are +also modes like ``'rb'``, ``'wb'``, and ``'r+b'``. Python distinguishes +between text and binary files. Binary files are read and written without +any data transformation. In text mode, platform-specific newline +representations are automatically converted to newlines when read and +newline characters are automatically converted to the proper +platform-specific representation when written. This makes writing portable +code which reads or writes text files easier. In addition, when reading +from or writing to text files, the data are automatically decoded or +encoding, respectively, using the encoding associated with the file. + +This behind-the-scenes modification to file data is fine for text files, but +will corrupt binary data like that in :file:`JPEG` or :file:`EXE` files. Be +very careful to use binary mode when reading and writing such files. .. _tut-filemethods: Modified: python/branches/py3k-importlib/Doc/tutorial/interpreter.rst ============================================================================== --- python/branches/py3k-importlib/Doc/tutorial/interpreter.rst (original) +++ python/branches/py3k-importlib/Doc/tutorial/interpreter.rst Sat Sep 29 22:20:33 2007 @@ -101,11 +101,14 @@ prints a welcome message stating its version number and a copyright notice before printing the first prompt:: - python - Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5 - Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam + $ python + Python 3.0a1 (py3k, Sep 12 2007, 12:21:02) + [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2 + Type "help", "copyright", "credits" or "license" for more information. >>> +.. XXX update for final release of Python 3.0 + Continuation lines are needed when entering a multi-line construct. As an example, take a look at this :keyword:`if` statement:: @@ -170,44 +173,32 @@ Source Code Encoding -------------------- -.. XXX out of date! - -It is possible to use encodings different than ASCII in Python source files. The -best way to do it is to put one more special comment line right after the ``#!`` -line to define the source file encoding:: +By default, Python source files are treated as encoded in UTF-8. In that +encoding, characters of most languages in the world can be used simultaneously +in string literals, identifiers and comments --- although the standard library +only uses ASCII characters for identifiers, a convention that any portable code +should follow. To display all these characters properly, your editor must +recognize that the file is UTF-8, and it must use a font that supports all the +characters in the file. + +It is also possible to specify a different encoding for source files. In order +to do this, put one more special comment line right after the ``#!`` line to +define the source file encoding:: # -*- coding: encoding -*- - -With that declaration, all characters in the source file will be treated as -having the encoding *encoding*, and it will be possible to directly write -Unicode string literals in the selected encoding. The list of possible -encodings can be found in the Python Library Reference, in the section on -:mod:`codecs`. - -For example, to write Unicode literals including the Euro currency symbol, the -ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value -164. This script will print the value 8364 (the Unicode codepoint corresponding -to the Euro symbol) and then exit:: - - # -*- coding: iso-8859-15 -*- - - currency = u"?" - print(ord(currency)) - -If your editor supports saving files as ``UTF-8`` with a UTF-8 *byte order mark* -(aka BOM), you can use that instead of an encoding declaration. IDLE supports -this capability if ``Options/General/Default Source Encoding/UTF-8`` is set. -Notice that this signature is not understood in older Python releases (2.2 and -earlier), and also not understood by the operating system for script files with -``#!`` lines (only used on Unix systems). - -By using UTF-8 (either through the signature or an encoding declaration), -characters of most languages in the world can be used simultaneously in string -literals and comments. Using non-ASCII characters in identifiers is not -supported. To display all these characters properly, your editor must recognize -that the file is UTF-8, and it must use a font that supports all the characters -in the file. +With that declaration, everything in the source file will be treated as having +the encoding *encoding* instead of UTF-8. The list of possible encodings can be +found in the Python Library Reference, in the section on :mod:`codecs`. + +For example, if your editor of choice does not support UTF-8 encoded files and +insists on using some other encoding, say Windows-1252, you can write:: + + # -*- coding: cp-1252 -*- + +and still use all characters in the Windows-1252 character set in the source +files. The special encoding comment must be in the *first or second* line +within the file. .. _tut-startup: Modified: python/branches/py3k-importlib/Doc/tutorial/introduction.rst ============================================================================== --- python/branches/py3k-importlib/Doc/tutorial/introduction.rst (original) +++ python/branches/py3k-importlib/Doc/tutorial/introduction.rst Sat Sep 29 22:20:33 2007 @@ -131,9 +131,9 @@ 0.5 The conversion functions to floating point and integer (:func:`float`, -:func:`int` and :func:`long`) don't work for complex numbers --- there is no one -correct way to convert a complex number to a real number. Use ``abs(z)`` to get -its magnitude (as a float) or ``z.real`` to get its real part. :: +:func:`int`) don't work for complex numbers --- there is not one correct way to +convert a complex number to a real number. Use ``abs(z)`` to get its magnitude +(as a float) or ``z.real`` to get its real part:: >>> a=3.0+4.0j >>> float(a) Modified: python/branches/py3k-importlib/Include/abstract.h ============================================================================== --- python/branches/py3k-importlib/Include/abstract.h (original) +++ python/branches/py3k-importlib/Include/abstract.h Sat Sep 29 22:20:33 2007 @@ -542,7 +542,7 @@ /* Return 1 if the getbuffer function is available, otherwise return 0 */ - PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, PyBuffer *view, + PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags); /* This is a C-API version of the getbuffer function call. It checks @@ -552,7 +552,7 @@ */ - PyAPI_FUNC(void) PyObject_ReleaseBuffer(PyObject *obj, PyBuffer *view); + PyAPI_FUNC(void) PyObject_ReleaseBuffer(PyObject *obj, Py_buffer *view); /* C-API version of the releasebuffer function call. It @@ -570,7 +570,7 @@ buffer */ - PyAPI_FUNC(void *) PyBuffer_GetPointer(PyBuffer *view, Py_ssize_t *indices); + PyAPI_FUNC(void *) PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices); /* Get the memory area pointed to by the indices for the buffer given. Note that view->ndim is the assumed size of indices @@ -583,10 +583,10 @@ - PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, PyBuffer *view, + PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort); - PyAPI_FUNC(int) PyBuffer_FromContiguous(PyBuffer *view, void *buf, + PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort); @@ -611,7 +611,7 @@ /* Copy the data from the src buffer to the buffer of destination */ - PyAPI_FUNC(int) PyBuffer_IsContiguous(PyBuffer *view, char fortran); + PyAPI_FUNC(int) PyBuffer_IsContiguous(Py_buffer *view, char fortran); PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims, @@ -626,7 +626,7 @@ per element. */ - PyAPI_FUNC(int) PyBuffer_FillInfo(PyBuffer *view, void *buf, + PyAPI_FUNC(int) PyBuffer_FillInfo(Py_buffer *view, void *buf, Py_ssize_t len, int readonly, int flags); Modified: python/branches/py3k-importlib/Include/memoryobject.h ============================================================================== --- python/branches/py3k-importlib/Include/memoryobject.h (original) +++ python/branches/py3k-importlib/Include/memoryobject.h Sat Sep 29 22:20:33 2007 @@ -10,7 +10,7 @@ typedef struct { PyObject_HEAD PyObject *base; - PyBuffer view; + Py_buffer view; } PyMemoryViewObject; @@ -57,7 +57,7 @@ PyAPI_FUNC(PyObject *) PyMemoryView_FromObject(PyObject *base); -PyAPI_FUNC(PyObject *) PyMemoryView_FromMemory(PyBuffer *info); +PyAPI_FUNC(PyObject *) PyMemoryView_FromMemory(Py_buffer *info); /* create new if bufptr is NULL will be a new bytesobject in base */ Modified: python/branches/py3k-importlib/Include/object.h ============================================================================== --- python/branches/py3k-importlib/Include/object.h (original) +++ python/branches/py3k-importlib/Include/object.h Sat Sep 29 22:20:33 2007 @@ -133,7 +133,6 @@ typedef PyObject * (*ternaryfunc)(PyObject *, PyObject *, PyObject *); typedef int (*inquiry)(PyObject *); typedef Py_ssize_t (*lenfunc)(PyObject *); -typedef int (*coercion)(PyObject **, PyObject **); typedef PyObject *(*ssizeargfunc)(PyObject *, Py_ssize_t); typedef PyObject *(*ssizessizeargfunc)(PyObject *, Py_ssize_t, Py_ssize_t); typedef int(*ssizeobjargproc)(PyObject *, Py_ssize_t, PyObject *); @@ -154,10 +153,10 @@ Py_ssize_t *strides; Py_ssize_t *suboffsets; void *internal; -} PyBuffer; +} Py_buffer; -typedef int (*getbufferproc)(PyObject *, PyBuffer *, int); -typedef void (*releasebufferproc)(PyObject *, PyBuffer *); +typedef int (*getbufferproc)(PyObject *, Py_buffer *, int); +typedef void (*releasebufferproc)(PyObject *, Py_buffer *); /* Flags for getting buffers */ #define PyBUF_SIMPLE 0 @@ -222,7 +221,7 @@ binaryfunc nb_and; binaryfunc nb_xor; binaryfunc nb_or; - coercion nb_coerce; + int nb_reserved; /* unused, used to be nb_coerce */ unaryfunc nb_int; unaryfunc nb_long; unaryfunc nb_float; Modified: python/branches/py3k-importlib/Lib/distutils/fancy_getopt.py ============================================================================== --- python/branches/py3k-importlib/Lib/distutils/fancy_getopt.py (original) +++ python/branches/py3k-importlib/Lib/distutils/fancy_getopt.py Sat Sep 29 22:20:33 2007 @@ -388,7 +388,7 @@ text = text.expandtabs() text = text.translate(WS_TRANS) chunks = re.split(r'( +|-+)', text) - chunks = filter(None, chunks) # ' - ' results in empty strings + chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings lines = [] while chunks: Modified: python/branches/py3k-importlib/Lib/lib-tk/turtle.py ============================================================================== --- python/branches/py3k-importlib/Lib/lib-tk/turtle.py (original) +++ python/branches/py3k-importlib/Lib/lib-tk/turtle.py Sat Sep 29 22:20:33 2007 @@ -531,7 +531,7 @@ def _goto(self, x1, y1): x0, y0 = self._position - self._position = map(float, (x1, y1)) + self._position = (float(x1), float(y1)) if self._filling: self._path.append(self._position) if self._drawing: @@ -749,25 +749,25 @@ global _width, _height, _startx, _starty width = geometry.get('width',_width) - if width >= 0 or width == None: + if width is None or width >= 0: _width = width else: raise ValueError("width can not be less than 0") height = geometry.get('height',_height) - if height >= 0 or height == None: + if height is None or height >= 0: _height = height else: raise ValueError("height can not be less than 0") startx = geometry.get('startx', _startx) - if startx >= 0 or startx == None: + if startx is None or startx >= 0: _startx = _startx else: raise ValueError("startx can not be less than 0") starty = geometry.get('starty', _starty) - if starty >= 0 or starty == None: + if starty is None or starty >= 0: _starty = starty else: raise ValueError("startx can not be less than 0") Modified: python/branches/py3k-importlib/Lib/test/string_tests.py ============================================================================== --- python/branches/py3k-importlib/Lib/test/string_tests.py (original) +++ python/branches/py3k-importlib/Lib/test/string_tests.py Sat Sep 29 22:20:33 2007 @@ -13,6 +13,7 @@ class BadSeq1(Sequence): def __init__(self): self.seq = [7, 'hello', 123] + def __str__(self): return '{0} {1} {2}'.format(*self.seq) class BadSeq2(Sequence): def __init__(self): self.seq = ['a', 'b', 'c'] @@ -987,19 +988,19 @@ self.checkequal('abc', 'a', 'join', ('abc',)) self.checkequal('z', 'a', 'join', UserList(['z'])) self.checkequal('a.b.c', '.', 'join', ['a', 'b', 'c']) - self.checkraises(TypeError, '.', 'join', ['a', 'b', 3]) + self.checkequal('a.b.3', '.', 'join', ['a', 'b', 3]) for i in [5, 25, 125]: self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join', ['a' * i] * i) self.checkequal(((('a' * i) + '-') * i)[:-1], '-', 'join', ('a' * i,) * i) - self.checkraises(TypeError, ' ', 'join', BadSeq1()) + self.checkequal(str(BadSeq1()), ' ', 'join', BadSeq1()) self.checkequal('a b c', ' ', 'join', BadSeq2()) self.checkraises(TypeError, ' ', 'join') self.checkraises(TypeError, ' ', 'join', 7) - self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123])) + self.checkraises(TypeError, ' ', 'join', [1, 2, bytes()]) try: def f(): yield 4 + "" Modified: python/branches/py3k-importlib/Lib/test/test_descr.py ============================================================================== --- python/branches/py3k-importlib/Lib/test/test_descr.py (original) +++ python/branches/py3k-importlib/Lib/test/test_descr.py Sat Sep 29 22:20:33 2007 @@ -3238,10 +3238,6 @@ except ValueError: pass else: raise TestFailed("''.split('') doesn't raise ValueError") - try: ''.join([0]) - except TypeError: pass - else: raise TestFailed("''.join([0]) doesn't raise TypeError") - try: ''.rindex('5') except ValueError: pass else: raise TestFailed("''.rindex('5') doesn't raise ValueError") Modified: python/branches/py3k-importlib/Lib/test/test_unicode.py ============================================================================== --- python/branches/py3k-importlib/Lib/test/test_unicode.py (original) +++ python/branches/py3k-importlib/Lib/test/test_unicode.py Sat Sep 29 22:20:33 2007 @@ -178,6 +178,10 @@ def test_join(self): string_tests.MixinStrUnicodeUserStringTest.test_join(self) + class MyWrapper: + def __init__(self, sval): self.sval = sval + def __str__(self): return self.sval + # mixed arguments self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd']) self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd')) @@ -186,6 +190,8 @@ self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd']) self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd')) self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz')) + self.checkequalnofix('1 2 foo', ' ', 'join', [1, 2, MyWrapper('foo')]) + self.checkraises(TypeError, ' ', 'join', [1, 2, 3, bytes()]) def test_replace(self): string_tests.CommonTest.test_replace(self) Modified: python/branches/py3k-importlib/Modules/_bsddb.c ============================================================================== --- python/branches/py3k-importlib/Modules/_bsddb.c (original) +++ python/branches/py3k-importlib/Modules/_bsddb.c Sat Sep 29 22:20:33 2007 @@ -382,7 +382,7 @@ /* Cleanup a Python buffer API view created by make_dbt() */ -static void free_buf_view(PyObject *obj, PyBuffer *view) +static void free_buf_view(PyObject *obj, Py_buffer *view) { if (view) { PyObject_ReleaseBuffer(obj, view); @@ -400,13 +400,13 @@ } while(0); -static PyBuffer * _malloc_view(PyObject *obj) +static Py_buffer * _malloc_view(PyObject *obj) { - PyBuffer *view; + Py_buffer *view; - if (!(view = PyMem_Malloc(sizeof(PyBuffer)))) { + if (!(view = PyMem_Malloc(sizeof(Py_buffer)))) { PyErr_SetString(PyExc_MemoryError, - "PyBuffer malloc failed"); + "Py_buffer malloc failed"); return NULL; } /* XXX(gps): PyBUF_LOCKDATA is desired to prevent other theads from @@ -429,11 +429,11 @@ /* Create a DBT structure (containing key and data values) from Python strings. Returns >= 1 on success, 0 on an error. The returned_view_p - may be filled with a newly allocated PyBuffer view on success. - The caller MUST call free_buf_view() on any returned PyBuffer. */ -static int make_dbt(PyObject* obj, DBT* dbt, PyBuffer** returned_view_p) + may be filled with a newly allocated Py_buffer view on success. + The caller MUST call free_buf_view() on any returned Py_buffer. */ +static int make_dbt(PyObject* obj, DBT* dbt, Py_buffer** returned_view_p) { - PyBuffer *view; + Py_buffer *view; /* simple way to ensure the caller can detect if we've returned a new buffer view or not: require their pointer to start out NULL. */ @@ -464,14 +464,14 @@ what's been given, verifies that it's allowed, and then makes the DBT. Caller MUST call FREE_DBT_VIEW(keydbt, keyobj, key_view) with all - returned DBT and PyBuffer values when done. */ + returned DBT and Py_buffer values when done. */ static int make_key_dbt(DBObject* self, PyObject* keyobj, DBT* key, int* pflags, - PyBuffer** returned_view_p) + Py_buffer** returned_view_p) { db_recno_t recno; int type; - PyBuffer *view; + Py_buffer *view; /* simple way to ensure the caller can detect if we've returned a new buffer view or not: require their pointer to start out NULL. */ @@ -1221,7 +1221,7 @@ { PyObject* txnobj = NULL; PyObject* dataobj; - PyBuffer* data_buf_view = NULL; + Py_buffer* data_buf_view = NULL; db_recno_t recno; DBT key, data; DB_TXN *txn = NULL; @@ -1534,7 +1534,7 @@ PyObject* txnobj = NULL; int flags = 0; PyObject* keyobj; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; DBT key; DB_TXN *txn = NULL; static char* kwnames[] = { "key", "txn", "flags", NULL }; @@ -1585,7 +1585,7 @@ PyObject* keyobj; PyObject* dfltobj = NULL; PyObject* retval = NULL; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; int dlen = -1; int doff = -1; DBT key, data; @@ -1654,7 +1654,7 @@ PyObject* keyobj; PyObject* dfltobj = NULL; PyObject* retval = NULL; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; int dlen = -1; int doff = -1; DBT key, pkey, data; @@ -1758,7 +1758,7 @@ PyObject* txnobj = NULL; PyObject* keyobj; PyObject* retval = NULL; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; DBT key, data; DB_TXN *txn = NULL; static char* kwnames[] = { "key", "txn", NULL }; @@ -1802,8 +1802,8 @@ PyObject* keyobj; PyObject* dataobj; PyObject* retval = NULL; - PyBuffer* data_buf_view = NULL; - PyBuffer* key_buf_view = NULL; + Py_buffer* data_buf_view = NULL; + Py_buffer* key_buf_view = NULL; DBT key, data; void *orig_data; DB_TXN *txn = NULL; @@ -1969,7 +1969,7 @@ int err, flags=0; PyObject* txnobj = NULL; PyObject* keyobj; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; DBT key; DB_TXN *txn = NULL; DB_KEY_RANGE range; @@ -2100,8 +2100,8 @@ int dlen = -1; int doff = -1; PyObject *keyobj, *dataobj, *retval; - PyBuffer *data_buf_view = NULL; - PyBuffer *key_buf_view = NULL; + Py_buffer *data_buf_view = NULL; + Py_buffer *key_buf_view = NULL; DBT key, data; DB_TXN *txn = NULL; static char* kwnames[] = { "key", "data", "txn", "flags", "dlen", @@ -2881,7 +2881,7 @@ { int err; PyObject* retval; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; DBT key; DBT data; @@ -2920,8 +2920,8 @@ DBT key, data; int retval; int flags = 0; - PyBuffer *data_buf_view = NULL; - PyBuffer *key_buf_view = NULL; + Py_buffer *data_buf_view = NULL; + Py_buffer *key_buf_view = NULL; if (self->db == NULL) { PyObject *t = Py_BuildValue("(is)", 0, "DB object has been closed"); @@ -2966,7 +2966,7 @@ { int err; PyObject* keyobj; - PyBuffer* key_buf_view = NULL; + Py_buffer* key_buf_view = NULL; DBT key, data; PyObject* txnobj = NULL; DB_TXN *txn = NULL; @@ -3263,8 +3263,8 @@ PyObject* keyobj = NULL; PyObject* dataobj = NULL; PyObject* retval = NULL; - PyBuffer* data_buf_view = NULL; - PyBuffer* key_buf_view = NULL; + Py_buffer* data_buf_view = NULL; + Py_buffer* key_buf_view = NULL; int dlen = -1; int doff = -1; DBT key, data; @@ -3354,8 +3354,8 @@ PyObject* keyobj = NULL; PyObject* dataobj = NULL; PyObject* retval = NULL; - PyBuffer* data_buf_view = NULL; - PyBuffer* key_buf_view = NULL; + Py_buffer* data_buf_view = NULL; + Py_buffer* key_buf_view = NULL; int dlen = -1; int doff = -1; DBT key, pkey, data; @@ -3517,8 +3517,8 @@ { int err, flags = 0; PyObject *keyobj, *dataobj; - PyBuffer *data_buf_view = NULL; - PyBuffer *key_buf_view = NULL; + Py_buffer *data_buf_view = NULL; + Py_buffer *key_buf_view = NULL; DBT key, data; static char* kwnames[] = { "key", "data", "flags", "dlen", "doff", NULL }; @@ -3558,7 +3558,7 @@ int err, flags = 0; DBT key, data; PyObject *retval, *keyobj; - PyBuffer *key_buf_view = NULL; + Py_buffer *key_buf_view = NULL; static char* kwnames[] = { "key", "flags", "dlen", "doff", NULL }; int dlen = -1; int doff = -1; @@ -3630,7 +3630,7 @@ int err, flags = 0; DBT key, data; PyObject *retval, *keyobj; - PyBuffer *key_buf_view = NULL; + Py_buffer *key_buf_view = NULL; static char* kwnames[] = { "key", "flags", "dlen", "doff", NULL }; int dlen = -1; int doff = -1; @@ -3705,8 +3705,8 @@ int err; DBT key, data; PyObject *retval; - PyBuffer *data_buf_view = NULL; - PyBuffer *key_buf_view = NULL; + Py_buffer *data_buf_view = NULL; + Py_buffer *key_buf_view = NULL; /* the caller did this: CHECK_CURSOR_NOT_CLOSED(self); */ if (!make_key_dbt(self->mydb, keyobj, &key, NULL, &key_buf_view)) @@ -4480,7 +4480,7 @@ int locker, lock_mode; DBT obj; PyObject *objobj, *retval; - PyBuffer *obj_buf_view = NULL; + Py_buffer *obj_buf_view = NULL; if (!PyArg_ParseTuple(args, "iOi|i:lock_get", &locker, &objobj, &lock_mode, &flags)) return NULL; @@ -5057,7 +5057,7 @@ { int err, flags = 0; PyObject *keyobj; - PyBuffer *key_buf_view = NULL; + Py_buffer *key_buf_view = NULL; PyObject *txnobj = NULL; DB_TXN *txn = NULL; DBT key; Modified: python/branches/py3k-importlib/Modules/_ctypes/_ctypes.c ============================================================================== --- python/branches/py3k-importlib/Modules/_ctypes/_ctypes.c (original) +++ python/branches/py3k-importlib/Modules/_ctypes/_ctypes.c Sat Sep 29 22:20:33 2007 @@ -740,7 +740,7 @@ char *ptr; Py_ssize_t size; int rel = 0; - PyBuffer view; + Py_buffer view; if (PyBuffer_Check(value)) { if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0) @@ -2083,7 +2083,7 @@ { NULL }, }; -static int CData_GetBuffer(PyObject *_self, PyBuffer *view, int flags) +static int CData_GetBuffer(PyObject *_self, Py_buffer *view, int flags) { CDataObject *self = (CDataObject *)_self; return PyBuffer_FillInfo(view, self->b_ptr, self->b_size, 0, flags); @@ -3833,48 +3833,6 @@ } static int -Array_ass_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *value) -{ - CDataObject *self = (CDataObject *)_self; - Py_ssize_t i, len; - - if (value == NULL) { - PyErr_SetString(PyExc_TypeError, - "Array does not support item deletion"); - return -1; - } - - if (ilow < 0) - ilow = 0; - else if (ilow > self->b_length) - ilow = self->b_length; - if (ihigh < 0) - ihigh = 0; - if (ihigh < ilow) - ihigh = ilow; - else if (ihigh > self->b_length) - ihigh = self->b_length; - - len = PySequence_Length(value); - if (len != ihigh - ilow) { - PyErr_SetString(PyExc_ValueError, - "Can only assign sequence of same size"); - return -1; - } - for (i = 0; i < len; i++) { - PyObject *item = PySequence_GetItem(value, i); - int result; - if (item == NULL) - return -1; - result = Array_ass_item(_self, i+ilow, item); - Py_DECREF(item); - if (result == -1) - return -1; - } - return 0; -} - -static int Array_ass_subscript(PyObject *_self, PyObject *item, PyObject *value) { CDataObject *self = (CDataObject *)_self; Modified: python/branches/py3k-importlib/Modules/_hashopenssl.c ============================================================================== --- python/branches/py3k-importlib/Modules/_hashopenssl.c (original) +++ python/branches/py3k-importlib/Modules/_hashopenssl.c Sat Sep 29 22:20:33 2007 @@ -176,7 +176,7 @@ EVP_update(EVPobject *self, PyObject *args) { PyObject *obj; - PyBuffer view; + Py_buffer view; if (!PyArg_ParseTuple(args, "O:update", &obj)) return NULL; @@ -252,7 +252,7 @@ static char *kwlist[] = {"name", "string", NULL}; PyObject *name_obj = NULL; PyObject *data_obj = NULL; - PyBuffer view; + Py_buffer view; char *nameStr; const EVP_MD *digest; @@ -397,7 +397,7 @@ static char *kwlist[] = {"name", "string", NULL}; PyObject *name_obj = NULL; PyObject *data_obj = NULL; - PyBuffer view = { 0 }; + Py_buffer view = { 0 }; PyObject *ret_obj; char *name; const EVP_MD *digest; @@ -437,7 +437,7 @@ EVP_new_ ## NAME (PyObject *self, PyObject *args) \ { \ PyObject *data_obj = NULL; \ - PyBuffer view = { 0 }; \ + Py_buffer view = { 0 }; \ PyObject *ret_obj; \ \ if (!PyArg_ParseTuple(args, "|O:" #NAME , &data_obj)) { \ Modified: python/branches/py3k-importlib/Modules/_sre.c ============================================================================== --- python/branches/py3k-importlib/Modules/_sre.c (original) +++ python/branches/py3k-importlib/Modules/_sre.c Sat Sep 29 22:20:33 2007 @@ -1672,7 +1672,7 @@ Py_ssize_t size, bytes; int charsize; void* ptr; - PyBuffer view; + Py_buffer view; /* get pointer to string buffer */ view.len = -1; Modified: python/branches/py3k-importlib/Modules/arraymodule.c ============================================================================== --- python/branches/py3k-importlib/Modules/arraymodule.c (original) +++ python/branches/py3k-importlib/Modules/arraymodule.c Sat Sep 29 22:20:33 2007 @@ -1784,7 +1784,7 @@ static int -array_buffer_getbuf(arrayobject *self, PyBuffer *view, int flags) +array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags) { if ((flags & PyBUF_CHARACTER)) { PyErr_SetString(PyExc_TypeError, @@ -1825,7 +1825,7 @@ } static void -array_buffer_relbuf(arrayobject *self, PyBuffer *view) +array_buffer_relbuf(arrayobject *self, Py_buffer *view) { self->ob_exports--; } Modified: python/branches/py3k-importlib/Modules/datetimemodule.c ============================================================================== --- python/branches/py3k-importlib/Modules/datetimemodule.c (original) +++ python/branches/py3k-importlib/Modules/datetimemodule.c Sat Sep 29 22:20:33 2007 @@ -2082,7 +2082,7 @@ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ - 0, /*nb_coerce*/ + 0, /*nb_reserved*/ 0, /*nb_int*/ 0, /*nb_long*/ 0, /*nb_float*/ Modified: python/branches/py3k-importlib/Modules/mmapmodule.c ============================================================================== --- python/branches/py3k-importlib/Modules/mmapmodule.c (original) +++ python/branches/py3k-importlib/Modules/mmapmodule.c Sat Sep 29 22:20:33 2007 @@ -601,7 +601,7 @@ /* Functions for treating an mmap'ed file as a buffer */ static int -mmap_buffer_getbuf(mmap_object *self, PyBuffer *view, int flags) +mmap_buffer_getbuf(mmap_object *self, Py_buffer *view, int flags) { CHECK_VALID(-1); if (PyBuffer_FillInfo(view, self->data, self->size, @@ -612,7 +612,7 @@ } static void -mmap_buffer_releasebuf(mmap_object *self, PyBuffer *view) +mmap_buffer_releasebuf(mmap_object *self, Py_buffer *view) { self->exports--; } Modified: python/branches/py3k-importlib/Objects/abstract.c ============================================================================== --- python/branches/py3k-importlib/Objects/abstract.c (original) +++ python/branches/py3k-importlib/Objects/abstract.c Sat Sep 29 22:20:33 2007 @@ -224,7 +224,7 @@ Py_ssize_t *buffer_len) { PyBufferProcs *pb; - PyBuffer view; + Py_buffer view; if (obj == NULL || buffer == NULL || buffer_len == NULL) { null_error(); @@ -267,7 +267,7 @@ Py_ssize_t *buffer_len) { PyBufferProcs *pb; - PyBuffer view; + Py_buffer view; if (obj == NULL || buffer == NULL || buffer_len == NULL) { null_error(); @@ -295,7 +295,7 @@ Py_ssize_t *buffer_len) { PyBufferProcs *pb; - PyBuffer view; + Py_buffer view; if (obj == NULL || buffer == NULL || buffer_len == NULL) { null_error(); @@ -320,7 +320,7 @@ /* Buffer C-API for Python 3.0 */ int -PyObject_GetBuffer(PyObject *obj, PyBuffer *view, int flags) +PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { if (!PyObject_CheckBuffer(obj)) { PyErr_SetString(PyExc_TypeError, @@ -331,7 +331,7 @@ } void -PyObject_ReleaseBuffer(PyObject *obj, PyBuffer *view) +PyObject_ReleaseBuffer(PyObject *obj, Py_buffer *view) { if (obj->ob_type->tp_as_buffer != NULL && obj->ob_type->tp_as_buffer->bf_releasebuffer != NULL) { @@ -341,7 +341,7 @@ static int -_IsFortranContiguous(PyBuffer *view) +_IsFortranContiguous(Py_buffer *view) { Py_ssize_t sd, dim; int i; @@ -362,7 +362,7 @@ } static int -_IsCContiguous(PyBuffer *view) +_IsCContiguous(Py_buffer *view) { Py_ssize_t sd, dim; int i; @@ -383,7 +383,7 @@ } int -PyBuffer_IsContiguous(PyBuffer *view, char fort) +PyBuffer_IsContiguous(Py_buffer *view, char fort) { if (view->suboffsets != NULL) return 0; @@ -399,7 +399,7 @@ void* -PyBuffer_GetPointer(PyBuffer *view, Py_ssize_t *indices) +PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices) { char* pointer; int i; @@ -452,7 +452,7 @@ */ int -PyBuffer_ToContiguous(void *buf, PyBuffer *view, Py_ssize_t len, char fort) +PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort) { int k; void (*addone)(int, Py_ssize_t *, Py_ssize_t *); @@ -503,7 +503,7 @@ } int -PyBuffer_FromContiguous(PyBuffer *view, void *buf, Py_ssize_t len, char fort) +PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort) { int k; void (*addone)(int, Py_ssize_t *, Py_ssize_t *); @@ -556,7 +556,7 @@ int PyObject_CopyData(PyObject *dest, PyObject *src) { - PyBuffer view_dest, view_src; + Py_buffer view_dest, view_src; int k; Py_ssize_t *indices, elements; char *dptr, *sptr; @@ -649,7 +649,7 @@ } int -PyBuffer_FillInfo(PyBuffer *view, void *buf, Py_ssize_t len, +PyBuffer_FillInfo(Py_buffer *view, void *buf, Py_ssize_t len, int readonly, int flags) { if (view == NULL) return 0; Modified: python/branches/py3k-importlib/Objects/boolobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/boolobject.c (original) +++ python/branches/py3k-importlib/Objects/boolobject.c Sat Sep 29 22:20:33 2007 @@ -108,7 +108,7 @@ bool_and, /* nb_and */ bool_xor, /* nb_xor */ bool_or, /* nb_or */ - 0, /* nb_coerce */ + 0, /* nb_reserved */ 0, /* nb_int */ 0, /* nb_long */ 0, /* nb_float */ Modified: python/branches/py3k-importlib/Objects/bufferobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/bufferobject.c (original) +++ python/branches/py3k-importlib/Objects/bufferobject.c Sat Sep 29 22:20:33 2007 @@ -16,11 +16,12 @@ static int -get_buf(PyBufferObject *self, PyBuffer *view, int flags) +get_buf(PyBufferObject *self, Py_buffer *view, int flags) { if (self->b_base == NULL) { view->buf = self->b_ptr; view->len = self->b_size; + view->readonly = 0; } else { Py_ssize_t count, offset; @@ -46,7 +47,7 @@ static int -buffer_getbuf(PyBufferObject *self, PyBuffer *view, int flags) +buffer_getbuf(PyBufferObject *self, Py_buffer *view, int flags) { if (view == NULL) return 0; if (!get_buf(self, view, flags)) @@ -57,7 +58,7 @@ static void -buffer_releasebuf(PyBufferObject *self, PyBuffer *view) +buffer_releasebuf(PyBufferObject *self, Py_buffer *view) { /* No-op if there is no self->b_base */ if (self->b_base != NULL) { @@ -229,7 +230,7 @@ } static int -get_bufx(PyObject *obj, PyBuffer *view, int flags) +get_bufx(PyObject *obj, Py_buffer *view, int flags) { PyBufferProcs *bp; @@ -256,7 +257,7 @@ void *p1, *p2; Py_ssize_t len1, len2, min_len; int cmp, ok; - PyBuffer v1, v2; + Py_buffer v1, v2; ok = 1; if (!get_bufx(self, &v1, PyBUF_SIMPLE)) @@ -318,7 +319,7 @@ static long buffer_hash(PyBufferObject *self) { - PyBuffer view; + Py_buffer view; register Py_ssize_t len; register unsigned char *p; register long x; @@ -351,7 +352,7 @@ static PyObject * buffer_str(PyBufferObject *self) { - PyBuffer view; + Py_buffer view; PyObject *res; if (!get_buf(self, &view, PyBUF_SIMPLE)) @@ -366,7 +367,7 @@ static Py_ssize_t buffer_length(PyBufferObject *self) { - PyBuffer view; + Py_buffer view; if (!get_buf(self, &view, PyBUF_SIMPLE)) return -1; @@ -380,7 +381,7 @@ PyBufferProcs *pb = other->ob_type->tp_as_buffer; char *p; PyObject *ob; - PyBuffer view, view2; + Py_buffer view, view2; if (pb == NULL || pb->bf_getbuffer == NULL) @@ -426,7 +427,7 @@ { PyObject *ob; register char *p; - PyBuffer view; + Py_buffer view; if (count < 0) count = 0; @@ -450,7 +451,7 @@ static PyObject * buffer_item(PyBufferObject *self, Py_ssize_t idx) { - PyBuffer view; + Py_buffer view; PyObject *ob; if (!get_buf(self, &view, PyBUF_SIMPLE)) @@ -467,7 +468,7 @@ static PyObject * buffer_subscript(PyBufferObject *self, PyObject *item) { - PyBuffer view; + Py_buffer view; PyObject *ob; if (!get_buf(self, &view, PyBUF_SIMPLE)) @@ -537,7 +538,7 @@ buffer_ass_item(PyBufferObject *self, Py_ssize_t idx, PyObject *other) { PyBufferProcs *pb; - PyBuffer view, view2; + Py_buffer view, view2; if (!get_buf(self, &view, PyBUF_SIMPLE)) return -1; @@ -585,7 +586,7 @@ static int buffer_ass_subscript(PyBufferObject *self, PyObject *item, PyObject *value) { - PyBuffer v1; + Py_buffer v1; if (!get_buf(self, &v1, PyBUF_SIMPLE)) return -1; @@ -606,7 +607,7 @@ } else if (PySlice_Check(item)) { Py_ssize_t start, stop, step, slicelength; - PyBuffer v2; + Py_buffer v2; PyBufferProcs *pb; if (PySlice_GetIndicesEx((PySliceObject *)item, v1.len, Modified: python/branches/py3k-importlib/Objects/bytesobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/bytesobject.c (original) +++ python/branches/py3k-importlib/Objects/bytesobject.c Sat Sep 29 22:20:33 2007 @@ -50,7 +50,7 @@ } static int -bytes_getbuffer(PyBytesObject *obj, PyBuffer *view, int flags) +bytes_getbuffer(PyBytesObject *obj, Py_buffer *view, int flags) { int ret; void *ptr; @@ -70,13 +70,13 @@ } static void -bytes_releasebuffer(PyBytesObject *obj, PyBuffer *view) +bytes_releasebuffer(PyBytesObject *obj, Py_buffer *view) { obj->ob_exports--; } static Py_ssize_t -_getbuffer(PyObject *obj, PyBuffer *view) +_getbuffer(PyObject *obj, Py_buffer *view) { PyBufferProcs *buffer = Py_Type(obj)->tp_as_buffer; @@ -213,7 +213,7 @@ PyBytes_Concat(PyObject *a, PyObject *b) { Py_ssize_t size; - PyBuffer va, vb; + Py_buffer va, vb; PyBytesObject *result; va.len = -1; @@ -266,7 +266,7 @@ { Py_ssize_t mysize; Py_ssize_t size; - PyBuffer vo; + Py_buffer vo; if (_getbuffer(other, &vo) < 0) { PyErr_Format(PyExc_TypeError, "can't concat bytes to %.100s", @@ -462,7 +462,7 @@ { Py_ssize_t avail, needed; void *bytes; - PyBuffer vbytes; + Py_buffer vbytes; int res = 0; vbytes.len = -1; @@ -814,7 +814,7 @@ /* Use the modern buffer interface */ if (PyObject_CheckBuffer(arg)) { Py_ssize_t size; - PyBuffer view; + Py_buffer view; if (PyObject_GetBuffer(arg, &view, PyBUF_FULL_RO) < 0) return -1; size = view.len; @@ -954,7 +954,7 @@ bytes_richcompare(PyObject *self, PyObject *other, int op) { Py_ssize_t self_size, other_size; - PyBuffer self_bytes, other_bytes; + Py_buffer self_bytes, other_bytes; PyObject *res; Py_ssize_t minsize; int cmp; @@ -1067,7 +1067,7 @@ bytes_find_internal(PyBytesObject *self, PyObject *args, int dir) { PyObject *subobj; - PyBuffer subbuf; + Py_buffer subbuf; Py_ssize_t start=0, end=PY_SSIZE_T_MAX; Py_ssize_t res; @@ -2033,7 +2033,7 @@ { Py_ssize_t count = -1; PyObject *from, *to, *res; - PyBuffer vfrom, vto; + Py_buffer vfrom, vto; if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count)) return NULL; @@ -2187,7 +2187,7 @@ Py_ssize_t maxsplit = -1, count = 0; const char *s = PyBytes_AS_STRING(self), *sub; PyObject *list, *str, *subobj = Py_None; - PyBuffer vsub; + Py_buffer vsub; #ifdef USE_FAST Py_ssize_t pos; #endif @@ -2396,7 +2396,7 @@ Py_ssize_t maxsplit = -1, count = 0; const char *s = PyBytes_AS_STRING(self), *sub; PyObject *list, *str, *subobj = Py_None; - PyBuffer vsub; + Py_buffer vsub; if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit)) return NULL; @@ -2647,7 +2647,7 @@ Py_ssize_t left, right, mysize, argsize; void *myptr, *argptr; PyObject *arg = Py_None; - PyBuffer varg; + Py_buffer varg; if (!PyArg_ParseTuple(args, "|O:strip", &arg)) return NULL; if (arg == Py_None) { @@ -2683,7 +2683,7 @@ Py_ssize_t left, right, mysize, argsize; void *myptr, *argptr; PyObject *arg = Py_None; - PyBuffer varg; + Py_buffer varg; if (!PyArg_ParseTuple(args, "|O:lstrip", &arg)) return NULL; if (arg == Py_None) { @@ -2716,7 +2716,7 @@ Py_ssize_t left, right, mysize, argsize; void *myptr, *argptr; PyObject *arg = Py_None; - PyBuffer varg; + Py_buffer varg; if (!PyArg_ParseTuple(args, "|O:rstrip", &arg)) return NULL; if (arg == Py_None) { Modified: python/branches/py3k-importlib/Objects/complexobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/complexobject.c (original) +++ python/branches/py3k-importlib/Objects/complexobject.c Sat Sep 29 22:20:33 2007 @@ -963,7 +963,7 @@ 0, /* nb_and */ 0, /* nb_xor */ 0, /* nb_or */ - (coercion)0, /* nb_coerce */ + 0, /* nb_reserved */ complex_int, /* nb_int */ complex_long, /* nb_long */ complex_float, /* nb_float */ Modified: python/branches/py3k-importlib/Objects/floatobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/floatobject.c (original) +++ python/branches/py3k-importlib/Objects/floatobject.c Sat Sep 29 22:20:33 2007 @@ -235,8 +235,7 @@ } /* Macro and helper that convert PyObject obj to a C double and store - the value in dbl; this replaces the functionality of the coercion - slot function. If conversion to double raises an exception, obj is + the value in dbl. If conversion to double raises an exception, obj is set to NULL, and the function invoking this macro returns NULL. If obj is not of float, int or long type, Py_NotImplemented is incref'ed, stored in obj, and returned from the function invoking this macro. @@ -1069,7 +1068,7 @@ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ - (coercion)0, /*nb_coerce*/ + 0, /*nb_reserved*/ float_trunc, /*nb_int*/ float_trunc, /*nb_long*/ float_float, /*nb_float*/ Modified: python/branches/py3k-importlib/Objects/longobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/longobject.c (original) +++ python/branches/py3k-importlib/Objects/longobject.c Sat Sep 29 22:20:33 2007 @@ -3631,7 +3631,7 @@ long_and, /*nb_and*/ long_xor, /*nb_xor*/ long_or, /*nb_or*/ - 0, /*nb_coerce*/ + 0, /*nb_reserved*/ long_long, /*nb_int*/ long_long, /*nb_long*/ long_float, /*nb_float*/ Modified: python/branches/py3k-importlib/Objects/memoryobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/memoryobject.c (original) +++ python/branches/py3k-importlib/Objects/memoryobject.c Sat Sep 29 22:20:33 2007 @@ -4,16 +4,16 @@ #include "Python.h" static int -memory_getbuf(PyMemoryViewObject *self, PyBuffer *view, int flags) +memory_getbuf(PyMemoryViewObject *self, Py_buffer *view, int flags) { - if (view != NULL) - memcpy(view, &(self->view), sizeof(PyBuffer)); - return self->base->ob_type->tp_as_buffer->bf_getbuffer(self->base, - NULL, PyBUF_FULL); + if (view != NULL) + *view = self->view; + return self->base->ob_type->tp_as_buffer->bf_getbuffer(self->base, NULL, + PyBUF_FULL); } static void -memory_releasebuf(PyMemoryViewObject *self, PyBuffer *view) +memory_releasebuf(PyMemoryViewObject *self, Py_buffer *view) { PyObject_ReleaseBuffer(self->base, NULL); } @@ -24,11 +24,16 @@ Create a new memoryview object which references the given object."); PyObject * -PyMemoryView_FromMemory(PyBuffer *info) +PyMemoryView_FromMemory(Py_buffer *info) { - /* XXX(nnorwitz): need to implement something here? */ - PyErr_SetString(PyExc_NotImplementedError, "need to implement"); - return NULL; + PyMemoryViewObject *mview; + + mview = (PyMemoryViewObject *)PyObject_New(PyMemoryViewObject, + &PyMemoryView_Type); + if (mview == NULL) return NULL; + mview->base = NULL; + mview->view = *info; + return (PyObject *)mview; } PyObject * @@ -37,16 +42,16 @@ PyMemoryViewObject *mview; if (!PyObject_CheckBuffer(base)) { - PyErr_SetString(PyExc_TypeError, - "cannot make memory view because object does "\ + PyErr_SetString(PyExc_TypeError, + "cannot make memory view because object does " "not have the buffer interface"); - return NULL; + return NULL; } - - mview = (PyMemoryViewObject *)PyObject_New(PyMemoryViewObject, + + mview = (PyMemoryViewObject *)PyObject_New(PyMemoryViewObject, &PyMemoryView_Type); if (mview == NULL) return NULL; - + mview->base = NULL; if (PyObject_GetBuffer(base, &(mview->view), PyBUF_FULL) < 0) { Py_DECREF(mview); @@ -64,12 +69,12 @@ PyObject *obj; if (!PyArg_UnpackTuple(args, "memoryview", 1, 1, &obj)) return NULL; - return PyMemoryView_FromObject(obj); + return PyMemoryView_FromObject(obj); } static void -_strided_copy_nd(char *dest, char *src, int nd, Py_ssize_t *shape, +_strided_copy_nd(char *dest, char *src, int nd, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char fort) { int k; @@ -87,23 +92,23 @@ } else { if (fort == 'F') { - /* Copy first dimension first, + /* Copy first dimension first, second dimension second, etc... Set up the recursive loop backwards so that final - dimension is actually copied last. + dimension is actually copied last. */ outstride = itemsize; for (k=1; kndim); if (indices == NULL) { @@ -148,7 +153,7 @@ for (k=0; kndim;k++) { indices[k] = 0; } - + elements = 1; for (k=0; kndim; k++) { elements *= view->shape[k]; @@ -165,26 +170,26 @@ memcpy(dest, ptr, view->itemsize); dest += view->itemsize; } - + PyMem_Free(indices); return 0; } -/* +/* Get a the data from an object as a contiguous chunk of memory (in either 'C' or 'F'ortran order) even if it means copying it into a separate memory area. Returns a new reference to a Memory view object. If no copy is needed, - the memory view object points to the original memory and holds a + the memory view object points to the original memory and holds a lock on the original. If a copy is needed, then the memory view object - points to a brand-new Bytes object (and holds a memory lock on it). + points to a brand-new Bytes object (and holds a memory lock on it). buffertype PyBUF_READ buffer only needs to be read-only PyBUF_WRITE buffer needs to be writable (give error if not contiguous) - PyBUF_SHADOW buffer needs to be writable so shadow it with + PyBUF_SHADOW buffer needs to be writable so shadow it with a contiguous buffer if it is not. The view will point to the shadow buffer which can be written to and then will be copied back into the other buffer when the memory @@ -196,7 +201,7 @@ { PyMemoryViewObject *mem; PyObject *bytes; - PyBuffer *view; + Py_buffer *view; int flags; char *dest; @@ -205,7 +210,7 @@ "object does not have the buffer interface"); return NULL; } - + mem = PyObject_New(PyMemoryViewObject, &PyMemoryView_Type); if (mem == NULL) return NULL; @@ -235,8 +240,8 @@ if (buffertype == PyBUF_WRITE) { PyObject_DEL(mem); PyErr_SetString(PyExc_BufferError, - "writable contiguous buffer requested for a non-contiguous" \ - "object."); + "writable contiguous buffer requested " + "for a non-contiguousobject."); return NULL; } bytes = PyBytes_FromStringAndSize(NULL, view->len); @@ -250,22 +255,25 @@ */ /* strided or in-direct copy */ if (view->suboffsets==NULL) { - _strided_copy_nd(dest, view->buf, view->ndim, view->shape, - view->strides, view->itemsize, fort); + _strided_copy_nd(dest, view->buf, view->ndim, view->shape, + view->strides, view->itemsize, fort); } else { if (_indirect_copy_nd(dest, view, fort) < 0) { Py_DECREF(bytes); PyObject_ReleaseBuffer(obj, view); return NULL; - } + } } if (buffertype == PyBUF_SHADOW) { /* return a shadowed memory-view object */ view->buf = dest; mem->base = PyTuple_Pack(2, obj, bytes); - /* XXX(nnorwitz): need to verify alloc was successful. */ Py_DECREF(bytes); + if (mem->base == NULL) { + PyObject_ReleaseBuffer(obj, view); + return NULL; + } } else { PyObject_ReleaseBuffer(obj, view); @@ -348,7 +356,7 @@ return PyInt_FromLong(self->view.ndim); } -static PyGetSetDef memory_getsetlist[] ={ +static PyGetSetDef memory_getsetlist[] ={ {"format", (getter)memory_format_get, NULL, NULL}, {"itemsize", (getter)memory_itemsize_get, NULL, NULL}, {"shape", (getter)memory_shape_get, NULL, NULL}, @@ -364,13 +372,15 @@ static PyObject * memory_tobytes(PyMemoryViewObject *mem, PyObject *noargs) { - /* Create new Bytes object for data */ return PyBytes_FromObject((PyObject *)mem); } static PyObject * memory_tolist(PyMemoryViewObject *mem, PyObject *noargs) { + /* This should construct a (nested) list of unpacked objects + possibly using the struct module. + */ Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -393,16 +403,16 @@ with buffer interface and the second element is a contiguous "shadow" that must be copied back into the data areay of the first tuple element before - releasing the buffer on the first element. + releasing the buffer on the first element. */ - + PyObject_CopyData(PyTuple_GET_ITEM(self->base,0), PyTuple_GET_ITEM(self->base,1)); /* The view member should have readonly == -1 in this instance indicating that the memory can be "locked" and was locked and will be unlocked - again after this call. + again after this call. */ PyObject_ReleaseBuffer(PyTuple_GET_ITEM(self->base,0), &(self->view)); @@ -429,12 +439,12 @@ static PyObject * memory_str(PyMemoryViewObject *self) { - PyBuffer view; + Py_buffer view; PyObject *res; if (PyObject_GetBuffer((PyObject *)self, &view, PyBUF_FULL) < 0) return NULL; - + res = PyBytes_FromStringAndSize(NULL, view.len); PyBuffer_ToContiguous(PyBytes_AS_STRING(res), &view, view.len, 'C'); PyObject_ReleaseBuffer((PyObject *)self, &view); @@ -446,7 +456,7 @@ static Py_ssize_t memory_length(PyMemoryViewObject *self) { - PyBuffer view; + Py_buffer view; if (PyObject_GetBuffer((PyObject *)self, &view, PyBUF_FULL) < 0) return -1; @@ -454,9 +464,61 @@ return view.len; } +/* + mem[obj] returns a bytes object holding the data for one element if + obj fully indexes the memory view or another memory-view object + if it does not. + + 0-d memory-view objects can be referenced using ... or () but + not with anything else. + */ static PyObject * memory_subscript(PyMemoryViewObject *self, PyObject *key) { + Py_buffer *view; + view = &(self->view); + + if (view->ndim == 0) { + if (key == Py_Ellipsis || + (PyTuple_Check(key) && PyTuple_GET_SIZE(key)==0)) { + Py_INCREF(self); + return (PyObject *)self; + } + else { + PyErr_SetString(PyExc_IndexError, + "invalid indexing of 0-dim memory"); + return NULL; + } + } + if (PyIndex_Check(key)) { + Py_ssize_t result; + result = PyNumber_AsSsize_t(key, NULL); + if (result == -1 && PyErr_Occurred()) + return NULL; + if (view->ndim == 1) { + /* Return a bytes object */ + char *ptr; + ptr = (char *)view->buf; + if (view->strides == NULL) + ptr += view->itemsize * result; + else + ptr += view->strides[0] * result; + if (view->suboffsets != NULL && + view->suboffsets[0] >= 0) + { + ptr = *((char **)ptr) + view->suboffsets[0]; + } + return PyBytes_FromStringAndSize(ptr, view->itemsize); + } + else { + /* Return a new memory-view object */ + Py_buffer newview; + PyMemoryView_FromMemory(&newview); + } + } + + + Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -511,7 +573,7 @@ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ - memory_methods, /* tp_methods */ + memory_methods, /* tp_methods */ 0, /* tp_members */ memory_getsetlist, /* tp_getset */ 0, /* tp_base */ Modified: python/branches/py3k-importlib/Objects/setobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/setobject.c (original) +++ python/branches/py3k-importlib/Objects/setobject.c Sat Sep 29 22:20:33 2007 @@ -1881,7 +1881,7 @@ (binaryfunc)set_and, /*nb_and*/ (binaryfunc)set_xor, /*nb_xor*/ (binaryfunc)set_or, /*nb_or*/ - 0, /*nb_coerce*/ + 0, /*nb_reserved*/ 0, /*nb_int*/ 0, /*nb_long*/ 0, /*nb_float*/ Modified: python/branches/py3k-importlib/Objects/stringobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/stringobject.c (original) +++ python/branches/py3k-importlib/Objects/stringobject.c Sat Sep 29 22:20:33 2007 @@ -1160,7 +1160,7 @@ } static int -string_buffer_getbuffer(PyStringObject *self, PyBuffer *view, int flags) +string_buffer_getbuffer(PyStringObject *self, Py_buffer *view, int flags) { return PyBuffer_FillInfo(view, (void *)self->ob_sval, Py_Size(self), 0, flags); } Modified: python/branches/py3k-importlib/Objects/unicodeobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/unicodeobject.c (original) +++ python/branches/py3k-importlib/Objects/unicodeobject.c Sat Sep 29 22:20:33 2007 @@ -5412,14 +5412,20 @@ item = PySequence_Fast_GET_ITEM(fseq, i); /* Convert item to Unicode. */ - if (! PyUnicode_Check(item) && ! PyString_Check(item)) { - PyErr_Format(PyExc_TypeError, - "sequence item %zd: expected string or Unicode," - " %.80s found", - i, Py_Type(item)->tp_name); - goto onError; + if (!PyString_Check(item) && !PyUnicode_Check(item)) + { + if (PyBytes_Check(item)) + { + PyErr_Format(PyExc_TypeError, + "sequence item %d: join() will not operate on " + "bytes objects", i); + goto onError; + } + item = PyObject_Unicode(item); } - item = PyUnicode_FromObject(item); + else + item = PyUnicode_FromObject(item); + if (item == NULL) goto onError; /* We own a reference to item from here on. */ @@ -8104,7 +8110,7 @@ static int -unicode_buffer_getbuffer(PyUnicodeObject *self, PyBuffer *view, int flags) +unicode_buffer_getbuffer(PyUnicodeObject *self, Py_buffer *view, int flags) { if (flags & PyBUF_CHARACTER) { Modified: python/branches/py3k-importlib/Objects/weakrefobject.c ============================================================================== --- python/branches/py3k-importlib/Objects/weakrefobject.c (original) +++ python/branches/py3k-importlib/Objects/weakrefobject.c Sat Sep 29 22:20:33 2007 @@ -589,7 +589,7 @@ proxy_and, /*nb_and*/ proxy_xor, /*nb_xor*/ proxy_or, /*nb_or*/ - 0, /*nb_coerce*/ + 0, /*nb_reserved*/ proxy_int, /*nb_int*/ proxy_long, /*nb_long*/ proxy_float, /*nb_float*/ Modified: python/branches/py3k-importlib/PC/_winreg.c ============================================================================== --- python/branches/py3k-importlib/PC/_winreg.c (original) +++ python/branches/py3k-importlib/PC/_winreg.c Sat Sep 29 22:20:33 2007 @@ -430,7 +430,7 @@ PyHKEY_binaryFailureFunc, /* nb_and */ PyHKEY_binaryFailureFunc, /* nb_xor */ PyHKEY_binaryFailureFunc, /* nb_or */ - NULL, /* nb_coerce */ + 0, /* nb_reserved */ PyHKEY_intFunc, /* nb_int */ PyHKEY_unaryFailureFunc, /* nb_long */ PyHKEY_unaryFailureFunc, /* nb_float */ @@ -773,7 +773,7 @@ if (value == Py_None) *retDataSize = 0; else { - PyBuffer view; + Py_buffer view; if (!PyObject_CheckBuffer(value)) { PyErr_Format(PyExc_TypeError, Modified: python/branches/py3k-importlib/Parser/tokenizer.c ============================================================================== --- python/branches/py3k-importlib/Parser/tokenizer.c (original) +++ python/branches/py3k-importlib/Parser/tokenizer.c Sat Sep 29 22:20:33 2007 @@ -139,7 +139,7 @@ tok->alterror = 1; tok->alttabsize = 1; tok->altindstack[0] = 0; - tok->decoding_state = 0; + tok->decoding_state = STATE_INIT; tok->decoding_erred = 0; tok->read_coding_spec = 0; tok->encoding = NULL; @@ -280,7 +280,7 @@ if (cs != NULL) { tok->read_coding_spec = 1; if (tok->encoding == NULL) { - assert(tok->decoding_state == 1); /* raw */ + assert(tok->decoding_state == STATE_RAW); if (strcmp(cs, "utf-8") == 0 || strcmp(cs, "iso-8859-1") == 0) { tok->encoding = cs; @@ -288,7 +288,7 @@ r = set_readline(tok, cs); if (r) { tok->encoding = cs; - tok->decoding_state = -1; + tok->decoding_state = STATE_NORMAL; } else PyMem_FREE(cs); @@ -318,7 +318,7 @@ struct tok_state *tok) { int ch = get_char(tok); - tok->decoding_state = 1; + tok->decoding_state = STATE_RAW; if (ch == EOF) { return 1; } else if (ch == 0xEF) { @@ -330,11 +330,11 @@ } else if (ch == 0xFE) { ch = get_char(tok); if (ch != 0xFF) goto NON_BOM; if (!set_readline(tok, "utf-16-be")) return 0; - tok->decoding_state = -1; + tok->decoding_state = STATE_NORMAL; } else if (ch == 0xFF) { ch = get_char(tok); if (ch != 0xFE) goto NON_BOM; if (!set_readline(tok, "utf-16-le")) return 0; - tok->decoding_state = -1; + tok->decoding_state = STATE_NORMAL; #endif } else { unget_char(ch, tok); @@ -494,12 +494,12 @@ char *line = NULL; int badchar = 0; for (;;) { - if (tok->decoding_state < 0) { + if (tok->decoding_state == STATE_NORMAL) { /* We already have a codec associated with this input. */ line = fp_readl(s, size, tok); break; - } else if (tok->decoding_state > 0) { + } else if (tok->decoding_state == STATE_RAW) { /* We want a 'raw' read. */ line = Py_UniversalNewlineFgets(s, size, tok->fp, NULL); @@ -510,7 +510,7 @@ reader functions from now on. */ if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok)) return error_ret(tok); - assert(tok->decoding_state != 0); + assert(tok->decoding_state != STATE_INIT); } } if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) { @@ -550,7 +550,7 @@ static int decoding_feof(struct tok_state *tok) { - if (tok->decoding_state >= 0) { + if (tok->decoding_state != STATE_NORMAL) { return feof(tok->fp); } else { PyObject* buf = tok->decoding_buffer; @@ -700,7 +700,7 @@ return NULL; } strcpy(tok->encoding, enc); - tok->decoding_state = -1; + tok->decoding_state = STATE_NORMAL; } return tok; } Modified: python/branches/py3k-importlib/Parser/tokenizer.h ============================================================================== --- python/branches/py3k-importlib/Parser/tokenizer.h (original) +++ python/branches/py3k-importlib/Parser/tokenizer.h Sat Sep 29 22:20:33 2007 @@ -12,6 +12,12 @@ #define MAXINDENT 100 /* Max indentation level */ +enum decoding_state { + STATE_INIT, + STATE_RAW, + STATE_NORMAL, /* have a codec associated with input */ +}; + /* Tokenizer state */ struct tok_state { /* Input state; buf <= cur <= inp <= end */ @@ -40,7 +46,7 @@ int alttabsize; /* Alternate tab spacing */ int altindstack[MAXINDENT]; /* Stack of alternate indents */ /* Stuff for PEP 0263 */ - int decoding_state; /* -1:decoding, 0:init, 1:raw */ + enum decoding_state decoding_state; int decoding_erred; /* whether erred in decoding */ int read_coding_spec; /* whether 'coding:...' has been read */ char *encoding; Modified: python/branches/py3k-importlib/Python/getargs.c ============================================================================== --- python/branches/py3k-importlib/Python/getargs.c (original) +++ python/branches/py3k-importlib/Python/getargs.c Sat Sep 29 22:20:33 2007 @@ -1211,7 +1211,7 @@ PyBufferProcs *pb = arg->ob_type->tp_as_buffer; int count; int temp=-1; - PyBuffer view; + Py_buffer view; if (pb == NULL || pb->bf_getbuffer == NULL || @@ -1242,7 +1242,7 @@ char **p = va_arg(*p_va, char **); PyBufferProcs *pb = arg->ob_type->tp_as_buffer; int count; - PyBuffer view; + Py_buffer view; if (*format++ != '#') return converterr( @@ -1286,7 +1286,7 @@ { PyBufferProcs *pb = arg->ob_type->tp_as_buffer; Py_ssize_t count; - PyBuffer view; + Py_buffer view; *errmsg = NULL; *p = NULL; Modified: python/branches/py3k-importlib/Python/marshal.c ============================================================================== --- python/branches/py3k-importlib/Python/marshal.c (original) +++ python/branches/py3k-importlib/Python/marshal.c Sat Sep 29 22:20:33 2007 @@ -367,7 +367,7 @@ /* Write unknown buffer-style objects as a string */ char *s; PyBufferProcs *pb = v->ob_type->tp_as_buffer; - PyBuffer view; + Py_buffer view; if ((*pb->bf_getbuffer)(v, &view, PyBUF_SIMPLE) != 0) { w_byte(TYPE_UNKNOWN, p); p->error = 1; Modified: python/branches/py3k-importlib/Tools/modulator/Templates/object_tp_as_number ============================================================================== --- python/branches/py3k-importlib/Tools/modulator/Templates/object_tp_as_number (original) +++ python/branches/py3k-importlib/Tools/modulator/Templates/object_tp_as_number Sat Sep 29 22:20:33 2007 @@ -103,13 +103,6 @@ /* XXXX */ } -static int -$abbrev$_coerce(PyObject **pv, PyObject **pw) -{ - /* XXXX I haven't a clue... */ - return 1; -} - static PyObject * $abbrev$_int($abbrev$object *v) { Modified: python/branches/py3k-importlib/Tools/scripts/byext.py ============================================================================== --- python/branches/py3k-importlib/Tools/scripts/byext.py (original) +++ python/branches/py3k-importlib/Tools/scripts/byext.py Sat Sep 29 22:20:33 2007 @@ -1,4 +1,4 @@ -#! /usr/bin/env python +#! /usr/bin/env python3.0 """Show file statistics by extension.""" @@ -60,13 +60,13 @@ data = f.read() f.close() self.addstats(ext, "bytes", len(data)) - if '\0' in data: + if b'\0' in data: self.addstats(ext, "binary", 1) return if not data: self.addstats(ext, "empty", 1) #self.addstats(ext, "chars", len(data)) - lines = data.splitlines() + lines = str(data, "latin-1").splitlines() self.addstats(ext, "lines", len(lines)) del lines words = data.split() @@ -77,14 +77,12 @@ d[key] = d.get(key, 0) + n def report(self): - exts = self.stats.keys() - exts.sort() + exts = sorted(self.stats) # Get the column keys columns = {} for ext in exts: columns.update(self.stats[ext]) - cols = columns.keys() - cols.sort() + cols = sorted(columns) colwidth = {} colwidth["ext"] = max([len(ext) for ext in exts]) minwidth = 6