From: <th...@us...> - 2008-09-01 14:34:02
|
Revision: 5280 http://jython.svn.sourceforge.net/jython/?rev=5280&view=rev Author: thobes Date: 2008-09-01 14:33:42 +0000 (Mon, 01 Sep 2008) Log Message: ----------- Manually performing the merge I would have liked svnmerge to do. However I could not figure out how get the merge right. The problem was that the advanced branch is a branch from a branch (asm), and that the branch has been merged into trunk. I wanted to merge in changes that had occured both in the asm branch and in trunk so that I could merge from trunk in the future. This was simply too many circular merges for svnmerge to handle. Anyhow the merge in this commit brings the advanced branch up to the state where the asm branch was merged into trunk. The branch pointer has also been redirected to point to trunk so that svnmerge will work for future merges. Modified Paths: -------------- branches/advanced/.classpath branches/advanced/CPythonLib.includes branches/advanced/CoreExposed.includes branches/advanced/Lib/codeop.py branches/advanced/Lib/datetime.py branches/advanced/Lib/distutils/ccompiler.py branches/advanced/Lib/distutils/command/bdist.py branches/advanced/Lib/distutils/command/bdist_dumb.py branches/advanced/Lib/distutils/command/install.py branches/advanced/Lib/distutils/command/sdist.py branches/advanced/Lib/distutils/file_util.py branches/advanced/Lib/distutils/spawn.py branches/advanced/Lib/distutils/sysconfig.py branches/advanced/Lib/distutils/util.py branches/advanced/Lib/ntpath.py branches/advanced/Lib/os.py branches/advanced/Lib/posixpath.py branches/advanced/Lib/random.py branches/advanced/Lib/site.py branches/advanced/Lib/socket.py branches/advanced/Lib/subprocess.py branches/advanced/Lib/test/list_tests.py branches/advanced/Lib/test/regrtest.py branches/advanced/Lib/test/test__rawffi.py branches/advanced/Lib/test/test_array_jy.py branches/advanced/Lib/test/test_ast.py branches/advanced/Lib/test/test_builtin.py branches/advanced/Lib/test/test_cmd_line.py branches/advanced/Lib/test/test_deque.py branches/advanced/Lib/test/test_descr_jy.py branches/advanced/Lib/test/test_descrtut.py branches/advanced/Lib/test/test_dict_jy.py branches/advanced/Lib/test/test_exceptions_jy.py branches/advanced/Lib/test/test_file_newlines.py branches/advanced/Lib/test/test_float_jy.py branches/advanced/Lib/test/test_format.py branches/advanced/Lib/test/test_functools.py branches/advanced/Lib/test/test_grammar_jy.py branches/advanced/Lib/test/test_importhooks.py branches/advanced/Lib/test/test_inspect.py branches/advanced/Lib/test/test_java_integration.py branches/advanced/Lib/test/test_javashell.py branches/advanced/Lib/test/test_jreload.py branches/advanced/Lib/test/test_jser2.py branches/advanced/Lib/test/test_jy_internals.py branches/advanced/Lib/test/test_re_jy.py branches/advanced/Lib/test/test_select.py branches/advanced/Lib/test/test_select_new.py branches/advanced/Lib/test/test_slots_jy.py branches/advanced/Lib/test/test_socket.py branches/advanced/Lib/test/test_subclasses.py branches/advanced/Lib/test/test_support.py branches/advanced/Lib/test/test_sys_jy.py branches/advanced/Lib/test/test_traceback.py branches/advanced/Lib/threading.py branches/advanced/Misc/make_binops.py branches/advanced/NEWS branches/advanced/README.txt branches/advanced/ast/asdl_antlr.py branches/advanced/ast/astdump.py branches/advanced/build.xml branches/advanced/compiler/org/python/compiler/AdvancedCompiler.java branches/advanced/extlibs/jna-posix.jar branches/advanced/grammar/Python.g branches/advanced/grammar/PythonPartial.g branches/advanced/grammar/PythonWalker.g branches/advanced/src/com/ziclix/python/sql/DataHandler.java branches/advanced/src/com/ziclix/python/sql/Fetch.java branches/advanced/src/com/ziclix/python/sql/PyConnection.java branches/advanced/src/com/ziclix/python/sql/PyCursor.java branches/advanced/src/com/ziclix/python/sql/PyExtendedCursor.java branches/advanced/src/com/ziclix/python/sql/PyStatement.java branches/advanced/src/com/ziclix/python/sql/connect/Connect.java branches/advanced/src/com/ziclix/python/sql/connect/Connectx.java branches/advanced/src/com/ziclix/python/sql/connect/Lookup.java branches/advanced/src/com/ziclix/python/sql/util/BCP.java branches/advanced/src/org/python/antlr/ExpressionParser.java branches/advanced/src/org/python/antlr/InteractiveParser.java branches/advanced/src/org/python/antlr/ModuleParser.java branches/advanced/src/org/python/antlr/ParseException.java branches/advanced/src/org/python/antlr/PythonTokenSource.java branches/advanced/src/org/python/antlr/PythonTree.java branches/advanced/src/org/python/antlr/PythonTreeAdaptor.java branches/advanced/src/org/python/antlr/ast/Assert.java branches/advanced/src/org/python/antlr/ast/Assign.java branches/advanced/src/org/python/antlr/ast/Attribute.java branches/advanced/src/org/python/antlr/ast/AugAssign.java branches/advanced/src/org/python/antlr/ast/BinOp.java branches/advanced/src/org/python/antlr/ast/BoolOp.java branches/advanced/src/org/python/antlr/ast/Break.java branches/advanced/src/org/python/antlr/ast/Call.java branches/advanced/src/org/python/antlr/ast/ClassDef.java branches/advanced/src/org/python/antlr/ast/Compare.java branches/advanced/src/org/python/antlr/ast/Continue.java branches/advanced/src/org/python/antlr/ast/Delete.java branches/advanced/src/org/python/antlr/ast/Dict.java branches/advanced/src/org/python/antlr/ast/Ellipsis.java branches/advanced/src/org/python/antlr/ast/Exec.java branches/advanced/src/org/python/antlr/ast/Expr.java branches/advanced/src/org/python/antlr/ast/Expression.java branches/advanced/src/org/python/antlr/ast/ExtSlice.java branches/advanced/src/org/python/antlr/ast/For.java branches/advanced/src/org/python/antlr/ast/FunctionDef.java branches/advanced/src/org/python/antlr/ast/GeneratorExp.java branches/advanced/src/org/python/antlr/ast/Global.java branches/advanced/src/org/python/antlr/ast/If.java branches/advanced/src/org/python/antlr/ast/IfExp.java branches/advanced/src/org/python/antlr/ast/Import.java branches/advanced/src/org/python/antlr/ast/ImportFrom.java branches/advanced/src/org/python/antlr/ast/Index.java branches/advanced/src/org/python/antlr/ast/Interactive.java branches/advanced/src/org/python/antlr/ast/Lambda.java branches/advanced/src/org/python/antlr/ast/List.java branches/advanced/src/org/python/antlr/ast/ListComp.java branches/advanced/src/org/python/antlr/ast/Module.java branches/advanced/src/org/python/antlr/ast/Name.java branches/advanced/src/org/python/antlr/ast/Num.java branches/advanced/src/org/python/antlr/ast/Pass.java branches/advanced/src/org/python/antlr/ast/Print.java branches/advanced/src/org/python/antlr/ast/Raise.java branches/advanced/src/org/python/antlr/ast/Repr.java branches/advanced/src/org/python/antlr/ast/Return.java branches/advanced/src/org/python/antlr/ast/Slice.java branches/advanced/src/org/python/antlr/ast/Str.java branches/advanced/src/org/python/antlr/ast/Subscript.java branches/advanced/src/org/python/antlr/ast/Suite.java branches/advanced/src/org/python/antlr/ast/TryExcept.java branches/advanced/src/org/python/antlr/ast/TryFinally.java branches/advanced/src/org/python/antlr/ast/Tuple.java branches/advanced/src/org/python/antlr/ast/UnaryOp.java branches/advanced/src/org/python/antlr/ast/Unicode.java branches/advanced/src/org/python/antlr/ast/While.java branches/advanced/src/org/python/antlr/ast/With.java branches/advanced/src/org/python/antlr/ast/Yield.java branches/advanced/src/org/python/antlr/ast/aliasType.java branches/advanced/src/org/python/antlr/ast/argumentsType.java branches/advanced/src/org/python/antlr/ast/comprehensionType.java branches/advanced/src/org/python/antlr/ast/excepthandlerType.java branches/advanced/src/org/python/antlr/ast/keywordType.java branches/advanced/src/org/python/compiler/APIVersion.java branches/advanced/src/org/python/compiler/ClassFile.java branches/advanced/src/org/python/compiler/Code.java branches/advanced/src/org/python/compiler/CodeCompiler.java branches/advanced/src/org/python/compiler/Module.java branches/advanced/src/org/python/compiler/ScopeInfo.java branches/advanced/src/org/python/compiler/ScopesCompiler.java branches/advanced/src/org/python/core/AbstractArray.java branches/advanced/src/org/python/core/ArgParser.java branches/advanced/src/org/python/core/CompilerFacade.java branches/advanced/src/org/python/core/CompilerFlags.java branches/advanced/src/org/python/core/FunctionThread.java branches/advanced/src/org/python/core/ParserFacade.java branches/advanced/src/org/python/core/Py.java branches/advanced/src/org/python/core/PyArray.java branches/advanced/src/org/python/core/PyArrayDerived.java branches/advanced/src/org/python/core/PyBaseException.java branches/advanced/src/org/python/core/PyBaseExceptionDerived.java branches/advanced/src/org/python/core/PyBooleanDerived.java branches/advanced/src/org/python/core/PyClass.java branches/advanced/src/org/python/core/PyClassMethodDerived.java branches/advanced/src/org/python/core/PyComplex.java branches/advanced/src/org/python/core/PyComplexDerived.java branches/advanced/src/org/python/core/PyDictionaryDerived.java branches/advanced/src/org/python/core/PyEnumerateDerived.java branches/advanced/src/org/python/core/PyFileDerived.java branches/advanced/src/org/python/core/PyFloat.java branches/advanced/src/org/python/core/PyFloatDerived.java branches/advanced/src/org/python/core/PyFrame.java branches/advanced/src/org/python/core/PyFrozenSetDerived.java branches/advanced/src/org/python/core/PyGenerator.java branches/advanced/src/org/python/core/PyInstance.java branches/advanced/src/org/python/core/PyInteger.java branches/advanced/src/org/python/core/PyIntegerDerived.java branches/advanced/src/org/python/core/PyJavaClass.java branches/advanced/src/org/python/core/PyJavaPackage.java branches/advanced/src/org/python/core/PyList.java branches/advanced/src/org/python/core/PyListDerived.java branches/advanced/src/org/python/core/PyLong.java branches/advanced/src/org/python/core/PyLongDerived.java branches/advanced/src/org/python/core/PyMethod.java branches/advanced/src/org/python/core/PyModule.java branches/advanced/src/org/python/core/PyModuleDerived.java branches/advanced/src/org/python/core/PyObject.java branches/advanced/src/org/python/core/PyObjectDerived.java branches/advanced/src/org/python/core/PyPropertyDerived.java branches/advanced/src/org/python/core/PySequence.java branches/advanced/src/org/python/core/PySequenceIter.java branches/advanced/src/org/python/core/PySetDerived.java branches/advanced/src/org/python/core/PySlice.java branches/advanced/src/org/python/core/PySliceDerived.java branches/advanced/src/org/python/core/PyString.java branches/advanced/src/org/python/core/PyStringDerived.java branches/advanced/src/org/python/core/PySuper.java branches/advanced/src/org/python/core/PySuperDerived.java branches/advanced/src/org/python/core/PySyntaxError.java branches/advanced/src/org/python/core/PySystemState.java branches/advanced/src/org/python/core/PyTableCode.java branches/advanced/src/org/python/core/PyTraceback.java branches/advanced/src/org/python/core/PyTuple.java branches/advanced/src/org/python/core/PyTupleDerived.java branches/advanced/src/org/python/core/PyType.java branches/advanced/src/org/python/core/PyTypeDerived.java branches/advanced/src/org/python/core/PyUnicode.java branches/advanced/src/org/python/core/PyUnicodeDerived.java branches/advanced/src/org/python/core/StdoutWrapper.java branches/advanced/src/org/python/core/ThreadState.java branches/advanced/src/org/python/core/__builtin__.java branches/advanced/src/org/python/core/imp.java branches/advanced/src/org/python/core/io/FileIO.java branches/advanced/src/org/python/core/io/TextIOBase.java branches/advanced/src/org/python/modules/ArrayModule.java branches/advanced/src/org/python/modules/Setup.java branches/advanced/src/org/python/modules/_codecs.java branches/advanced/src/org/python/modules/_weakref/ProxyType.java branches/advanced/src/org/python/modules/_weakref/ReferenceTypeDerived.java branches/advanced/src/org/python/modules/cPickle.java branches/advanced/src/org/python/modules/cStringIO.java branches/advanced/src/org/python/modules/collections/PyDefaultDictDerived.java branches/advanced/src/org/python/modules/collections/PyDeque.java branches/advanced/src/org/python/modules/collections/PyDequeDerived.java branches/advanced/src/org/python/modules/imp.java branches/advanced/src/org/python/modules/operator.java branches/advanced/src/org/python/modules/random/PyRandomDerived.java branches/advanced/src/org/python/modules/sre/MatchObject.java branches/advanced/src/org/python/modules/sre/PatternObject.java branches/advanced/src/org/python/modules/struct.java branches/advanced/src/org/python/modules/thread/PyLocalDerived.java branches/advanced/src/org/python/modules/thread/thread.java branches/advanced/src/org/python/modules/zipimport/zipimporter.java branches/advanced/src/org/python/modules/zipimport/zipimporterDerived.java branches/advanced/src/org/python/util/InteractiveInterpreter.java branches/advanced/src/org/python/util/PythonInterpreter.java branches/advanced/src/org/python/util/jython.java branches/advanced/src/shell/jython branches/advanced/src/templates/mappings branches/advanced/src/templates/object.derived Added Paths: ----------- branches/advanced/Lib/decimal.py branches/advanced/Lib/distutils/tests/ branches/advanced/Lib/distutils/tests/test_build_py.py branches/advanced/Lib/grp.py branches/advanced/Lib/pkgutil.py branches/advanced/Lib/pwd.py branches/advanced/Lib/test/bad_coding2.py branches/advanced/Lib/test/test_array.py branches/advanced/Lib/test/test_class.py branches/advanced/Lib/test/test_cmp_jy.py branches/advanced/Lib/test/test_codeop.py branches/advanced/Lib/test/test_compile.py branches/advanced/Lib/test/test_cpickle_jy.py branches/advanced/Lib/test/test_generators.py branches/advanced/Lib/test/test_genexps.py branches/advanced/Lib/test/test_iter_jy.py branches/advanced/Lib/test/test_operator.py branches/advanced/Lib/test/test_pkgimport.py branches/advanced/Lib/test/test_subprocess_jy.py branches/advanced/Lib/test/test_syntax.py branches/advanced/Lib/test/test_tuple.py branches/advanced/extlibs/antlr-3.1.jar branches/advanced/extlibs/antlr-runtime-3.1.jar branches/advanced/extlibs/stringtemplate-3.2.jar branches/advanced/src/com/ziclix/python/sql/Jython22DataHandler.java branches/advanced/src/org/python/antlr/BaseParser.java branches/advanced/src/org/python/antlr/ErrorHandler.java branches/advanced/src/org/python/antlr/FailFastHandler.java branches/advanced/src/org/python/antlr/GrammarActions.java branches/advanced/src/org/python/antlr/ListErrorHandler.java branches/advanced/src/org/python/antlr/PythonErrorNode.java branches/advanced/src/org/python/antlr/ast/ErrorExpr.java branches/advanced/src/org/python/antlr/ast/ErrorMod.java branches/advanced/src/org/python/antlr/ast/ErrorSlice.java branches/advanced/src/org/python/antlr/ast/ErrorStmt.java branches/advanced/src/org/python/core/APIReader.java branches/advanced/src/org/python/core/PyFastSequenceIter.java branches/advanced/src/org/python/core/PyIndentationError.java branches/advanced/src/org/python/core/io/TextIOInputStream.java branches/advanced/src/org/python/modules/_csv/ branches/advanced/src/org/python/modules/_csv/PyDialect.java branches/advanced/src/org/python/modules/_csv/PyDialectDerived.java branches/advanced/src/org/python/modules/_csv/PyReader.java branches/advanced/src/org/python/modules/_csv/PyWriter.java branches/advanced/src/org/python/modules/_csv/QuoteStyle.java branches/advanced/src/org/python/modules/_csv/_csv.java branches/advanced/src/org/python/modules/_functools/ branches/advanced/src/org/python/modules/_functools/PyPartial.java branches/advanced/src/org/python/modules/_functools/PyPartialDerived.java branches/advanced/src/org/python/modules/_functools/_functools.java branches/advanced/src/org/python/modules/_systemrestart.java branches/advanced/src/shell/jython.bat branches/advanced/src/templates/dialect.derived branches/advanced/src/templates/partial.derived branches/advanced/tests/java/org/python/antlr/ branches/advanced/tests/java/org/python/antlr/GrammarTester.java branches/advanced/tests/java/org/python/antlr/PythonPartialTester.java branches/advanced/tests/java/org/python/antlr/PythonTreeTester.java branches/advanced/tests/java/org/python/antlr/WalkerTester.java Removed Paths: ------------- branches/advanced/Lib/UserList.py branches/advanced/Lib/distutils/tests/test_build_py.py branches/advanced/Lib/functools.py branches/advanced/Lib/test/output/test_array_jy branches/advanced/Lib/test/output/test_re branches/advanced/Lib/test/seq_tests.py branches/advanced/Lib/test/test_userlist.py branches/advanced/extlibs/antlr-3.1b1.jar branches/advanced/extlibs/antlr-runtime-3.1b1.jar branches/advanced/extlibs/stringtemplate-3.1b1.jar branches/advanced/src/org/python/antlr/GrammarTester.java branches/advanced/src/org/python/antlr/IParserHost.java branches/advanced/src/org/python/antlr/ImaginaryToken.java branches/advanced/src/org/python/antlr/LeadingSpaceSkippingStream.java branches/advanced/src/org/python/antlr/PythonPartialTester.java branches/advanced/src/org/python/antlr/PythonPartialTokenSource.java branches/advanced/src/org/python/antlr/PythonTreeTester.java branches/advanced/src/org/python/antlr/WalkerTester.java branches/advanced/src/org/python/modules/_csv/PyDialect.java branches/advanced/src/org/python/modules/_csv/PyDialectDerived.java branches/advanced/src/org/python/modules/_csv/PyReader.java branches/advanced/src/org/python/modules/_csv/PyWriter.java branches/advanced/src/org/python/modules/_csv/QuoteStyle.java branches/advanced/src/org/python/modules/_csv/_csv.java branches/advanced/src/org/python/modules/_functools/PyPartial.java branches/advanced/src/org/python/modules/_functools/PyPartialDerived.java branches/advanced/src/org/python/modules/_functools/_functools.java branches/advanced/src/org/python/modules/xreadlines.java branches/advanced/tests/java/org/python/antlr/GrammarTester.java branches/advanced/tests/java/org/python/antlr/PythonPartialTester.java branches/advanced/tests/java/org/python/antlr/PythonTreeTester.java branches/advanced/tests/java/org/python/antlr/WalkerTester.java Property Changed: ---------------- branches/advanced/ Property changes on: branches/advanced ___________________________________________________________________ Modified: svnmerge-integrated - /branches/asm:1-4928 /trunk/jython:1-4899 + /trunk/jython:1-5210 Modified: branches/advanced/.classpath =================================================================== --- branches/advanced/.classpath 2008-09-01 06:32:39 UTC (rev 5279) +++ branches/advanced/.classpath 2008-09-01 14:33:42 UTC (rev 5280) @@ -19,6 +19,6 @@ <classpathentry kind="lib" path="extlibs/servlet-api-2.5.jar"/> <classpathentry kind="lib" path="build/jarjar"/> <classpathentry kind="var" path="Ant"/> - <classpathentry kind="lib" path="extlibs/antlr-3.1b1.jar"/> + <classpathentry kind="lib" path="extlibs/antlr-runtime-3.1.jar"/> <classpathentry kind="output" path="bugtests/classes"/> </classpath> Modified: branches/advanced/CPythonLib.includes =================================================================== --- branches/advanced/CPythonLib.includes 2008-09-01 06:32:39 UTC (rev 5279) +++ branches/advanced/CPythonLib.includes 2008-09-01 14:33:42 UTC (rev 5280) @@ -43,11 +43,12 @@ copy.py copy_reg.py Cookie.py -decimal.py +csv.py difflib.py dircache.py dircmp.py dis.py +DocXMLRPCServer.py dospath.py dumbdbm.py exceptions.py @@ -57,6 +58,7 @@ formatter.py fpformat.py ftplib.py +functools.py getopt.py gettext.py glob.py @@ -69,6 +71,7 @@ htmllib.py HTMLParser.py httplib.py +ihooks.py imaplib.py imghdr.py inspect.py @@ -116,6 +119,7 @@ repr.py rfc822.py rlcompleter.py +robotparser.py runpy.py sched.py sha.py @@ -136,6 +140,7 @@ string.py StringIO.py symbol.py +tabnanny.py this.py threading.py textwrap.py @@ -151,6 +156,7 @@ urlparse.py user.py UserDict.py +UserList.py UserString.py uu.py uuid.py Modified: branches/advanced/CoreExposed.includes =================================================================== --- branches/advanced/CoreExposed.includes 2008-09-01 06:32:39 UTC (rev 5279) +++ branches/advanced/CoreExposed.includes 2008-09-01 14:33:42 UTC (rev 5280) @@ -35,6 +35,11 @@ org/python/core/PyType.class org/python/core/PyUnicode.class org/python/core/PyXRange.class +org/python/modules/_codecs$EncodingMap.class +org/python/modules/_csv/PyDialect.class +org/python/modules/_csv/PyReader.class +org/python/modules/_csv/PyWriter.class +org/python/modules/_functools/PyPartial.class org/python/modules/_weakref/CallableProxyType.class org/python/modules/_weakref/ReferenceType.class org/python/modules/_weakref/ProxyType.class Deleted: branches/advanced/Lib/UserList.py =================================================================== --- branches/advanced/Lib/UserList.py 2008-09-01 06:32:39 UTC (rev 5279) +++ branches/advanced/Lib/UserList.py 2008-09-01 14:33:42 UTC (rev 5280) @@ -1,94 +0,0 @@ -"""A more or less complete user-defined wrapper around list objects.""" - -#Imported from Python 2.3.5 and added _fixindex -class UserList: - def __init__(self, initlist=None): - self.data = [] - if initlist is not None: - # XXX should this accept an arbitrary sequence? - if type(initlist) == type(self.data): - self.data[:] = initlist - elif isinstance(initlist, UserList): - self.data[:] = initlist.data[:] - else: - self.data = list(initlist) - def __repr__(self): return repr(self.data) - def __lt__(self, other): return self.data < self.__cast(other) - def __le__(self, other): return self.data <= self.__cast(other) - def __eq__(self, other): return self.data == self.__cast(other) - def __ne__(self, other): return self.data != self.__cast(other) - def __gt__(self, other): return self.data > self.__cast(other) - def __ge__(self, other): return self.data >= self.__cast(other) - def __cast(self, other): - if isinstance(other, UserList): return other.data - else: return other - def __cmp__(self, other): - return cmp(self.data, self.__cast(other)) - def __contains__(self, item): return item in self.data - def __len__(self): return len(self.data) - def __getitem__(self, i): return self.data[i] - def __setitem__(self, i, item): self.data[i] = item - def __delitem__(self, i): del self.data[i] - def __getslice__(self, i, j): - i = self._fixindex(i); j = self._fixindex(j) - return self.__class__(self.data[i:j]) - def __setslice__(self, i, j, other): - i = self._fixindex(i); j = self._fixindex(j) - if isinstance(other, UserList): - self.data[i:j] = other.data - elif isinstance(other, type(self.data)): - self.data[i:j] = other - else: - self.data[i:j] = list(other) - def __delslice__(self, i, j): - i = self._fixindex(i); j = self._fixindex(j) - del self.data[i:j] - def __add__(self, other): - if isinstance(other, UserList): - return self.__class__(self.data + other.data) - elif isinstance(other, type(self.data)): - return self.__class__(self.data + other) - else: - return self.__class__(self.data + list(other)) - def __radd__(self, other): - if isinstance(other, UserList): - return self.__class__(other.data + self.data) - elif isinstance(other, type(self.data)): - return self.__class__(other + self.data) - else: - return self.__class__(list(other) + self.data) - def __iadd__(self, other): - if isinstance(other, UserList): - self.data += other.data - elif isinstance(other, type(self.data)): - self.data += other - else: - self.data += list(other) - return self - def __mul__(self, n): - return self.__class__(self.data*n) - __rmul__ = __mul__ - def __imul__(self, n): - self.data *= n - return self - def append(self, item): self.data.append(item) - def insert(self, i, item): self.data.insert(i, item) - def pop(self, i=-1): return self.data.pop(i) - def remove(self, item): self.data.remove(item) - def count(self, item): return self.data.count(item) - def index(self, item, *args): return self.data.index(item, *args) - def reverse(self): self.data.reverse() - def sort(self, *args): self.data.sort(*args) - def extend(self, other): - if isinstance(other, UserList): - self.data.extend(other.data) - else: - self.data.extend(other) - def _fixindex(self, index): - if index < 0: - index += len(self.data) - elif index > len(self.data): - index = len(self.data) - index = max(index, 0) - return index - Modified: branches/advanced/Lib/codeop.py =================================================================== --- branches/advanced/Lib/codeop.py 2008-09-01 06:32:39 UTC (rev 5279) +++ branches/advanced/Lib/codeop.py 2008-09-01 14:33:42 UTC (rev 5280) @@ -58,6 +58,7 @@ # import internals, not guaranteed interface from org.python.core import Py,CompilerFlags +from org.python.core.CompilerFlags import PyCF_DONT_IMPLY_DEDENT # public interface Modified: branches/advanced/Lib/datetime.py =================================================================== --- branches/advanced/Lib/datetime.py 2008-09-01 06:32:39 UTC (rev 5279) +++ branches/advanced/Lib/datetime.py 2008-09-01 14:33:42 UTC (rev 5280) @@ -981,6 +981,24 @@ def __reduce__(self): return (self.__class__, self.__getstate()) + def __tojava__(self, java_class): + from java.lang import Object + from java.sql import Date + from java.util import Calendar + from org.python.core import Py + + if java_class not in (Calendar, Date, Object): + return Py.NoConversion + + calendar = Calendar.getInstance() + calendar.clear() + calendar.set(self.year, self.month - 1, self.day) + if java_class == Calendar: + return calendar + else: + return Date(calendar.getTimeInMillis()) + + _date_class = date # so functions w/ args named "date" can get at the class date.min = date(1, 1, 1) @@ -1346,6 +1364,28 @@ def __reduce__(self): return (time, self.__getstate()) + def __tojava__(self, java_class): + # TODO, if self.tzinfo is not None, convert time to UTC + from java.lang import Object + from java.sql import Time + from java.util import Calendar + from org.python.core import Py + + if java_class not in (Calendar, Time, Object): + return Py.NoConversion + + calendar = Calendar.getInstance() + calendar.clear() + calendar.set(Calendar.HOUR_OF_DAY, self.hour) + calendar.set(Calendar.MINUTE, self.minute) + calendar.set(Calendar.SECOND, self.second) + calendar.set(Calendar.MILLISECOND, self.microsecond // 1000) + if java_class == Calendar: + return calendar + else: + return Time(calendar.getTimeInMillis()) + + _time_class = time # so functions w/ args named "time" can get at the class time.min = time(0, 0, 0) @@ -1799,7 +1839,28 @@ def __reduce__(self): return (self.__class__, self.__getstate()) + def __tojava__(self, java_class): + # TODO, if self.tzinfo is not None, convert time to UTC + from java.lang import Object + from java.sql import Timestamp + from java.util import Calendar + from org.python.core import Py + if java_class not in (Calendar, Timestamp, Object): + return Py.NoConversion + + calendar = Calendar.getInstance() + calendar.clear() + calendar.set(self.year, self.month - 1, self.day, + self.hour, self.minute, self.second) + calendar.set(Calendar.MILLISECOND, self.microsecond // 1000) + + if java_class == Calendar: + return calendar + else: + return Timestamp(calendar.getTimeInMillis()) + + datetime.min = datetime(1, 1, 1) datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999) datetime.resolution = timedelta(microseconds=1) Copied: branches/advanced/Lib/decimal.py (from rev 4988, branches/asm/Lib/decimal.py) =================================================================== --- branches/advanced/Lib/decimal.py (rev 0) +++ branches/advanced/Lib/decimal.py 2008-09-01 14:33:42 UTC (rev 5280) @@ -0,0 +1,5173 @@ +# Copyright (c) 2004 Python Software Foundation. +# All rights reserved. + +# Written by Eric Price <eprice at tjhsst.edu> +# and Facundo Batista <facundo at taniquetil.com.ar> +# and Raymond Hettinger <python at rcn.com> +# and Aahz <aahz at pobox.com> +# and Tim Peters + +# This module is currently Py2.3 compatible and should be kept that way +# unless a major compelling advantage arises. IOW, 2.3 compatibility is +# strongly preferred, but not guaranteed. + +# Also, this module should be kept in sync with the latest updates of +# the IBM specification as it evolves. Those updates will be treated +# as bug fixes (deviation from the spec is a compatibility, usability +# bug) and will be backported. At this point the spec is stabilizing +# and the updates are becoming fewer, smaller, and less significant. + +""" +This is a Py2.3 implementation of decimal floating point arithmetic based on +the General Decimal Arithmetic Specification: + + www2.hursley.ibm.com/decimal/decarith.html + +and IEEE standard 854-1987: + + www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html + +Decimal floating point has finite precision with arbitrarily large bounds. + +The purpose of this module is to support arithmetic using familiar +"schoolhouse" rules and to avoid some of the tricky representation +issues associated with binary floating point. The package is especially +useful for financial applications or for contexts where users have +expectations that are at odds with binary floating point (for instance, +in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead +of the expected Decimal("0.00") returned by decimal floating point). + +Here are some examples of using the decimal module: + +>>> from decimal import * +>>> setcontext(ExtendedContext) +>>> Decimal(0) +Decimal("0") +>>> Decimal("1") +Decimal("1") +>>> Decimal("-.0123") +Decimal("-0.0123") +>>> Decimal(123456) +Decimal("123456") +>>> Decimal("123.45e12345678901234567890") +Decimal("1.2345E+12345678901234567892") +>>> Decimal("1.33") + Decimal("1.27") +Decimal("2.60") +>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41") +Decimal("-2.20") +>>> dig = Decimal(1) +>>> print dig / Decimal(3) +0.333333333 +>>> getcontext().prec = 18 +>>> print dig / Decimal(3) +0.333333333333333333 +>>> print dig.sqrt() +1 +>>> print Decimal(3).sqrt() +1.73205080756887729 +>>> print Decimal(3) ** 123 +4.85192780976896427E+58 +>>> inf = Decimal(1) / Decimal(0) +>>> print inf +Infinity +>>> neginf = Decimal(-1) / Decimal(0) +>>> print neginf +-Infinity +>>> print neginf + inf +NaN +>>> print neginf * inf +-Infinity +>>> print dig / 0 +Infinity +>>> getcontext().traps[DivisionByZero] = 1 +>>> print dig / 0 +Traceback (most recent call last): + ... + ... + ... +DivisionByZero: x / 0 +>>> c = Context() +>>> c.traps[InvalidOperation] = 0 +>>> print c.flags[InvalidOperation] +0 +>>> c.divide(Decimal(0), Decimal(0)) +Decimal("NaN") +>>> c.traps[InvalidOperation] = 1 +>>> print c.flags[InvalidOperation] +1 +>>> c.flags[InvalidOperation] = 0 +>>> print c.flags[InvalidOperation] +0 +>>> print c.divide(Decimal(0), Decimal(0)) +Traceback (most recent call last): + ... + ... + ... +InvalidOperation: 0 / 0 +>>> print c.flags[InvalidOperation] +1 +>>> c.flags[InvalidOperation] = 0 +>>> c.traps[InvalidOperation] = 0 +>>> print c.divide(Decimal(0), Decimal(0)) +NaN +>>> print c.flags[InvalidOperation] +1 +>>> +""" + +__all__ = [ + # Two major classes + 'Decimal', 'Context', + + # Contexts + 'DefaultContext', 'BasicContext', 'ExtendedContext', + + # Exceptions + 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero', + 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow', + + # 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_05UP', + + # Functions for manipulating contexts + 'setcontext', 'getcontext', 'localcontext' +] + +import copy as _copy + +# Rounding +ROUND_DOWN = 'ROUND_DOWN' +ROUND_HALF_UP = 'ROUND_HALF_UP' +ROUND_HALF_EVEN = 'ROUND_HALF_EVEN' +ROUND_CEILING = 'ROUND_CEILING' +ROUND_FLOOR = 'ROUND_FLOOR' +ROUND_UP = 'ROUND_UP' +ROUND_HALF_DOWN = 'ROUND_HALF_DOWN' +ROUND_05UP = 'ROUND_05UP' + +# Errors + +class DecimalException(ArithmeticError): + """Base exception class. + + Used exceptions derive from this. + If an exception derives from another exception besides this (such as + Underflow (Inexact, Rounded, Subnormal) that indicates that it is only + called if the others are present. This isn't actually used for + anything, though. + + handle -- Called when context._raise_error is called and the + trap_enabler is set. First argument is self, second is the + context. More arguments can be given, those being after + the explanation in _raise_error (For example, + context._raise_error(NewError, '(-x)!', self._sign) would + call NewError().handle(context, self._sign).) + + To define a new exception, it should be sufficient to have it derive + from DecimalException. + """ + def handle(self, context, *args): + pass + + +class Clamped(DecimalException): + """Exponent of a 0 changed to fit bounds. + + This occurs and signals clamped if the exponent of a result has been + altered in order to fit the constraints of a specific concrete + representation. This may occur when the exponent of a zero result would + be outside the bounds of a representation, or when a large normal + number would have an encoded exponent that cannot be represented. In + this latter case, the exponent is reduced to fit and the corresponding + number of zero digits are appended to the coefficient ("fold-down"). + """ + +class InvalidOperation(DecimalException): + """An invalid operation was performed. + + Various bad things cause this: + + Something creates a signaling NaN + -INF + INF + 0 * (+-)INF + (+-)INF / (+-)INF + x % 0 + (+-)INF % x + x._rescale( non-integer ) + sqrt(-x) , x > 0 + 0 ** 0 + 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: + ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True) + return ans._fix_nan(context) + return NaN + +class ConversionSyntax(InvalidOperation): + """Trying to convert badly formed string. + + This occurs and signals invalid-operation if an string is being + 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 NaN + +class DivisionByZero(DecimalException, ZeroDivisionError): + """Division by 0. + + This occurs and signals division-by-zero if division of a finite number + by zero was attempted (during a divide-integer or divide operation, or a + power operation with negative right-hand operand), and the dividend was + not zero. + + The result of the operation is [sign,inf], where sign is the exclusive + or of the signs of the operands for divide, or is 1 for an odd power of + -0, for power. + """ + + def handle(self, context, sign, *args): + return Infsign[sign] + +class DivisionImpossible(InvalidOperation): + """Cannot perform the division adequately. + + This occurs and signals invalid-operation if the integer result of a + divide-integer or remainder operation had too many digits (would be + longer than precision). The result is [0,qNaN]. + """ + + def handle(self, context, *args): + return NaN + +class DivisionUndefined(InvalidOperation, ZeroDivisionError): + """Undefined result of division. + + This occurs and signals invalid-operation if division by zero was + attempted (during a divide-integer, divide, or remainder operation), and + the dividend is also zero. The result is [0,qNaN]. + """ + + def handle(self, context, *args): + return NaN + +class Inexact(DecimalException): + """Had to round, losing information. + + This occurs and signals inexact whenever the result of an operation is + not exact (that is, it needed to be rounded and any discarded digits + were non-zero), or if an overflow or underflow condition occurs. The + result in all cases is unchanged. + + The inexact signal may be tested (or trapped) to determine if a given + operation (or sequence of operations) was inexact. + """ + +class InvalidContext(InvalidOperation): + """Invalid context. Unknown rounding, for example. + + This occurs and signals invalid-operation if an invalid context was + detected during an operation. This can occur if contexts are not checked + on creation and either the precision exceeds the capability of the + underlying concrete representation or an unknown or unsupported rounding + was specified. These aspects of the context need only be checked when + the values are required to be used. The result is [0,qNaN]. + """ + + def handle(self, context, *args): + return NaN + +class Rounded(DecimalException): + """Number got rounded (not necessarily changed during rounding). + + This occurs and signals rounded whenever the result of an operation is + rounded (that is, some zero or non-zero digits were discarded from the + coefficient), or if an overflow or underflow condition occurs. The + result in all cases is unchanged. + + The rounded signal may be tested (or trapped) to determine if a given + operation (or sequence of operations) caused a loss of precision. + """ + +class Subnormal(DecimalException): + """Exponent < Emin before rounding. + + This occurs and signals subnormal whenever the result of a conversion or + operation is subnormal (that is, its adjusted exponent is less than + Emin, before any rounding). The result in all cases is unchanged. + + The subnormal signal may be tested (or trapped) to determine if a given + or operation (or sequence of operations) yielded a subnormal result. + """ + +class Overflow(Inexact, Rounded): + """Numerical overflow. + + This occurs and signals overflow if the adjusted exponent of a result + (from a conversion or from an operation that is not an attempt to divide + by zero), after rounding, would be greater than the largest value that + can be handled by the implementation (the value Emax). + + The result depends on the rounding mode: + + For round-half-up and round-half-even (and for round-half-down and + round-up, if implemented), the result of the operation is [sign,inf], + where sign is the sign of the intermediate result. For round-down, the + result is the largest finite number that can be represented in the + current precision, with the sign of the intermediate result. For + round-ceiling, the result is the same as for round-down if the sign of + the intermediate result is 1, or is [0,inf] otherwise. For round-floor, + the result is the same as for round-down if the sign of the intermediate + result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded + will also be raised. + """ + + def handle(self, context, sign, *args): + if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN, + ROUND_HALF_DOWN, ROUND_UP): + return Infsign[sign] + if sign == 0: + if context.rounding == ROUND_CEILING: + return Infsign[sign] + return _dec_from_triple(sign, '9'*context.prec, + context.Emax-context.prec+1) + if sign == 1: + if context.rounding == ROUND_FLOOR: + return Infsign[sign] + return _dec_from_triple(sign, '9'*context.prec, + context.Emax-context.prec+1) + + +class Underflow(Inexact, Rounded, Subnormal): + """Numerical underflow with result rounded to 0. + + This occurs and signals underflow if a result is inexact and the + adjusted exponent of the result would be smaller (more negative) than + the smallest value that can be handled by the implementation (the value + Emin). That is, the result is both inexact and subnormal. + + The result after an underflow will be a subnormal number rounded, if + necessary, so that its exponent is not less than Etiny. This may result + in 0 with the sign of the intermediate result and an exponent of Etiny. + + In all cases, Inexact, Rounded, and Subnormal will also be raised. + """ + +# List of public traps and flags +_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded, + Underflow, InvalidOperation, Subnormal] + +# Map conditions (per the spec) to signals +_condition_map = {ConversionSyntax:InvalidOperation, + DivisionImpossible:InvalidOperation, + DivisionUndefined:InvalidOperation, + InvalidContext:InvalidOperation} + +##### Context Functions ################################################## + +# The getcontext() and setcontext() function manage access to a thread-local +# current context. Py2.4 offers direct support for thread locals. If that +# is not available, use threading.currentThread() which is slower but will +# work for older Pythons. If threads are not part of the build, create a +# mock threading object with threading.local() returning the module namespace. + +try: + import threading +except ImportError: + # Python was compiled without threads; create a mock object instead + import sys + class MockThreading(object): + def local(self, sys=sys): + return sys.modules[__name__] + threading = MockThreading() + del sys, MockThreading + +try: + threading.local + +except AttributeError: + + # To fix reloading, force it to create a new context + # Old contexts have different exceptions in their dicts, making problems. + if hasattr(threading.currentThread(), '__decimal_context__'): + del threading.currentThread().__decimal_context__ + + def setcontext(context): + """Set this thread's context to context.""" + if context in (DefaultContext, BasicContext, ExtendedContext): + context = context.copy() + context.clear_flags() + threading.currentThread().__decimal_context__ = context + + def getcontext(): + """Returns this thread's context. + + If this thread does not yet have a context, returns + a new context and sets this thread's context. + New contexts are copies of DefaultContext. + """ + try: + return threading.currentThread().__decimal_context__ + except AttributeError: + context = Context() + threading.currentThread().__decimal_context__ = context + return context + +else: + + local = threading.local() + if hasattr(local, '__decimal_context__'): + del local.__decimal_context__ + + def getcontext(_local=local): + """Returns this thread's context. + + If this thread does not yet have a context, returns + a new context and sets this thread's context. + New contexts are copies of DefaultContext. + """ + try: + return _local.__decimal_context__ + except AttributeError: + context = Context() + _local.__decimal_context__ = context + return context + + def setcontext(context, _local=local): + """Set this thread's context to context.""" + if context in (DefaultContext, BasicContext, ExtendedContext): + context = context.copy() + context.clear_flags() + _local.__decimal_context__ = context + + del threading, local # Don't contaminate the namespace + +def localcontext(ctx=None): + """Return a context manager for a copy of the supplied context + + Uses a copy of the current context if no context is specified + The returned context manager creates a local decimal context + in a with statement: + def sin(x): + with localcontext() as ctx: + ctx.prec += 2 + # Rest of sin calculation algorithm + # uses a precision 2 greater than normal + return +s # Convert result to normal precision + + def sin(x): + with localcontext(ExtendedContext): + # Rest of sin calculation algorithm + # uses the Extended Context from the + # General Decimal Arithmetic Specification + return +s # Convert result to normal context + + """ + # The string below can't be included in the docstring until Python 2.6 + # as the doctest module doesn't understand __future__ statements + """ + >>> from __future__ import with_statement + >>> print getcontext().prec + 28 + >>> with localcontext(): + ... ctx = getcontext() + ... ctx.prec += 2 + ... print ctx.prec + ... + 30 + >>> with localcontext(ExtendedContext): + ... print getcontext().prec + ... + 9 + >>> print getcontext().prec + 28 + """ + if ctx is None: ctx = getcontext() + return _ContextManager(ctx) + + +##### Decimal class ####################################################### + +class Decimal(object): + """Floating point class for decimal arithmetic.""" + + __slots__ = ('_exp','_int','_sign', '_is_special') + # Generally, the value of the Decimal instance is given by + # (-1)**_sign * _int * 10**_exp + # Special values are signified by _is_special == True + + # We're immutable, so use __new__ not __init__ + def __new__(cls, value="0", context=None): + """Create a decimal point instance. + + >>> Decimal('3.14') # string input + Decimal("3.14") + >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent) + Decimal("3.14") + >>> Decimal(314) # int or long + Decimal("314") + >>> Decimal(Decimal(314)) # another decimal instance + Decimal("314") + """ + + # Note that the coefficient, self._int, is actually stored as + # a string rather than as a tuple of digits. This speeds up + # the "digits to integer" and "integer to digits" conversions + # that are used in almost every arithmetic operation on + # Decimals. This is an internal detail: the as_tuple function + # and the Decimal constructor still deal with tuples of + # digits. + + self = object.__new__(cls) + + # From a string + # REs insist on real strings, so we can too. + if isinstance(value, basestring): + m = _parser(value) + if m is None: + if context is None: + context = getcontext() + return context._raise_error(ConversionSyntax, + "Invalid literal for Decimal: %r" % value) + + if m.group('sign') == "-": + self._sign = 1 + else: + self._sign = 0 + intpart = m.group('int') + if intpart is not None: + # finite number + fracpart = m.group('frac') + exp = int(m.group('exp') or '0') + if fracpart is not None: + self._int = str((intpart+fracpart).lstrip('0') or '0') + self._exp = exp - len(fracpart) + else: + self._int = str(intpart.lstrip('0') or '0') + self._exp = exp + self._is_special = False + else: + diag = m.group('diag') + if diag is not None: + # NaN + self._int = str(diag.lstrip('0')) + if m.group('signal'): + self._exp = 'N' + else: + self._exp = 'n' + else: + # infinity + self._int = '0' + self._exp = 'F' + self._is_special = True + return self + + # From an integer + if isinstance(value, (int,long)): + if value >= 0: + self._sign = 0 + else: + self._sign = 1 + self._exp = 0 + self._int = str(abs(value)) + self._is_special = False + return self + + # From another decimal + if isinstance(value, Decimal): + self._exp = value._exp + self._sign = value._sign + self._int = value._int + self._is_special = value._is_special + return self + + # From an internal working value + if isinstance(value, _WorkRep): + self._sign = value.sign + self._int = str(value.int) + self._exp = int(value.exp) + self._is_special = False + return self + + # tuple/list conversion (possibly from as_tuple()) + if isinstance(value, (list,tuple)): + if len(value) != 3: + raise ValueError('Invalid tuple size in creation of Decimal ' + 'from list or tuple. The list or tuple ' + 'should have exactly three elements.') + # process sign. The isinstance test rejects floats + if not (isinstance(value[0], (int, long)) and value[0] in (0,1)): + raise ValueError("Invalid sign. The first value in the tuple " + "should be an integer; either 0 for a " + "positive number or 1 for a negative number.") + self._sign = value[0] + if value[2] == 'F': + # infinity: value[1] is ignored + self._int = '0' + self._exp = value[2] + self._is_special = True + else: + # process and validate the digits in value[1] + digits = [] + for digit in value[1]: + if isinstance(digit, (int, long)) and 0 <= digit <= 9: + # skip leading zeros + if digits or digit != 0: + digits.append(digit) + else: + raise ValueError("The second value in the tuple must " + "be composed of integers in the range " + "0 through 9.") + if value[2] in ('n', 'N'): + # NaN: digits form the diagnostic + self._int = ''.join(map(str, digits)) + self._exp = value[2] + self._is_special = True + elif isinstance(value[2], (int, long)): + # finite number: digits give the coefficient + self._int = ''.join(map(str, digits or [0])) + self._exp = value[2] + self._is_special = False + else: + raise ValueError("The third value in the tuple must " + "be an integer, or one of the " + "strings 'F', 'n', 'N'.") + return self + + if isinstance(value, float): + raise TypeError("Cannot convert float to Decimal. " + + "First convert the float to a string") + + raise TypeError("Cannot convert %r to Decimal" % value) + + def _isnan(self): + """Returns whether the number is not actually one. + + 0 if a number + 1 if NaN + 2 if sNaN + """ + if self._is_special: + exp = self._exp + if exp == 'n': + return 1 + elif exp == 'N': + return 2 + return 0 + + def _isinfinity(self): + """Returns whether the number is infinite + + 0 if finite or not a number + 1 if +INF + -1 if -INF + """ + if self._exp == 'F': + if self._sign: + return -1 + return 1 + return 0 + + def _check_nans(self, other=None, context=None): + """Returns whether the number is not actually one. + + if self, other are sNaN, signal + if self, other are NaN return nan + return 0 + + Done before operations. + """ + + self_is_nan = self._isnan() + if other is None: + other_is_nan = False + else: + other_is_nan = other._isnan() + + if self_is_nan or other_is_nan: + if context is None: + context = getcontext() + + if self_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + self) + if other_is_nan == 2: + return context._raise_error(InvalidOperation, 'sNaN', + other) + if self_is_nan: + return self._fix_nan(context) + + return other._fix_nan(context) + return 0 + + def __nonzero__(self): + """Return True if self is nonzero; otherwise return False. + + NaNs and infinities are considered nonzero. + """ + return self._is_special or self._int != '0' + + def __cmp__(self, other): + other = _convert_other(other) + if other is NotImplemented: + # Never return NotImplemented + return 1 + + if self._is_special or other._is_special: + # 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()) + + # 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: + return -1 + if self._sign < other._sign: + return 1 + + self_adjusted = self.adjusted() + other_adjusted = other.adjusted() + 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 + else: # self_adjusted < other_adjusted + return -((-1)**self._sign) + + def __eq__(self, other): + if not isinstance(other, (Decimal, int, long)): + return NotImplemented + return self.__cmp__(other) == 0 + + def __ne__(self, other): + if not isinstance(other, (Decimal, int, long)): + return NotImplemented + return self.__cmp__(other) != 0 + + def compare(self, other, context=None): + """Compares one to another. + + -1 => a < b + 0 => a = b + 1 => a > b + NaN => one is NaN + Like __cmp__, but returns Decimal instances. + """ + other = _convert_other(other, raiseit=True) + + # Compare(NaN, NaN) = NaN + if (self._is_special or other and other._is_special): + ans = self._check_nans(other, context) + if ans: + return ans + + return Decimal(self.__cmp__(other)) + + def __hash__(self): + """x.__hash__() <==> hash(x)""" + # Decimal integers must hash the same as the ints + # + # The hash of a nonspecial noninteger Decimal must depend only + # on the value of that Decimal, and not on its representation. + # For example: hash(Decimal("100E-1")) == hash(Decimal("10")). + if self._is_special: + if self._isnan(): + raise TypeError('Cannot hash a NaN value.') + return hash(str(self)) + if not self: + return 0 + if self._isinteger(): + op = _WorkRep(self.to_integral_value()) + return hash((-1)**op.sign*op.int*10**op.exp) + # The value of a nonzero nonspecial Decimal instance is + # faithfully represented by the triple consisting of its sign, + # its adjusted exponent, and its coefficient with trailing + # zeros removed. + return hash((self._sign, + self._exp+len(self._int), + self._int.rstrip('0'))) + + def as_tuple(self): + """Represents the number as a triple tuple. + + To show the internals exactly as they are. + """ + return (self._sign, tuple(map(int, self._int)), self._exp) + + def __repr__(self): + """Represents the number as an instance of Decimal.""" + # Invariant: eval(repr(d)) == d + return 'Decimal("%s")' % str(self) + + 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. + """ + + sign = ['', '-'][self._sign] + if self._is_special: + if self._exp == 'F': + return sign + 'Infinity' + elif self._exp == 'n': + return sign + 'NaN' + self._int + else: # self._exp == 'N' + return sign + 'sNaN' + self._int + + # number of digits of self._int to left of decimal point + leftdigits = self._exp + len(self._int) + + # dotplace is number of digits of self._int to the left of the + # decimal point in the mantissa of the output string (that... [truncated message content] |