[Python-checkins] r53867 - in python/branches/p3yk-noslice: BROKEN Doc/api/concrete.tex Doc/commontex/license.tex Doc/dist/dist.tex Doc/howto/TODO Doc/howto/curses.tex Doc/howto/doanddont.tex Doc/howto/regex.tex Doc/lib/emailgenerator.tex Doc/lib/libcollections.tex Doc/lib/libdis.tex Doc/lib/libexcs.tex Doc/lib/libfunctools.tex Doc/lib/libheapq.tex Doc/lib/libimageop.tex Doc/lib/libitertools.tex Doc/lib/liblocale.tex Doc/lib/liblogging.tex Doc/lib/libmailbox.tex Doc/lib/libos.tex Doc/lib/librandom.tex Doc/lib/libshutil.tex Doc/lib/libsmtplib.tex Doc/lib/libsocket.tex Doc/lib/libstdtypes.tex Doc/lib/libstruct.tex Doc/lib/libtarfile.tex Doc/lib/libtest.tex Doc/lib/libtime.tex Doc/lib/libzipfile.tex Doc/ref/ref3.tex Doc/ref/ref4.tex Doc/ref/ref6.tex Doc/tut/tut.tex Doc/whatsnew/whatsnew26.tex Grammar/Grammar INTBENCH Include/Python-ast.h Include/abstract.h Include/boolobject.h Include/ceval.h Include/dictobject.h Include/fileobject.h Include/graminit.h Include/intobject.h Include/longobject.h Include/object.h Include/opcode.h Lib/BaseHTTPServer.py Lib/Bastion.py Lib/CGIHTTPServer.py Lib/ConfigParser.py Lib/Cookie.py Lib/DocXMLRPCServer.py Lib/SimpleXMLRPCServer.py Lib/SocketServer.py Lib/StringIO.py Lib/UserDict.py Lib/UserString.py Lib/_LWPCookieJar.py Lib/_strptime.py Lib/_threading_local.py Lib/aifc.py Lib/asynchat.py Lib/asyncore.py Lib/atexit.py Lib/audiodev.py Lib/base64.py Lib/bdb.py Lib/bsddb/dbrecio.py Lib/bsddb/dbtables.py Lib/bsddb/test/test_all.py Lib/bsddb/test/test_associate.py Lib/bsddb/test/test_basics.py Lib/bsddb/test/test_compat.py Lib/bsddb/test/test_dbshelve.py Lib/bsddb/test/test_dbtables.py Lib/bsddb/test/test_join.py Lib/bsddb/test/test_lock.py Lib/bsddb/test/test_queue.py Lib/bsddb/test/test_recno.py Lib/bsddb/test/test_thread.py Lib/cProfile.py Lib/calendar.py Lib/cgi.py Lib/code.py Lib/compileall.py Lib/compiler/ast.py Lib/compiler/future.py Lib/compiler/misc.py Lib/compiler/pyassem.py Lib/compiler/pycodegen.py Lib/compiler/symbols.py Lib/compiler/syntax.py Lib/compiler/transformer.py Lib/compiler/visitor.py Lib/cookielib.py Lib/copy.py Lib/csv.py Lib/ctypes/__init__.py Lib/ctypes/test/__init__.py Lib/ctypes/test/test_as_parameter.py Lib/ctypes/test/test_byteswap.py Lib/ctypes/test/test_find.py Lib/ctypes/test/test_functions.py Lib/ctypes/test/test_keeprefs.py Lib/ctypes/test/test_loading.py Lib/ctypes/test/test_numbers.py Lib/ctypes/test/test_objects.py Lib/ctypes/test/test_pointers.py Lib/ctypes/test/test_prototypes.py Lib/ctypes/test/test_strings.py Lib/ctypes/test/test_win32.py Lib/ctypes/util.py Lib/ctypes/wintypes.py Lib/curses/has_key.py Lib/curses/textpad.py Lib/decimal.py Lib/difflib.py Lib/dis.py Lib/distutils/bcppcompiler.py Lib/distutils/ccompiler.py Lib/distutils/cmd.py Lib/distutils/command/bdist_rpm.py Lib/distutils/command/build_ext.py Lib/distutils/command/config.py Lib/distutils/command/install.py Lib/distutils/command/register.py Lib/distutils/command/upload.py Lib/distutils/core.py Lib/distutils/dist.py Lib/distutils/fancy_getopt.py Lib/distutils/filelist.py Lib/distutils/log.py Lib/distutils/mwerkscompiler.py Lib/distutils/spawn.py Lib/distutils/sysconfig.py Lib/distutils/tests/test_dist.py Lib/distutils/text_file.py Lib/distutils/versionpredicate.py Lib/doctest.py Lib/dumbdbm.py Lib/dummy_thread.py Lib/dummy_threading.py Lib/email/charset.py Lib/email/generator.py Lib/email/iterators.py Lib/email/test/test_email.py Lib/email/test/test_email_codecs.py Lib/email/test/test_email_codecs_renamed.py Lib/email/test/test_email_renamed.py Lib/encodings/__init__.py Lib/encodings/aliases.py Lib/encodings/punycode.py Lib/filecmp.py Lib/fileinput.py Lib/formatter.py Lib/fpformat.py Lib/ftplib.py Lib/getopt.py Lib/getpass.py Lib/gettext.py Lib/gopherlib.py Lib/gzip.py Lib/heapq.py Lib/hotshot/log.py Lib/hotshot/stones.py Lib/htmlentitydefs.py Lib/htmllib.py Lib/httplib.py Lib/idlelib/AutoCompleteWindow.py Lib/idlelib/CallTips.py Lib/idlelib/CodeContext.py Lib/idlelib/ColorDelegator.py Lib/idlelib/Delegator.py Lib/idlelib/EditorWindow.py Lib/idlelib/FileList.py Lib/idlelib/GrepDialog.py Lib/idlelib/IOBinding.py Lib/idlelib/MultiCall.py Lib/idlelib/NEWS.txt Lib/idlelib/Percolator.py Lib/idlelib/PyShell.py Lib/idlelib/ScrolledList.py Lib/idlelib/UndoDelegator.py Lib/idlelib/WidgetRedirector.py Lib/idlelib/WindowList.py Lib/idlelib/configHandler.py Lib/idlelib/configHelpSourceEdit.py Lib/idlelib/configSectionNameDialog.py Lib/idlelib/help.txt Lib/idlelib/keybindingDialog.py Lib/idlelib/rpc.py Lib/idlelib/run.py Lib/ihooks.py Lib/imaplib.py Lib/imghdr.py Lib/imputil.py Lib/lib-tk/Dialog.py Lib/lib-tk/FileDialog.py Lib/lib-tk/SimpleDialog.py Lib/lib-tk/Tkinter.py Lib/lib-tk/tkColorChooser.py Lib/lib-tk/tkFileDialog.py Lib/lib-tk/tkFont.py Lib/lib-tk/tkMessageBox.py Lib/lib-tk/tkSimpleDialog.py Lib/locale.py Lib/logging/__init__.py Lib/logging/config.py Lib/logging/handlers.py Lib/macurl2path.py Lib/mailbox.py Lib/mailcap.py Lib/mhlib.py Lib/mimetypes.py Lib/mimify.py Lib/modulefinder.py Lib/msilib/__init__.py Lib/netrc.py Lib/nntplib.py Lib/ntpath.py Lib/opcode.py Lib/optparse.py Lib/pdb.py Lib/pickle.py Lib/pickletools.py Lib/pipes.py Lib/plat-aix3/IN.py Lib/plat-aix4/IN.py Lib/plat-atheos/IN.py Lib/plat-atheos/TYPES.py Lib/plat-beos5/IN.py Lib/plat-freebsd2/IN.py Lib/plat-freebsd3/IN.py Lib/plat-irix5/IN.py Lib/plat-irix5/cddb.py Lib/plat-irix5/cdplayer.py Lib/plat-irix5/flp.py Lib/plat-irix5/panel.py Lib/plat-irix6/FILE.py Lib/plat-irix6/IN.py Lib/plat-irix6/WAIT.py Lib/plat-irix6/cddb.py Lib/plat-irix6/cdplayer.py Lib/plat-irix6/flp.py Lib/plat-irix6/panel.py Lib/plat-linux2/DLFCN.py Lib/plat-linux2/IN.py Lib/plat-linux2/TYPES.py Lib/plat-mac/Audio_mac.py Lib/plat-mac/Carbon/CarbonEvents.py Lib/plat-mac/Carbon/Components.py Lib/plat-mac/Carbon/Controls.py Lib/plat-mac/Carbon/Dragconst.py Lib/plat-mac/Carbon/Folders.py Lib/plat-mac/Carbon/Fonts.py Lib/plat-mac/Carbon/Icons.py Lib/plat-mac/Carbon/MacTextEditor.py Lib/plat-mac/Carbon/OSAconst.py Lib/plat-mac/Carbon/QDOffscreen.py Lib/plat-mac/Carbon/QuickDraw.py Lib/plat-mac/Carbon/QuickTime.py Lib/plat-mac/Carbon/Sound.py Lib/plat-mac/Carbon/Windows.py Lib/plat-mac/EasyDialogs.py Lib/plat-mac/FrameWork.py Lib/plat-mac/MiniAEFrame.py Lib/plat-mac/aepack.py Lib/plat-mac/aetools.py Lib/plat-mac/applesingle.py Lib/plat-mac/argvemulator.py Lib/plat-mac/bundlebuilder.py Lib/plat-mac/findertools.py Lib/plat-mac/gensuitemodule.py Lib/plat-mac/ic.py Lib/plat-mac/macfs.py Lib/plat-mac/macresource.py Lib/plat-mac/pimp.py Lib/plat-mac/plistlib.py Lib/plat-mac/videoreader.py Lib/plat-os2emx/IN.py Lib/plat-os2emx/_emx_link.py Lib/plat-riscos/rourl2path.py Lib/plat-sunos5/IN.py Lib/plat-sunos5/STROPTS.py Lib/plat-sunos5/TYPES.py Lib/plat-unixware7/IN.py Lib/plat-unixware7/STROPTS.py Lib/platform.py Lib/popen2.py Lib/poplib.py Lib/pprint.py Lib/profile.py Lib/pstats.py Lib/pty.py Lib/py_compile.py Lib/pyclbr.py Lib/pydoc.py Lib/quopri.py Lib/random.py Lib/repr.py Lib/rexec.py Lib/rfc822.py Lib/robotparser.py Lib/runpy.py Lib/sgmllib.py Lib/shelve.py Lib/shlex.py Lib/shutil.py Lib/site.py Lib/smtpd.py Lib/smtplib.py Lib/sndhdr.py Lib/socket.py Lib/sqlite3/dbapi2.py Lib/sqlite3/test/dbapi.py Lib/sqlite3/test/factory.py Lib/sqlite3/test/regression.py Lib/sqlite3/test/types.py Lib/sre_compile.py Lib/sre_constants.py Lib/sre_parse.py Lib/stat.py Lib/string.py Lib/stringold.py Lib/subprocess.py Lib/sunau.py Lib/sunaudio.py Lib/symbol.py Lib/symtable.py Lib/tabnanny.py Lib/tarfile.py Lib/telnetlib.py Lib/test/badsyntax_future8.py Lib/test/badsyntax_future9.py Lib/test/crashers/bogus_sre_bytecode.py Lib/test/crashers/borrowed_ref_1.py Lib/test/crashers/borrowed_ref_2.py Lib/test/crashers/gc_inspection.py Lib/test/crashers/loosing_mro_ref.py Lib/test/crashers/modify_dict_attr.py Lib/test/crashers/nasty_eq_vs_dict.py Lib/test/crashers/weakref_in_del.py Lib/test/doctest_aliases.py Lib/test/fork_wait.py Lib/test/inspect_fodder2.py Lib/test/list_tests.py Lib/test/mapping_tests.py Lib/test/output/test_cProfile Lib/test/output/test_class Lib/test/output/test_new Lib/test/output/test_popen Lib/test/output/test_profile Lib/test/output/test_resource Lib/test/pickletester.py Lib/test/pydocfodder.py Lib/test/pystone.py Lib/test/regrtest.py Lib/test/reperf.py Lib/test/sample_doctest.py Lib/test/seq_tests.py Lib/test/sortperf.py Lib/test/string_tests.py Lib/test/test___all__.py Lib/test/test_al.py Lib/test/test_anydbm.py Lib/test/test_array.py Lib/test/test_ast.py Lib/test/test_asynchat.py Lib/test/test_atexit.py Lib/test/test_audioop.py Lib/test/test_bigmem.py Lib/test/test_binop.py Lib/test/test_bisect.py Lib/test/test_bool.py Lib/test/test_bsddb.py Lib/test/test_bsddb3.py Lib/test/test_builtin.py Lib/test/test_bytes.py Lib/test/test_capi.py Lib/test/test_cd.py Lib/test/test_cfgparser.py Lib/test/test_cgi.py Lib/test/test_cl.py Lib/test/test_class.py Lib/test/test_cmath.py Lib/test/test_code.py Lib/test/test_codecs.py Lib/test/test_compare.py Lib/test/test_compile.py Lib/test/test_compiler.py Lib/test/test_complex.py Lib/test/test_cookie.py Lib/test/test_cookielib.py Lib/test/test_copy.py Lib/test/test_copy_reg.py Lib/test/test_crypt.py Lib/test/test_csv.py Lib/test/test_curses.py Lib/test/test_datetime.py Lib/test/test_dbm.py Lib/test/test_decimal.py Lib/test/test_defaultdict.py Lib/test/test_deque.py Lib/test/test_descr.py Lib/test/test_descrtut.py Lib/test/test_dict.py Lib/test/test_dictviews.py Lib/test/test_dis.py Lib/test/test_dl.py Lib/test/test_doctest.py Lib/test/test_doctest.txt Lib/test/test_doctest2.py Lib/test/test_dumbdbm.py Lib/test/test_dummy_thread.py Lib/test/test_dummy_threading.py Lib/test/test_enumerate.py Lib/test/test_errno.py Lib/test/test_exceptions.py Lib/test/test_extcall.py Lib/test/test_fcntl.py Lib/test/test_file.py Lib/test/test_fileinput.py Lib/test/test_format.py Lib/test/test_funcattrs.py Lib/test/test_functools.py Lib/test/test_gc.py Lib/test/test_gdbm.py Lib/test/test_generators.py Lib/test/test_genexps.py Lib/test/test_getargs2.py Lib/test/test_getopt.py Lib/test/test_gl.py Lib/test/test_grammar.py Lib/test/test_grp.py Lib/test/test_gzip.py Lib/test/test_hash.py Lib/test/test_heapq.py Lib/test/test_hexoct.py Lib/test/test_imageop.py Lib/test/test_imgfile.py Lib/test/test_import.py Lib/test/test_importhooks.py Lib/test/test_index.py Lib/test/test_inspect.py Lib/test/test_isinstance.py Lib/test/test_iter.py Lib/test/test_iterlen.py Lib/test/test_itertools.py Lib/test/test_largefile.py Lib/test/test_linuxaudiodev.py Lib/test/test_list.py Lib/test/test_locale.py Lib/test/test_long.py Lib/test/test_long_future.py Lib/test/test_mailbox.py Lib/test/test_marshal.py Lib/test/test_mhlib.py Lib/test/test_minidom.py Lib/test/test_module.py Lib/test/test_multibytecodec.py Lib/test/test_multibytecodec_support.py Lib/test/test_mutants.py Lib/test/test_new.py Lib/test/test_normalization.py Lib/test/test_ntpath.py Lib/test/test_old_mailbox.py Lib/test/test_operations.py Lib/test/test_operator.py Lib/test/test_optparse.py Lib/test/test_ossaudiodev.py Lib/test/test_parser.py Lib/test/test_peepholer.py Lib/test/test_pep247.py Lib/test/test_pep277.py Lib/test/test_pep352.py Lib/test/test_pkg.py Lib/test/test_poll.py Lib/test/test_popen.py Lib/test/test_popen2.py Lib/test/test_posix.py Lib/test/test_posixpath.py Lib/test/test_pow.py Lib/test/test_pprint.py Lib/test/test_pty.py Lib/test/test_pwd.py Lib/test/test_pyclbr.py Lib/test/test_pyexpat.py Lib/test/test_queue.py Lib/test/test_random.py Lib/test/test_re.py Lib/test/test_repr.py Lib/test/test_resource.py Lib/test/test_rfc822.py Lib/test/test_rgbimg.py Lib/test/test_richcmp.py Lib/test/test_runpy.py Lib/test/test_sax.py Lib/test/test_scope.py Lib/test/test_select.py Lib/test/test_set.py Lib/test/test_signal.py Lib/test/test_site.py Lib/test/test_slice.py Lib/test/test_socket.py Lib/test/test_socket_ssl.py Lib/test/test_socketserver.py Lib/test/test_softspace.py Lib/test/test_sort.py Lib/test/test_strftime.py Lib/test/test_string.py Lib/test/test_strop.py Lib/test/test_strptime.py Lib/test/test_struct.py Lib/test/test_subprocess.py Lib/test/test_sundry.py Lib/test/test_support.py Lib/test/test_syntax.py Lib/test/test_tarfile.py Lib/test/test_thread.py Lib/test/test_threaded_import.py Lib/test/test_threadedtempfile.py Lib/test/test_threading.py Lib/test/test_time.py Lib/test/test_timeout.py Lib/test/test_tokenize.py Lib/test/test_trace.py Lib/test/test_traceback.py Lib/test/test_types.py Lib/test/test_unary.py Lib/test/test_unicode.py Lib/test/test_urllib2.py Lib/test/test_urllib2net.py Lib/test/test_userdict.py Lib/test/test_uu.py Lib/test/test_uuid.py Lib/test/test_weakref.py Lib/test/test_winreg.py Lib/test/test_with.py Lib/test/test_xdrlib.py Lib/test/test_xml_etree.py Lib/test/test_xml_etree_c.py Lib/test/test_xmlrpc.py Lib/test/test_xrange.py Lib/test/test_zipfile.py Lib/test/test_zipfile64.py Lib/test/test_zipimport.py Lib/test/test_zlib.py Lib/test/time_hashlib.py Lib/textwrap.py Lib/this.py Lib/threading.py Lib/timeit.py Lib/token.py Lib/tokenize.py Lib/trace.py Lib/types.py Lib/unittest.py Lib/urllib.py Lib/urllib2.py Lib/urlparse.py Lib/uu.py Lib/uuid.py Lib/warnings.py Lib/weakref.py Lib/webbrowser.py Lib/whichdb.py Lib/wsgiref/simple_server.py Lib/xdrlib.py Lib/xml/dom/NodeFilter.py Lib/xml/dom/minidom.py Lib/xml/dom/pulldom.py Lib/xml/etree/ElementTree.py Lib/xml/sax/handler.py Lib/xml/sax/saxutils.py Lib/xml/sax/xmlreader.py Lib/xmllib.py Lib/xmlrpclib.py Lib/zipfile.py Makefile.pre.in Misc/ACKS Misc/NEWS Modules/_csv.c Modules/_ctypes/_ctypes.c Modules/_ctypes/_ctypes_test.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_ctypes/libffi_msvc/ffi.c Modules/_cursesmodule.c Modules/_randommodule.c Modules/_sqlite/cache.c Modules/_sqlite/cache.h Modules/_sqlite/connection.c Modules/_sqlite/connection.h Modules/_sqlite/cursor.c Modules/_sqlite/cursor.h Modules/_sqlite/microprotocols.c Modules/_sqlite/microprotocols.h Modules/_sqlite/module.c Modules/_sqlite/module.h Modules/_sqlite/prepare_protocol.c Modules/_sqlite/prepare_protocol.h Modules/_sqlite/row.c Modules/_sqlite/row.h Modules/_sqlite/statement.c Modules/_sqlite/statement.h Modules/_sqlite/util.c Modules/_sqlite/util.h Modules/_sre.c Modules/_struct.c Modules/_testcapimodule.c Modules/_tkinter.c Modules/arraymodule.c Modules/bz2module.c Modules/cPickle.c Modules/cStringIO.c Modules/cjkcodecs/multibytecodec.c Modules/collectionsmodule.c Modules/datetimemodule.c Modules/dlmodule.c Modules/itertoolsmodule.c Modules/parsermodule.c Modules/posixmodule.c Modules/socketmodule.c Modules/socketmodule.h Modules/timemodule.c Objects/abstract.c Objects/boolobject.c Objects/complexobject.c Objects/dictnotes.txt Objects/dictobject.c Objects/enumobject.c Objects/exceptions.c Objects/fileobject.c Objects/floatobject.c Objects/frameobject.c Objects/intobject.c Objects/iterobject.c Objects/listobject.c Objects/longobject.c Objects/object.c Objects/setobject.c Objects/stringobject.c Objects/typeobject.c Objects/unicodeobject.c Objects/weakrefobject.c PC/_msi.c PCbuild/_bsddb.vcproj PCbuild/_elementtree.vcproj PCbuild/_msi.vcproj PCbuild/_socket.vcproj PCbuild/_sqlite3.vcproj PCbuild/_ssl.mak PCbuild/_testcapi.vcproj PCbuild/_tkinter.vcproj PCbuild/build_ssl.py PCbuild/bz2.vcproj PCbuild/pyexpat.vcproj PCbuild/python.vcproj PCbuild/pythoncore.vcproj PCbuild/pythonw.vcproj PCbuild/select.vcproj PCbuild/unicodedata.vcproj PCbuild/winsound.vcproj Parser/Python.asdl Parser/asdl_c.py Parser/tokenizer.c Python/Python-ast.c Python/ast.c Python/bltinmodule.c Python/ceval.c Python/compile.c Python/frozen.c Python/getargs.c Python/graminit.c Python/import.c Python/marshal.c Python/pythonrun.c Python/symtable.c Python/sysmodule.c Python/traceback.c Tools/compiler/ast.txt Tools/freeze Tools/freeze/bkfile.py Tools/freeze/freeze.py Tools/freeze/hello.py Tools/freeze/makeconfig.py Tools/freeze/makefreeze.py Tools/freeze/parsesetup.py Tools/freeze/winmakemakefile.py Tools/msi/uuids.py Tools/pybench/CommandLine.py Tools/pybench/Dict.py Tools/pybench/Exceptions.py Tools/pybench/Lookups.py Tools/pybench/pybench.py configure configure.in pyconfig.h.in setup.py
thomas.wouters
python-checkins at python.org
Fri Feb 23 18:33:06 CET 2007
Author: thomas.wouters
Date: Fri Feb 23 18:29:35 2007
New Revision: 53867
Added:
python/branches/p3yk-noslice/BROKEN
python/branches/p3yk-noslice/INTBENCH
- copied unchanged from r53866, python/branches/p3yk/INTBENCH
python/branches/p3yk-noslice/Lib/test/test_dictviews.py
- copied unchanged from r53866, python/branches/p3yk/Lib/test/test_dictviews.py
Removed:
python/branches/p3yk-noslice/Lib/test/output/test_new
python/branches/p3yk-noslice/Lib/test/output/test_popen
python/branches/p3yk-noslice/Lib/test/output/test_resource
python/branches/p3yk-noslice/Lib/test/test_softspace.py
Modified:
python/branches/p3yk-noslice/ (props changed)
python/branches/p3yk-noslice/Doc/api/concrete.tex
python/branches/p3yk-noslice/Doc/commontex/license.tex
python/branches/p3yk-noslice/Doc/dist/dist.tex
python/branches/p3yk-noslice/Doc/howto/TODO
python/branches/p3yk-noslice/Doc/howto/curses.tex
python/branches/p3yk-noslice/Doc/howto/doanddont.tex
python/branches/p3yk-noslice/Doc/howto/regex.tex
python/branches/p3yk-noslice/Doc/lib/emailgenerator.tex
python/branches/p3yk-noslice/Doc/lib/libcollections.tex
python/branches/p3yk-noslice/Doc/lib/libdis.tex
python/branches/p3yk-noslice/Doc/lib/libexcs.tex
python/branches/p3yk-noslice/Doc/lib/libfunctools.tex
python/branches/p3yk-noslice/Doc/lib/libheapq.tex
python/branches/p3yk-noslice/Doc/lib/libimageop.tex
python/branches/p3yk-noslice/Doc/lib/libitertools.tex
python/branches/p3yk-noslice/Doc/lib/liblocale.tex
python/branches/p3yk-noslice/Doc/lib/liblogging.tex
python/branches/p3yk-noslice/Doc/lib/libmailbox.tex
python/branches/p3yk-noslice/Doc/lib/libos.tex
python/branches/p3yk-noslice/Doc/lib/librandom.tex
python/branches/p3yk-noslice/Doc/lib/libshutil.tex
python/branches/p3yk-noslice/Doc/lib/libsmtplib.tex
python/branches/p3yk-noslice/Doc/lib/libsocket.tex
python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex
python/branches/p3yk-noslice/Doc/lib/libstruct.tex
python/branches/p3yk-noslice/Doc/lib/libtarfile.tex
python/branches/p3yk-noslice/Doc/lib/libtest.tex
python/branches/p3yk-noslice/Doc/lib/libtime.tex
python/branches/p3yk-noslice/Doc/lib/libzipfile.tex
python/branches/p3yk-noslice/Doc/ref/ref3.tex
python/branches/p3yk-noslice/Doc/ref/ref4.tex
python/branches/p3yk-noslice/Doc/ref/ref6.tex
python/branches/p3yk-noslice/Doc/tut/tut.tex
python/branches/p3yk-noslice/Doc/whatsnew/whatsnew26.tex
python/branches/p3yk-noslice/Grammar/Grammar
python/branches/p3yk-noslice/Include/Python-ast.h
python/branches/p3yk-noslice/Include/abstract.h
python/branches/p3yk-noslice/Include/boolobject.h
python/branches/p3yk-noslice/Include/ceval.h
python/branches/p3yk-noslice/Include/dictobject.h
python/branches/p3yk-noslice/Include/fileobject.h
python/branches/p3yk-noslice/Include/graminit.h
python/branches/p3yk-noslice/Include/intobject.h
python/branches/p3yk-noslice/Include/longobject.h
python/branches/p3yk-noslice/Include/object.h
python/branches/p3yk-noslice/Include/opcode.h
python/branches/p3yk-noslice/Lib/BaseHTTPServer.py
python/branches/p3yk-noslice/Lib/Bastion.py
python/branches/p3yk-noslice/Lib/CGIHTTPServer.py
python/branches/p3yk-noslice/Lib/ConfigParser.py
python/branches/p3yk-noslice/Lib/Cookie.py
python/branches/p3yk-noslice/Lib/DocXMLRPCServer.py
python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py
python/branches/p3yk-noslice/Lib/SocketServer.py
python/branches/p3yk-noslice/Lib/StringIO.py
python/branches/p3yk-noslice/Lib/UserDict.py
python/branches/p3yk-noslice/Lib/UserString.py
python/branches/p3yk-noslice/Lib/_LWPCookieJar.py
python/branches/p3yk-noslice/Lib/_strptime.py
python/branches/p3yk-noslice/Lib/_threading_local.py
python/branches/p3yk-noslice/Lib/aifc.py
python/branches/p3yk-noslice/Lib/asynchat.py
python/branches/p3yk-noslice/Lib/asyncore.py
python/branches/p3yk-noslice/Lib/atexit.py
python/branches/p3yk-noslice/Lib/audiodev.py
python/branches/p3yk-noslice/Lib/base64.py
python/branches/p3yk-noslice/Lib/bdb.py
python/branches/p3yk-noslice/Lib/bsddb/dbrecio.py
python/branches/p3yk-noslice/Lib/bsddb/dbtables.py
python/branches/p3yk-noslice/Lib/bsddb/test/test_all.py
python/branches/p3yk-noslice/Lib/bsddb/test/test_associate.py
python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py
python/branches/p3yk-noslice/Lib/bsddb/test/test_compat.py
python/branches/p3yk-noslice/Lib/bsddb/test/test_dbshelve.py
python/branches/p3yk-noslice/Lib/bsddb/test/test_dbtables.py
python/branches/p3yk-noslice/Lib/bsddb/test/test_join.py
python/branches/p3yk-noslice/Lib/bsddb/test/test_lock.py
python/branches/p3yk-noslice/Lib/bsddb/test/test_queue.py
python/branches/p3yk-noslice/Lib/bsddb/test/test_recno.py
python/branches/p3yk-noslice/Lib/bsddb/test/test_thread.py
python/branches/p3yk-noslice/Lib/cProfile.py
python/branches/p3yk-noslice/Lib/calendar.py
python/branches/p3yk-noslice/Lib/cgi.py
python/branches/p3yk-noslice/Lib/code.py
python/branches/p3yk-noslice/Lib/compileall.py
python/branches/p3yk-noslice/Lib/compiler/ast.py
python/branches/p3yk-noslice/Lib/compiler/future.py
python/branches/p3yk-noslice/Lib/compiler/misc.py
python/branches/p3yk-noslice/Lib/compiler/pyassem.py
python/branches/p3yk-noslice/Lib/compiler/pycodegen.py
python/branches/p3yk-noslice/Lib/compiler/symbols.py
python/branches/p3yk-noslice/Lib/compiler/syntax.py
python/branches/p3yk-noslice/Lib/compiler/transformer.py
python/branches/p3yk-noslice/Lib/compiler/visitor.py
python/branches/p3yk-noslice/Lib/cookielib.py
python/branches/p3yk-noslice/Lib/copy.py
python/branches/p3yk-noslice/Lib/csv.py
python/branches/p3yk-noslice/Lib/ctypes/__init__.py
python/branches/p3yk-noslice/Lib/ctypes/test/__init__.py
python/branches/p3yk-noslice/Lib/ctypes/test/test_as_parameter.py
python/branches/p3yk-noslice/Lib/ctypes/test/test_byteswap.py
python/branches/p3yk-noslice/Lib/ctypes/test/test_find.py
python/branches/p3yk-noslice/Lib/ctypes/test/test_functions.py
python/branches/p3yk-noslice/Lib/ctypes/test/test_keeprefs.py
python/branches/p3yk-noslice/Lib/ctypes/test/test_loading.py
python/branches/p3yk-noslice/Lib/ctypes/test/test_numbers.py
python/branches/p3yk-noslice/Lib/ctypes/test/test_objects.py
python/branches/p3yk-noslice/Lib/ctypes/test/test_pointers.py
python/branches/p3yk-noslice/Lib/ctypes/test/test_prototypes.py
python/branches/p3yk-noslice/Lib/ctypes/test/test_strings.py
python/branches/p3yk-noslice/Lib/ctypes/test/test_win32.py
python/branches/p3yk-noslice/Lib/ctypes/util.py
python/branches/p3yk-noslice/Lib/ctypes/wintypes.py
python/branches/p3yk-noslice/Lib/curses/has_key.py
python/branches/p3yk-noslice/Lib/curses/textpad.py
python/branches/p3yk-noslice/Lib/decimal.py
python/branches/p3yk-noslice/Lib/difflib.py
python/branches/p3yk-noslice/Lib/dis.py
python/branches/p3yk-noslice/Lib/distutils/bcppcompiler.py
python/branches/p3yk-noslice/Lib/distutils/ccompiler.py
python/branches/p3yk-noslice/Lib/distutils/cmd.py
python/branches/p3yk-noslice/Lib/distutils/command/bdist_rpm.py
python/branches/p3yk-noslice/Lib/distutils/command/build_ext.py
python/branches/p3yk-noslice/Lib/distutils/command/config.py
python/branches/p3yk-noslice/Lib/distutils/command/install.py
python/branches/p3yk-noslice/Lib/distutils/command/register.py
python/branches/p3yk-noslice/Lib/distutils/command/upload.py
python/branches/p3yk-noslice/Lib/distutils/core.py
python/branches/p3yk-noslice/Lib/distutils/dist.py
python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py
python/branches/p3yk-noslice/Lib/distutils/filelist.py
python/branches/p3yk-noslice/Lib/distutils/log.py
python/branches/p3yk-noslice/Lib/distutils/mwerkscompiler.py
python/branches/p3yk-noslice/Lib/distutils/spawn.py
python/branches/p3yk-noslice/Lib/distutils/sysconfig.py
python/branches/p3yk-noslice/Lib/distutils/tests/test_dist.py
python/branches/p3yk-noslice/Lib/distutils/text_file.py
python/branches/p3yk-noslice/Lib/distutils/versionpredicate.py
python/branches/p3yk-noslice/Lib/doctest.py
python/branches/p3yk-noslice/Lib/dumbdbm.py
python/branches/p3yk-noslice/Lib/dummy_thread.py
python/branches/p3yk-noslice/Lib/dummy_threading.py
python/branches/p3yk-noslice/Lib/email/charset.py
python/branches/p3yk-noslice/Lib/email/generator.py
python/branches/p3yk-noslice/Lib/email/iterators.py
python/branches/p3yk-noslice/Lib/email/test/test_email.py
python/branches/p3yk-noslice/Lib/email/test/test_email_codecs.py
python/branches/p3yk-noslice/Lib/email/test/test_email_codecs_renamed.py
python/branches/p3yk-noslice/Lib/email/test/test_email_renamed.py
python/branches/p3yk-noslice/Lib/encodings/__init__.py
python/branches/p3yk-noslice/Lib/encodings/aliases.py
python/branches/p3yk-noslice/Lib/encodings/punycode.py
python/branches/p3yk-noslice/Lib/filecmp.py
python/branches/p3yk-noslice/Lib/fileinput.py
python/branches/p3yk-noslice/Lib/formatter.py
python/branches/p3yk-noslice/Lib/fpformat.py
python/branches/p3yk-noslice/Lib/ftplib.py
python/branches/p3yk-noslice/Lib/getopt.py
python/branches/p3yk-noslice/Lib/getpass.py
python/branches/p3yk-noslice/Lib/gettext.py
python/branches/p3yk-noslice/Lib/gopherlib.py
python/branches/p3yk-noslice/Lib/gzip.py
python/branches/p3yk-noslice/Lib/heapq.py
python/branches/p3yk-noslice/Lib/hotshot/log.py
python/branches/p3yk-noslice/Lib/hotshot/stones.py
python/branches/p3yk-noslice/Lib/htmlentitydefs.py
python/branches/p3yk-noslice/Lib/htmllib.py
python/branches/p3yk-noslice/Lib/httplib.py
python/branches/p3yk-noslice/Lib/idlelib/AutoCompleteWindow.py
python/branches/p3yk-noslice/Lib/idlelib/CallTips.py
python/branches/p3yk-noslice/Lib/idlelib/CodeContext.py
python/branches/p3yk-noslice/Lib/idlelib/ColorDelegator.py
python/branches/p3yk-noslice/Lib/idlelib/Delegator.py
python/branches/p3yk-noslice/Lib/idlelib/EditorWindow.py
python/branches/p3yk-noslice/Lib/idlelib/FileList.py
python/branches/p3yk-noslice/Lib/idlelib/GrepDialog.py
python/branches/p3yk-noslice/Lib/idlelib/IOBinding.py
python/branches/p3yk-noslice/Lib/idlelib/MultiCall.py
python/branches/p3yk-noslice/Lib/idlelib/NEWS.txt
python/branches/p3yk-noslice/Lib/idlelib/Percolator.py
python/branches/p3yk-noslice/Lib/idlelib/PyShell.py
python/branches/p3yk-noslice/Lib/idlelib/ScrolledList.py
python/branches/p3yk-noslice/Lib/idlelib/UndoDelegator.py
python/branches/p3yk-noslice/Lib/idlelib/WidgetRedirector.py
python/branches/p3yk-noslice/Lib/idlelib/WindowList.py
python/branches/p3yk-noslice/Lib/idlelib/configHandler.py
python/branches/p3yk-noslice/Lib/idlelib/configHelpSourceEdit.py
python/branches/p3yk-noslice/Lib/idlelib/configSectionNameDialog.py
python/branches/p3yk-noslice/Lib/idlelib/help.txt
python/branches/p3yk-noslice/Lib/idlelib/keybindingDialog.py
python/branches/p3yk-noslice/Lib/idlelib/rpc.py
python/branches/p3yk-noslice/Lib/idlelib/run.py
python/branches/p3yk-noslice/Lib/ihooks.py
python/branches/p3yk-noslice/Lib/imaplib.py
python/branches/p3yk-noslice/Lib/imghdr.py
python/branches/p3yk-noslice/Lib/imputil.py
python/branches/p3yk-noslice/Lib/lib-tk/Dialog.py
python/branches/p3yk-noslice/Lib/lib-tk/FileDialog.py
python/branches/p3yk-noslice/Lib/lib-tk/SimpleDialog.py
python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py
python/branches/p3yk-noslice/Lib/lib-tk/tkColorChooser.py
python/branches/p3yk-noslice/Lib/lib-tk/tkFileDialog.py
python/branches/p3yk-noslice/Lib/lib-tk/tkFont.py
python/branches/p3yk-noslice/Lib/lib-tk/tkMessageBox.py
python/branches/p3yk-noslice/Lib/lib-tk/tkSimpleDialog.py
python/branches/p3yk-noslice/Lib/locale.py
python/branches/p3yk-noslice/Lib/logging/__init__.py
python/branches/p3yk-noslice/Lib/logging/config.py
python/branches/p3yk-noslice/Lib/logging/handlers.py
python/branches/p3yk-noslice/Lib/macurl2path.py
python/branches/p3yk-noslice/Lib/mailbox.py
python/branches/p3yk-noslice/Lib/mailcap.py
python/branches/p3yk-noslice/Lib/mhlib.py
python/branches/p3yk-noslice/Lib/mimetypes.py
python/branches/p3yk-noslice/Lib/mimify.py
python/branches/p3yk-noslice/Lib/modulefinder.py
python/branches/p3yk-noslice/Lib/msilib/__init__.py
python/branches/p3yk-noslice/Lib/netrc.py
python/branches/p3yk-noslice/Lib/nntplib.py
python/branches/p3yk-noslice/Lib/ntpath.py
python/branches/p3yk-noslice/Lib/opcode.py
python/branches/p3yk-noslice/Lib/optparse.py
python/branches/p3yk-noslice/Lib/pdb.py
python/branches/p3yk-noslice/Lib/pickle.py
python/branches/p3yk-noslice/Lib/pickletools.py
python/branches/p3yk-noslice/Lib/pipes.py
python/branches/p3yk-noslice/Lib/plat-aix3/IN.py
python/branches/p3yk-noslice/Lib/plat-aix4/IN.py
python/branches/p3yk-noslice/Lib/plat-atheos/IN.py
python/branches/p3yk-noslice/Lib/plat-atheos/TYPES.py
python/branches/p3yk-noslice/Lib/plat-beos5/IN.py
python/branches/p3yk-noslice/Lib/plat-freebsd2/IN.py
python/branches/p3yk-noslice/Lib/plat-freebsd3/IN.py
python/branches/p3yk-noslice/Lib/plat-irix5/IN.py
python/branches/p3yk-noslice/Lib/plat-irix5/cddb.py
python/branches/p3yk-noslice/Lib/plat-irix5/cdplayer.py
python/branches/p3yk-noslice/Lib/plat-irix5/flp.py
python/branches/p3yk-noslice/Lib/plat-irix5/panel.py
python/branches/p3yk-noslice/Lib/plat-irix6/FILE.py
python/branches/p3yk-noslice/Lib/plat-irix6/IN.py
python/branches/p3yk-noslice/Lib/plat-irix6/WAIT.py
python/branches/p3yk-noslice/Lib/plat-irix6/cddb.py
python/branches/p3yk-noslice/Lib/plat-irix6/cdplayer.py
python/branches/p3yk-noslice/Lib/plat-irix6/flp.py
python/branches/p3yk-noslice/Lib/plat-irix6/panel.py
python/branches/p3yk-noslice/Lib/plat-linux2/DLFCN.py
python/branches/p3yk-noslice/Lib/plat-linux2/IN.py
python/branches/p3yk-noslice/Lib/plat-linux2/TYPES.py
python/branches/p3yk-noslice/Lib/plat-mac/Audio_mac.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/CarbonEvents.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Components.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Controls.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Dragconst.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Folders.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Fonts.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Icons.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/MacTextEditor.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/OSAconst.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QDOffscreen.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickDraw.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickTime.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Sound.py
python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Windows.py
python/branches/p3yk-noslice/Lib/plat-mac/EasyDialogs.py
python/branches/p3yk-noslice/Lib/plat-mac/FrameWork.py
python/branches/p3yk-noslice/Lib/plat-mac/MiniAEFrame.py
python/branches/p3yk-noslice/Lib/plat-mac/aepack.py
python/branches/p3yk-noslice/Lib/plat-mac/aetools.py
python/branches/p3yk-noslice/Lib/plat-mac/applesingle.py
python/branches/p3yk-noslice/Lib/plat-mac/argvemulator.py
python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py
python/branches/p3yk-noslice/Lib/plat-mac/findertools.py
python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.py
python/branches/p3yk-noslice/Lib/plat-mac/ic.py
python/branches/p3yk-noslice/Lib/plat-mac/macfs.py
python/branches/p3yk-noslice/Lib/plat-mac/macresource.py
python/branches/p3yk-noslice/Lib/plat-mac/pimp.py
python/branches/p3yk-noslice/Lib/plat-mac/plistlib.py
python/branches/p3yk-noslice/Lib/plat-mac/videoreader.py
python/branches/p3yk-noslice/Lib/plat-os2emx/IN.py
python/branches/p3yk-noslice/Lib/plat-os2emx/_emx_link.py
python/branches/p3yk-noslice/Lib/plat-riscos/rourl2path.py
python/branches/p3yk-noslice/Lib/plat-sunos5/IN.py
python/branches/p3yk-noslice/Lib/plat-sunos5/STROPTS.py
python/branches/p3yk-noslice/Lib/plat-sunos5/TYPES.py
python/branches/p3yk-noslice/Lib/plat-unixware7/IN.py
python/branches/p3yk-noslice/Lib/plat-unixware7/STROPTS.py
python/branches/p3yk-noslice/Lib/platform.py
python/branches/p3yk-noslice/Lib/popen2.py
python/branches/p3yk-noslice/Lib/poplib.py
python/branches/p3yk-noslice/Lib/pprint.py
python/branches/p3yk-noslice/Lib/profile.py
python/branches/p3yk-noslice/Lib/pstats.py
python/branches/p3yk-noslice/Lib/pty.py
python/branches/p3yk-noslice/Lib/py_compile.py
python/branches/p3yk-noslice/Lib/pyclbr.py
python/branches/p3yk-noslice/Lib/pydoc.py
python/branches/p3yk-noslice/Lib/quopri.py
python/branches/p3yk-noslice/Lib/random.py
python/branches/p3yk-noslice/Lib/repr.py
python/branches/p3yk-noslice/Lib/rexec.py
python/branches/p3yk-noslice/Lib/rfc822.py
python/branches/p3yk-noslice/Lib/robotparser.py
python/branches/p3yk-noslice/Lib/runpy.py
python/branches/p3yk-noslice/Lib/sgmllib.py
python/branches/p3yk-noslice/Lib/shelve.py
python/branches/p3yk-noslice/Lib/shlex.py
python/branches/p3yk-noslice/Lib/shutil.py
python/branches/p3yk-noslice/Lib/site.py
python/branches/p3yk-noslice/Lib/smtpd.py
python/branches/p3yk-noslice/Lib/smtplib.py
python/branches/p3yk-noslice/Lib/sndhdr.py
python/branches/p3yk-noslice/Lib/socket.py
python/branches/p3yk-noslice/Lib/sqlite3/dbapi2.py
python/branches/p3yk-noslice/Lib/sqlite3/test/dbapi.py
python/branches/p3yk-noslice/Lib/sqlite3/test/factory.py
python/branches/p3yk-noslice/Lib/sqlite3/test/regression.py
python/branches/p3yk-noslice/Lib/sqlite3/test/types.py
python/branches/p3yk-noslice/Lib/sre_compile.py
python/branches/p3yk-noslice/Lib/sre_constants.py
python/branches/p3yk-noslice/Lib/sre_parse.py
python/branches/p3yk-noslice/Lib/stat.py
python/branches/p3yk-noslice/Lib/string.py
python/branches/p3yk-noslice/Lib/stringold.py
python/branches/p3yk-noslice/Lib/subprocess.py
python/branches/p3yk-noslice/Lib/sunau.py
python/branches/p3yk-noslice/Lib/sunaudio.py
python/branches/p3yk-noslice/Lib/symbol.py
python/branches/p3yk-noslice/Lib/symtable.py
python/branches/p3yk-noslice/Lib/tabnanny.py
python/branches/p3yk-noslice/Lib/tarfile.py
python/branches/p3yk-noslice/Lib/telnetlib.py
python/branches/p3yk-noslice/Lib/test/badsyntax_future8.py
python/branches/p3yk-noslice/Lib/test/badsyntax_future9.py
python/branches/p3yk-noslice/Lib/test/crashers/bogus_sre_bytecode.py
python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_1.py
python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_2.py
python/branches/p3yk-noslice/Lib/test/crashers/gc_inspection.py
python/branches/p3yk-noslice/Lib/test/crashers/loosing_mro_ref.py
python/branches/p3yk-noslice/Lib/test/crashers/modify_dict_attr.py
python/branches/p3yk-noslice/Lib/test/crashers/nasty_eq_vs_dict.py
python/branches/p3yk-noslice/Lib/test/crashers/weakref_in_del.py
python/branches/p3yk-noslice/Lib/test/doctest_aliases.py
python/branches/p3yk-noslice/Lib/test/fork_wait.py
python/branches/p3yk-noslice/Lib/test/inspect_fodder2.py
python/branches/p3yk-noslice/Lib/test/list_tests.py
python/branches/p3yk-noslice/Lib/test/mapping_tests.py
python/branches/p3yk-noslice/Lib/test/output/test_cProfile
python/branches/p3yk-noslice/Lib/test/output/test_class
python/branches/p3yk-noslice/Lib/test/output/test_profile
python/branches/p3yk-noslice/Lib/test/pickletester.py
python/branches/p3yk-noslice/Lib/test/pydocfodder.py
python/branches/p3yk-noslice/Lib/test/pystone.py
python/branches/p3yk-noslice/Lib/test/regrtest.py
python/branches/p3yk-noslice/Lib/test/reperf.py
python/branches/p3yk-noslice/Lib/test/sample_doctest.py
python/branches/p3yk-noslice/Lib/test/seq_tests.py
python/branches/p3yk-noslice/Lib/test/sortperf.py
python/branches/p3yk-noslice/Lib/test/string_tests.py
python/branches/p3yk-noslice/Lib/test/test___all__.py
python/branches/p3yk-noslice/Lib/test/test_al.py
python/branches/p3yk-noslice/Lib/test/test_anydbm.py
python/branches/p3yk-noslice/Lib/test/test_array.py
python/branches/p3yk-noslice/Lib/test/test_ast.py
python/branches/p3yk-noslice/Lib/test/test_asynchat.py
python/branches/p3yk-noslice/Lib/test/test_atexit.py
python/branches/p3yk-noslice/Lib/test/test_audioop.py
python/branches/p3yk-noslice/Lib/test/test_bigmem.py
python/branches/p3yk-noslice/Lib/test/test_binop.py
python/branches/p3yk-noslice/Lib/test/test_bisect.py
python/branches/p3yk-noslice/Lib/test/test_bool.py
python/branches/p3yk-noslice/Lib/test/test_bsddb.py
python/branches/p3yk-noslice/Lib/test/test_bsddb3.py
python/branches/p3yk-noslice/Lib/test/test_builtin.py
python/branches/p3yk-noslice/Lib/test/test_bytes.py
python/branches/p3yk-noslice/Lib/test/test_capi.py
python/branches/p3yk-noslice/Lib/test/test_cd.py
python/branches/p3yk-noslice/Lib/test/test_cfgparser.py
python/branches/p3yk-noslice/Lib/test/test_cgi.py
python/branches/p3yk-noslice/Lib/test/test_cl.py
python/branches/p3yk-noslice/Lib/test/test_class.py
python/branches/p3yk-noslice/Lib/test/test_cmath.py
python/branches/p3yk-noslice/Lib/test/test_code.py
python/branches/p3yk-noslice/Lib/test/test_codecs.py
python/branches/p3yk-noslice/Lib/test/test_compare.py
python/branches/p3yk-noslice/Lib/test/test_compile.py
python/branches/p3yk-noslice/Lib/test/test_compiler.py
python/branches/p3yk-noslice/Lib/test/test_complex.py
python/branches/p3yk-noslice/Lib/test/test_cookie.py
python/branches/p3yk-noslice/Lib/test/test_cookielib.py
python/branches/p3yk-noslice/Lib/test/test_copy.py
python/branches/p3yk-noslice/Lib/test/test_copy_reg.py
python/branches/p3yk-noslice/Lib/test/test_crypt.py
python/branches/p3yk-noslice/Lib/test/test_csv.py
python/branches/p3yk-noslice/Lib/test/test_curses.py
python/branches/p3yk-noslice/Lib/test/test_datetime.py
python/branches/p3yk-noslice/Lib/test/test_dbm.py
python/branches/p3yk-noslice/Lib/test/test_decimal.py
python/branches/p3yk-noslice/Lib/test/test_defaultdict.py
python/branches/p3yk-noslice/Lib/test/test_deque.py
python/branches/p3yk-noslice/Lib/test/test_descr.py
python/branches/p3yk-noslice/Lib/test/test_descrtut.py
python/branches/p3yk-noslice/Lib/test/test_dict.py
python/branches/p3yk-noslice/Lib/test/test_dis.py
python/branches/p3yk-noslice/Lib/test/test_dl.py
python/branches/p3yk-noslice/Lib/test/test_doctest.py
python/branches/p3yk-noslice/Lib/test/test_doctest.txt
python/branches/p3yk-noslice/Lib/test/test_doctest2.py
python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py
python/branches/p3yk-noslice/Lib/test/test_dummy_thread.py
python/branches/p3yk-noslice/Lib/test/test_dummy_threading.py
python/branches/p3yk-noslice/Lib/test/test_enumerate.py
python/branches/p3yk-noslice/Lib/test/test_errno.py
python/branches/p3yk-noslice/Lib/test/test_exceptions.py
python/branches/p3yk-noslice/Lib/test/test_extcall.py
python/branches/p3yk-noslice/Lib/test/test_fcntl.py
python/branches/p3yk-noslice/Lib/test/test_file.py
python/branches/p3yk-noslice/Lib/test/test_fileinput.py
python/branches/p3yk-noslice/Lib/test/test_format.py
python/branches/p3yk-noslice/Lib/test/test_funcattrs.py
python/branches/p3yk-noslice/Lib/test/test_functools.py
python/branches/p3yk-noslice/Lib/test/test_gc.py
python/branches/p3yk-noslice/Lib/test/test_gdbm.py
python/branches/p3yk-noslice/Lib/test/test_generators.py
python/branches/p3yk-noslice/Lib/test/test_genexps.py
python/branches/p3yk-noslice/Lib/test/test_getargs2.py
python/branches/p3yk-noslice/Lib/test/test_getopt.py
python/branches/p3yk-noslice/Lib/test/test_gl.py
python/branches/p3yk-noslice/Lib/test/test_grammar.py
python/branches/p3yk-noslice/Lib/test/test_grp.py
python/branches/p3yk-noslice/Lib/test/test_gzip.py
python/branches/p3yk-noslice/Lib/test/test_hash.py
python/branches/p3yk-noslice/Lib/test/test_heapq.py
python/branches/p3yk-noslice/Lib/test/test_hexoct.py
python/branches/p3yk-noslice/Lib/test/test_imageop.py
python/branches/p3yk-noslice/Lib/test/test_imgfile.py
python/branches/p3yk-noslice/Lib/test/test_import.py
python/branches/p3yk-noslice/Lib/test/test_importhooks.py
python/branches/p3yk-noslice/Lib/test/test_index.py
python/branches/p3yk-noslice/Lib/test/test_inspect.py
python/branches/p3yk-noslice/Lib/test/test_isinstance.py
python/branches/p3yk-noslice/Lib/test/test_iter.py
python/branches/p3yk-noslice/Lib/test/test_iterlen.py
python/branches/p3yk-noslice/Lib/test/test_itertools.py
python/branches/p3yk-noslice/Lib/test/test_largefile.py
python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py
python/branches/p3yk-noslice/Lib/test/test_list.py
python/branches/p3yk-noslice/Lib/test/test_locale.py
python/branches/p3yk-noslice/Lib/test/test_long.py
python/branches/p3yk-noslice/Lib/test/test_long_future.py
python/branches/p3yk-noslice/Lib/test/test_mailbox.py
python/branches/p3yk-noslice/Lib/test/test_marshal.py
python/branches/p3yk-noslice/Lib/test/test_mhlib.py
python/branches/p3yk-noslice/Lib/test/test_minidom.py
python/branches/p3yk-noslice/Lib/test/test_module.py
python/branches/p3yk-noslice/Lib/test/test_multibytecodec.py
python/branches/p3yk-noslice/Lib/test/test_multibytecodec_support.py
python/branches/p3yk-noslice/Lib/test/test_mutants.py
python/branches/p3yk-noslice/Lib/test/test_new.py
python/branches/p3yk-noslice/Lib/test/test_normalization.py
python/branches/p3yk-noslice/Lib/test/test_ntpath.py
python/branches/p3yk-noslice/Lib/test/test_old_mailbox.py
python/branches/p3yk-noslice/Lib/test/test_operations.py
python/branches/p3yk-noslice/Lib/test/test_operator.py
python/branches/p3yk-noslice/Lib/test/test_optparse.py
python/branches/p3yk-noslice/Lib/test/test_ossaudiodev.py
python/branches/p3yk-noslice/Lib/test/test_parser.py
python/branches/p3yk-noslice/Lib/test/test_peepholer.py
python/branches/p3yk-noslice/Lib/test/test_pep247.py
python/branches/p3yk-noslice/Lib/test/test_pep277.py
python/branches/p3yk-noslice/Lib/test/test_pep352.py
python/branches/p3yk-noslice/Lib/test/test_pkg.py
python/branches/p3yk-noslice/Lib/test/test_poll.py
python/branches/p3yk-noslice/Lib/test/test_popen.py
python/branches/p3yk-noslice/Lib/test/test_popen2.py
python/branches/p3yk-noslice/Lib/test/test_posix.py
python/branches/p3yk-noslice/Lib/test/test_posixpath.py
python/branches/p3yk-noslice/Lib/test/test_pow.py
python/branches/p3yk-noslice/Lib/test/test_pprint.py
python/branches/p3yk-noslice/Lib/test/test_pty.py
python/branches/p3yk-noslice/Lib/test/test_pwd.py
python/branches/p3yk-noslice/Lib/test/test_pyclbr.py
python/branches/p3yk-noslice/Lib/test/test_pyexpat.py
python/branches/p3yk-noslice/Lib/test/test_queue.py
python/branches/p3yk-noslice/Lib/test/test_random.py
python/branches/p3yk-noslice/Lib/test/test_re.py
python/branches/p3yk-noslice/Lib/test/test_repr.py
python/branches/p3yk-noslice/Lib/test/test_resource.py
python/branches/p3yk-noslice/Lib/test/test_rfc822.py
python/branches/p3yk-noslice/Lib/test/test_rgbimg.py
python/branches/p3yk-noslice/Lib/test/test_richcmp.py
python/branches/p3yk-noslice/Lib/test/test_runpy.py
python/branches/p3yk-noslice/Lib/test/test_sax.py
python/branches/p3yk-noslice/Lib/test/test_scope.py
python/branches/p3yk-noslice/Lib/test/test_select.py
python/branches/p3yk-noslice/Lib/test/test_set.py
python/branches/p3yk-noslice/Lib/test/test_signal.py
python/branches/p3yk-noslice/Lib/test/test_site.py
python/branches/p3yk-noslice/Lib/test/test_slice.py
python/branches/p3yk-noslice/Lib/test/test_socket.py
python/branches/p3yk-noslice/Lib/test/test_socket_ssl.py
python/branches/p3yk-noslice/Lib/test/test_socketserver.py
python/branches/p3yk-noslice/Lib/test/test_sort.py
python/branches/p3yk-noslice/Lib/test/test_strftime.py
python/branches/p3yk-noslice/Lib/test/test_string.py
python/branches/p3yk-noslice/Lib/test/test_strop.py
python/branches/p3yk-noslice/Lib/test/test_strptime.py
python/branches/p3yk-noslice/Lib/test/test_struct.py
python/branches/p3yk-noslice/Lib/test/test_subprocess.py
python/branches/p3yk-noslice/Lib/test/test_sundry.py
python/branches/p3yk-noslice/Lib/test/test_support.py
python/branches/p3yk-noslice/Lib/test/test_syntax.py
python/branches/p3yk-noslice/Lib/test/test_tarfile.py
python/branches/p3yk-noslice/Lib/test/test_thread.py
python/branches/p3yk-noslice/Lib/test/test_threaded_import.py
python/branches/p3yk-noslice/Lib/test/test_threadedtempfile.py
python/branches/p3yk-noslice/Lib/test/test_threading.py
python/branches/p3yk-noslice/Lib/test/test_time.py
python/branches/p3yk-noslice/Lib/test/test_timeout.py
python/branches/p3yk-noslice/Lib/test/test_tokenize.py
python/branches/p3yk-noslice/Lib/test/test_trace.py
python/branches/p3yk-noslice/Lib/test/test_traceback.py
python/branches/p3yk-noslice/Lib/test/test_types.py
python/branches/p3yk-noslice/Lib/test/test_unary.py
python/branches/p3yk-noslice/Lib/test/test_unicode.py
python/branches/p3yk-noslice/Lib/test/test_urllib2.py
python/branches/p3yk-noslice/Lib/test/test_urllib2net.py
python/branches/p3yk-noslice/Lib/test/test_userdict.py
python/branches/p3yk-noslice/Lib/test/test_uu.py
python/branches/p3yk-noslice/Lib/test/test_uuid.py
python/branches/p3yk-noslice/Lib/test/test_weakref.py
python/branches/p3yk-noslice/Lib/test/test_winreg.py
python/branches/p3yk-noslice/Lib/test/test_with.py
python/branches/p3yk-noslice/Lib/test/test_xdrlib.py
python/branches/p3yk-noslice/Lib/test/test_xml_etree.py
python/branches/p3yk-noslice/Lib/test/test_xml_etree_c.py
python/branches/p3yk-noslice/Lib/test/test_xmlrpc.py
python/branches/p3yk-noslice/Lib/test/test_xrange.py
python/branches/p3yk-noslice/Lib/test/test_zipfile.py
python/branches/p3yk-noslice/Lib/test/test_zipfile64.py
python/branches/p3yk-noslice/Lib/test/test_zipimport.py
python/branches/p3yk-noslice/Lib/test/test_zlib.py
python/branches/p3yk-noslice/Lib/test/time_hashlib.py
python/branches/p3yk-noslice/Lib/textwrap.py
python/branches/p3yk-noslice/Lib/this.py
python/branches/p3yk-noslice/Lib/threading.py
python/branches/p3yk-noslice/Lib/timeit.py
python/branches/p3yk-noslice/Lib/token.py
python/branches/p3yk-noslice/Lib/tokenize.py
python/branches/p3yk-noslice/Lib/trace.py
python/branches/p3yk-noslice/Lib/types.py
python/branches/p3yk-noslice/Lib/unittest.py
python/branches/p3yk-noslice/Lib/urllib.py
python/branches/p3yk-noslice/Lib/urllib2.py
python/branches/p3yk-noslice/Lib/urlparse.py
python/branches/p3yk-noslice/Lib/uu.py
python/branches/p3yk-noslice/Lib/uuid.py
python/branches/p3yk-noslice/Lib/warnings.py
python/branches/p3yk-noslice/Lib/weakref.py
python/branches/p3yk-noslice/Lib/webbrowser.py
python/branches/p3yk-noslice/Lib/whichdb.py
python/branches/p3yk-noslice/Lib/wsgiref/simple_server.py
python/branches/p3yk-noslice/Lib/xdrlib.py
python/branches/p3yk-noslice/Lib/xml/dom/NodeFilter.py
python/branches/p3yk-noslice/Lib/xml/dom/minidom.py
python/branches/p3yk-noslice/Lib/xml/dom/pulldom.py
python/branches/p3yk-noslice/Lib/xml/etree/ElementTree.py
python/branches/p3yk-noslice/Lib/xml/sax/handler.py
python/branches/p3yk-noslice/Lib/xml/sax/saxutils.py
python/branches/p3yk-noslice/Lib/xml/sax/xmlreader.py
python/branches/p3yk-noslice/Lib/xmllib.py
python/branches/p3yk-noslice/Lib/xmlrpclib.py
python/branches/p3yk-noslice/Lib/zipfile.py
python/branches/p3yk-noslice/Makefile.pre.in
python/branches/p3yk-noslice/Misc/ACKS
python/branches/p3yk-noslice/Misc/NEWS
python/branches/p3yk-noslice/Modules/_csv.c
python/branches/p3yk-noslice/Modules/_ctypes/_ctypes.c
python/branches/p3yk-noslice/Modules/_ctypes/_ctypes_test.c
python/branches/p3yk-noslice/Modules/_ctypes/callproc.c
python/branches/p3yk-noslice/Modules/_ctypes/cfield.c
python/branches/p3yk-noslice/Modules/_ctypes/libffi_msvc/ffi.c
python/branches/p3yk-noslice/Modules/_cursesmodule.c
python/branches/p3yk-noslice/Modules/_randommodule.c
python/branches/p3yk-noslice/Modules/_sqlite/cache.c
python/branches/p3yk-noslice/Modules/_sqlite/cache.h
python/branches/p3yk-noslice/Modules/_sqlite/connection.c
python/branches/p3yk-noslice/Modules/_sqlite/connection.h
python/branches/p3yk-noslice/Modules/_sqlite/cursor.c
python/branches/p3yk-noslice/Modules/_sqlite/cursor.h
python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.c
python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.h
python/branches/p3yk-noslice/Modules/_sqlite/module.c
python/branches/p3yk-noslice/Modules/_sqlite/module.h
python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.c
python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.h
python/branches/p3yk-noslice/Modules/_sqlite/row.c
python/branches/p3yk-noslice/Modules/_sqlite/row.h
python/branches/p3yk-noslice/Modules/_sqlite/statement.c
python/branches/p3yk-noslice/Modules/_sqlite/statement.h
python/branches/p3yk-noslice/Modules/_sqlite/util.c
python/branches/p3yk-noslice/Modules/_sqlite/util.h
python/branches/p3yk-noslice/Modules/_sre.c
python/branches/p3yk-noslice/Modules/_struct.c
python/branches/p3yk-noslice/Modules/_testcapimodule.c
python/branches/p3yk-noslice/Modules/_tkinter.c
python/branches/p3yk-noslice/Modules/arraymodule.c
python/branches/p3yk-noslice/Modules/bz2module.c
python/branches/p3yk-noslice/Modules/cPickle.c
python/branches/p3yk-noslice/Modules/cStringIO.c
python/branches/p3yk-noslice/Modules/cjkcodecs/multibytecodec.c
python/branches/p3yk-noslice/Modules/collectionsmodule.c
python/branches/p3yk-noslice/Modules/datetimemodule.c
python/branches/p3yk-noslice/Modules/dlmodule.c
python/branches/p3yk-noslice/Modules/itertoolsmodule.c
python/branches/p3yk-noslice/Modules/parsermodule.c
python/branches/p3yk-noslice/Modules/posixmodule.c
python/branches/p3yk-noslice/Modules/socketmodule.c
python/branches/p3yk-noslice/Modules/socketmodule.h
python/branches/p3yk-noslice/Modules/timemodule.c
python/branches/p3yk-noslice/Objects/abstract.c
python/branches/p3yk-noslice/Objects/boolobject.c
python/branches/p3yk-noslice/Objects/complexobject.c
python/branches/p3yk-noslice/Objects/dictnotes.txt
python/branches/p3yk-noslice/Objects/dictobject.c
python/branches/p3yk-noslice/Objects/enumobject.c
python/branches/p3yk-noslice/Objects/exceptions.c
python/branches/p3yk-noslice/Objects/fileobject.c
python/branches/p3yk-noslice/Objects/floatobject.c
python/branches/p3yk-noslice/Objects/frameobject.c
python/branches/p3yk-noslice/Objects/intobject.c
python/branches/p3yk-noslice/Objects/iterobject.c
python/branches/p3yk-noslice/Objects/listobject.c
python/branches/p3yk-noslice/Objects/longobject.c
python/branches/p3yk-noslice/Objects/object.c
python/branches/p3yk-noslice/Objects/setobject.c
python/branches/p3yk-noslice/Objects/stringobject.c
python/branches/p3yk-noslice/Objects/typeobject.c
python/branches/p3yk-noslice/Objects/unicodeobject.c
python/branches/p3yk-noslice/Objects/weakrefobject.c
python/branches/p3yk-noslice/PC/_msi.c
python/branches/p3yk-noslice/PCbuild/_bsddb.vcproj
python/branches/p3yk-noslice/PCbuild/_elementtree.vcproj
python/branches/p3yk-noslice/PCbuild/_msi.vcproj
python/branches/p3yk-noslice/PCbuild/_socket.vcproj
python/branches/p3yk-noslice/PCbuild/_sqlite3.vcproj
python/branches/p3yk-noslice/PCbuild/_ssl.mak
python/branches/p3yk-noslice/PCbuild/_testcapi.vcproj
python/branches/p3yk-noslice/PCbuild/_tkinter.vcproj
python/branches/p3yk-noslice/PCbuild/build_ssl.py
python/branches/p3yk-noslice/PCbuild/bz2.vcproj
python/branches/p3yk-noslice/PCbuild/pyexpat.vcproj
python/branches/p3yk-noslice/PCbuild/python.vcproj
python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj
python/branches/p3yk-noslice/PCbuild/pythonw.vcproj
python/branches/p3yk-noslice/PCbuild/select.vcproj
python/branches/p3yk-noslice/PCbuild/unicodedata.vcproj
python/branches/p3yk-noslice/PCbuild/winsound.vcproj
python/branches/p3yk-noslice/Parser/Python.asdl
python/branches/p3yk-noslice/Parser/asdl_c.py
python/branches/p3yk-noslice/Parser/tokenizer.c
python/branches/p3yk-noslice/Python/Python-ast.c
python/branches/p3yk-noslice/Python/ast.c
python/branches/p3yk-noslice/Python/bltinmodule.c
python/branches/p3yk-noslice/Python/ceval.c
python/branches/p3yk-noslice/Python/compile.c
python/branches/p3yk-noslice/Python/frozen.c
python/branches/p3yk-noslice/Python/getargs.c
python/branches/p3yk-noslice/Python/graminit.c
python/branches/p3yk-noslice/Python/import.c
python/branches/p3yk-noslice/Python/marshal.c
python/branches/p3yk-noslice/Python/pythonrun.c
python/branches/p3yk-noslice/Python/symtable.c
python/branches/p3yk-noslice/Python/sysmodule.c
python/branches/p3yk-noslice/Python/traceback.c
python/branches/p3yk-noslice/Tools/compiler/ast.txt
python/branches/p3yk-noslice/Tools/freeze/ (props changed)
python/branches/p3yk-noslice/Tools/freeze/bkfile.py
python/branches/p3yk-noslice/Tools/freeze/freeze.py
python/branches/p3yk-noslice/Tools/freeze/hello.py
python/branches/p3yk-noslice/Tools/freeze/makeconfig.py
python/branches/p3yk-noslice/Tools/freeze/makefreeze.py
python/branches/p3yk-noslice/Tools/freeze/parsesetup.py
python/branches/p3yk-noslice/Tools/freeze/winmakemakefile.py
python/branches/p3yk-noslice/Tools/msi/uuids.py
python/branches/p3yk-noslice/Tools/pybench/CommandLine.py
python/branches/p3yk-noslice/Tools/pybench/Dict.py
python/branches/p3yk-noslice/Tools/pybench/Exceptions.py
python/branches/p3yk-noslice/Tools/pybench/Lookups.py
python/branches/p3yk-noslice/Tools/pybench/pybench.py
python/branches/p3yk-noslice/configure
python/branches/p3yk-noslice/configure.in
python/branches/p3yk-noslice/pyconfig.h.in
python/branches/p3yk-noslice/setup.py
Log:
Merge p3yk into p3yk-noslice branch.
Merged revisions 53364-53866 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/p3yk
................
r53417 | guido.van.rossum | 2007-01-14 00:54:39 +0100 (Sun, 14 Jan 2007) | 2 lines
Fix pybench so it works -- Larry Hastings.
................
r53421 | guido.van.rossum | 2007-01-14 04:31:43 +0100 (Sun, 14 Jan 2007) | 9 lines
Merged the int/long unification branch, by very crude means (sorry Thomas!).
I banged on the code (beyond what's in that branch) to make fewer tests fail;
the only tests that fail now are:
test_descr -- can't pickle ints?!
test_pickletools -- ???
test_socket -- See python.org/sf/1619659
test_sqlite -- ???
I'll deal with those later.
................
r53422 | guido.van.rossum | 2007-01-14 04:42:30 +0100 (Sun, 14 Jan 2007) | 2 lines
News about int/long unification and except syntax change.
................
r53424 | guido.van.rossum | 2007-01-14 05:02:16 +0100 (Sun, 14 Jan 2007) | 3 lines
Fix cPickle breakage due to last-minute change to the name of the 'long' type
(it's not called 'int' :-).
................
r53433 | guido.van.rossum | 2007-01-14 17:55:36 +0100 (Sun, 14 Jan 2007) | 2 lines
Honesty before all.
................
r53438 | guido.van.rossum | 2007-01-14 19:43:49 +0100 (Sun, 14 Jan 2007) | 2 lines
Fix new bug in ftplib.py introduced by exception scope limitation.
................
r53439 | guido.van.rossum | 2007-01-14 19:52:06 +0100 (Sun, 14 Jan 2007) | 2 lines
One more test breakage hits the dust. The test was clearly in the wrong.
................
r53443 | guido.van.rossum | 2007-01-15 01:07:32 +0100 (Mon, 15 Jan 2007) | 10 lines
Merged revisions 53434 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r53434 | guido.van.rossum | 2007-01-14 09:03:32 -0800 (Sun, 14 Jan 2007) | 3 lines
Patch #1635058 by Mark Roberts: ensure that htonl and friends never accept or
return negative numbers, per the underlying C implementation.
........
................
r53444 | guido.van.rossum | 2007-01-15 01:14:39 +0100 (Mon, 15 Jan 2007) | 2 lines
Fix repr.py -- it was triggering on the type name 'long', should be 'int'.
................
r53445 | guido.van.rossum | 2007-01-15 01:21:46 +0100 (Mon, 15 Jan 2007) | 3 lines
Fix pickletools doctests -- all we get nowadays is longs.
(Hmm... Shouldn't longs of certain sizes be pickled using 'I' opcodes? Later.)
................
r53446 | guido.van.rossum | 2007-01-15 01:31:49 +0100 (Mon, 15 Jan 2007) | 3 lines
Fix the sqlite failure -- it was the usual, PyInt_Check -> PyInt_CheckExact.
Clarify some OverflowError messages from the various PyLong_AsXXX methods.
................
r53448 | guido.van.rossum | 2007-01-15 01:38:25 +0100 (Mon, 15 Jan 2007) | 2 lines
No more tests are broken AFAIK.
................
r53451 | thomas.wouters | 2007-01-15 16:49:28 +0100 (Mon, 15 Jan 2007) | 216 lines
Merged revisions 53304-53433,53435-53450 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r53304 | vinay.sajip | 2007-01-09 15:50:28 +0100 (Tue, 09 Jan 2007) | 1 line
Bug #1627575: Added _open() method to FileHandler which can be used to reopen files. The FileHandler instance now saves the encoding (which can be None) in an attribute called "encoding".
........
r53305 | vinay.sajip | 2007-01-09 15:51:36 +0100 (Tue, 09 Jan 2007) | 1 line
Added entry about addition of _open() method to logging.FileHandler.
........
r53306 | vinay.sajip | 2007-01-09 15:54:56 +0100 (Tue, 09 Jan 2007) | 1 line
Added a docstring
........
r53316 | thomas.heller | 2007-01-09 20:19:33 +0100 (Tue, 09 Jan 2007) | 4 lines
Verify the sizes of the basic ctypes data types against the struct
module.
Will backport to release25-maint.
........
r53340 | gustavo.niemeyer | 2007-01-10 17:13:40 +0100 (Wed, 10 Jan 2007) | 3 lines
Mention in the int() docstring that a base zero has meaning, as
stated in http://docs.python.org/lib/built-in-funcs.html as well.
........
r53341 | gustavo.niemeyer | 2007-01-10 17:15:48 +0100 (Wed, 10 Jan 2007) | 2 lines
Minor change in int() docstring for proper spacing.
........
r53358 | thomas.heller | 2007-01-10 21:12:13 +0100 (Wed, 10 Jan 2007) | 1 line
Change the ctypes version number to "1.1.0".
........
r53361 | thomas.heller | 2007-01-10 21:51:19 +0100 (Wed, 10 Jan 2007) | 1 line
Must change the version number in the _ctypes extension as well.
........
r53362 | guido.van.rossum | 2007-01-11 00:12:56 +0100 (Thu, 11 Jan 2007) | 3 lines
Fix the signature of log_error(). (A subclass that did the right thing
was getting complaints from pychecker.)
........
r53370 | matthias.klose | 2007-01-11 11:26:31 +0100 (Thu, 11 Jan 2007) | 2 lines
- Make the documentation match the code and the docstring
........
r53375 | matthias.klose | 2007-01-11 12:44:04 +0100 (Thu, 11 Jan 2007) | 2 lines
- idle: Honor the "Cancel" action in the save dialog (Debian bug #299092).
........
r53381 | raymond.hettinger | 2007-01-11 19:22:55 +0100 (Thu, 11 Jan 2007) | 1 line
SF #1486663 -- Allow keyword args in subclasses of set() and frozenset().
........
r53388 | thomas.heller | 2007-01-11 22:18:56 +0100 (Thu, 11 Jan 2007) | 4 lines
Fixes for 64-bit Windows: In ctypes.wintypes, correct the definitions
of HANDLE, WPARAM, LPARAM data types. Make parameterless foreign
function calls work.
........
r53390 | thomas.heller | 2007-01-11 22:23:12 +0100 (Thu, 11 Jan 2007) | 2 lines
Correct the comments: the code is right.
........
r53393 | brett.cannon | 2007-01-12 08:27:52 +0100 (Fri, 12 Jan 2007) | 3 lines
Fix error where the end of a funcdesc environment was accidentally moved too
far down.
........
r53397 | anthony.baxter | 2007-01-12 10:35:56 +0100 (Fri, 12 Jan 2007) | 3 lines
add parsetok.h as a dependency - previously, changing this file doesn't
cause the right files to be rebuilt.
........
r53401 | thomas.heller | 2007-01-12 21:08:19 +0100 (Fri, 12 Jan 2007) | 3 lines
Avoid warnings in the test suite because ctypes.wintypes cannot be
imported on non-windows systems.
........
r53402 | thomas.heller | 2007-01-12 21:17:34 +0100 (Fri, 12 Jan 2007) | 6 lines
patch #1610795: BSD version of ctypes.util.find_library, by Martin
Kammerhofer.
release25-maint backport candidate, but the release manager has to
decide.
........
r53403 | thomas.heller | 2007-01-12 21:21:53 +0100 (Fri, 12 Jan 2007) | 3 lines
patch #1610795: BSD version of ctypes.util.find_library, by Martin
Kammerhofer.
........
r53406 | brett.cannon | 2007-01-13 01:29:49 +0100 (Sat, 13 Jan 2007) | 2 lines
Deprecate the sets module.
........
r53407 | georg.brandl | 2007-01-13 13:31:51 +0100 (Sat, 13 Jan 2007) | 3 lines
Fix typo.
........
r53409 | marc-andre.lemburg | 2007-01-13 22:00:08 +0100 (Sat, 13 Jan 2007) | 16 lines
Bump version number and change copyright year.
Add new API linux_distribution() which supports reading the full distribution
name and also knows how to parse LSB-style release files.
Redirect the old dist() API to the new API (using the short distribution name
taken from the release file filename).
Add branch and revision to _sys_version().
Add work-around for Cygwin to libc_ver().
Add support for IronPython (thanks for Anthony Baxter) and make
Jython support more robust.
........
r53410 | neal.norwitz | 2007-01-13 22:22:37 +0100 (Sat, 13 Jan 2007) | 1 line
Fix grammar in docstrings
........
r53411 | marc-andre.lemburg | 2007-01-13 23:32:21 +0100 (Sat, 13 Jan 2007) | 9 lines
Add parameter sys_version to _sys_version().
Change the cache for _sys_version() to take the parameter into account.
Add support for parsing the IronPython 1.0.1 sys.version value - even
though it still returns '1.0.0'; the version string no longer includes
the patch level.
........
r53412 | peter.astrand | 2007-01-13 23:35:35 +0100 (Sat, 13 Jan 2007) | 1 line
Fix for bug #1634343: allow specifying empty arguments on Windows
........
r53414 | marc-andre.lemburg | 2007-01-13 23:59:36 +0100 (Sat, 13 Jan 2007) | 14 lines
Add Python implementation to the machine details.
Pretty-print the Python version used for running PyBench.
Let the user know when calibration has finished.
[ 1563844 ] pybench support for IronPython:
Simplify Unicode version detection.
Make garbage collection and check interval settings optional if
the Python implementation doesn't support thess (e.g. IronPython).
........
r53415 | marc-andre.lemburg | 2007-01-14 00:13:54 +0100 (Sun, 14 Jan 2007) | 5 lines
Use defaults if sys.executable isn't set (e.g. on Jython).
This change allows running PyBench under Jython.
........
r53416 | marc-andre.lemburg | 2007-01-14 00:15:33 +0100 (Sun, 14 Jan 2007) | 3 lines
Jython doesn't have sys.setcheckinterval() - ignore it in that case.
........
r53420 | gerhard.haering | 2007-01-14 02:43:50 +0100 (Sun, 14 Jan 2007) | 29 lines
Merged changes from standalone version 2.3.3. This should probably all be
merged into the 2.5 maintenance branch:
- self->statement was not checked while fetching data, which could
lead to crashes if you used the pysqlite API in unusual ways.
Closing the cursor and continuing to fetch data was enough.
- Converters are stored in a converters dictionary. The converter name
is uppercased first. The old upper-casing algorithm was wrong and
was replaced by a simple call to the Python string's upper() method
instead.
-Applied patch by Glyph Lefkowitz that fixes the problem with
subsequent SQLITE_SCHEMA errors.
- Improvement to the row type: rows can now be iterated over and have a keys()
method. This improves compatibility with both tuple and dict a lot.
- A bugfix for the subsecond resolution in timestamps.
- Corrected the way the flags PARSE_DECLTYPES and PARSE_COLNAMES are
checked for. Now they work as documented.
- gcc on Linux sucks. It exports all symbols by default in shared
libraries, so if symbols are not unique it can lead to problems with
symbol lookup. pysqlite used to crash under Apache when mod_cache
was enabled because both modules had the symbol cache_init. I fixed
this by applying the prefix pysqlite_ almost everywhere. Sigh.
........
r53423 | guido.van.rossum | 2007-01-14 04:46:33 +0100 (Sun, 14 Jan 2007) | 2 lines
Remove a dependency of this test on $COLUMNS.
........
r53425 | ka-ping.yee | 2007-01-14 05:25:15 +0100 (Sun, 14 Jan 2007) | 3 lines
Handle old-style instances more gracefully (display documentation on
the relevant class instead of documentation on <type 'instance'>).
........
r53440 | vinay.sajip | 2007-01-14 22:49:59 +0100 (Sun, 14 Jan 2007) | 1 line
Added WatchedFileHandler (based on SF patch #1598415)
........
r53441 | vinay.sajip | 2007-01-14 22:50:50 +0100 (Sun, 14 Jan 2007) | 1 line
Added documentation for WatchedFileHandler (based on SF patch #1598415)
........
r53442 | guido.van.rossum | 2007-01-15 01:02:35 +0100 (Mon, 15 Jan 2007) | 2 lines
Doc patch matching r53434 (htonl etc. now always take/return positive ints).
........
................
r53452 | guido.van.rossum | 2007-01-15 17:59:06 +0100 (Mon, 15 Jan 2007) | 3 lines
Rip out 'long' and 'L'-suffixed integer literals.
(Rough first cut.)
................
r53453 | guido.van.rossum | 2007-01-15 18:02:51 +0100 (Mon, 15 Jan 2007) | 2 lines
Fix L-suffixed literal straggler.
................
r53598 | brett.cannon | 2007-01-30 00:43:38 +0100 (Tue, 30 Jan 2007) | 2 lines
Fix minor grammar typo.
................
r53599 | brett.cannon | 2007-01-30 00:44:37 +0100 (Tue, 30 Jan 2007) | 2 lines
Add missing entry for PEP 3102 (keyword-only arguments).
................
r53600 | guido.van.rossum | 2007-01-30 01:00:40 +0100 (Tue, 30 Jan 2007) | 2 lines
Update news about int/long unification.
................
r53610 | thomas.wouters | 2007-02-01 19:02:27 +0100 (Thu, 01 Feb 2007) | 180 lines
Merged revisions 53451-53537 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r53454 | brett.cannon | 2007-01-15 20:12:08 +0100 (Mon, 15 Jan 2007) | 3 lines
Add a note for strptime that just because strftime supports some extra
directive that is not documented that strptime will as well.
........
r53458 | vinay.sajip | 2007-01-16 10:50:07 +0100 (Tue, 16 Jan 2007) | 1 line
Updated rotating file handlers to use _open().
........
r53459 | marc-andre.lemburg | 2007-01-16 14:03:06 +0100 (Tue, 16 Jan 2007) | 2 lines
Add news items for the recent pybench and platform changes.
........
r53460 | sjoerd.mullender | 2007-01-16 17:42:38 +0100 (Tue, 16 Jan 2007) | 4 lines
Fixed ntpath.expandvars to not replace references to non-existing
variables with nothing. Also added tests.
This fixes bug #494589.
........
r53464 | neal.norwitz | 2007-01-17 07:23:51 +0100 (Wed, 17 Jan 2007) | 1 line
Give Calvin Spealman access for python-dev summaries.
........
r53465 | neal.norwitz | 2007-01-17 09:37:26 +0100 (Wed, 17 Jan 2007) | 1 line
Remove Calvin since he only has access to the website currently.
........
r53466 | thomas.heller | 2007-01-17 10:40:34 +0100 (Wed, 17 Jan 2007) | 2 lines
Replace C++ comments with C comments.
........
r53472 | andrew.kuchling | 2007-01-17 20:55:06 +0100 (Wed, 17 Jan 2007) | 1 line
[Part of bug #1599254] Add suggestion to Mailbox docs to use Maildir, and warn user to lock/unlock mailboxes when modifying them
........
r53475 | georg.brandl | 2007-01-17 22:09:04 +0100 (Wed, 17 Jan 2007) | 2 lines
Bug #1637967: missing //= operator in list.
........
r53477 | georg.brandl | 2007-01-17 22:19:58 +0100 (Wed, 17 Jan 2007) | 2 lines
Bug #1629125: fix wrong data type (int -> Py_ssize_t) in PyDict_Next docs.
........
r53481 | neal.norwitz | 2007-01-18 06:40:58 +0100 (Thu, 18 Jan 2007) | 1 line
Try reverting part of r53145 that seems to cause the Windows buildbots to fail in test_uu.UUFileTest.test_encode
........
r53482 | fred.drake | 2007-01-18 06:42:30 +0100 (Thu, 18 Jan 2007) | 1 line
add missing version entry
........
r53483 | neal.norwitz | 2007-01-18 07:20:55 +0100 (Thu, 18 Jan 2007) | 7 lines
This test doesn't pass on Windows. The cause seems to be that chmod
doesn't support the same funcationality as on Unix. I'm not sure if
this fix is the best (or if it will even work)--it's a test to see
if the buildbots start passing again.
It might be better to not even run this test if it's windows (or non-posix).
........
r53488 | neal.norwitz | 2007-01-19 06:53:33 +0100 (Fri, 19 Jan 2007) | 1 line
SF #1635217, Fix unbalanced paren
........
r53489 | martin.v.loewis | 2007-01-19 07:42:22 +0100 (Fri, 19 Jan 2007) | 3 lines
Prefix AST symbols with _Py_. Fixes #1637022.
Will backport.
........
r53497 | martin.v.loewis | 2007-01-19 19:01:38 +0100 (Fri, 19 Jan 2007) | 2 lines
Add UUIDs for 2.5.1 and 2.5.2
........
r53499 | raymond.hettinger | 2007-01-19 19:07:18 +0100 (Fri, 19 Jan 2007) | 1 line
SF# 1635892: Fix docs for betavariate's input parameters .
........
r53503 | martin.v.loewis | 2007-01-20 15:05:39 +0100 (Sat, 20 Jan 2007) | 2 lines
Merge 53501 and 53502 from 25 branch:
Add /GS- for AMD64 and Itanium builds where missing.
........
r53504 | walter.doerwald | 2007-01-20 18:28:31 +0100 (Sat, 20 Jan 2007) | 2 lines
Port test_resource.py to unittest.
........
r53505 | walter.doerwald | 2007-01-20 19:19:33 +0100 (Sat, 20 Jan 2007) | 2 lines
Add argument tests an calls of resource.getrusage().
........
r53506 | walter.doerwald | 2007-01-20 20:03:17 +0100 (Sat, 20 Jan 2007) | 2 lines
resource.RUSAGE_BOTH might not exist.
........
r53507 | walter.doerwald | 2007-01-21 00:07:28 +0100 (Sun, 21 Jan 2007) | 2 lines
Port test_new.py to unittest.
........
r53508 | martin.v.loewis | 2007-01-21 10:33:07 +0100 (Sun, 21 Jan 2007) | 2 lines
Patch #1610575: Add support for _Bool to struct.
........
r53509 | georg.brandl | 2007-01-21 11:28:43 +0100 (Sun, 21 Jan 2007) | 3 lines
Bug #1486663: don't reject keyword arguments for subclasses of builtin
types.
........
r53511 | georg.brandl | 2007-01-21 11:35:10 +0100 (Sun, 21 Jan 2007) | 2 lines
Patch #1627441: close sockets properly in urllib2.
........
r53517 | georg.brandl | 2007-01-22 20:40:21 +0100 (Mon, 22 Jan 2007) | 3 lines
Use new email module names (#1637162, #1637159, #1637157).
........
r53518 | andrew.kuchling | 2007-01-22 21:26:40 +0100 (Mon, 22 Jan 2007) | 1 line
Improve pattern used for mbox 'From' lines; add a simple test
........
r53519 | andrew.kuchling | 2007-01-22 21:27:50 +0100 (Mon, 22 Jan 2007) | 1 line
Make comment match the code
........
r53522 | georg.brandl | 2007-01-22 22:10:33 +0100 (Mon, 22 Jan 2007) | 2 lines
Bug #1249573: fix rfc822.parsedate not accepting a certain date format
........
r53524 | georg.brandl | 2007-01-22 22:23:41 +0100 (Mon, 22 Jan 2007) | 2 lines
Bug #1627316: handle error in condition/ignore pdb commands more gracefully.
........
r53526 | lars.gustaebel | 2007-01-23 12:17:33 +0100 (Tue, 23 Jan 2007) | 4 lines
Patch #1507247: tarfile.py: use current umask for intermediate
directories.
........
r53527 | thomas.wouters | 2007-01-23 14:42:00 +0100 (Tue, 23 Jan 2007) | 13 lines
SF patch #1630975: Fix crash when replacing sys.stdout in sitecustomize
When running the interpreter in an environment that would cause it to set
stdout/stderr/stdin's encoding, having a sitecustomize that would replace
them with something other than PyFile objects would crash the interpreter.
Fix it by simply ignoring the encoding-setting for non-files.
This could do with a test, but I can think of no maintainable and portable
way to test this bug, short of adding a sitecustomize.py to the buildsystem
and have it always run with it (hmmm....)
........
r53528 | thomas.wouters | 2007-01-23 14:50:49 +0100 (Tue, 23 Jan 2007) | 4 lines
Add news entry about last checkin (oops.)
........
r53531 | martin.v.loewis | 2007-01-23 22:11:47 +0100 (Tue, 23 Jan 2007) | 4 lines
Make PyTraceBack_Here use the current thread, not the
frame's thread state. Fixes #1579370.
Will backport.
........
r53535 | brett.cannon | 2007-01-24 00:21:22 +0100 (Wed, 24 Jan 2007) | 5 lines
Fix crasher for when an object's __del__ creates a new weakref to itself.
Patch only fixes new-style classes; classic classes still buggy.
Closes bug #1377858. Already backported.
........
r53536 | walter.doerwald | 2007-01-24 01:42:19 +0100 (Wed, 24 Jan 2007) | 2 lines
Port test_popen.py to unittest.
........
................
r53627 | thomas.wouters | 2007-02-03 22:49:06 +0100 (Sat, 03 Feb 2007) | 8 lines
- Fix conversion glitch in test_pyclbr, which caused a test to not fail
when it should.
- Remove unneeded classic-class support from pydoc (which would otherwise
cause test_pyclbr to fail.)
................
r53634 | thomas.wouters | 2007-02-05 02:24:16 +0100 (Mon, 05 Feb 2007) | 96 lines
Merged revisions 53538-53622 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r53545 | andrew.kuchling | 2007-01-24 21:06:41 +0100 (Wed, 24 Jan 2007) | 1 line
Strengthen warning about using lock()
........
r53556 | thomas.heller | 2007-01-25 19:34:14 +0100 (Thu, 25 Jan 2007) | 3 lines
Fix for #1643874: When calling SysAllocString, create a PyCObject
which will eventually call SysFreeString to free the BSTR resource.
........
r53563 | andrew.kuchling | 2007-01-25 21:02:13 +0100 (Thu, 25 Jan 2007) | 1 line
Add item
........
r53564 | brett.cannon | 2007-01-25 21:22:02 +0100 (Thu, 25 Jan 2007) | 8 lines
Fix time.strptime's %U support. Basically rewrote the algorithm to be more
generic so that one only has to shift certain values based on whether the week
was specified to start on Monday or Sunday. Cut out a lot of edge case code
compared to the previous version. Also broke algorithm out into its own
function (that is private to the module).
Fixes bug #1643943 (thanks Biran Nahas for the report).
........
r53570 | brett.cannon | 2007-01-26 00:30:39 +0100 (Fri, 26 Jan 2007) | 4 lines
Remove specific mention of my name and email address from modules. Not really
needed and all bug reports should go to the bug tracker, not directly to me.
Plus I am not the only person to have edited these files at this point.
........
r53573 | fred.drake | 2007-01-26 17:28:44 +0100 (Fri, 26 Jan 2007) | 1 line
fix typo (extraneous ")")
........
r53575 | georg.brandl | 2007-01-27 18:43:02 +0100 (Sat, 27 Jan 2007) | 4 lines
Patch #1638243: the compiler package is now able to correctly compile
a with statement; previously, executing code containing a with statement
compiled by the compiler package crashed the interpreter.
........
r53578 | georg.brandl | 2007-01-27 18:59:42 +0100 (Sat, 27 Jan 2007) | 3 lines
Patch #1634778: add missing encoding aliases for iso8859_15 and
iso8859_16.
........
r53579 | georg.brandl | 2007-01-27 20:38:50 +0100 (Sat, 27 Jan 2007) | 2 lines
Bug #1645944: os.access now returns bool but docstring is not updated
........
r53590 | brett.cannon | 2007-01-28 21:58:00 +0100 (Sun, 28 Jan 2007) | 2 lines
Use the thread lock's context manager instead of a try/finally statement.
........
r53591 | brett.cannon | 2007-01-29 05:41:44 +0100 (Mon, 29 Jan 2007) | 2 lines
Add a test for slicing an exception.
........
r53594 | andrew.kuchling | 2007-01-29 21:21:43 +0100 (Mon, 29 Jan 2007) | 1 line
Minor edits to the curses HOWTO
........
r53596 | andrew.kuchling | 2007-01-29 21:55:40 +0100 (Mon, 29 Jan 2007) | 1 line
Various minor edits
........
r53597 | andrew.kuchling | 2007-01-29 22:28:48 +0100 (Mon, 29 Jan 2007) | 1 line
More edits
........
r53601 | tim.peters | 2007-01-30 04:03:46 +0100 (Tue, 30 Jan 2007) | 2 lines
Whitespace normalization.
........
r53603 | georg.brandl | 2007-01-30 21:21:30 +0100 (Tue, 30 Jan 2007) | 2 lines
Bug #1648191: typo in docs.
........
r53605 | brett.cannon | 2007-01-30 22:34:36 +0100 (Tue, 30 Jan 2007) | 8 lines
No more raising of string exceptions!
The next step of PEP 352 (for 2.6) causes raising a string exception to trigger
a TypeError. Trying to catch a string exception raises a DeprecationWarning.
References to string exceptions has been removed from the docs since they are
now just an error.
........
r53618 | raymond.hettinger | 2007-02-01 22:02:59 +0100 (Thu, 01 Feb 2007) | 1 line
Bug #1648179: set.update() not recognizing __iter__ overrides in dict subclasses.
........
................
r53651 | martin.v.loewis | 2007-02-06 22:05:30 +0100 (Tue, 06 Feb 2007) | 2 lines
Fix refcounting bugs related to CONVERT_BINOP.
................
r53652 | martin.v.loewis | 2007-02-06 22:30:59 +0100 (Tue, 06 Feb 2007) | 3 lines
Remove bogus INCREF of ziptuple: it is a
freshly-allocated tuple object.
................
r53685 | guido.van.rossum | 2007-02-09 06:32:43 +0100 (Fri, 09 Feb 2007) | 3 lines
Essential changes for print function changes.
Lib will be changed in a separate run.
................
r53686 | guido.van.rossum | 2007-02-09 06:37:30 +0100 (Fri, 09 Feb 2007) | 9 lines
Fix most trivially-findable print statements.
There's one major and one minor category still unfixed:
doctests are the major category (and I hope to be able to augment the
refactoring tool to refactor bona fide doctests soon);
other code generating print statements in strings is the minor category.
(Oh, and I don't know if the compiler package works.)
................
r53688 | guido.van.rossum | 2007-02-09 06:42:38 +0100 (Fri, 09 Feb 2007) | 2 lines
Note that print is a function now.
................
r53701 | guido.van.rossum | 2007-02-09 21:13:25 +0100 (Fri, 09 Feb 2007) | 3 lines
Fix a bunch of doctests with the -d option of refactor.py.
We still have 27 failing tests (down from 39).
................
r53702 | guido.van.rossum | 2007-02-09 21:33:44 +0100 (Fri, 09 Feb 2007) | 2 lines
Revert doubly-converted doctests.
................
r53703 | guido.van.rossum | 2007-02-09 21:50:08 +0100 (Fri, 09 Feb 2007) | 7 lines
Fix an unfortunate mis-conversion: sometimes "print x," must be
converted to "print(x, end=' ')", but other times it must be converted
to "print(x, end='')". There's no easy way to find out, because it
depends on whether x ends with a newline. I'm sure I'll find more
like this.
................
r53704 | georg.brandl | 2007-02-09 22:28:07 +0100 (Fri, 09 Feb 2007) | 7 lines
* Remove PRINT_ITEM(_TO), PRINT_NEWLINE(_TO) opcodes.
* Fix some docstrings and one Print -> print.
* Fix test_{class,code,descrtut,dis,extcall,parser,popen,pkg,subprocess,syntax,traceback}.
These were the ones that generated code with a print statement.
In most remaining failing tests there's an issue with the soft space.
................
r53705 | guido.van.rossum | 2007-02-09 22:54:58 +0100 (Fri, 09 Feb 2007) | 2 lines
Some more tests pass now. (Also test_compiler.py with -u all.)
................
r53706 | guido.van.rossum | 2007-02-09 23:09:01 +0100 (Fri, 09 Feb 2007) | 2 lines
Fix another test.
................
r53707 | guido.van.rossum | 2007-02-09 23:11:20 +0100 (Fri, 09 Feb 2007) | 2 lines
Two tests fixed with one fix.
................
r53708 | guido.van.rossum | 2007-02-09 23:16:54 +0100 (Fri, 09 Feb 2007) | 2 lines
Fix a bogus end=' ' here.
................
r53709 | guido.van.rossum | 2007-02-09 23:18:41 +0100 (Fri, 09 Feb 2007) | 2 lines
More prints embedded in strings.
................
r53710 | guido.van.rossum | 2007-02-09 23:27:36 +0100 (Fri, 09 Feb 2007) | 3 lines
Found another difference between old and new print:
old print would suppress the softspace after \t.
................
r53711 | guido.van.rossum | 2007-02-09 23:28:28 +0100 (Fri, 09 Feb 2007) | 2 lines
Trivial fix for test_profile.py.
................
r53712 | guido.van.rossum | 2007-02-09 23:36:02 +0100 (Fri, 09 Feb 2007) | 2 lines
Fairly subtle fix for failing tests.
................
r53713 | guido.van.rossum | 2007-02-09 23:43:10 +0100 (Fri, 09 Feb 2007) | 2 lines
Fix the roundtripping function.
................
r53714 | guido.van.rossum | 2007-02-09 23:43:47 +0100 (Fri, 09 Feb 2007) | 2 lines
Redue the failure rate to 13 tests. Bah.
................
r53715 | guido.van.rossum | 2007-02-10 00:20:19 +0100 (Sat, 10 Feb 2007) | 4 lines
Kill off softspace completely (except in formatter.py which seems to have
a different feature with the same name).
The change to test_doctest.txt reduces the doctest failures to 3.
................
r53716 | guido.van.rossum | 2007-02-10 00:27:01 +0100 (Sat, 10 Feb 2007) | 2 lines
Fix test_frozen.
................
r53717 | guido.van.rossum | 2007-02-10 00:38:28 +0100 (Sat, 10 Feb 2007) | 2 lines
Ignore *.py[co].
................
r53718 | guido.van.rossum | 2007-02-10 00:39:59 +0100 (Sat, 10 Feb 2007) | 4 lines
Fix the remaining doctest failures.
One was a modified line that was echoed in an exception;
the other two were softspace problems, fixed clumsily but effectively.
................
r53719 | guido.van.rossum | 2007-02-10 00:52:14 +0100 (Sat, 10 Feb 2007) | 2 lines
News about softspace.
................
r53721 | guido.van.rossum | 2007-02-10 02:11:45 +0100 (Sat, 10 Feb 2007) | 2 lines
Very preliminary work on dict views.
................
r53723 | guido.van.rossum | 2007-02-10 05:54:19 +0100 (Sat, 10 Feb 2007) | 2 lines
Endow dict views with a proper length method.
................
r53724 | guido.van.rossum | 2007-02-10 19:55:06 +0100 (Sat, 10 Feb 2007) | 4 lines
Implement __contains__ for dict_keys and dict_items.
(Not for dict_values, where it can't be done faster than
the default implementation which just iterates the elements.)
................
r53727 | guido.van.rossum | 2007-02-10 23:53:17 +0100 (Sat, 10 Feb 2007) | 2 lines
Random change to make this work unchanged when dict.keys() returns a dict view.
................
r53732 | guido.van.rossum | 2007-02-11 07:12:03 +0100 (Sun, 11 Feb 2007) | 9 lines
- PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone;
and .keys(), .items(), .values() return dict views.
The dict views aren't fully functional yet; in particular, they can't
be compared to sets yet. but they are useful as "iterator wells".
There are still 27 failing unit tests; I expect that many of these
have fairly trivial fixes, but there are so many, I could use help.
................
r53734 | guido.van.rossum | 2007-02-11 08:05:21 +0100 (Sun, 11 Feb 2007) | 2 lines
With the help of the improved fixer, test_with.py is now fixed.
................
r53738 | guido.van.rossum | 2007-02-11 19:44:55 +0100 (Sun, 11 Feb 2007) | 2 lines
Make test_sax pass.
................
r53739 | guido.van.rossum | 2007-02-11 19:53:00 +0100 (Sun, 11 Feb 2007) | 2 lines
Another fix. Partly reverted the tweaks done by the previous fix.
................
r53740 | guido.van.rossum | 2007-02-11 19:54:18 +0100 (Sun, 11 Feb 2007) | 2 lines
Two more trivial fixes.
................
r53742 | guido.van.rossum | 2007-02-11 23:59:48 +0100 (Sun, 11 Feb 2007) | 2 lines
Nailed test_weakref.py. Pfew, messy!
................
r53743 | georg.brandl | 2007-02-12 00:06:17 +0100 (Mon, 12 Feb 2007) | 3 lines
Checkin the regenerated Python-ast.c and fix test_optparse.
................
r53746 | guido.van.rossum | 2007-02-12 01:07:01 +0100 (Mon, 12 Feb 2007) | 2 lines
Make test_logging pass.
................
r53747 | guido.van.rossum | 2007-02-12 01:22:55 +0100 (Mon, 12 Feb 2007) | 2 lines
Fix another unit test.
................
r53748 | guido.van.rossum | 2007-02-12 01:23:56 +0100 (Mon, 12 Feb 2007) | 2 lines
Fix unittest.
................
r53749 | guido.van.rossum | 2007-02-12 03:23:40 +0100 (Mon, 12 Feb 2007) | 4 lines
Make dict.keys() and dict.items() comparable to sets, using == and !=.
(PEP 3106 requires subset comparisons too, those will come later if someone
really wants them. :-)
................
r53759 | guido.van.rossum | 2007-02-13 06:46:39 +0100 (Tue, 13 Feb 2007) | 2 lines
List of broken tests at this time. If you fix a test, please update this file.
................
r53773 | guido.van.rossum | 2007-02-13 20:55:23 +0100 (Tue, 13 Feb 2007) | 2 lines
Get rid of some old TO TO items.
................
r53779 | guido.van.rossum | 2007-02-14 18:49:04 +0100 (Wed, 14 Feb 2007) | 2 lines
Fix for test_dict.py, thanks to Eduardo O Padoan.
................
r53780 | guido.van.rossum | 2007-02-15 04:49:08 +0100 (Thu, 15 Feb 2007) | 6 lines
Fix the damage to UserDict and its tests.
Clearly this is not the right way to fix this; UserDict and MixinDict
ought to be redesigned with the new dict API in mind. But I'm not
claiming to be in charge of library redesign, I only want zero failing
tests.
................
r53781 | guido.van.rossum | 2007-02-15 05:01:01 +0100 (Thu, 15 Feb 2007) | 2 lines
Some more test now pass.
................
r53841 | brett.cannon | 2007-02-21 22:18:18 +0100 (Wed, 21 Feb 2007) | 2 lines
Fix plistlib to work with dict views.
................
r53843 | brett.cannon | 2007-02-21 22:57:55 +0100 (Wed, 21 Feb 2007) | 2 lines
Fix test_os from breakage due to dict views.
................
r53844 | brett.cannon | 2007-02-21 22:59:58 +0100 (Wed, 21 Feb 2007) | 2 lines
Fix test_mutants for dict views.
................
r53845 | brett.cannon | 2007-02-21 23:05:37 +0100 (Wed, 21 Feb 2007) | 7 lines
Fix xml.dom.minidom so it works again after the dict views introduction.
There are some methods in minidom that return dict.keys() directly. There were
left alone since the tests passed without touching them, but it might be
prudent to just wrap them in a 'list' call to be safe for people expecting a
list.
................
r53852 | brett.cannon | 2007-02-22 05:45:13 +0100 (Thu, 22 Feb 2007) | 7 lines
Fix test_iterlen by returning the iterator of dict views. Problem is that
iteritems and itervalues' previous object were both an iterator *and* and
iterable. The tests expected an iterator but were given an iterable.
Should the 2to3 conversion for iter(values|items|keys) change the code to
``iter(dict.keys())`` to be more compatible?
................
r53853 | brett.cannon | 2007-02-22 05:49:03 +0100 (Thu, 22 Feb 2007) | 2 lines
Fix test_iter after the dict views conversion.
................
r53854 | brett.cannon | 2007-02-22 05:50:21 +0100 (Thu, 22 Feb 2007) | 2 lines
Fix test_importhooks for dict views.
................
r53855 | brett.cannon | 2007-02-22 06:04:32 +0100 (Thu, 22 Feb 2007) | 3 lines
Fix dumbdbm and test_dumbdbm to work with dict views. Bug in dumbdbm was from
dict views not being iterators but just iterables.
................
r53856 | brett.cannon | 2007-02-22 06:05:21 +0100 (Thu, 22 Feb 2007) | 2 lines
Remove test_dumbdbm as failing.
................
r53857 | brett.cannon | 2007-02-22 07:12:19 +0100 (Thu, 22 Feb 2007) | 3 lines
Fix obvious problems from switch to dict views. Some tests still fail over
some reference count issue (I think).
................
r53858 | brett.cannon | 2007-02-22 07:40:59 +0100 (Thu, 22 Feb 2007) | 2 lines
Fix test_bsddb3 (along with something bsddb) to work with dict views.
................
r53859 | guido.van.rossum | 2007-02-23 00:55:25 +0100 (Fri, 23 Feb 2007) | 5 lines
Fix the last two tests.
Thanks to Brett for fixing so many before!
I see some tracebacks from threads when testing test_bsddbd3 (on OSX)
but the test claims to pass, so I'm ignoring these.
................
r53866 | thomas.wouters | 2007-02-23 16:07:44 +0100 (Fri, 23 Feb 2007) | 294 lines
Merged revisions 53623-53858 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk
........
r53624 | peter.astrand | 2007-02-02 20:06:36 +0100 (Fri, 02 Feb 2007) | 1 line
We had several if statements checking the value of a fd. This is unsafe, since valid fds might be zero. We should check for not None instead.
........
r53635 | kurt.kaiser | 2007-02-05 07:03:18 +0100 (Mon, 05 Feb 2007) | 2 lines
Add 'raw' support to configHandler. Patch 1650174 Tal Einat.
........
r53641 | kurt.kaiser | 2007-02-06 00:02:16 +0100 (Tue, 06 Feb 2007) | 5 lines
1. Calltips now 'handle' tuples in the argument list (display '<tuple>' :)
Suggested solution by Christos Georgiou, Bug 791968.
2. Clean up tests, were not failing when they should have been.
4. Remove some camelcase and an unneeded try/except block.
........
r53644 | kurt.kaiser | 2007-02-06 04:21:40 +0100 (Tue, 06 Feb 2007) | 2 lines
Clean up ModifiedInterpreter.runcode() structure
........
r53646 | peter.astrand | 2007-02-06 16:37:50 +0100 (Tue, 06 Feb 2007) | 1 line
Applied patch 1124861.3.patch to solve bug #1124861: Automatically create pipes on Windows, if GetStdHandle fails. Will backport.
........
r53648 | lars.gustaebel | 2007-02-06 19:38:13 +0100 (Tue, 06 Feb 2007) | 4 lines
Patch #1652681: create nonexistent files in append mode and
allow appending to empty files.
........
r53649 | kurt.kaiser | 2007-02-06 20:09:43 +0100 (Tue, 06 Feb 2007) | 4 lines
Updated patch (CodeContext.061217.patch) to
[ 1362975 ] CodeContext - Improved text indentation
Tal Einat 16Dec06
........
r53650 | kurt.kaiser | 2007-02-06 20:21:19 +0100 (Tue, 06 Feb 2007) | 2 lines
narrow exception per [ 1540849 ] except too broad
........
r53653 | kurt.kaiser | 2007-02-07 04:39:41 +0100 (Wed, 07 Feb 2007) | 4 lines
[ 1621265 ] Auto-completion list placement
Move AC window below input line unless not enough space, then put it above.
Patch: Tal Einat
........
r53654 | kurt.kaiser | 2007-02-07 09:07:13 +0100 (Wed, 07 Feb 2007) | 2 lines
Handle AttributeError during calltip lookup
........
r53656 | raymond.hettinger | 2007-02-07 21:08:22 +0100 (Wed, 07 Feb 2007) | 3 lines
SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses
........
r53658 | raymond.hettinger | 2007-02-07 22:04:20 +0100 (Wed, 07 Feb 2007) | 1 line
SF: 1397711 Set docs conflated immutable and hashable
........
r53660 | raymond.hettinger | 2007-02-07 22:42:17 +0100 (Wed, 07 Feb 2007) | 1 line
Check for a common user error with defaultdict().
........
r53662 | raymond.hettinger | 2007-02-07 23:24:07 +0100 (Wed, 07 Feb 2007) | 1 line
Bug #1575169: operator.isSequenceType() now returns False for subclasses of dict.
........
r53664 | raymond.hettinger | 2007-02-08 00:49:03 +0100 (Thu, 08 Feb 2007) | 1 line
Silence compiler warning
........
r53666 | raymond.hettinger | 2007-02-08 01:07:32 +0100 (Thu, 08 Feb 2007) | 1 line
Do not let overflows in enumerate() and count() pass silently.
........
r53668 | raymond.hettinger | 2007-02-08 01:50:39 +0100 (Thu, 08 Feb 2007) | 1 line
Bypass set specific optimizations for set and frozenset subclasses.
........
r53670 | raymond.hettinger | 2007-02-08 02:42:35 +0100 (Thu, 08 Feb 2007) | 1 line
Fix docstring bug
........
r53671 | martin.v.loewis | 2007-02-08 10:13:36 +0100 (Thu, 08 Feb 2007) | 3 lines
Bug #1653736: Complain about keyword arguments to time.isoformat.
Will backport to 2.5.
........
r53679 | kurt.kaiser | 2007-02-08 23:58:18 +0100 (Thu, 08 Feb 2007) | 6 lines
Corrected some bugs in AutoComplete. Also, Page Up/Down in ACW implemented;
mouse and cursor selection in ACWindow implemented; double Tab inserts current
selection and closes ACW (similar to double-click and Return); scroll wheel now
works in ACW. Added AutoComplete instructions to IDLE Help.
........
r53689 | martin.v.loewis | 2007-02-09 13:19:32 +0100 (Fri, 09 Feb 2007) | 3 lines
Bug #1653736: Properly discard third argument to slot_nb_inplace_power.
Will backport.
........
r53691 | martin.v.loewis | 2007-02-09 13:36:48 +0100 (Fri, 09 Feb 2007) | 4 lines
Bug #1600860: Search for shared python library in LIBDIR, not
lib/python/config, on "linux" and "gnu" systems.
Will backport.
........
r53693 | martin.v.loewis | 2007-02-09 13:58:49 +0100 (Fri, 09 Feb 2007) | 2 lines
Update broken link. Will backport to 2.5.
........
r53697 | georg.brandl | 2007-02-09 19:48:41 +0100 (Fri, 09 Feb 2007) | 2 lines
Bug #1656078: typo in in profile docs.
........
r53731 | brett.cannon | 2007-02-11 06:36:00 +0100 (Sun, 11 Feb 2007) | 3 lines
Change a very minor inconsistency (that is purely cosmetic) in the AST
definition.
........
r53735 | skip.montanaro | 2007-02-11 19:24:37 +0100 (Sun, 11 Feb 2007) | 1 line
fix trace.py --ignore-dir
........
r53741 | brett.cannon | 2007-02-11 20:44:41 +0100 (Sun, 11 Feb 2007) | 3 lines
Check in changed Python-ast.c from a cosmetic change to Python.asdl (in
r53731).
........
r53751 | brett.cannon | 2007-02-12 04:51:02 +0100 (Mon, 12 Feb 2007) | 5 lines
Modify Parser/asdl_c.py so that the __version__ number for Python/Python-ast.c
is specified at the top of the file. Also add a note that Python/Python-ast.c
needs to be committed separately after a change to the AST grammar to capture
the revision number of the change (which is what __version__ is set to).
........
r53752 | lars.gustaebel | 2007-02-12 10:25:53 +0100 (Mon, 12 Feb 2007) | 3 lines
Bug #1656581: Point out that external file objects are supposed to be
at position 0.
........
r53754 | martin.v.loewis | 2007-02-12 13:21:10 +0100 (Mon, 12 Feb 2007) | 3 lines
Patch 1463026: Support default namespace in XMLGenerator.
Fixes #847665. Will backport.
........
r53757 | armin.rigo | 2007-02-12 17:23:24 +0100 (Mon, 12 Feb 2007) | 4 lines
Fix the line to what is my guess at the original author's meaning.
(The line has no effect anyway, but is present because it's
customary call the base class __init__).
........
r53763 | martin.v.loewis | 2007-02-13 09:34:45 +0100 (Tue, 13 Feb 2007) | 3 lines
Patch #685268: Consider a package's __path__ in imputil.
Will backport.
........
r53765 | martin.v.loewis | 2007-02-13 10:49:38 +0100 (Tue, 13 Feb 2007) | 2 lines
Patch #698833: Support file decryption in zipfile.
........
r53766 | martin.v.loewis | 2007-02-13 11:10:39 +0100 (Tue, 13 Feb 2007) | 3 lines
Patch #1517891: Make 'a' create the file if it doesn't exist.
Fixes #1514451.
........
r53767 | martin.v.loewis | 2007-02-13 13:08:24 +0100 (Tue, 13 Feb 2007) | 3 lines
Bug #1658794: Remove extraneous 'this'.
Will backport to 2.5.
........
r53769 | martin.v.loewis | 2007-02-13 13:14:19 +0100 (Tue, 13 Feb 2007) | 3 lines
Patch #1657276: Make NETLINK_DNRTMSG conditional.
Will backport.
........
r53771 | lars.gustaebel | 2007-02-13 17:09:24 +0100 (Tue, 13 Feb 2007) | 4 lines
Patch #1647484: Renamed GzipFile's filename attribute to name. The
filename attribute is still accessible as a property that emits a
DeprecationWarning.
........
r53772 | lars.gustaebel | 2007-02-13 17:24:00 +0100 (Tue, 13 Feb 2007) | 3 lines
Strip the '.gz' extension from the filename that is written to the
gzip header.
........
r53774 | martin.v.loewis | 2007-02-14 11:07:37 +0100 (Wed, 14 Feb 2007) | 2 lines
Patch #1432399: Add HCI sockets.
........
r53775 | martin.v.loewis | 2007-02-14 12:30:07 +0100 (Wed, 14 Feb 2007) | 2 lines
Update 1432399 to removal of _BT_SOCKADDR_MEMB.
........
r53776 | martin.v.loewis | 2007-02-14 12:30:56 +0100 (Wed, 14 Feb 2007) | 3 lines
Ignore directory time stamps when considering
whether to rerun libffi configure.
........
r53778 | lars.gustaebel | 2007-02-14 15:45:12 +0100 (Wed, 14 Feb 2007) | 4 lines
A missing binary mode in AppendTest caused failures in Windows
Buildbot.
........
r53782 | martin.v.loewis | 2007-02-15 10:51:35 +0100 (Thu, 15 Feb 2007) | 2 lines
Patch #1397848: add the reasoning behind no-resize-on-shrinkage.
........
r53783 | georg.brandl | 2007-02-15 11:37:59 +0100 (Thu, 15 Feb 2007) | 2 lines
Make functools.wraps() docs a bit clearer.
........
r53785 | georg.brandl | 2007-02-15 12:29:04 +0100 (Thu, 15 Feb 2007) | 2 lines
Patch #1494140: Add documentation for the new struct.Struct object.
........
r53787 | georg.brandl | 2007-02-15 12:29:55 +0100 (Thu, 15 Feb 2007) | 2 lines
Add missing \versionadded.
........
r53800 | brett.cannon | 2007-02-15 23:54:39 +0100 (Thu, 15 Feb 2007) | 11 lines
Update the encoding package's search function to use absolute imports when
calling __import__. This helps make the expected search locations for encoding
modules be more explicit.
One could use an explicit value for __path__ when making the call to __import__
to force the exact location searched for encodings. This would give the most
strict search path possible if one is worried about malicious code being
imported. The unfortunate side-effect of that is that if __path__ was modified
on 'encodings' on purpose in a safe way it would not be picked up in future
__import__ calls.
........
r53801 | brett.cannon | 2007-02-16 20:33:01 +0100 (Fri, 16 Feb 2007) | 2 lines
Make the __import__ call in encodings.__init__ absolute with a level 0 call.
........
r53809 | vinay.sajip | 2007-02-16 23:36:24 +0100 (Fri, 16 Feb 2007) | 1 line
Minor fix for currentframe (SF #1652788).
........
r53818 | raymond.hettinger | 2007-02-19 03:03:19 +0100 (Mon, 19 Feb 2007) | 3 lines
Extend work on revision 52962: Eliminate redundant calls to PyObject_Hash().
........
r53820 | raymond.hettinger | 2007-02-19 05:08:43 +0100 (Mon, 19 Feb 2007) | 1 line
Add merge() function to heapq.
........
r53821 | raymond.hettinger | 2007-02-19 06:28:28 +0100 (Mon, 19 Feb 2007) | 1 line
Add tie-breaker count to preserve sort stability.
........
r53822 | raymond.hettinger | 2007-02-19 07:59:32 +0100 (Mon, 19 Feb 2007) | 1 line
Use C heapreplace() instead of slower _siftup() in pure python.
........
r53823 | raymond.hettinger | 2007-02-19 08:30:21 +0100 (Mon, 19 Feb 2007) | 1 line
Add test for merge stability
........
r53824 | raymond.hettinger | 2007-02-19 10:14:10 +0100 (Mon, 19 Feb 2007) | 1 line
Provide an example of defaultdict with non-zero constant factory function.
........
r53825 | lars.gustaebel | 2007-02-19 10:54:47 +0100 (Mon, 19 Feb 2007) | 2 lines
Moved misplaced news item.
........
r53826 | martin.v.loewis | 2007-02-19 11:55:19 +0100 (Mon, 19 Feb 2007) | 3 lines
Patch #1490190: posixmodule now includes os.chflags() and os.lchflags()
functions on platforms where the underlying system calls are available.
........
r53827 | raymond.hettinger | 2007-02-19 19:15:04 +0100 (Mon, 19 Feb 2007) | 1 line
Fixup docstrings for merge().
........
r53829 | raymond.hettinger | 2007-02-19 21:44:04 +0100 (Mon, 19 Feb 2007) | 1 line
Fixup set/dict interoperability.
........
r53837 | raymond.hettinger | 2007-02-21 06:20:38 +0100 (Wed, 21 Feb 2007) | 1 line
Add itertools.izip_longest().
........
r53838 | raymond.hettinger | 2007-02-21 18:22:05 +0100 (Wed, 21 Feb 2007) | 1 line
Remove filler struct item and fix leak.
........
................
Added: python/branches/p3yk-noslice/BROKEN
==============================================================================
--- (empty file)
+++ python/branches/p3yk-noslice/BROKEN Fri Feb 23 18:29:35 2007
@@ -0,0 +1 @@
+ test_exceptions (needs slice object support)
Modified: python/branches/p3yk-noslice/Doc/api/concrete.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/api/concrete.tex (original)
+++ python/branches/p3yk-noslice/Doc/api/concrete.tex Fri Feb 23 18:29:35 2007
@@ -2082,7 +2082,7 @@
\begin{verbatim}
PyObject *key, *value;
-int pos = 0;
+Py_ssize_t pos = 0;
while (PyDict_Next(self->dict, &pos, &key, &value)) {
/* do something interesting with the values... */
@@ -2097,7 +2097,7 @@
\begin{verbatim}
PyObject *key, *value;
-int pos = 0;
+Py_ssize_t pos = 0;
while (PyDict_Next(self->dict, &pos, &key, &value)) {
int i = PyInt_AS_LONG(value) + 1;
Modified: python/branches/p3yk-noslice/Doc/commontex/license.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/commontex/license.tex (original)
+++ python/branches/p3yk-noslice/Doc/commontex/license.tex Fri Feb 23 18:29:35 2007
@@ -50,6 +50,7 @@
\linev{2.4.1}{2.4}{2005}{PSF}{yes}
\linev{2.4.2}{2.4.1}{2005}{PSF}{yes}
\linev{2.4.3}{2.4.2}{2006}{PSF}{yes}
+ \linev{2.4.4}{2.4.3}{2006}{PSF}{yes}
\linev{2.5}{2.4}{2006}{PSF}{yes}
\end{tablev}
Modified: python/branches/p3yk-noslice/Doc/dist/dist.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/dist/dist.tex (original)
+++ python/branches/p3yk-noslice/Doc/dist/dist.tex Fri Feb 23 18:29:35 2007
@@ -692,7 +692,7 @@
\begin{tableii}{l|l}{code}{Provides Expression}{Explanation}
\lineii{mypkg} {Provide \code{mypkg}, using the distribution version}
- \lineii{mypkg (1.1} {Provide \code{mypkg} version 1.1, regardless of the
+ \lineii{mypkg (1.1)} {Provide \code{mypkg} version 1.1, regardless of the
distribution version}
\end{tableii}
Modified: python/branches/p3yk-noslice/Doc/howto/TODO
==============================================================================
--- python/branches/p3yk-noslice/Doc/howto/TODO (original)
+++ python/branches/p3yk-noslice/Doc/howto/TODO Fri Feb 23 18:29:35 2007
@@ -1,7 +1,7 @@
Short-term tasks:
- Quick revision pass to make HOWTOs match the current state of Python:
-curses doanddont regex sockets sorting
+ Quick revision pass to make HOWTOs match the current state of Python
+doanddont regex sockets
Medium-term tasks:
Revisit the regex howto.
Modified: python/branches/p3yk-noslice/Doc/howto/curses.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/howto/curses.tex (original)
+++ python/branches/p3yk-noslice/Doc/howto/curses.tex Fri Feb 23 18:29:35 2007
@@ -2,7 +2,7 @@
\title{Curses Programming with Python}
-\release{2.01}
+\release{2.02}
\author{A.M. Kuchling, Eric S. Raymond}
\authoraddress{\email{amk at amk.ca}, \email{esr at thyrsus.com}}
@@ -147,10 +147,10 @@
In Python you can avoid these complications and make debugging much
easier by importing the module \module{curses.wrapper}. It supplies a
-function \function{wrapper} that takes a hook argument. It does the
+\function{wrapper()} function that takes a callable. It does the
initializations described above, and also initializes colors if color
-support is present. It then runs your hook, and then finally
-deinitializes appropriately. The hook is called inside a try-catch
+support is present. It then runs your provided callable and finally
+deinitializes appropriately. The callable is called inside a try-catch
clause which catches exceptions, performs curses deinitialization, and
then passes the exception upwards. Thus, your terminal won't be left
in a funny state on exception.
@@ -159,7 +159,7 @@
Windows are the basic abstraction in curses. A window object
represents a rectangular area of the screen, and supports various
- methods to display text, erase it, allow the user to input strings,
+methods to display text, erase it, allow the user to input strings,
and so forth.
The \code{stdscr} object returned by the \function{initscr()} function
@@ -223,14 +223,14 @@
The \function{refresh()} call displays a section of the pad in the
rectangle extending from coordinate (5,5) to coordinate (20,75) on the
-screen;the upper left corner of the displayed section is coordinate
+screen; the upper left corner of the displayed section is coordinate
(0,0) on the pad. Beyond that difference, pads are exactly like
ordinary windows and support the same methods.
If you have multiple windows and pads on screen there is a more
efficient way to go, which will prevent annoying screen flicker at
-refresh time. Use the methods \method{noutrefresh()} and/or
-\method{noutrefresh()} of each window to update the data structure
+refresh time. Use the \method{noutrefresh()} method
+of each window to update the data structure
representing the desired state of the screen; then change the physical
screen to match the desired state in one go with the function
\function{doupdate()}. The normal \method{refresh()} method calls
@@ -254,9 +254,9 @@
\begin{tableii}{|c|l|}{textrm}{Form}{Description}
\lineii{\var{str} or \var{ch}}{Display the string \var{str} or
-character \var{ch}}
+character \var{ch} at the current position}
\lineii{\var{str} or \var{ch}, \var{attr}}{Display the string \var{str} or
-character \var{ch}, using attribute \var{attr}}
+character \var{ch}, using attribute \var{attr} at the current position}
\lineii{\var{y}, \var{x}, \var{str} or \var{ch}}
{Move to position \var{y,x} within the window, and display \var{str}
or \var{ch}}
@@ -271,7 +271,7 @@
The \function{addstr()} function takes a Python string as the value to
be displayed, while the \function{addch()} functions take a character,
-which can be either a Python string of length 1, or an integer. If
+which can be either a Python string of length 1 or an integer. If
it's a string, you're limited to displaying characters between 0 and
255. SVr4 curses provides constants for extension characters; these
constants are integers greater than 255. For example,
@@ -331,15 +331,15 @@
provide it, The most common such terminal is probably the Linux
console, followed by color xterms.
-To use color, you must call the \function{start_color()} function
-soon after calling \function{initscr()}, to initialize the default
-color set (the \function{curses.wrapper.wrapper()} function does this
+To use color, you must call the \function{start_color()} function soon
+after calling \function{initscr()}, to initialize the default color
+set (the \function{curses.wrapper.wrapper()} function does this
automatically). Once that's done, the \function{has_colors()}
function returns TRUE if the terminal in use can actually display
-color. (Note from AMK: curses uses the American spelling
-'color', instead of the Canadian/British spelling 'colour'. If you're
-like me, you'll have to resign yourself to misspelling it for the sake
-of these functions.)
+color. (Note: curses uses the American spelling 'color', instead of
+the Canadian/British spelling 'colour'. If you're used to the British
+spelling, you'll have to resign yourself to misspelling it for the
+sake of these functions.)
The curses library maintains a finite number of color pairs,
containing a foreground (or text) color and a background color. You
@@ -400,18 +400,19 @@
lack.
The most common way to get input to a window is to use its
-\method{getch()} method. that pauses, and waits for the user to hit
-a key, displaying it if \function{echo()} has been called earlier.
-You can optionally specify a coordinate to which the cursor should be
-moved before pausing.
+\method{getch()} method. \method{getch()} pauses and waits for the
+user to hit a key, displaying it if \function{echo()} has been called
+earlier. You can optionally specify a coordinate to which the cursor
+should be moved before pausing.
It's possible to change this behavior with the method
\method{nodelay()}. After \method{nodelay(1)}, \method{getch()} for
-the window becomes non-blocking and returns ERR (-1) when no input is
-ready. There's also a \function{halfdelay()} function, which can be
-used to (in effect) set a timer on each \method{getch()}; if no input
-becomes available within the number of milliseconds specified as the
-argument to \function{halfdelay()}, curses throws an exception.
+the window becomes non-blocking and returns \code{curses.ERR} (a value
+of -1) when no input is ready. There's also a \function{halfdelay()}
+function, which can be used to (in effect) set a timer on each
+\method{getch()}; if no input becomes available within the number of
+milliseconds specified as the argument to \function{halfdelay()},
+curses raises an exception.
The \method{getch()} method returns an integer; if it's between 0 and
255, it represents the ASCII code of the key pressed. Values greater
Modified: python/branches/p3yk-noslice/Doc/howto/doanddont.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/howto/doanddont.tex (original)
+++ python/branches/p3yk-noslice/Doc/howto/doanddont.tex Fri Feb 23 18:29:35 2007
@@ -32,7 +32,7 @@
\subsubsection{Inside Function Definitions}
\code{from module import *} is {\em invalid} inside function definitions.
-While many versions of Python do no check for the invalidity, it does not
+While many versions of Python do not check for the invalidity, it does not
make it more valid, no more then having a smart lawyer makes a man innocent.
Do not use it like that ever. Even in versions where it was accepted, it made
the function execution slower, because the compiler could not be certain
Modified: python/branches/p3yk-noslice/Doc/howto/regex.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/howto/regex.tex (original)
+++ python/branches/p3yk-noslice/Doc/howto/regex.tex Fri Feb 23 18:29:35 2007
@@ -34,17 +34,18 @@
The \module{re} module was added in Python 1.5, and provides
Perl-style regular expression patterns. Earlier versions of Python
came with the \module{regex} module, which provided Emacs-style
-patterns. \module{regex} module was removed in Python 2.5.
+patterns. The \module{regex} module was removed completely in Python 2.5.
-Regular expressions (or REs) are essentially a tiny, highly
-specialized programming language embedded inside Python and made
-available through the \module{re} module. Using this little language,
-you specify the rules for the set of possible strings that you want to
-match; this set might contain English sentences, or e-mail addresses,
-or TeX commands, or anything you like. You can then ask questions
-such as ``Does this string match the pattern?'', or ``Is there a match
-for the pattern anywhere in this string?''. You can also use REs to
-modify a string or to split it apart in various ways.
+Regular expressions (called REs, or regexes, or regex patterns) are
+essentially a tiny, highly specialized programming language embedded
+inside Python and made available through the \module{re} module.
+Using this little language, you specify the rules for the set of
+possible strings that you want to match; this set might contain
+English sentences, or e-mail addresses, or TeX commands, or anything
+you like. You can then ask questions such as ``Does this string match
+the pattern?'', or ``Is there a match for the pattern anywhere in this
+string?''. You can also use REs to modify a string or to split it
+apart in various ways.
Regular expression patterns are compiled into a series of bytecodes
which are then executed by a matching engine written in C. For
@@ -80,11 +81,12 @@
would let this RE match \samp{Test} or \samp{TEST} as well; more
about this later.)
-There are exceptions to this rule; some characters are
-special, and don't match themselves. Instead, they signal that some
-out-of-the-ordinary thing should be matched, or they affect other
-portions of the RE by repeating them. Much of this document is
-devoted to discussing various metacharacters and what they do.
+There are exceptions to this rule; some characters are special
+\dfn{metacharacters}, and don't match themselves. Instead, they
+signal that some out-of-the-ordinary thing should be matched, or they
+affect other portions of the RE by repeating them or changing their
+meaning. Much of this document is devoted to discussing various
+metacharacters and what they do.
Here's a complete list of the metacharacters; their meanings will be
discussed in the rest of this HOWTO.
@@ -111,9 +113,10 @@
usually a metacharacter, but inside a character class it's stripped of
its special nature.
-You can match the characters not within a range by \dfn{complementing}
-the set. This is indicated by including a \character{\^} as the first
-character of the class; \character{\^} elsewhere will simply match the
+You can match the characters not listed within the class by
+\dfn{complementing} the set. This is indicated by including a
+\character{\^} as the first character of the class; \character{\^}
+outside a character class will simply match the
\character{\^} character. For example, \verb|[^5]| will match any
character except \character{5}.
@@ -176,7 +179,7 @@
For example, \regexp{ca*t} will match \samp{ct} (0 \samp{a}
characters), \samp{cat} (1 \samp{a}), \samp{caaat} (3 \samp{a}
characters), and so forth. The RE engine has various internal
-limitations stemming from the size of C's \code{int} type, that will
+limitations stemming from the size of C's \code{int} type that will
prevent it from matching over 2 billion \samp{a} characters; you
probably don't have enough memory to construct a string that large, so
you shouldn't run into that limit.
@@ -238,9 +241,9 @@
You can omit either \var{m} or \var{n}; in that case, a reasonable
value is assumed for the missing value. Omitting \var{m} is
-interpreted as a lower limit of 0, while omitting \var{n} results in an
-upper bound of infinity --- actually, the 2 billion limit mentioned
-earlier, but that might as well be infinity.
+interpreted as a lower limit of 0, while omitting \var{n} results in
+an upper bound of infinity --- actually, the upper bound is the
+2-billion limit mentioned earlier, but that might as well be infinity.
Readers of a reductionist bent may notice that the three other qualifiers
can all be expressed using this notation. \regexp{\{0,\}} is the same
@@ -285,7 +288,7 @@
no need to bloat the language specification by including them.)
Instead, the \module{re} module is simply a C extension module
included with Python, just like the \module{socket} or \module{zlib}
-module.
+modules.
Putting REs in strings keeps the Python language simpler, but has one
disadvantage which is the topic of the next section.
@@ -326,7 +329,7 @@
a string literal prefixed with \character{r}, so \code{r"\e n"} is a
two-character string containing \character{\e} and \character{n},
while \code{"\e n"} is a one-character string containing a newline.
-Frequently regular expressions will be expressed in Python
+Regular expressions will often be written in Python
code using this raw string notation.
\begin{tableii}{c|c}{code}{Regular String}{Raw string}
@@ -368,9 +371,9 @@
\file{redemo.py} can be quite useful when trying to debug a
complicated RE. Phil Schwartz's
\ulink{Kodos}{http://www.phil-schwartz.com/kodos.spy} is also an interactive
-tool for developing and testing RE patterns. This HOWTO will use the
-standard Python interpreter for its examples.
+tool for developing and testing RE patterns.
+This HOWTO uses the standard Python interpreter for its examples.
First, run the Python interpreter, import the \module{re} module, and
compile a RE:
@@ -401,7 +404,7 @@
later use.
\begin{verbatim}
->>> m = p.match( 'tempo')
+>>> m = p.match('tempo')
>>> print m
<_sre.SRE_Match object at 80c4f68>
\end{verbatim}
@@ -472,9 +475,9 @@
\end{verbatim}
\method{findall()} has to create the entire list before it can be
-returned as the result. In Python 2.2, the \method{finditer()} method
-is also available, returning a sequence of \class{MatchObject} instances
-as an iterator.
+returned as the result. The \method{finditer()} method returns a
+sequence of \class{MatchObject} instances as an
+iterator.\footnote{Introduced in Python 2.2.2.}
\begin{verbatim}
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
@@ -491,13 +494,13 @@
\subsection{Module-Level Functions}
-You don't have to produce a \class{RegexObject} and call its methods;
+You don't have to create a \class{RegexObject} and call its methods;
the \module{re} module also provides top-level functions called
-\function{match()}, \function{search()}, \function{sub()}, and so
-forth. These functions take the same arguments as the corresponding
-\class{RegexObject} method, with the RE string added as the first
-argument, and still return either \code{None} or a \class{MatchObject}
-instance.
+\function{match()}, \function{search()}, \function{findall()},
+\function{sub()}, and so forth. These functions take the same
+arguments as the corresponding \class{RegexObject} method, with the RE
+string added as the first argument, and still return either
+\code{None} or a \class{MatchObject} instance.
\begin{verbatim}
>>> print re.match(r'From\s+', 'Fromage amk')
@@ -514,7 +517,7 @@
Should you use these module-level functions, or should you get the
\class{RegexObject} and call its methods yourself? That choice
depends on how frequently the RE will be used, and on your personal
-coding style. If a RE is being used at only one point in the code,
+coding style. If the RE is being used at only one point in the code,
then the module functions are probably more convenient. If a program
contains a lot of regular expressions, or re-uses the same ones in
several locations, then it might be worthwhile to collect all the
@@ -537,7 +540,7 @@
Compilation flags let you modify some aspects of how regular
expressions work. Flags are available in the \module{re} module under
-two names, a long name such as \constant{IGNORECASE}, and a short,
+two names, a long name such as \constant{IGNORECASE} and a short,
one-letter form such as \constant{I}. (If you're familiar with Perl's
pattern modifiers, the one-letter forms use the same letters; the
short form of \constant{re.VERBOSE} is \constant{re.X}, for example.)
@@ -617,7 +620,7 @@
format them. When this flag has been specified, whitespace within the
RE string is ignored, except when the whitespace is in a character
class or preceded by an unescaped backslash; this lets you organize
-and indent the RE more clearly. It also enables you to put comments
+and indent the RE more clearly. This flag also lets you put comments
within a RE that will be ignored by the engine; comments are marked by
a \character{\#} that's neither in a character class or preceded by an
unescaped backslash.
@@ -629,18 +632,19 @@
charref = re.compile(r"""
&[#] # Start of a numeric entity reference
(
- [0-9]+[^0-9] # Decimal form
- | 0[0-7]+[^0-7] # Octal form
- | x[0-9a-fA-F]+[^0-9a-fA-F] # Hexadecimal form
+ 0[0-7]+ # Octal form
+ | [0-9]+ # Decimal form
+ | x[0-9a-fA-F]+ # Hexadecimal form
)
+ ; # Trailing semicolon
""", re.VERBOSE)
\end{verbatim}
Without the verbose setting, the RE would look like this:
\begin{verbatim}
-charref = re.compile("&#([0-9]+[^0-9]"
- "|0[0-7]+[^0-7]"
- "|x[0-9a-fA-F]+[^0-9a-fA-F])")
+charref = re.compile("&#(0[0-7]+"
+ "|[0-9]+"
+ "|x[0-9a-fA-F]+);")
\end{verbatim}
In the above example, Python's automatic concatenation of string
@@ -722,12 +726,12 @@
\item[\regexp{\e A}] Matches only at the start of the string. When
not in \constant{MULTILINE} mode, \regexp{\e A} and \regexp{\^} are
-effectively the same. In \constant{MULTILINE} mode, however, they're
-different; \regexp{\e A} still matches only at the beginning of the
+effectively the same. In \constant{MULTILINE} mode, they're
+different: \regexp{\e A} still matches only at the beginning of the
string, but \regexp{\^} may match at any location inside the string
that follows a newline character.
-\item[\regexp{\e Z}]Matches only at the end of the string.
+\item[\regexp{\e Z}] Matches only at the end of the string.
\item[\regexp{\e b}] Word boundary.
This is a zero-width assertion that matches only at the
@@ -782,14 +786,23 @@
strings by writing a RE divided into several subgroups which
match different components of interest. For example, an RFC-822
header line is divided into a header name and a value, separated by a
-\character{:}. This can be handled by writing a regular expression
+\character{:}, like this:
+
+\begin{verbatim}
+From: author at example.com
+User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
+MIME-Version: 1.0
+To: editor at example.com
+\end{verbatim}
+
+This can be handled by writing a regular expression
which matches an entire header line, and has one group which matches the
header name, and another group which matches the header's value.
Groups are marked by the \character{(}, \character{)} metacharacters.
\character{(} and \character{)} have much the same meaning as they do
in mathematical expressions; they group together the expressions
-contained inside them. For example, you can repeat the contents of a
+contained inside them, and you can repeat the contents of a
group with a repeating qualifier, such as \regexp{*}, \regexp{+},
\regexp{?}, or \regexp{\{\var{m},\var{n}\}}. For example,
\regexp{(ab)*} will match zero or more repetitions of \samp{ab}.
@@ -881,12 +894,13 @@
syntax for regular expression extensions, so we'll look at that first.
Perl 5 added several additional features to standard regular
-expressions, and the Python \module{re} module supports most of them.
-It would have been difficult to choose new single-keystroke
-metacharacters or new special sequences beginning with \samp{\e} to
-represent the new features without making Perl's regular expressions
-confusingly different from standard REs. If you chose \samp{\&} as a
-new metacharacter, for example, old expressions would be assuming that
+expressions, and the Python \module{re} module supports most of them.
+It would have been difficult to choose new
+single-keystroke metacharacters or new special sequences beginning
+with \samp{\e} to represent the new features without making Perl's
+regular expressions confusingly different from standard REs. If you
+chose \samp{\&} as a new metacharacter, for example, old expressions
+would be assuming that
\samp{\&} was a regular character and wouldn't have escaped it by
writing \regexp{\e \&} or \regexp{[\&]}.
@@ -913,15 +927,15 @@
to the features that simplify working with groups in complex REs.
Since groups are numbered from left to right and a complex expression
may use many groups, it can become difficult to keep track of the
-correct numbering, and modifying such a complex RE is annoying.
-Insert a new group near the beginning, and you change the numbers of
+correct numbering. Modifying such a complex RE is annoying, too:
+insert a new group near the beginning and you change the numbers of
everything that follows it.
-First, sometimes you'll want to use a group to collect a part of a
-regular expression, but aren't interested in retrieving the group's
-contents. You can make this fact explicit by using a non-capturing
-group: \regexp{(?:...)}, where you can put any other regular
-expression inside the parentheses.
+Sometimes you'll want to use a group to collect a part of a regular
+expression, but aren't interested in retrieving the group's contents.
+You can make this fact explicit by using a non-capturing group:
+\regexp{(?:...)}, where you can replace the \regexp{...}
+with any other regular expression.
\begin{verbatim}
>>> m = re.match("([abc])+", "abc")
@@ -937,23 +951,23 @@
capturing group; you can put anything inside it, repeat it with a
repetition metacharacter such as \samp{*}, and nest it within other
groups (capturing or non-capturing). \regexp{(?:...)} is particularly
-useful when modifying an existing group, since you can add new groups
+useful when modifying an existing pattern, since you can add new groups
without changing how all the other groups are numbered. It should be
mentioned that there's no performance difference in searching between
capturing and non-capturing groups; neither form is any faster than
the other.
-The second, and more significant, feature is named groups; instead of
+A more significant feature is named groups: instead of
referring to them by numbers, groups can be referenced by a name.
The syntax for a named group is one of the Python-specific extensions:
\regexp{(?P<\var{name}>...)}. \var{name} is, obviously, the name of
-the group. Except for associating a name with a group, named groups
-also behave identically to capturing groups. The \class{MatchObject}
-methods that deal with capturing groups all accept either integers, to
-refer to groups by number, or a string containing the group name.
-Named groups are still given numbers, so you can retrieve information
-about a group in two ways:
+the group. Named groups also behave exactly like capturing groups,
+and additionally associate a name with a group. The
+\class{MatchObject} methods that deal with capturing groups all accept
+either integers that refer to the group by number or strings that
+contain the desired group's name. Named groups are still given
+numbers, so you can retrieve information about a group in two ways:
\begin{verbatim}
>>> p = re.compile(r'(?P<word>\b\w+\b)')
@@ -980,11 +994,11 @@
It's obviously much easier to retrieve \code{m.group('zonem')},
instead of having to remember to retrieve group 9.
-Since the syntax for backreferences, in an expression like
-\regexp{(...)\e 1}, refers to the number of the group there's
+The syntax for backreferences in an expression such as
+\regexp{(...)\e 1} refers to the number of the group. There's
naturally a variant that uses the group name instead of the number.
-This is also a Python extension: \regexp{(?P=\var{name})} indicates
-that the contents of the group called \var{name} should again be found
+This is another Python extension: \regexp{(?P=\var{name})} indicates
+that the contents of the group called \var{name} should again be matched
at the current point. The regular expression for finding doubled
words, \regexp{(\e b\e w+)\e s+\e 1} can also be written as
\regexp{(?P<word>\e b\e w+)\e s+(?P=word)}:
@@ -1014,11 +1028,11 @@
\emph{doesn't} match at the current position in the string.
\end{itemize}
-An example will help make this concrete by demonstrating a case
-where a lookahead is useful. Consider a simple pattern to match a
-filename and split it apart into a base name and an extension,
-separated by a \samp{.}. For example, in \samp{news.rc}, \samp{news}
-is the base name, and \samp{rc} is the filename's extension.
+To make this concrete, let's look at a case where a lookahead is
+useful. Consider a simple pattern to match a filename and split it
+apart into a base name and an extension, separated by a \samp{.}. For
+example, in \samp{news.rc}, \samp{news} is the base name, and
+\samp{rc} is the filename's extension.
The pattern to match this is quite simple:
@@ -1065,12 +1079,12 @@
exclude both \samp{bat} and \samp{exe} as extensions, the pattern
would get even more complicated and confusing.
-A negative lookahead cuts through all this:
+A negative lookahead cuts through all this confusion:
\regexp{.*[.](?!bat\$).*\$}
% $
-The lookahead means: if the expression \regexp{bat} doesn't match at
+The negative lookahead means: if the expression \regexp{bat} doesn't match at
this point, try the rest of the pattern; if \regexp{bat\$} does match,
the whole pattern will fail. The trailing \regexp{\$} is required to
ensure that something like \samp{sample.batch}, where the extension
@@ -1087,7 +1101,7 @@
\section{Modifying Strings}
Up to this point, we've simply performed searches against a static
-string. Regular expressions are also commonly used to modify a string
+string. Regular expressions are also commonly used to modify strings
in various ways, using the following \class{RegexObject} methods:
\begin{tableii}{c|l}{code}{Method/Attribute}{Purpose}
Modified: python/branches/p3yk-noslice/Doc/lib/emailgenerator.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/emailgenerator.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/emailgenerator.tex Fri Feb 23 18:29:35 2007
@@ -33,7 +33,7 @@
line. This is the only guaranteed portable way to avoid having such
lines be mistaken for a \UNIX{} mailbox format envelope header separator (see
\ulink{WHY THE CONTENT-LENGTH FORMAT IS BAD}
-{http://home.netscape.com/eng/mozilla/2.0/relnotes/demo/content-length.html}
+{http://www.jwz.org/doc/content-length.html}
for details). \var{mangle_from_} defaults to \code{True}, but you
might want to set this to \code{False} if you are not writing \UNIX{}
mailbox format files.
Modified: python/branches/p3yk-noslice/Doc/lib/libcollections.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libcollections.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libcollections.tex Fri Feb 23 18:29:35 2007
@@ -311,16 +311,20 @@
When a letter is first encountered, it is missing from the mapping, so the
\member{default_factory} function calls \function{int()} to supply a default
count of zero. The increment operation then builds up the count for each
-letter. This technique makes counting simpler and faster than an equivalent
-technique using \method{dict.get()}:
+letter.
-\begin{verbatim}
->>> d = {}
->>> for k in s:
- d[k] = d.get(k, 0) + 1
+The function \function{int()} which always returns zero is just a special
+case of constant functions. A faster and more flexible way to create
+constant functions is to use \function{itertools.repeat()} which can supply
+any constant value (not just zero):
->>> d.items()
-[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
+\begin{verbatim}
+>>> def constant_factory(value):
+... return itertools.repeat(value).next
+>>> d = defaultdict(constant_factory('<missing>'))
+>>> d.update(name='John', action='ran')
+>>> '%(name)s %(action)s to %(object)s' % d
+'John ran to <missing>'
\end{verbatim}
Setting the \member{default_factory} to \class{set} makes the
Modified: python/branches/p3yk-noslice/Doc/lib/libdis.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libdis.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libdis.tex Fri Feb 23 18:29:35 2007
@@ -300,27 +300,6 @@
expression statement is terminated with \code{POP_STACK}.
\end{opcodedesc}
-\begin{opcodedesc}{PRINT_ITEM}{}
-Prints TOS to the file-like object bound to \code{sys.stdout}. There
-is one such instruction for each item in the \keyword{print} statement.
-\end{opcodedesc}
-
-\begin{opcodedesc}{PRINT_ITEM_TO}{}
-Like \code{PRINT_ITEM}, but prints the item second from TOS to the
-file-like object at TOS. This is used by the extended print statement.
-\end{opcodedesc}
-
-\begin{opcodedesc}{PRINT_NEWLINE}{}
-Prints a new line on \code{sys.stdout}. This is generated as the
-last operation of a \keyword{print} statement, unless the statement
-ends with a comma.
-\end{opcodedesc}
-
-\begin{opcodedesc}{PRINT_NEWLINE_TO}{}
-Like \code{PRINT_NEWLINE}, but prints the new line on the file-like
-object on the TOS. This is used by the extended print statement.
-\end{opcodedesc}
-
\begin{opcodedesc}{BREAK_LOOP}{}
Terminates a loop due to a \keyword{break} statement.
\end{opcodedesc}
Modified: python/branches/p3yk-noslice/Doc/lib/libexcs.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libexcs.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libexcs.tex Fri Feb 23 18:29:35 2007
@@ -10,22 +10,6 @@
provided in the built-in namespace as well as the \module{exceptions}
module.
-\begin{notice}
-In past versions of Python string exceptions were supported. In
-Python 1.5 and newer versions, all standard exceptions have been
-converted to class objects and users are encouraged to do the same.
-String exceptions will raise a \code{DeprecationWarning} in Python 2.5 and
-newer.
-In future versions, support for string exceptions will be removed.
-
-Two distinct string objects with the same value are considered different
-exceptions. This is done to force programmers to use exception names
-rather than their string value when specifying exception handlers.
-The string value of all built-in exceptions is their name, but this is
-not a requirement for user-defined exceptions or exceptions defined by
-library modules.
-\end{notice}
-
For class exceptions, in a \keyword{try}\stindex{try} statement with
an \keyword{except}\stindex{except} clause that mentions a particular
class, that clause also handles any exception classes derived from
Modified: python/branches/p3yk-noslice/Doc/lib/libfunctools.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libfunctools.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libfunctools.tex Fri Feb 23 18:29:35 2007
@@ -66,15 +66,16 @@
\begin{funcdesc}{update_wrapper}
{wrapper, wrapped\optional{, assigned}\optional{, updated}}
-Update a wrapper function to look like the wrapped function. The optional
-arguments are tuples to specify which attributes of the original
+Update a \var{wrapper} function to look like the \var{wrapped} function.
+The optional arguments are tuples to specify which attributes of the original
function are assigned directly to the matching attributes on the wrapper
function and which attributes of the wrapper function are updated with
the corresponding attributes from the original function. The default
values for these arguments are the module level constants
-\var{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper function's name,
-module and documentation string) and \var{WRAPPER_UPDATES} (which
-updates the wrapper function's instance dictionary).
+\var{WRAPPER_ASSIGNMENTS} (which assigns to the wrapper function's
+\var{__name__}, \var{__module__} and \var{__doc__}, the documentation string)
+and \var{WRAPPER_UPDATES} (which updates the wrapper function's \var{__dict__},
+i.e. the instance dictionary).
The main intended use for this function is in decorator functions
which wrap the decorated function and return the wrapper. If the
@@ -98,6 +99,7 @@
...
>>> @my_decorator
... def example():
+ ... """Docstring"""
... print 'Called example function'
...
>>> example()
@@ -105,9 +107,12 @@
Called example function
>>> example.__name__
'example'
+ >>> example.__doc__
+ 'Docstring'
\end{verbatim}
Without the use of this decorator factory, the name of the example
-function would have been \code{'wrapper'}.
+function would have been \code{'wrapper'}, and the docstring of the
+original \function{example()} would have been lost.
\end{funcdesc}
Modified: python/branches/p3yk-noslice/Doc/lib/libheapq.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libheapq.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libheapq.tex Fri Feb 23 18:29:35 2007
@@ -88,7 +88,18 @@
>>>
\end{verbatim}
-The module also offers two general purpose functions based on heaps.
+The module also offers three general purpose functions based on heaps.
+
+\begin{funcdesc}{merge}{*iterables}
+Merge multiple sorted inputs into a single sorted output (for example, merge
+timestamped entries from multiple log files). Returns an iterator over
+over the sorted values.
+
+Similar to \code{sorted(itertools.chain(*iterables))} but returns an iterable,
+does 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}
+\end{funcdesc}
\begin{funcdesc}{nlargest}{n, iterable\optional{, key}}
Return a list with the \var{n} largest elements from the dataset defined
@@ -110,7 +121,7 @@
\versionchanged[Added the optional \var{key} argument]{2.5}
\end{funcdesc}
-Both functions perform best for smaller values of \var{n}. For larger
+The latter two functions perform best for smaller values of \var{n}. For larger
values, it is more efficient to use the \function{sorted()} function. Also,
when \code{n==1}, it is more efficient to use the builtin \function{min()}
and \function{max()} functions.
Modified: python/branches/p3yk-noslice/Doc/lib/libimageop.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libimageop.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libimageop.tex Fri Feb 23 18:29:35 2007
@@ -19,7 +19,7 @@
\begin{funcdesc}{crop}{image, psize, width, height, x0, y0, x1, y1}
-Return the selected part of \var{image}, which should by
+Return the selected part of \var{image}, which should be
\var{width} by \var{height} in size and consist of pixels of
\var{psize} bytes. \var{x0}, \var{y0}, \var{x1} and \var{y1} are like
the \function{gl.lrectread()} parameters, i.e.\ the boundary is
Modified: python/branches/p3yk-noslice/Doc/lib/libitertools.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libitertools.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libitertools.tex Fri Feb 23 18:29:35 2007
@@ -302,6 +302,33 @@
don't care about trailing, unmatched values from the longer iterables.
\end{funcdesc}
+\begin{funcdesc}{izip_longest}{*iterables\optional{, fillvalue}}
+ Make an iterator that aggregates elements from each of the iterables.
+ If the iterables are of uneven length, missing values are filled-in
+ with \var{fillvalue}. Iteration continues until the longest iterable
+ is exhausted. Equivalent to:
+
+ \begin{verbatim}
+ def izip_longest(*args, **kwds):
+ fillvalue = kwds.get('fillvalue')
+ def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
+ yield counter() # yields the fillvalue, or raises IndexError
+ fillers = repeat(fillvalue)
+ iters = [chain(it, sentinel(), fillers) for it in args]
+ try:
+ for tup in izip(*iters):
+ yield tup
+ except IndexError:
+ pass
+ \end{verbatim}
+
+ If one of the iterables is potentially infinite, then the
+ \function{izip_longest()} function should be wrapped with something
+ that limits the number of calls (for example \function{islice()} or
+ \function{take()}).
+ \versionadded{2.6}
+\end{funcdesc}
+
\begin{funcdesc}{repeat}{object\optional{, times}}
Make an iterator that returns \var{object} over and over again.
Runs indefinitely unless the \var{times} argument is specified.
Modified: python/branches/p3yk-noslice/Doc/lib/liblocale.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/liblocale.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/liblocale.tex Fri Feb 23 18:29:35 2007
@@ -481,7 +481,7 @@
locale settings. When a call to the \function{setlocale()} function
changes the \constant{LC_CTYPE} settings, the variables
\code{string.lowercase}, \code{string.uppercase} and
-\code{string.letters} are recalculated. Note that this code that uses
+\code{string.letters} are recalculated. Note that code that uses
these variable through `\keyword{from} ... \keyword{import} ...',
e.g.\ \code{from string import letters}, is not affected by subsequent
\function{setlocale()} calls.
Modified: python/branches/p3yk-noslice/Doc/lib/liblogging.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/liblogging.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/liblogging.tex Fri Feb 23 18:29:35 2007
@@ -989,10 +989,11 @@
package, sends logging output to a disk file. It inherits the output
functionality from \class{StreamHandler}.
-\begin{classdesc}{FileHandler}{filename\optional{, mode}}
+\begin{classdesc}{FileHandler}{filename\optional{, mode\optional{, encoding}}}
Returns a new instance of the \class{FileHandler} class. The specified
file is opened and used as the stream for logging. If \var{mode} is
-not specified, \constant{'a'} is used. By default, the file grows
+not specified, \constant{'a'} is used. If \var{encoding} is not \var{None},
+it is used to open the file with that encoding. By default, the file grows
indefinitely.
\end{classdesc}
@@ -1004,6 +1005,41 @@
Outputs the record to the file.
\end{methoddesc}
+\subsubsection{WatchedFileHandler}
+
+\versionadded{2.6}
+The \class{WatchedFileHandler} class, located in the \module{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.
+
+A file change can happen because of usage of programs such as \var{newsyslog}
+and \var{logrotate} which perform log file rotation. This handler, intended
+for use under Unix/Linux, watches the file to see if it has changed since the
+last emit. (A file is deemed to have changed if its device or inode have
+changed.) If the file has changed, the old file stream is closed, and the file
+opened to get a new stream.
+
+This handler is not appropriate for use under Windows, because under Windows
+open log files cannot be moved or renamed - logging opens the files with
+exclusive locks - and so there is no need for such a handler. Furthermore,
+\var{ST_INO} is not supported under Windows; \function{stat()} always returns
+zero for this value.
+
+\begin{classdesc}{WatchedFileHandler}{filename\optional{,mode\optional{,
+ encoding}}}
+Returns a new instance of the \class{WatchedFileHandler} class. The specified
+file is opened and used as the stream for logging. If \var{mode} is
+not specified, \constant{'a'} is used. If \var{encoding} is not \var{None},
+it is used to open the file with that encoding. By default, the file grows
+indefinitely.
+\end{classdesc}
+
+\begin{methoddesc}{emit}{record}
+Outputs the record to the file, but first checks to see if the file has
+changed. If it has, the existing stream is flushed and closed and the file
+opened again, before outputting the record to the file.
+\end{methoddesc}
+
\subsubsection{RotatingFileHandler}
The \class{RotatingFileHandler} class, located in the \module{logging.handlers}
Modified: python/branches/p3yk-noslice/Doc/lib/libmailbox.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libmailbox.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libmailbox.tex Fri Feb 23 18:29:35 2007
@@ -25,22 +25,29 @@
A mailbox, which may be inspected and modified.
\end{classdesc*}
+The \class{Mailbox} class defines an interface and
+is not intended to be instantiated. Instead, format-specific
+subclasses should inherit from \class{Mailbox} and your code
+should instantiate a particular subclass.
+
The \class{Mailbox} interface is dictionary-like, with small keys
-corresponding to messages. Keys are issued by the \class{Mailbox} instance
-with which they will be used and are only meaningful to that \class{Mailbox}
-instance. A key continues to identify a message even if the corresponding
-message is modified, such as by replacing it with another message. Messages may
-be added to a \class{Mailbox} instance using the set-like method
-\method{add()} and removed using a \code{del} statement or the set-like methods
-\method{remove()} and \method{discard()}.
+corresponding to messages. Keys are issued by the \class{Mailbox}
+instance with which they will be used and are only meaningful to that
+\class{Mailbox} instance. A key continues to identify a message even
+if the corresponding message is modified, such as by replacing it with
+another message.
+
+Messages may be added to a \class{Mailbox} instance using the set-like
+method \method{add()} and removed using a \code{del} statement or the
+set-like methods \method{remove()} and \method{discard()}.
\class{Mailbox} interface semantics differ from dictionary semantics in some
-noteworthy ways. Each time a message is requested, a new representation
-(typically a \class{Message} instance) is generated, based upon the current
-state of the mailbox. Similarly, when a message is added to a \class{Mailbox}
-instance, the provided message representation's contents are copied. In neither
-case is a reference to the message representation kept by the \class{Mailbox}
-instance.
+noteworthy ways. Each time a message is requested, a new
+representation (typically a \class{Message} instance) is generated
+based upon the current state of the mailbox. Similarly, when a message
+is added to a \class{Mailbox} instance, the provided message
+representation's contents are copied. In neither case is a reference
+to the message representation kept by the \class{Mailbox} instance.
The default \class{Mailbox} iterator iterates over message representations, not
keys as the default dictionary iterator does. Moreover, modification of a
@@ -51,9 +58,18 @@
\exception{KeyError} exception if the corresponding message is subsequently
removed.
-\class{Mailbox} itself is intended to define an interface and to be inherited
-from by format-specific subclasses but is not intended to be instantiated.
-Instead, you should instantiate a subclass.
+\begin{notice}[warning]
+Be very cautious when modifying mailboxes that might be
+simultaneously changed by some other process. The safest mailbox
+format to use for such tasks is Maildir; try to avoid using
+single-file formats such as mbox for concurrent writing. If you're
+modifying a mailbox, you
+\emph{must} lock it by calling the \method{lock()} and
+\method{unlock()} methods \emph{before} reading any messages in the file
+or making any changes by adding or deleting a message. Failing to
+lock the mailbox runs the risk of losing messages or corrupting the entire
+mailbox.
+\end{notice}
\class{Mailbox} instances have the following methods:
@@ -202,15 +218,16 @@
\begin{methoddesc}{flush}{}
Write any pending changes to the filesystem. For some \class{Mailbox}
-subclasses, changes are always written immediately and this method does
-nothing.
+subclasses, changes are always written immediately and \method{flush()} does
+nothing, but you should still make a habit of calling this method.
\end{methoddesc}
\begin{methoddesc}{lock}{}
Acquire an exclusive advisory lock on the mailbox so that other processes know
not to modify it. An \exception{ExternalClashError} is raised if the lock is
not available. The particular locking mechanisms used depend upon the mailbox
-format.
+format. You should \emph{always} lock the mailbox before making any
+modifications to its contents.
\end{methoddesc}
\begin{methoddesc}{unlock}{}
@@ -1373,36 +1390,55 @@
\begin{verbatim}
import mailbox
destination = mailbox.MH('~/Mail')
+destination.lock()
for message in mailbox.Babyl('~/RMAIL'):
destination.add(MHMessage(message))
+destination.flush()
+destination.unlock()
\end{verbatim}
-An example of sorting mail from numerous mailing lists, being careful to avoid
-mail corruption due to concurrent modification by other programs, mail loss due
-to interruption of the program, or premature termination due to malformed
-messages in the mailbox:
+This example sorts mail from several mailing lists into different
+mailboxes, being careful to avoid mail corruption due to concurrent
+modification by other programs, mail loss due to interruption of the
+program, or premature termination due to malformed messages in the
+mailbox:
\begin{verbatim}
import mailbox
import email.Errors
+
list_names = ('python-list', 'python-dev', 'python-bugs')
+
boxes = dict((name, mailbox.mbox('~/email/%s' % name)) for name in list_names)
-inbox = mailbox.Maildir('~/Maildir', None)
+inbox = mailbox.Maildir('~/Maildir', factory=None)
+
for key in inbox.iterkeys():
try:
message = inbox[key]
except email.Errors.MessageParseError:
continue # The message is malformed. Just leave it.
+
for name in list_names:
list_id = message['list-id']
if list_id and name in list_id:
+ # Get mailbox to use
box = boxes[name]
+
+ # Write copy to disk before removing original.
+ # If there's a crash, you might duplicate a message, but
+ # that's better than losing a message completely.
box.lock()
box.add(message)
- box.flush() # Write copy to disk before removing original.
+ box.flush()
box.unlock()
+
+ # Remove original message
+ inbox.lock()
inbox.discard(key)
+ inbox.flush()
+ inbox.unlock()
break # Found destination, so stop looking.
+
for box in boxes.itervalues():
box.close()
\end{verbatim}
Modified: python/branches/p3yk-noslice/Doc/lib/libos.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libos.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libos.tex Fri Feb 23 18:29:35 2007
@@ -758,6 +758,26 @@
\versionadded{2.3}
\end{funcdesc}
+\begin{funcdesc}{chflags}{path, flags}
+Set the flags of \var{path} to the numeric \var{flags}.
+\var{flags} may take a combination (bitwise OR) of the following values
+(as defined in the \module{stat} module):
+\begin{itemize}
+ \item \code{UF_NODUMP}
+ \item \code{UF_IMMUTABLE}
+ \item \code{UF_APPEND}
+ \item \code{UF_OPAQUE}
+ \item \code{UF_NOUNLINK}
+ \item \code{SF_ARCHIVED}
+ \item \code{SF_IMMUTABLE}
+ \item \code{SF_APPEND}
+ \item \code{SF_NOUNLINK}
+ \item \code{SF_SNAPSHOT}
+\end{itemize}
+Availability: Macintosh, \UNIX.
+\versionadded{2.6}
+\end{funcdesc}
+
\begin{funcdesc}{chroot}{path}
Change the root directory of the current process to \var{path}.
Availability: Macintosh, \UNIX.
@@ -804,6 +824,13 @@
Availability: Macintosh, \UNIX.
\end{funcdesc}
+\begin{funcdesc}{lchflags}{path, flags}
+Set the flags of \var{path} to the numeric \var{flags}, like
+\function{chflags()}, but do not follow symbolic links.
+Availability: \UNIX.
+\versionadded{2.6}
+\end{funcdesc}
+
\begin{funcdesc}{lchown}{path, uid, gid}
Change the owner and group id of \var{path} to the numeric \var{uid}
and gid. This function will not follow symbolic links.
Modified: python/branches/p3yk-noslice/Doc/lib/librandom.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/librandom.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/librandom.tex Fri Feb 23 18:29:35 2007
@@ -185,7 +185,7 @@
\begin{funcdesc}{betavariate}{alpha, beta}
Beta distribution. Conditions on the parameters are
- \code{\var{alpha} > -1} and \code{\var{beta} > -1}.
+ \code{\var{alpha} > 0} and \code{\var{beta} > 0}.
Returned values range between 0 and 1.
\end{funcdesc}
Modified: python/branches/p3yk-noslice/Doc/lib/libshutil.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libshutil.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libshutil.tex Fri Feb 23 18:29:35 2007
@@ -44,8 +44,8 @@
\end{funcdesc}
\begin{funcdesc}{copystat}{src, dst}
- Copy the permission bits, last access time, and last modification
- time from \var{src} to \var{dst}. The file contents, owner, and
+ Copy the permission bits, last access time, last modification time,
+ and flags from \var{src} to \var{dst}. The file contents, owner, and
group are unaffected. \var{src} and \var{dst} are path names given
as strings.
\end{funcdesc}
Modified: python/branches/p3yk-noslice/Doc/lib/libsmtplib.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libsmtplib.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libsmtplib.tex Fri Feb 23 18:29:35 2007
@@ -185,7 +185,7 @@
The server didn't reply properly to the \samp{HELO} greeting.
\item[\exception{SMTPAuthenticationError}]
The server didn't accept the username/password combination.
- \item[\exception{SMTPError}]
+ \item[\exception{SMTPException}]
No suitable authentication method was found.
\end{description}
\end{methoddesc}
Modified: python/branches/p3yk-noslice/Doc/lib/libsocket.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libsocket.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libsocket.tex Fri Feb 23 18:29:35 2007
@@ -331,25 +331,25 @@
\end{funcdesc}
\begin{funcdesc}{ntohl}{x}
-Convert 32-bit integers from network to host byte order. On machines
+Convert 32-bit positive integers from network to host byte order. On machines
where the host byte order is the same as network byte order, this is a
no-op; otherwise, it performs a 4-byte swap operation.
\end{funcdesc}
\begin{funcdesc}{ntohs}{x}
-Convert 16-bit integers from network to host byte order. On machines
+Convert 16-bit positive integers from network to host byte order. On machines
where the host byte order is the same as network byte order, this is a
no-op; otherwise, it performs a 2-byte swap operation.
\end{funcdesc}
\begin{funcdesc}{htonl}{x}
-Convert 32-bit integers from host to network byte order. On machines
+Convert 32-bit positive integers from host to network byte order. On machines
where the host byte order is the same as network byte order, this is a
no-op; otherwise, it performs a 4-byte swap operation.
\end{funcdesc}
\begin{funcdesc}{htons}{x}
-Convert 16-bit integers from host to network byte order. On machines
+Convert 16-bit positive integers from host to network byte order. On machines
where the host byte order is the same as network byte order, this is a
no-op; otherwise, it performs a 2-byte swap operation.
\end{funcdesc}
Modified: python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libstdtypes.tex Fri Feb 23 18:29:35 2007
@@ -1212,7 +1212,7 @@
\label{types-set}}
\obindex{set}
-A \dfn{set} object is an unordered collection of immutable values.
+A \dfn{set} object is an unordered collection of distinct hashable objects.
Common uses include membership testing, removing duplicates from a sequence,
and computing mathematical operations such as intersection, union, difference,
and symmetric difference.
Modified: python/branches/p3yk-noslice/Doc/lib/libstruct.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libstruct.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libstruct.tex Fri Feb 23 18:29:35 2007
@@ -29,6 +29,15 @@
exactly.
\end{funcdesc}
+\begin{funcdesc}{pack_into}{fmt, buffer, offset, v1, v2, \moreargs}
+ Pack the values \code{\var{v1}, \var{v2}, \textrm{\ldots}} according to the given
+ format, write the packed bytes into the writable \var{buffer} starting at
+ \var{offset}.
+ Note that the offset is not an optional argument.
+
+ \versionadded{2.5}
+\end{funcdesc}
+
\begin{funcdesc}{unpack}{fmt, string}
Unpack the string (presumably packed by \code{pack(\var{fmt},
\textrm{\ldots})}) according to the given format. The result is a
@@ -37,6 +46,16 @@
(\code{len(\var{string})} must equal \code{calcsize(\var{fmt})}).
\end{funcdesc}
+\begin{funcdesc}{unpack_from}{fmt, buffer\optional{,offset \code{= 0}}}
+ Unpack the \var{buffer} according to tthe given format.
+ The result is a tuple even if it contains exactly one item. The
+ \var{buffer} must contain at least the amount of data required by the
+ format (\code{len(buffer[offset:])} must be at least
+ \code{calcsize(\var{fmt})}).
+
+ \versionadded{2.5}
+\end{funcdesc}
+
\begin{funcdesc}{calcsize}{fmt}
Return the size of the struct (and hence of the string)
corresponding to the given format.
@@ -50,14 +69,15 @@
\lineiv{c}{\ctype{char}}{string of length 1}{}
\lineiv{b}{\ctype{signed char}}{integer}{}
\lineiv{B}{\ctype{unsigned char}}{integer}{}
+ \lineiv{t}{\ctype{_Bool}}{bool}{(1)}
\lineiv{h}{\ctype{short}}{integer}{}
\lineiv{H}{\ctype{unsigned short}}{integer}{}
\lineiv{i}{\ctype{int}}{integer}{}
\lineiv{I}{\ctype{unsigned int}}{long}{}
\lineiv{l}{\ctype{long}}{integer}{}
\lineiv{L}{\ctype{unsigned long}}{long}{}
- \lineiv{q}{\ctype{long long}}{long}{(1)}
- \lineiv{Q}{\ctype{unsigned long long}}{long}{(1)}
+ \lineiv{q}{\ctype{long long}}{long}{(2)}
+ \lineiv{Q}{\ctype{unsigned long long}}{long}{(2)}
\lineiv{f}{\ctype{float}}{float}{}
\lineiv{d}{\ctype{double}}{float}{}
\lineiv{s}{\ctype{char[]}}{string}{}
@@ -70,6 +90,11 @@
\begin{description}
\item[(1)]
+ The \character{t} conversion code corresponds to the \ctype{_Bool} type
+ defined by 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}
+\item[(2)]
The \character{q} and \character{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
@@ -118,6 +143,12 @@
meaning a Python long integer will be used to hold the pointer; other
platforms use 32-bit pointers and will use a Python integer.
+For the \character{t} format character, the return value is either
+\constant{True} or \constant{False}. When packing, the truth value
+of the argument object is used. Either 0 or 1 in the native or standard
+bool representation will be packed, and any non-zero value will be True
+when unpacking.
+
By default, C numbers are represented in the machine's native format
and byte order, and properly aligned by skipping pad bytes if
necessary (according to the rules used by the C compiler).
@@ -151,6 +182,7 @@
\ctype{long long} (\ctype{__int64} on Windows) is 8 bytes;
\ctype{float} and \ctype{double} are 32-bit and 64-bit
IEEE floating point numbers, respectively.
+\ctype{_Bool} is 1 byte.
Note the difference between \character{@} and \character{=}: both use
native byte order, but the size and alignment of the latter is
@@ -195,3 +227,43 @@
\seemodule{array}{Packed binary storage of homogeneous data.}
\seemodule{xdrlib}{Packing and unpacking of XDR data.}
\end{seealso}
+
+\subsection{Struct Objects \label{struct-objects}}
+
+The \module{struct} module also defines the following type:
+
+\begin{classdesc}{Struct}{format}
+ Return a new Struct object which writes and reads binary data according to
+ the format string \var{format}. Creating a Struct object once and calling
+ its methods is more efficient than calling the \module{struct} functions
+ with the same format since the format string only needs to be compiled once.
+
+ \versionadded{2.5}
+\end{classdesc}
+
+Compiled Struct objects support the following methods and attributes:
+
+\begin{methoddesc}[Struct]{pack}{v1, v2, \moreargs}
+ Identical to the \function{pack()} function, using the compiled format.
+ (\code{len(result)} will equal \member{self.size}.)
+\end{methoddesc}
+
+\begin{methoddesc}[Struct]{pack_into}{buffer, offset, v1, v2, \moreargs}
+ Identical to the \function{pack_into()} function, using the compiled format.
+\end{methoddesc}
+
+\begin{methoddesc}[Struct]{unpack}{string}
+ Identical to the \function{unpack()} function, using the compiled format.
+ (\code{len(string)} must equal \member{self.size}).
+\end{methoddesc}
+
+\begin{methoddesc}[Struct]{unpack_from}{buffer\optional{,offset
+ \code{= 0}}}
+ Identical to the \function{unpack_from()} function, using the compiled format.
+ (\code{len(buffer[offset:])} must be at least \member{self.size}).
+\end{methoddesc}
+
+\begin{memberdesc}[Struct]{format}
+ The format string used to construct this Struct object.
+\end{memberdesc}
+
Modified: python/branches/p3yk-noslice/Doc/lib/libtarfile.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libtarfile.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libtarfile.tex Fri Feb 23 18:29:35 2007
@@ -36,7 +36,8 @@
\lineii{'r:'}{Open for reading exclusively without compression.}
\lineii{'r:gz'}{Open for reading with gzip compression.}
\lineii{'r:bz2'}{Open for reading with bzip2 compression.}
- \lineii{'a' or 'a:'}{Open for appending with no compression.}
+ \lineii{'a' or 'a:'}{Open for appending with no compression. The file
+ is created if it does not exist.}
\lineii{'w' or 'w:'}{Open for uncompressed writing.}
\lineii{'w:gz'}{Open for gzip compressed writing.}
\lineii{'w:bz2'}{Open for bzip2 compressed writing.}
@@ -48,8 +49,8 @@
avoid this. If a compression method is not supported,
\exception{CompressionError} is raised.
- If \var{fileobj} is specified, it is used as an alternative to
- a file object opened for \var{name}.
+ If \var{fileobj} is specified, it is used as an alternative to a file
+ object opened for \var{name}. It is supposed to be at position 0.
For special purposes, there is a second format for \var{mode}:
\code{'filemode|[compression]'}. \function{open()} will return a
@@ -160,6 +161,7 @@
If \var{fileobj} is given, it is used for reading or writing data.
If it can be determined, \var{mode} is overridden by \var{fileobj}'s mode.
+ \var{fileobj} will be used from position 0.
\begin{notice}
\var{fileobj} is not closed, when \class{TarFile} is closed.
\end{notice}
Modified: python/branches/p3yk-noslice/Doc/lib/libtest.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libtest.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libtest.tex Fri Feb 23 18:29:35 2007
@@ -281,6 +281,7 @@
The optional argument \var{testclass} accepts one of the test classes in the
suite so as to print out more detailed information on where the testing suite
originated from.
+\end{funcdesc}
The \module{test.test_support} module defines the following classes:
@@ -299,4 +300,3 @@
Temporarily unset the environment variable \code{envvar}.
\end{methoddesc}
-\end{funcdesc}
Modified: python/branches/p3yk-noslice/Doc/lib/libtime.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libtime.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libtime.tex Fri Feb 23 18:29:35 2007
@@ -324,6 +324,12 @@
it is platform-specific except for recognizing UTC and GMT which are
always known (and are considered to be non-daylight savings
timezones).
+
+Only the directives specified in the documentation are supported. Because
+\code{strftime()} is implemented per platform it can sometimes offer more
+directives than those listed. But \code{strptime()} is independent of any
+platform and thus does not necessarily support all directives available that
+are not documented as supported.
\end{funcdesc}
\begin{datadesc}{struct_time}
Modified: python/branches/p3yk-noslice/Doc/lib/libzipfile.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/lib/libzipfile.tex (original)
+++ python/branches/p3yk-noslice/Doc/lib/libzipfile.tex Fri Feb 23 18:29:35 2007
@@ -17,8 +17,10 @@
{PKZIP Application Note}.
This module does not currently handle ZIP files which have appended
-comments, or multi-disk ZIP files. It can handle ZIP files that use the
-ZIP64 extensions (that is ZIP files that are more than 4 GByte in size).
+comments, or multi-disk ZIP files. It can handle ZIP files that use
+the ZIP64 extensions (that is ZIP files that are more than 4 GByte in
+size). It supports decryption of encrypted files in ZIP archives, but
+it cannot currently create an encrypted file.
The available attributes of this module are:
@@ -99,6 +101,8 @@
\end{verbatim}
also works, and at least \program{WinZip} can read such files.
+ If \var{mode} is \code{a} and the file does not exist at all,
+ it is created.
\var{compression} is the ZIP compression method to use when writing
the archive, and should be \constant{ZIP_STORED} or
\constant{ZIP_DEFLATED}; unrecognized values will cause
@@ -112,6 +116,9 @@
ZIP file would require ZIP64 extensions. ZIP64 extensions are disabled by
default because the default \program{zip} and \program{unzip} commands on
\UNIX{} (the InfoZIP utilities) don't support these extensions.
+
+ \versionchanged[If the file does not exist, it is created if the
+ mode is 'a']{2.6}
\end{classdesc}
\begin{methoddesc}{close}{}
@@ -138,9 +145,18 @@
Print a table of contents for the archive to \code{sys.stdout}.
\end{methoddesc}
-\begin{methoddesc}{read}{name}
+\begin{methoddesc}{setpassword}{pwd}
+ Set \var{pwd} as default password to extract encrypted files.
+ \versionadded{2.6}
+\end{methoddesc}
+
+\begin{methoddesc}{read}{name\optional{, pwd}}
Return the bytes of the file in the archive. The archive must be
- open for read or append.
+ open for read or append. \var{pwd} is the password used for encrypted
+ files and, if specified, it will override the default password set with
+ \method{setpassword()}.
+
+ \versionchanged[\var{pwd} was added]{2.6}
\end{methoddesc}
\begin{methoddesc}{testzip}{}
Modified: python/branches/p3yk-noslice/Doc/ref/ref3.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/ref/ref3.tex (original)
+++ python/branches/p3yk-noslice/Doc/ref/ref3.tex Fri Feb 23 18:29:35 2007
@@ -1997,8 +1997,8 @@
\methodline[numeric object]{__ixor__}{self, other}
\methodline[numeric object]{__ior__}{self, other}
These methods are called to implement the augmented arithmetic
-operations (\code{+=}, \code{-=}, \code{*=}, \code{/=}, \code{\%=},
-\code{**=}, \code{<<=}, \code{>>=}, \code{\&=},
+operations (\code{+=}, \code{-=}, \code{*=}, \code{/=}, \code{//=},
+\code{\%=}, \code{**=}, \code{<<=}, \code{>>=}, \code{\&=},
\code{\textasciicircum=}, \code{|=}). These methods should attempt to do the
operation in-place (modifying \var{self}) and return the result (which
could be, but does not have to be, \var{self}). If a specific method
Modified: python/branches/p3yk-noslice/Doc/ref/ref4.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/ref/ref4.tex (original)
+++ python/branches/p3yk-noslice/Doc/ref/ref4.tex Fri Feb 23 18:29:35 2007
@@ -197,10 +197,6 @@
value can be raised along with the identifying string which can be
passed to the handler.
-\deprecated{2.5}{String exceptions should not be used in new code.
-They will not be supported in a future version of Python. Old code
-should be rewritten to use class exceptions instead.}
-
\begin{notice}[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
Modified: python/branches/p3yk-noslice/Doc/ref/ref6.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/ref/ref6.tex (original)
+++ python/branches/p3yk-noslice/Doc/ref/ref6.tex Fri Feb 23 18:29:35 2007
@@ -12,7 +12,6 @@
\productioncont{| \token{augmented_assignment_stmt}}
\productioncont{| \token{pass_stmt}}
\productioncont{| \token{del_stmt}}
- \productioncont{| \token{print_stmt}}
\productioncont{| \token{return_stmt}}
\productioncont{| \token{yield_stmt}}
\productioncont{| \token{raise_stmt}}
@@ -370,60 +369,6 @@
\indexii{attribute}{deletion}
-\section{The \keyword{print} statement \label{print}}
-\stindex{print}
-
-\begin{productionlist}
- \production{print_stmt}
- {"print" ( \optional{\token{expression} ("," \token{expression})* \optional{","}}}
- \productioncont{| ">>" \token{expression}
- \optional{("," \token{expression})+ \optional{","}} )}
-\end{productionlist}
-
-\keyword{print} evaluates each expression in turn and writes the
-resulting object to standard output (see below). If an object is not
-a string, it is first converted to a string using the rules for string
-conversions. The (resulting or original) string is then written. A
-space is written before each object is (converted and) written, unless
-the output system believes it is positioned at the beginning of a
-line. This is the case (1) when no characters have yet been written
-to standard output, (2) when the last character written to standard
-output is \character{\e n}, or (3) when the last write operation on
-standard output was not a \keyword{print} statement. (In some cases
-it may be functional to write an empty string to standard output for
-this reason.) \note{Objects which act like file objects but which are
-not the built-in file objects often do not properly emulate this
-aspect of the file object's behavior, so it is best not to rely on
-this.}
-\index{output}
-\indexii{writing}{values}
-
-A \character{\e n} character is written at the end, unless the
-\keyword{print} statement ends with a comma. This is the only action
-if the statement contains just the keyword \keyword{print}.
-\indexii{trailing}{comma}
-\indexii{newline}{suppression}
-
-Standard output is defined as the file object named \code{stdout}
-in the built-in module \module{sys}. If no such object exists, or if
-it does not have a \method{write()} method, a \exception{RuntimeError}
-exception is raised.
-\indexii{standard}{output}
-\refbimodindex{sys}
-\withsubitem{(in module sys)}{\ttindex{stdout}}
-\exindex{RuntimeError}
-
-\keyword{print} also has an extended\index{extended print statement}
-form, defined by the second portion of the syntax described above.
-This form is sometimes referred to as ``\keyword{print} chevron.''
-In this form, the first expression after the \code{>>} must
-evaluate to a ``file-like'' object, specifically an object that has a
-\method{write()} method as described above. With this extended form,
-the subsequent expressions are printed to this file object. If the
-first expression evaluates to \code{None}, then \code{sys.stdout} is
-used as the file for output.
-
-
\section{The \keyword{return} statement \label{return}}
\stindex{return}
Modified: python/branches/p3yk-noslice/Doc/tut/tut.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/tut/tut.tex (original)
+++ python/branches/p3yk-noslice/Doc/tut/tut.tex Fri Feb 23 18:29:35 2007
@@ -1991,7 +1991,7 @@
There is a way to remove an item from a list given its index instead
of its value: the \keyword{del} statement. This differs from the
-\method{pop()}) method which returns a value. The \keyword{del}
+\method{pop()} method which returns a value. The \keyword{del}
statement can also be used to remove slices from a list or clear the
entire list (which we did earlier by assignment of an empty list to
the slice). For example:
Modified: python/branches/p3yk-noslice/Doc/whatsnew/whatsnew26.tex
==============================================================================
--- python/branches/p3yk-noslice/Doc/whatsnew/whatsnew26.tex (original)
+++ python/branches/p3yk-noslice/Doc/whatsnew/whatsnew26.tex Fri Feb 23 18:29:35 2007
@@ -72,6 +72,12 @@
This class supports an interface identical to the existing \class{SMTP}
class. (Contributed by Monty Taylor.)
+\item The \module{test.test_support} module now contains a
+\function{EnvironmentVarGuard} context manager that
+supports temporarily changing environment variables and
+automatically restores them to their old values.
+(Contributed by Brett Cannon.)
+
\end{itemize}
Modified: python/branches/p3yk-noslice/Grammar/Grammar
==============================================================================
--- python/branches/p3yk-noslice/Grammar/Grammar (original)
+++ python/branches/p3yk-noslice/Grammar/Grammar Fri Feb 23 18:29:35 2007
@@ -38,15 +38,13 @@
stmt: simple_stmt | compound_stmt
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
-small_stmt: (expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt |
+small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
import_stmt | global_stmt | assert_stmt)
expr_stmt: testlist (augassign (yield_expr|testlist) |
('=' (yield_expr|testlist))*)
augassign: ('+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^=' |
'<<=' | '>>=' | '**=' | '//=')
# For normal assignments, additional restrictions enforced by the interpreter
-print_stmt: 'print' ( [ test (',' test)* [','] ] |
- '>>' test [ (',' test)+ [','] ] )
del_stmt: 'del' exprlist
pass_stmt: 'pass'
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt
Modified: python/branches/p3yk-noslice/Include/Python-ast.h
==============================================================================
--- python/branches/p3yk-noslice/Include/Python-ast.h (original)
+++ python/branches/p3yk-noslice/Include/Python-ast.h Fri Feb 23 18:29:35 2007
@@ -1,4 +1,4 @@
-/* File automatically generated by Parser/asdl_c.py */
+/* File automatically generated by Parser/asdl_c.py. */
#include "asdl.h"
@@ -62,12 +62,11 @@
};
enum _stmt_kind {FunctionDef_kind=1, ClassDef_kind=2, Return_kind=3,
- Delete_kind=4, Assign_kind=5, AugAssign_kind=6, Print_kind=7,
- For_kind=8, While_kind=9, If_kind=10, With_kind=11,
- Raise_kind=12, TryExcept_kind=13, TryFinally_kind=14,
- Assert_kind=15, Import_kind=16, ImportFrom_kind=17,
- Global_kind=18, Expr_kind=19, Pass_kind=20, Break_kind=21,
- Continue_kind=22};
+ Delete_kind=4, Assign_kind=5, AugAssign_kind=6, For_kind=7,
+ While_kind=8, If_kind=9, With_kind=10, Raise_kind=11,
+ TryExcept_kind=12, TryFinally_kind=13, Assert_kind=14,
+ Import_kind=15, ImportFrom_kind=16, Global_kind=17,
+ Expr_kind=18, Pass_kind=19, Break_kind=20, Continue_kind=21};
struct _stmt {
enum _stmt_kind kind;
union {
@@ -105,12 +104,6 @@
} AugAssign;
struct {
- expr_ty dest;
- asdl_seq *values;
- bool nl;
- } Print;
-
- struct {
expr_ty target;
expr_ty iter;
asdl_seq *body;
@@ -366,97 +359,154 @@
};
-mod_ty Module(asdl_seq * body, PyArena *arena);
-mod_ty Interactive(asdl_seq * body, PyArena *arena);
-mod_ty Expression(expr_ty body, PyArena *arena);
-mod_ty Suite(asdl_seq * body, PyArena *arena);
-stmt_ty FunctionDef(identifier name, arguments_ty args, asdl_seq * body,
- asdl_seq * decorators, expr_ty returns, int lineno, int
- col_offset, PyArena *arena);
-stmt_ty ClassDef(identifier name, asdl_seq * bases, asdl_seq * body, int
- lineno, int col_offset, PyArena *arena);
-stmt_ty Return(expr_ty value, int lineno, int col_offset, PyArena *arena);
-stmt_ty Delete(asdl_seq * targets, int lineno, int col_offset, PyArena *arena);
-stmt_ty Assign(asdl_seq * targets, expr_ty value, int lineno, int col_offset,
- PyArena *arena);
-stmt_ty AugAssign(expr_ty target, operator_ty op, expr_ty value, int lineno,
- int col_offset, PyArena *arena);
-stmt_ty Print(expr_ty dest, asdl_seq * values, bool nl, int lineno, int
- col_offset, PyArena *arena);
-stmt_ty For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse,
- int lineno, int col_offset, PyArena *arena);
-stmt_ty While(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int
- col_offset, PyArena *arena);
-stmt_ty If(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno, int
- col_offset, PyArena *arena);
-stmt_ty With(expr_ty context_expr, expr_ty optional_vars, asdl_seq * body, int
- lineno, int col_offset, PyArena *arena);
-stmt_ty Raise(expr_ty type, expr_ty inst, expr_ty tback, int lineno, int
- col_offset, PyArena *arena);
-stmt_ty TryExcept(asdl_seq * body, asdl_seq * handlers, asdl_seq * orelse, int
- lineno, int col_offset, PyArena *arena);
-stmt_ty TryFinally(asdl_seq * body, asdl_seq * finalbody, int lineno, int
+#define Module(a0, a1) _Py_Module(a0, a1)
+mod_ty _Py_Module(asdl_seq * body, PyArena *arena);
+#define Interactive(a0, a1) _Py_Interactive(a0, a1)
+mod_ty _Py_Interactive(asdl_seq * body, PyArena *arena);
+#define Expression(a0, a1) _Py_Expression(a0, a1)
+mod_ty _Py_Expression(expr_ty body, PyArena *arena);
+#define Suite(a0, a1) _Py_Suite(a0, a1)
+mod_ty _Py_Suite(asdl_seq * body, PyArena *arena);
+#define FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) _Py_FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7)
+stmt_ty _Py_FunctionDef(identifier name, arguments_ty args, asdl_seq * body,
+ asdl_seq * decorators, expr_ty returns, int lineno, int
+ col_offset, PyArena *arena);
+#define ClassDef(a0, a1, a2, a3, a4, a5) _Py_ClassDef(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_ClassDef(identifier name, asdl_seq * bases, asdl_seq * body, int
+ lineno, int col_offset, PyArena *arena);
+#define Return(a0, a1, a2, a3) _Py_Return(a0, a1, a2, a3)
+stmt_ty _Py_Return(expr_ty value, int lineno, int col_offset, PyArena *arena);
+#define Delete(a0, a1, a2, a3) _Py_Delete(a0, a1, a2, a3)
+stmt_ty _Py_Delete(asdl_seq * targets, int lineno, int col_offset, PyArena
+ *arena);
+#define Assign(a0, a1, a2, a3, a4) _Py_Assign(a0, a1, a2, a3, a4)
+stmt_ty _Py_Assign(asdl_seq * targets, expr_ty value, int lineno, int
col_offset, PyArena *arena);
-stmt_ty Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, PyArena
- *arena);
-stmt_ty Import(asdl_seq * names, int lineno, int col_offset, PyArena *arena);
-stmt_ty ImportFrom(identifier module, asdl_seq * names, int level, int lineno,
- int col_offset, PyArena *arena);
-stmt_ty Global(asdl_seq * names, int lineno, int col_offset, PyArena *arena);
-stmt_ty Expr(expr_ty value, int lineno, int col_offset, PyArena *arena);
-stmt_ty Pass(int lineno, int col_offset, PyArena *arena);
-stmt_ty Break(int lineno, int col_offset, PyArena *arena);
-stmt_ty Continue(int lineno, int col_offset, PyArena *arena);
-expr_ty BoolOp(boolop_ty op, asdl_seq * values, int lineno, int col_offset,
- PyArena *arena);
-expr_ty BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno, int
- col_offset, PyArena *arena);
-expr_ty UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int col_offset,
- PyArena *arena);
-expr_ty Lambda(arguments_ty args, expr_ty body, int lineno, int col_offset,
- PyArena *arena);
-expr_ty IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno, int
- col_offset, PyArena *arena);
-expr_ty Dict(asdl_seq * keys, asdl_seq * values, int lineno, int col_offset,
- PyArena *arena);
-expr_ty Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena);
-expr_ty ListComp(expr_ty elt, asdl_seq * generators, int lineno, int
+#define AugAssign(a0, a1, a2, a3, a4, a5) _Py_AugAssign(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_AugAssign(expr_ty target, operator_ty op, expr_ty value, int
+ lineno, int col_offset, PyArena *arena);
+#define For(a0, a1, a2, a3, a4, a5, a6) _Py_For(a0, a1, a2, a3, a4, a5, a6)
+stmt_ty _Py_For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq *
+ orelse, int lineno, int col_offset, PyArena *arena);
+#define While(a0, a1, a2, a3, a4, a5) _Py_While(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_While(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno,
+ int col_offset, PyArena *arena);
+#define If(a0, a1, a2, a3, a4, a5) _Py_If(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_If(expr_ty test, asdl_seq * body, asdl_seq * orelse, int lineno,
+ int col_offset, PyArena *arena);
+#define With(a0, a1, a2, a3, a4, a5) _Py_With(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_With(expr_ty context_expr, expr_ty optional_vars, asdl_seq * body,
+ int lineno, int col_offset, PyArena *arena);
+#define Raise(a0, a1, a2, a3, a4, a5) _Py_Raise(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_Raise(expr_ty type, expr_ty inst, expr_ty tback, int lineno, int
+ col_offset, PyArena *arena);
+#define TryExcept(a0, a1, a2, a3, a4, a5) _Py_TryExcept(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_TryExcept(asdl_seq * body, asdl_seq * handlers, asdl_seq * orelse,
+ int lineno, int col_offset, PyArena *arena);
+#define TryFinally(a0, a1, a2, a3, a4) _Py_TryFinally(a0, a1, a2, a3, a4)
+stmt_ty _Py_TryFinally(asdl_seq * body, asdl_seq * finalbody, int lineno, int
+ col_offset, PyArena *arena);
+#define Assert(a0, a1, a2, a3, a4) _Py_Assert(a0, a1, a2, a3, a4)
+stmt_ty _Py_Assert(expr_ty test, expr_ty msg, int lineno, int col_offset,
+ PyArena *arena);
+#define Import(a0, a1, a2, a3) _Py_Import(a0, a1, a2, a3)
+stmt_ty _Py_Import(asdl_seq * names, int lineno, int col_offset, PyArena
+ *arena);
+#define ImportFrom(a0, a1, a2, a3, a4, a5) _Py_ImportFrom(a0, a1, a2, a3, a4, a5)
+stmt_ty _Py_ImportFrom(identifier module, asdl_seq * names, int level, int
+ lineno, int col_offset, PyArena *arena);
+#define Global(a0, a1, a2, a3) _Py_Global(a0, a1, a2, a3)
+stmt_ty _Py_Global(asdl_seq * names, int lineno, int col_offset, PyArena
+ *arena);
+#define Expr(a0, a1, a2, a3) _Py_Expr(a0, a1, a2, a3)
+stmt_ty _Py_Expr(expr_ty value, int lineno, int col_offset, PyArena *arena);
+#define Pass(a0, a1, a2) _Py_Pass(a0, a1, a2)
+stmt_ty _Py_Pass(int lineno, int col_offset, PyArena *arena);
+#define Break(a0, a1, a2) _Py_Break(a0, a1, a2)
+stmt_ty _Py_Break(int lineno, int col_offset, PyArena *arena);
+#define Continue(a0, a1, a2) _Py_Continue(a0, a1, a2)
+stmt_ty _Py_Continue(int lineno, int col_offset, PyArena *arena);
+#define BoolOp(a0, a1, a2, a3, a4) _Py_BoolOp(a0, a1, a2, a3, a4)
+expr_ty _Py_BoolOp(boolop_ty op, asdl_seq * values, int lineno, int col_offset,
+ PyArena *arena);
+#define BinOp(a0, a1, a2, a3, a4, a5) _Py_BinOp(a0, a1, a2, a3, a4, a5)
+expr_ty _Py_BinOp(expr_ty left, operator_ty op, expr_ty right, int lineno, int
+ col_offset, PyArena *arena);
+#define UnaryOp(a0, a1, a2, a3, a4) _Py_UnaryOp(a0, a1, a2, a3, a4)
+expr_ty _Py_UnaryOp(unaryop_ty op, expr_ty operand, int lineno, int col_offset,
+ PyArena *arena);
+#define Lambda(a0, a1, a2, a3, a4) _Py_Lambda(a0, a1, a2, a3, a4)
+expr_ty _Py_Lambda(arguments_ty args, expr_ty body, int lineno, int col_offset,
+ PyArena *arena);
+#define IfExp(a0, a1, a2, a3, a4, a5) _Py_IfExp(a0, a1, a2, a3, a4, a5)
+expr_ty _Py_IfExp(expr_ty test, expr_ty body, expr_ty orelse, int lineno, int
+ col_offset, PyArena *arena);
+#define Dict(a0, a1, a2, a3, a4) _Py_Dict(a0, a1, a2, a3, a4)
+expr_ty _Py_Dict(asdl_seq * keys, asdl_seq * values, int lineno, int
col_offset, PyArena *arena);
-expr_ty GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int
+#define Set(a0, a1, a2, a3) _Py_Set(a0, a1, a2, a3)
+expr_ty _Py_Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena);
+#define ListComp(a0, a1, a2, a3, a4) _Py_ListComp(a0, a1, a2, a3, a4)
+expr_ty _Py_ListComp(expr_ty elt, asdl_seq * generators, int lineno, int
col_offset, PyArena *arena);
-expr_ty Yield(expr_ty value, int lineno, int col_offset, PyArena *arena);
-expr_ty Compare(expr_ty left, asdl_int_seq * ops, asdl_seq * comparators, int
- lineno, int col_offset, PyArena *arena);
-expr_ty Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, expr_ty
- starargs, expr_ty kwargs, int lineno, int col_offset, PyArena
- *arena);
-expr_ty Num(object n, int lineno, int col_offset, PyArena *arena);
-expr_ty Str(string s, int lineno, int col_offset, PyArena *arena);
-expr_ty Ellipsis(int lineno, int col_offset, PyArena *arena);
-expr_ty Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int
- lineno, int col_offset, PyArena *arena);
-expr_ty Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int
- lineno, int col_offset, PyArena *arena);
-expr_ty Name(identifier id, expr_context_ty ctx, int lineno, int col_offset,
- PyArena *arena);
-expr_ty List(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset,
- PyArena *arena);
-expr_ty Tuple(asdl_seq * elts, expr_context_ty ctx, int lineno, int col_offset,
- PyArena *arena);
-slice_ty Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena);
-slice_ty ExtSlice(asdl_seq * dims, PyArena *arena);
-slice_ty Index(expr_ty value, PyArena *arena);
-comprehension_ty comprehension(expr_ty target, expr_ty iter, asdl_seq * ifs,
- PyArena *arena);
-excepthandler_ty excepthandler(expr_ty type, identifier name, asdl_seq * body,
- int lineno, int col_offset, PyArena *arena);
-arguments_ty arguments(asdl_seq * args, identifier vararg, expr_ty
- varargannotation, asdl_seq * kwonlyargs, identifier
- kwarg, expr_ty kwargannotation, asdl_seq * defaults,
- asdl_seq * kw_defaults, PyArena *arena);
-arg_ty SimpleArg(identifier arg, expr_ty annotation, PyArena *arena);
-arg_ty NestedArgs(asdl_seq * args, PyArena *arena);
-keyword_ty keyword(identifier arg, expr_ty value, PyArena *arena);
-alias_ty alias(identifier name, identifier asname, PyArena *arena);
+#define GeneratorExp(a0, a1, a2, a3, a4) _Py_GeneratorExp(a0, a1, a2, a3, a4)
+expr_ty _Py_GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int
+ col_offset, PyArena *arena);
+#define Yield(a0, a1, a2, a3) _Py_Yield(a0, a1, a2, a3)
+expr_ty _Py_Yield(expr_ty value, int lineno, int col_offset, PyArena *arena);
+#define Compare(a0, a1, a2, a3, a4, a5) _Py_Compare(a0, a1, a2, a3, a4, a5)
+expr_ty _Py_Compare(expr_ty left, asdl_int_seq * ops, asdl_seq * comparators,
+ int lineno, int col_offset, PyArena *arena);
+#define Call(a0, a1, a2, a3, a4, a5, a6, a7) _Py_Call(a0, a1, a2, a3, a4, a5, a6, a7)
+expr_ty _Py_Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, expr_ty
+ starargs, expr_ty kwargs, int lineno, int col_offset, PyArena
+ *arena);
+#define Num(a0, a1, a2, a3) _Py_Num(a0, a1, a2, a3)
+expr_ty _Py_Num(object n, int lineno, int col_offset, PyArena *arena);
+#define Str(a0, a1, a2, a3) _Py_Str(a0, a1, a2, a3)
+expr_ty _Py_Str(string s, int lineno, int col_offset, PyArena *arena);
+#define Ellipsis(a0, a1, a2) _Py_Ellipsis(a0, a1, a2)
+expr_ty _Py_Ellipsis(int lineno, int col_offset, PyArena *arena);
+#define Attribute(a0, a1, a2, a3, a4, a5) _Py_Attribute(a0, a1, a2, a3, a4, a5)
+expr_ty _Py_Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int
+ lineno, int col_offset, PyArena *arena);
+#define Subscript(a0, a1, a2, a3, a4, a5) _Py_Subscript(a0, a1, a2, a3, a4, a5)
+expr_ty _Py_Subscript(expr_ty value, slice_ty slice, expr_context_ty ctx, int
+ lineno, int col_offset, PyArena *arena);
+#define Name(a0, a1, a2, a3, a4) _Py_Name(a0, a1, a2, a3, a4)
+expr_ty _Py_Name(identifier id, expr_context_ty ctx, int lineno, int
+ col_offset, PyArena *arena);
+#define List(a0, a1, a2, a3, a4) _Py_List(a0, a1, a2, a3, a4)
+expr_ty _Py_List(asdl_seq * elts, expr_context_ty ctx, int lineno, int
+ col_offset, PyArena *arena);
+#define Tuple(a0, a1, a2, a3, a4) _Py_Tuple(a0, a1, a2, a3, a4)
+expr_ty _Py_Tuple(asdl_seq * elts, expr_context_ty ctx, int lineno, int
+ col_offset, PyArena *arena);
+#define Slice(a0, a1, a2, a3) _Py_Slice(a0, a1, a2, a3)
+slice_ty _Py_Slice(expr_ty lower, expr_ty upper, expr_ty step, PyArena *arena);
+#define ExtSlice(a0, a1) _Py_ExtSlice(a0, a1)
+slice_ty _Py_ExtSlice(asdl_seq * dims, PyArena *arena);
+#define Index(a0, a1) _Py_Index(a0, a1)
+slice_ty _Py_Index(expr_ty value, PyArena *arena);
+#define comprehension(a0, a1, a2, a3) _Py_comprehension(a0, a1, a2, a3)
+comprehension_ty _Py_comprehension(expr_ty target, expr_ty iter, asdl_seq *
+ ifs, PyArena *arena);
+#define excepthandler(a0, a1, a2, a3, a4, a5) _Py_excepthandler(a0, a1, a2, a3, a4, a5)
+excepthandler_ty _Py_excepthandler(expr_ty type, identifier name, asdl_seq *
+ body, int lineno, int col_offset, PyArena
+ *arena);
+#define arguments(a0, a1, a2, a3, a4, a5, a6, a7, a8) _Py_arguments(a0, a1, a2, a3, a4, a5, a6, a7, a8)
+arguments_ty _Py_arguments(asdl_seq * args, identifier vararg, expr_ty
+ varargannotation, asdl_seq * kwonlyargs, identifier
+ kwarg, expr_ty kwargannotation, asdl_seq * defaults,
+ asdl_seq * kw_defaults, PyArena *arena);
+#define SimpleArg(a0, a1, a2) _Py_SimpleArg(a0, a1, a2)
+arg_ty _Py_SimpleArg(identifier arg, expr_ty annotation, PyArena *arena);
+#define NestedArgs(a0, a1) _Py_NestedArgs(a0, a1)
+arg_ty _Py_NestedArgs(asdl_seq * args, PyArena *arena);
+#define keyword(a0, a1, a2) _Py_keyword(a0, a1, a2)
+keyword_ty _Py_keyword(identifier arg, expr_ty value, PyArena *arena);
+#define alias(a0, a1, a2) _Py_alias(a0, a1, a2)
+alias_ty _Py_alias(identifier name, identifier asname, PyArena *arena);
PyObject* PyAST_mod2obj(mod_ty t);
Modified: python/branches/p3yk-noslice/Include/abstract.h
==============================================================================
--- python/branches/p3yk-noslice/Include/abstract.h (original)
+++ python/branches/p3yk-noslice/Include/abstract.h Fri Feb 23 18:29:35 2007
@@ -716,7 +716,7 @@
is cleared and the value is clipped.
*/
- PyAPI_FUNC(PyObject *) PyNumber_Int(PyObject *o);
+ #define PyNumber_Int PyNumber_Long
/*
Returns the o converted to an integer object on success, or
@@ -1127,37 +1127,28 @@
*/
- /* Implemented as macro:
+ PyAPI_FUNC(PyObject *) PyMapping_Keys(PyObject *o);
- PyObject *PyMapping_Keys(PyObject *o);
-
- On success, return a list of the keys in object o. On
- failure, return NULL. This is equivalent to the Python
- expression: o.keys().
+ /*
+ On success, return a list or tuple of the keys in object o.
+ On failure, return NULL.
*/
-#define PyMapping_Keys(O) PyObject_CallMethod(O,"keys",NULL)
-
- /* Implemented as macro:
- PyObject *PyMapping_Values(PyObject *o);
+ PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o);
- On success, return a list of the values in object o. On
- failure, return NULL. This is equivalent to the Python
- expression: o.values().
+ /*
+ On success, return a list or tuple of the values in object o.
+ On failure, return NULL.
*/
-#define PyMapping_Values(O) PyObject_CallMethod(O,"values",NULL)
-
- /* Implemented as macro:
- PyObject *PyMapping_Items(PyObject *o);
+ PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o);
- On success, return a list of the items in object o, where
- each item is a tuple containing a key-value pair. On
- failure, return NULL. This is equivalent to the Python
- expression: o.items().
+ /*
+ On success, return a list or tuple of the items in object o,
+ where each item is a tuple containing a key-value pair.
+ On failure, return NULL.
*/
-#define PyMapping_Items(O) PyObject_CallMethod(O,"items",NULL)
PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, char *key);
Modified: python/branches/p3yk-noslice/Include/boolobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/boolobject.h (original)
+++ python/branches/p3yk-noslice/Include/boolobject.h Fri Feb 23 18:29:35 2007
@@ -7,8 +7,6 @@
#endif
-typedef PyIntObject PyBoolObject;
-
PyAPI_DATA(PyTypeObject) PyBool_Type;
#define PyBool_Check(x) ((x)->ob_type == &PyBool_Type)
@@ -17,10 +15,10 @@
Don't forget to apply Py_INCREF() when returning either!!! */
/* Don't use these directly */
-PyAPI_DATA(PyIntObject) _Py_ZeroStruct, _Py_TrueStruct;
+PyAPI_DATA(struct _longobject) _Py_FalseStruct, _Py_TrueStruct;
/* Use these macros */
-#define Py_False ((PyObject *) &_Py_ZeroStruct)
+#define Py_False ((PyObject *) &_Py_FalseStruct)
#define Py_True ((PyObject *) &_Py_TrueStruct)
/* Macros for returning Py_True or Py_False, respectively */
Modified: python/branches/p3yk-noslice/Include/ceval.h
==============================================================================
--- python/branches/p3yk-noslice/Include/ceval.h (original)
+++ python/branches/p3yk-noslice/Include/ceval.h Fri Feb 23 18:29:35 2007
@@ -40,8 +40,6 @@
flag was set, else return 0. */
PyAPI_FUNC(int) PyEval_MergeCompilerFlags(PyCompilerFlags *cf);
-PyAPI_FUNC(int) Py_FlushLine(void);
-
PyAPI_FUNC(int) Py_AddPendingCall(int (*func)(void *), void *arg);
PyAPI_FUNC(int) Py_MakePendingCalls(void);
Modified: python/branches/p3yk-noslice/Include/dictobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/dictobject.h (original)
+++ python/branches/p3yk-noslice/Include/dictobject.h Fri Feb 23 18:29:35 2007
@@ -100,12 +100,15 @@
PyAPI_FUNC(void) PyDict_Clear(PyObject *mp);
PyAPI_FUNC(int) PyDict_Next(
PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value);
+PyAPI_FUNC(int) _PyDict_Next(
+ PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, long *hash);
PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp);
PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp);
PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp);
PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp);
PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp);
PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key);
+PyAPI_FUNC(int) _PyDict_Contains(PyObject *mp, PyObject *key, long hash);
/* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */
PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other);
Modified: python/branches/p3yk-noslice/Include/fileobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/fileobject.h (original)
+++ python/branches/p3yk-noslice/Include/fileobject.h Fri Feb 23 18:29:35 2007
@@ -13,7 +13,6 @@
PyObject *f_name;
PyObject *f_mode;
int (*f_close)(FILE *);
- int f_softspace; /* Flag used by 'print' command */
int f_binary; /* Flag which indicates whether the file is
open in binary (1) or text (0) mode */
char* f_buf; /* Allocated readahead buffer */
@@ -41,7 +40,6 @@
PyAPI_FUNC(PyObject *) PyFile_Name(PyObject *);
PyAPI_FUNC(PyObject *) PyFile_GetLine(PyObject *, int);
PyAPI_FUNC(int) PyFile_WriteObject(PyObject *, PyObject *, int);
-PyAPI_FUNC(int) PyFile_SoftSpace(PyObject *, int);
PyAPI_FUNC(int) PyFile_WriteString(const char *, PyObject *);
PyAPI_FUNC(int) PyObject_AsFileDescriptor(PyObject *);
Modified: python/branches/p3yk-noslice/Include/graminit.h
==============================================================================
--- python/branches/p3yk-noslice/Include/graminit.h (original)
+++ python/branches/p3yk-noslice/Include/graminit.h Fri Feb 23 18:29:35 2007
@@ -18,71 +18,70 @@
#define small_stmt 273
#define expr_stmt 274
#define augassign 275
-#define print_stmt 276
-#define del_stmt 277
-#define pass_stmt 278
-#define flow_stmt 279
-#define break_stmt 280
-#define continue_stmt 281
-#define return_stmt 282
-#define yield_stmt 283
-#define raise_stmt 284
-#define import_stmt 285
-#define import_name 286
-#define import_from 287
-#define import_as_name 288
-#define dotted_as_name 289
-#define import_as_names 290
-#define dotted_as_names 291
-#define dotted_name 292
-#define global_stmt 293
-#define assert_stmt 294
-#define compound_stmt 295
-#define if_stmt 296
-#define while_stmt 297
-#define for_stmt 298
-#define try_stmt 299
-#define with_stmt 300
-#define with_var 301
-#define except_clause 302
-#define suite 303
-#define testlist_safe 304
-#define old_test 305
-#define old_lambdef 306
-#define test 307
-#define or_test 308
-#define and_test 309
-#define not_test 310
-#define comparison 311
-#define comp_op 312
-#define expr 313
-#define xor_expr 314
-#define and_expr 315
-#define shift_expr 316
-#define arith_expr 317
-#define term 318
-#define factor 319
-#define power 320
-#define atom 321
-#define listmaker 322
-#define testlist_gexp 323
-#define lambdef 324
-#define trailer 325
-#define subscriptlist 326
-#define subscript 327
-#define sliceop 328
-#define exprlist 329
-#define testlist 330
-#define dictsetmaker 331
-#define classdef 332
-#define arglist 333
-#define argument 334
-#define list_iter 335
-#define list_for 336
-#define list_if 337
-#define gen_iter 338
-#define gen_for 339
-#define gen_if 340
-#define testlist1 341
-#define encoding_decl 342
-#define yield_expr 343
+#define del_stmt 276
+#define pass_stmt 277
+#define flow_stmt 278
+#define break_stmt 279
+#define continue_stmt 280
+#define return_stmt 281
+#define yield_stmt 282
+#define raise_stmt 283
+#define import_stmt 284
+#define import_name 285
+#define import_from 286
+#define import_as_name 287
+#define dotted_as_name 288
+#define import_as_names 289
+#define dotted_as_names 290
+#define dotted_name 291
+#define global_stmt 292
+#define assert_stmt 293
+#define compound_stmt 294
+#define if_stmt 295
+#define while_stmt 296
+#define for_stmt 297
+#define try_stmt 298
+#define with_stmt 299
+#define with_var 300
+#define except_clause 301
+#define suite 302
+#define testlist_safe 303
+#define old_test 304
+#define old_lambdef 305
+#define test 306
+#define or_test 307
+#define and_test 308
+#define not_test 309
+#define comparison 310
+#define comp_op 311
+#define expr 312
+#define xor_expr 313
+#define and_expr 314
+#define shift_expr 315
+#define arith_expr 316
+#define term 317
+#define factor 318
+#define power 319
+#define atom 320
+#define listmaker 321
+#define testlist_gexp 322
+#define lambdef 323
+#define trailer 324
+#define subscriptlist 325
+#define subscript 326
+#define sliceop 327
+#define exprlist 328
+#define testlist 329
+#define dictsetmaker 330
+#define classdef 331
+#define arglist 332
+#define argument 333
+#define list_iter 334
+#define list_for 335
+#define list_if 336
+#define gen_iter 337
+#define gen_for 338
+#define gen_if 339
+#define testlist1 340
+#define encoding_decl 341
+#define yield_expr 342
Modified: python/branches/p3yk-noslice/Include/intobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/intobject.h (original)
+++ python/branches/p3yk-noslice/Include/intobject.h Fri Feb 23 18:29:35 2007
@@ -20,34 +20,31 @@
extern "C" {
#endif
+/*
typedef struct {
PyObject_HEAD
long ob_ival;
} PyIntObject;
PyAPI_DATA(PyTypeObject) PyInt_Type;
+*/
-#define PyInt_Check(op) PyObject_TypeCheck(op, &PyInt_Type)
-#define PyInt_CheckExact(op) ((op)->ob_type == &PyInt_Type)
+#define PyInt_Check(op) PyLong_Check(op)
+#define PyInt_CheckExact(op) (PyLong_CheckExact(op) && _PyLong_FitsInLong(op))
-PyAPI_FUNC(PyObject *) PyInt_FromString(char*, char**, int);
-#ifdef Py_USING_UNICODE
-PyAPI_FUNC(PyObject *) PyInt_FromUnicode(Py_UNICODE*, Py_ssize_t, int);
-#endif
-PyAPI_FUNC(PyObject *) PyInt_FromLong(long);
-PyAPI_FUNC(PyObject *) PyInt_FromSize_t(size_t);
-PyAPI_FUNC(PyObject *) PyInt_FromSsize_t(Py_ssize_t);
-PyAPI_FUNC(long) PyInt_AsLong(PyObject *);
-PyAPI_FUNC(Py_ssize_t) PyInt_AsSsize_t(PyObject *);
-PyAPI_FUNC(unsigned long) PyInt_AsUnsignedLongMask(PyObject *);
-#ifdef HAVE_LONG_LONG
-PyAPI_FUNC(unsigned PY_LONG_LONG) PyInt_AsUnsignedLongLongMask(PyObject *);
-#endif
+#define PyInt_FromString PyLong_FromString
+#define PyInt_FromUnicode PyLong_FromUnicode
+#define PyInt_FromLong PyLong_FromLong
+#define PyInt_FromSize_t PyLong_FromSize_t
+#define PyInt_FromSsize_t PyLong_FromSsize_t
+#define PyInt_AsLong PyLong_AsLong
+#define PyInt_AsSsize_t PyLong_AsSsize_t
+#define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
+#define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
PyAPI_FUNC(long) PyInt_GetMax(void);
-/* Macro, trading safety for speed */
-#define PyInt_AS_LONG(op) (((PyIntObject *)(op))->ob_ival)
+#define PyInt_AS_LONG(op) PyLong_AsLong(op)
/* These aren't really part of the Int object, but they're handy; the protos
* are necessary for systems that need the magic of PyAPI_FUNC and that want
Modified: python/branches/p3yk-noslice/Include/longobject.h
==============================================================================
--- python/branches/p3yk-noslice/Include/longobject.h (original)
+++ python/branches/p3yk-noslice/Include/longobject.h Fri Feb 23 18:29:35 2007
@@ -16,15 +16,16 @@
PyAPI_FUNC(PyObject *) PyLong_FromLong(long);
PyAPI_FUNC(PyObject *) PyLong_FromUnsignedLong(unsigned long);
+PyAPI_FUNC(PyObject *) PyLong_FromSize_t(size_t);
+PyAPI_FUNC(PyObject *) PyLong_FromSsize_t(Py_ssize_t);
PyAPI_FUNC(PyObject *) PyLong_FromDouble(double);
PyAPI_FUNC(long) PyLong_AsLong(PyObject *);
+PyAPI_FUNC(ssize_t) PyLong_AsSsize_t(PyObject *);
+PyAPI_FUNC(size_t) PyLong_AsSize_t(PyObject *);
PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLong(PyObject *);
PyAPI_FUNC(unsigned long) PyLong_AsUnsignedLongMask(PyObject *);
/* For use by intobject.c only */
-PyAPI_FUNC(Py_ssize_t) _PyLong_AsSsize_t(PyObject *);
-PyAPI_FUNC(PyObject *) _PyLong_FromSize_t(size_t);
-PyAPI_FUNC(PyObject *) _PyLong_FromSsize_t(Py_ssize_t);
PyAPI_DATA(int) _PyLong_DigitValue[256];
/* _PyLong_AsScaledDouble returns a double x and an exponent e such that
@@ -34,6 +35,7 @@
be multiplied by SHIFT! There may not be enough room in an int to store
e*SHIFT directly. */
PyAPI_FUNC(double) _PyLong_AsScaledDouble(PyObject *vv, int *e);
+ PyAPI_FUNC(int) _PyLong_FitsInLong(PyObject* vv);
PyAPI_FUNC(double) PyLong_AsDouble(PyObject *);
PyAPI_FUNC(PyObject *) PyLong_FromVoidPtr(void *);
Modified: python/branches/p3yk-noslice/Include/object.h
==============================================================================
--- python/branches/p3yk-noslice/Include/object.h (original)
+++ python/branches/p3yk-noslice/Include/object.h Fri Feb 23 18:29:35 2007
@@ -368,7 +368,7 @@
/* Generic operations on objects */
PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int);
-PyAPI_FUNC(void) _Py_Break(void);
+PyAPI_FUNC(void) _Py_BreakPoint(void);
PyAPI_FUNC(void) _PyObject_Dump(PyObject *);
PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);
PyAPI_FUNC(PyObject *) _PyObject_Str(PyObject *);
Modified: python/branches/p3yk-noslice/Include/opcode.h
==============================================================================
--- python/branches/p3yk-noslice/Include/opcode.h (original)
+++ python/branches/p3yk-noslice/Include/opcode.h Fri Feb 23 18:29:35 2007
@@ -52,10 +52,7 @@
#define GET_ITER 68
#define PRINT_EXPR 70
-#define PRINT_ITEM 71
-#define PRINT_NEWLINE 72
-#define PRINT_ITEM_TO 73
-#define PRINT_NEWLINE_TO 74
+
#define INPLACE_LSHIFT 75
#define INPLACE_RSHIFT 76
#define INPLACE_AND 77
Modified: python/branches/p3yk-noslice/Lib/BaseHTTPServer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/BaseHTTPServer.py (original)
+++ python/branches/p3yk-noslice/Lib/BaseHTTPServer.py Fri Feb 23 18:29:35 2007
@@ -331,12 +331,12 @@
"""
try:
- short, long = self.responses[code]
+ shortmsg, longmsg = self.responses[code]
except KeyError:
- short, long = '???', '???'
+ shortmsg, longmsg = '???', '???'
if message is None:
- message = short
- explain = long
+ message = shortmsg
+ explain = longmsg
self.log_error("code %d, message %s", code, message)
# using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201)
content = (self.error_message_format %
@@ -396,7 +396,7 @@
self.log_message('"%s" %s %s',
self.requestline, str(code), str(size))
- def log_error(self, *args):
+ def log_error(self, format, *args):
"""Log an error.
This is called when a request cannot be fulfilled. By
@@ -408,7 +408,7 @@
"""
- self.log_message(*args)
+ self.log_message(format, *args)
def log_message(self, format, *args):
"""Log an arbitrary message.
@@ -570,7 +570,7 @@
httpd = ServerClass(server_address, HandlerClass)
sa = httpd.socket.getsockname()
- print "Serving HTTP on", sa[0], "port", sa[1], "..."
+ print("Serving HTTP on", sa[0], "port", sa[1], "...")
httpd.serve_forever()
Modified: python/branches/p3yk-noslice/Lib/Bastion.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/Bastion.py (original)
+++ python/branches/p3yk-noslice/Lib/Bastion.py Fri Feb 23 18:29:35 2007
@@ -165,7 +165,7 @@
print "accessible"
\n"""
exec(testcode)
- print '='*20, "Using rexec:", '='*20
+ print('='*20, "Using rexec:", '='*20)
import rexec
r = rexec.RExec()
m = r.add_module('__main__')
Modified: python/branches/p3yk-noslice/Lib/CGIHTTPServer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/CGIHTTPServer.py (original)
+++ python/branches/p3yk-noslice/Lib/CGIHTTPServer.py Fri Feb 23 18:29:35 2007
@@ -107,7 +107,7 @@
"""Execute a CGI script."""
path = self.path
dir, rest = self.cgi_info
-
+
i = path.find('/', len(dir) + 1)
while i >= 0:
nextdir = path[:i]
Modified: python/branches/p3yk-noslice/Lib/ConfigParser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ConfigParser.py (original)
+++ python/branches/p3yk-noslice/Lib/ConfigParser.py Fri Feb 23 18:29:35 2007
@@ -214,7 +214,7 @@
def sections(self):
"""Return a list of section names, excluding [DEFAULT]"""
# self._sections will never have [DEFAULT] in it
- return self._sections.keys()
+ return list(self._sections.keys())
def add_section(self, section):
"""Create a new section in the configuration.
@@ -242,7 +242,7 @@
opts.update(self._defaults)
if '__name__' in opts:
del opts['__name__']
- return opts.keys()
+ return list(opts.keys())
def read(self, filenames):
"""Read and parse a filename or a list of filenames.
@@ -547,7 +547,7 @@
if vars:
for key, value in vars.items():
d[self.optionxform(key)] = value
- options = d.keys()
+ options = list(d.keys())
if "__name__" in options:
options.remove("__name__")
if raw:
Modified: python/branches/p3yk-noslice/Lib/Cookie.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/Cookie.py (original)
+++ python/branches/p3yk-noslice/Lib/Cookie.py Fri Feb 23 18:29:35 2007
@@ -80,9 +80,9 @@
>>> 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
The load() method of a Cookie extracts cookies from a string. In a
@@ -100,7 +100,7 @@
>>> 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;"
Each element of the Cookie also supports all of the RFC 2109
@@ -110,7 +110,7 @@
>>> C = Cookie.SmartCookie()
>>> C["oreo"] = "doublestuff"
>>> C["oreo"]["path"] = "/"
- >>> print C
+ >>> print(C)
Set-Cookie: oreo=doublestuff; Path=/
Each dictionary element has a 'value' attribute, which gives you
@@ -198,7 +198,7 @@
fact, this simply returns a SmartCookie.
>>> C = Cookie.Cookie()
- >>> print C.__class__.__name__
+ >>> print(C.__class__.__name__)
SmartCookie
@@ -488,8 +488,7 @@
# Now add any defined attributes
if attrs is None:
attrs = self._reserved
- items = self.items()
- items.sort()
+ items = sorted(self.items())
for K,V in items:
if V == "": continue
if K not in attrs: continue
@@ -582,8 +581,7 @@
def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
"""Return a string suitable for HTTP."""
result = []
- items = self.items()
- items.sort()
+ items = sorted(self.items())
for K,V in items:
result.append( V.output(attrs, header) )
return sep.join(result)
@@ -593,8 +591,7 @@
def __repr__(self):
L = []
- items = self.items()
- items.sort()
+ items = sorted(self.items())
for K,V in items:
L.append( '%s=%s' % (K,repr(V.value) ) )
return '<%s: %s>' % (self.__class__.__name__, _spacejoin(L))
@@ -602,8 +599,7 @@
def js_output(self, attrs=None):
"""Return a string suitable for JavaScript."""
result = []
- items = self.items()
- items.sort()
+ items = sorted(self.items())
for K,V in items:
result.append( V.js_output(attrs) )
return _nulljoin(result)
Modified: python/branches/p3yk-noslice/Lib/DocXMLRPCServer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/DocXMLRPCServer.py (original)
+++ python/branches/p3yk-noslice/Lib/DocXMLRPCServer.py Fri Feb 23 18:29:35 2007
@@ -270,9 +270,9 @@
response = self.generate_html_documentation()
- print 'Content-Type: text/html'
- print 'Content-Length: %d' % len(response)
- print
+ print('Content-Type: text/html')
+ print('Content-Length: %d' % len(response))
+ print()
sys.stdout.write(response)
def __init__(self):
Modified: python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py (original)
+++ python/branches/p3yk-noslice/Lib/SimpleXMLRPCServer.py Fri Feb 23 18:29:35 2007
@@ -543,9 +543,9 @@
response = self._marshaled_dispatch(request_text)
- print 'Content-Type: text/xml'
- print 'Content-Length: %d' % len(response)
- print
+ print('Content-Type: text/xml')
+ print('Content-Length: %d' % len(response))
+ print()
sys.stdout.write(response)
def handle_get(self):
@@ -565,10 +565,10 @@
'message' : message,
'explain' : explain
}
- print 'Status: %d %s' % (code, message)
- print 'Content-Type: text/html'
- print 'Content-Length: %d' % len(response)
- print
+ print('Status: %d %s' % (code, message))
+ print('Content-Type: text/html')
+ print('Content-Length: %d' % len(response))
+ print()
sys.stdout.write(response)
def handle_request(self, request_text = None):
@@ -590,7 +590,7 @@
self.handle_xmlrpc(request_text)
if __name__ == '__main__':
- print 'Running XML-RPC server on port 8000'
+ print('Running XML-RPC server on port 8000')
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_function(pow)
server.register_function(lambda x,y: x+y, 'add')
Modified: python/branches/p3yk-noslice/Lib/SocketServer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/SocketServer.py (original)
+++ python/branches/p3yk-noslice/Lib/SocketServer.py Fri Feb 23 18:29:35 2007
@@ -263,12 +263,12 @@
The default is to print a traceback and continue.
"""
- print '-'*40
- print 'Exception happened during processing of request from',
- print client_address
+ print('-'*40)
+ print('Exception happened during processing of request from', end=' ')
+ print(client_address)
import traceback
traceback.print_exc() # XXX But this goes to stderr!
- print '-'*40
+ print('-'*40)
class TCPServer(BaseServer):
Modified: python/branches/p3yk-noslice/Lib/StringIO.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/StringIO.py (original)
+++ python/branches/p3yk-noslice/Lib/StringIO.py Fri Feb 23 18:29:35 2007
@@ -60,7 +60,6 @@
self.buflist = []
self.pos = 0
self.closed = False
- self.softspace = 0
def __iter__(self):
return self
@@ -291,14 +290,14 @@
if f.getvalue() != text:
raise RuntimeError, 'write failed'
length = f.tell()
- print 'File length =', length
+ print('File length =', length)
f.seek(len(lines[0]))
f.write(lines[1])
f.seek(0)
- print 'First line =', repr(f.readline())
- print 'Position =', f.tell()
+ print('First line =', repr(f.readline()))
+ print('Position =', f.tell())
line = f.readline()
- print 'Second line =', repr(line)
+ print('Second line =', repr(line))
f.seek(-len(line), 1)
line2 = f.read(len(line))
if line != line2:
@@ -310,13 +309,13 @@
line2 = f.read()
if line != line2:
raise RuntimeError, 'bad result after seek back from EOF'
- print 'Read', len(list), 'more lines'
- print 'File length =', f.tell()
+ print('Read', len(list), 'more lines')
+ print('File length =', f.tell())
if f.tell() != length:
raise RuntimeError, 'bad length'
f.truncate(length/2)
f.seek(0, 2)
- print 'Truncated length =', f.tell()
+ print('Truncated length =', f.tell())
if f.tell() != length/2:
raise RuntimeError, 'truncate did not adjust length'
f.close()
Modified: python/branches/p3yk-noslice/Lib/UserDict.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/UserDict.py (original)
+++ python/branches/p3yk-noslice/Lib/UserDict.py Fri Feb 23 18:29:35 2007
@@ -42,9 +42,6 @@
return c
def keys(self): return self.data.keys()
def items(self): return self.data.items()
- def iteritems(self): return self.data.iteritems()
- def iterkeys(self): return self.data.iterkeys()
- def itervalues(self): return self.data.itervalues()
def values(self): return self.data.values()
def update(self, dict=None, **kwargs):
if dict is None:
@@ -91,6 +88,8 @@
# methods, progressively more efficiency comes with defining
# __contains__(), __iter__(), and iteritems().
+ # XXX It would make more sense to expect __iter__ to be primitive.
+
# second level definitions support higher levels
def __iter__(self):
for k in self.keys():
@@ -103,11 +102,11 @@
return True
# third level takes advantage of second level definitions
+ def iterkeys(self):
+ return self.__iter__()
def iteritems(self):
for k in self:
yield (k, self[k])
- def iterkeys(self):
- return self.__iter__()
# fourth level uses definitions from lower levels
def itervalues(self):
@@ -118,7 +117,7 @@
def items(self):
return list(self.iteritems())
def clear(self):
- for key in self.keys():
+ for key in list(self.iterkeys()):
del self[key]
def setdefault(self, key, default=None):
try:
@@ -152,6 +151,9 @@
elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups
for k, v in other.iteritems():
self[k] = v
+ elif hasattr(other, 'items'): # items may also save memory and lookups
+ for k, v in other.items():
+ self[k] = v
elif hasattr(other, 'keys'):
for k in other.keys():
self[k] = other[k]
Modified: python/branches/p3yk-noslice/Lib/UserString.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/UserString.py (original)
+++ python/branches/p3yk-noslice/Lib/UserString.py Fri Feb 23 18:29:35 2007
@@ -20,7 +20,7 @@
def __str__(self): return str(self.data)
def __repr__(self): return repr(self.data)
def __int__(self): return int(self.data)
- def __long__(self): return long(self.data)
+ def __long__(self): return int(self.data)
def __float__(self): return float(self.data)
def __complex__(self): return complex(self.data)
def __hash__(self): return hash(self.data)
Modified: python/branches/p3yk-noslice/Lib/_LWPCookieJar.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/_LWPCookieJar.py (original)
+++ python/branches/p3yk-noslice/Lib/_LWPCookieJar.py Fri Feb 23 18:29:35 2007
@@ -37,8 +37,7 @@
if cookie.comment: h.append(("comment", cookie.comment))
if cookie.comment_url: h.append(("commenturl", cookie.comment_url))
- keys = cookie._rest.keys()
- keys.sort()
+ keys = sorted(cookie._rest.keys())
for k in keys:
h.append((k, str(cookie._rest[k])))
Modified: python/branches/p3yk-noslice/Lib/_strptime.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/_strptime.py (original)
+++ python/branches/p3yk-noslice/Lib/_strptime.py Fri Feb 23 18:29:35 2007
@@ -22,9 +22,6 @@
except:
from dummy_thread import allocate_lock as _thread_allocate_lock
-__author__ = "Brett Cannon"
-__email__ = "brett at python.org"
-
__all__ = ['strptime']
def _getlang():
@@ -273,11 +270,31 @@
_CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache
_regex_cache = {}
+def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):
+ """Calculate the Julian day based on the year, week of the year, and day of
+ the week, with week_start_day representing whether the week of the year
+ assumes the week starts on Sunday or Monday (6 or 0)."""
+ first_weekday = datetime_date(year, 1, 1).weekday()
+ # If we are dealing with the %U directive (week starts on Sunday), it's
+ # easier to just shift the view to Sunday being the first day of the
+ # week.
+ if not week_starts_Mon:
+ first_weekday = (first_weekday + 1) % 7
+ day_of_week = (day_of_week + 1) % 7
+ # Need to watch out for a week 0 (when the first day of the year is not
+ # the same as that specified by %U or %W).
+ week_0_length = (7 - first_weekday) % 7
+ if week_of_year == 0:
+ return 1 + day_of_week - first_weekday
+ else:
+ days_to_week = week_0_length + (7 * (week_of_year - 1))
+ return 1 + days_to_week + day_of_week
+
+
def strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
"""Return a time struct based on the input string and the format string."""
global _TimeRE_cache, _regex_cache
- _cache_lock.acquire()
- try:
+ with _cache_lock:
time_re = _TimeRE_cache
locale_time = time_re.locale_time
if _getlang() != locale_time.lang:
@@ -302,8 +319,6 @@
except IndexError:
raise ValueError("stray %% in format '%s'" % format)
_regex_cache[format] = format_regex
- finally:
- _cache_lock.release()
found = format_regex.match(data_string)
if not found:
raise ValueError("time data %r does not match format %r" %
@@ -323,7 +338,7 @@
# values
weekday = julian = -1
found_dict = found.groupdict()
- for group_key in found_dict.iterkeys():
+ for group_key in found_dict.keys():
# Directives not explicitly handled below:
# c, x, X
# handled by making out of other directives
@@ -385,10 +400,10 @@
elif group_key in ('U', 'W'):
week_of_year = int(found_dict[group_key])
if group_key == 'U':
- # U starts week on Sunday
+ # U starts week on Sunday.
week_of_year_start = 6
else:
- # W starts week on Monday
+ # W starts week on Monday.
week_of_year_start = 0
elif group_key == 'Z':
# Since -1 is default value only need to worry about setting tz if
@@ -406,42 +421,20 @@
tz = value
break
# If we know the week of the year and what day of that week, we can figure
- # out the Julian day of the year
- # Calculations below assume 0 is a Monday
+ # out the Julian day of the year.
if julian == -1 and week_of_year != -1 and weekday != -1:
- # Calculate how many days in week 0
- first_weekday = datetime_date(year, 1, 1).weekday()
- preceeding_days = 7 - first_weekday
- if preceeding_days == 7:
- preceeding_days = 0
- # Adjust for U directive so that calculations are not dependent on
- # directive used to figure out week of year
- if weekday == 6 and week_of_year_start == 6:
- week_of_year -= 1
- # If a year starts and ends on a Monday but a week is specified to
- # start on a Sunday we need to up the week to counter-balance the fact
- # that with %W that first Monday starts week 1 while with %U that is
- # week 0 and thus shifts everything by a week
- if weekday == 0 and first_weekday == 0 and week_of_year_start == 6:
- week_of_year += 1
- # If in week 0, then just figure out how many days from Jan 1 to day of
- # week specified, else calculate by multiplying week of year by 7,
- # adding in days in week 0, and the number of days from Monday to the
- # day of the week
- if week_of_year == 0:
- julian = 1 + weekday - first_weekday
- else:
- days_to_week = preceeding_days + (7 * (week_of_year - 1))
- julian = 1 + days_to_week + weekday
+ week_starts_Mon = True if week_of_year_start == 0 else False
+ julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,
+ week_starts_Mon)
# Cannot pre-calculate datetime_date() since can change in Julian
- #calculation and thus could have different value for the day of the week
- #calculation
+ # calculation and thus could have different value for the day of the week
+ # calculation.
if julian == -1:
# Need to add 1 to result since first day of the year is 1, not 0.
julian = datetime_date(year, month, day).toordinal() - \
datetime_date(year, 1, 1).toordinal() + 1
else: # Assume that if they bothered to include Julian day it will
- #be accurate
+ # be accurate.
datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal())
year = datetime_result.year
month = datetime_result.month
Modified: python/branches/p3yk-noslice/Lib/_threading_local.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/_threading_local.py (original)
+++ python/branches/p3yk-noslice/Lib/_threading_local.py Fri Feb 23 18:29:35 2007
@@ -28,8 +28,7 @@
>>> log = []
>>> def f():
- ... items = mydata.__dict__.items()
- ... items.sort()
+ ... items = sorted(mydata.__dict__.items())
... log.append(items)
... mydata.number = 11
... log.append(mydata.number)
Modified: python/branches/p3yk-noslice/Lib/aifc.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/aifc.py (original)
+++ python/branches/p3yk-noslice/Lib/aifc.py Fri Feb 23 18:29:35 2007
@@ -142,7 +142,7 @@
class Error(Exception):
pass
-_AIFC_version = 0xA2805140L # Version 1 of AIFF-C
+_AIFC_version = 0xA2805140 # Version 1 of AIFF-C
_skiplist = 'COMT', 'INST', 'MIDI', 'AESD', \
'APPL', 'NAME', 'AUTH', '(c) ', 'ANNO'
@@ -191,7 +191,7 @@
f = _HUGE_VAL
else:
expon = expon - 16383
- f = (himant * 0x100000000L + lomant) * pow(2.0, expon - 63)
+ f = (himant * 0x100000000 + lomant) * pow(2.0, expon - 63)
return sign * f
def _write_short(f, x):
@@ -233,10 +233,10 @@
expon = expon | sign
fmant = math.ldexp(fmant, 32)
fsmant = math.floor(fmant)
- himant = long(fsmant)
+ himant = int(fsmant)
fmant = math.ldexp(fmant - fsmant, 32)
fsmant = math.floor(fmant)
- lomant = long(fsmant)
+ lomant = int(fsmant)
_write_short(f, expon)
_write_long(f, himant)
_write_long(f, lomant)
@@ -453,7 +453,7 @@
kludge = 0
if chunk.chunksize == 18:
kludge = 1
- print 'Warning: bad COMM chunk size'
+ print('Warning: bad COMM chunk size')
chunk.chunksize = 23
#DEBUG end
self._comptype = chunk.read(4)
@@ -518,11 +518,11 @@
# a position 0 and name ''
self._markers.append((id, pos, name))
except EOFError:
- print 'Warning: MARK chunk contains only',
- print len(self._markers),
- if len(self._markers) == 1: print 'marker',
- else: print 'markers',
- print 'instead of', nmarkers
+ print('Warning: MARK chunk contains only', end=' ')
+ print(len(self._markers), end=' ')
+ if len(self._markers) == 1: print('marker', end=' ')
+ else: print('markers', end=' ')
+ print('instead of', nmarkers)
class Aifc_write:
# Variables used in this class:
@@ -939,16 +939,16 @@
sys.argv.append('/usr/demos/data/audio/bach.aiff')
fn = sys.argv[1]
f = open(fn, 'r')
- print "Reading", fn
- print "nchannels =", f.getnchannels()
- print "nframes =", f.getnframes()
- print "sampwidth =", f.getsampwidth()
- print "framerate =", f.getframerate()
- print "comptype =", f.getcomptype()
- print "compname =", f.getcompname()
+ print("Reading", fn)
+ print("nchannels =", f.getnchannels())
+ print("nframes =", f.getnframes())
+ print("sampwidth =", f.getsampwidth())
+ print("framerate =", f.getframerate())
+ print("comptype =", f.getcomptype())
+ print("compname =", f.getcompname())
if sys.argv[2:]:
gn = sys.argv[2]
- print "Writing", gn
+ print("Writing", gn)
g = open(gn, 'w')
g.setparams(f.getparams())
while 1:
@@ -958,4 +958,4 @@
g.writeframes(data)
g.close()
f.close()
- print "Done."
+ print("Done.")
Modified: python/branches/p3yk-noslice/Lib/asynchat.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/asynchat.py (original)
+++ python/branches/p3yk-noslice/Lib/asynchat.py Fri Feb 23 18:29:35 2007
@@ -105,7 +105,7 @@
# no terminator, collect it all
self.collect_incoming_data (self.ac_in_buffer)
self.ac_in_buffer = ''
- elif isinstance(terminator, int) or isinstance(terminator, long):
+ elif isinstance(terminator, int) or isinstance(terminator, int):
# numeric terminator
n = terminator
if lb < n:
Modified: python/branches/p3yk-noslice/Lib/asyncore.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/asyncore.py (original)
+++ python/branches/p3yk-noslice/Lib/asyncore.py Fri Feb 23 18:29:35 2007
@@ -373,7 +373,7 @@
def log_info(self, message, type='info'):
if __debug__ or type != 'info':
- print '%s: %s' % (type, message)
+ print('%s: %s' % (type, message))
def handle_read_event(self):
if self.accepting:
Modified: python/branches/p3yk-noslice/Lib/atexit.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/atexit.py (original)
+++ python/branches/p3yk-noslice/Lib/atexit.py Fri Feb 23 18:29:35 2007
@@ -26,7 +26,7 @@
exc_info = sys.exc_info()
except:
import traceback
- print >> sys.stderr, "Error in atexit._run_exitfuncs:"
+ print("Error in atexit._run_exitfuncs:", file=sys.stderr)
traceback.print_exc()
exc_info = sys.exc_info()
@@ -53,11 +53,11 @@
if __name__ == "__main__":
def x1():
- print "running x1"
+ print("running x1")
def x2(n):
- print "running x2(%r)" % (n,)
+ print("running x2(%r)" % (n,))
def x3(n, kwd=None):
- print "running x3(%r, kwd=%r)" % (n, kwd)
+ print("running x3(%r, kwd=%r)" % (n, kwd))
register(x1)
register(x2, 12)
Modified: python/branches/p3yk-noslice/Lib/audiodev.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/audiodev.py (original)
+++ python/branches/p3yk-noslice/Lib/audiodev.py Fri Feb 23 18:29:35 2007
@@ -240,7 +240,7 @@
fn = 'f:just samples:just.aif'
import aifc
af = aifc.open(fn, 'r')
- print fn, af.getparams()
+ print(fn, af.getparams())
p = AudioDev()
p.setoutrate(af.getframerate())
p.setsampwidth(af.getsampwidth())
@@ -249,7 +249,7 @@
while 1:
data = af.readframes(BUFSIZ)
if not data: break
- print len(data)
+ print(len(data))
p.writeframes(data)
p.wait()
Modified: python/branches/p3yk-noslice/Lib/base64.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/base64.py (original)
+++ python/branches/p3yk-noslice/Lib/base64.py Fri Feb 23 18:29:35 2007
@@ -126,10 +126,8 @@
8: 'I', 17: 'R', 26: '2',
}
-_b32tab = _b32alphabet.items()
-_b32tab.sort()
-_b32tab = [v for k, v in _b32tab]
-_b32rev = dict([(v, long(k)) for k, v in _b32alphabet.items()])
+_b32tab = [v for k, v in sorted(_b32alphabet.items())]
+_b32rev = dict([(v, int(k)) for k, v in _b32alphabet.items()])
def b32encode(s):
@@ -330,11 +328,11 @@
opts, args = getopt.getopt(sys.argv[1:], 'deut')
except getopt.error as msg:
sys.stdout = sys.stderr
- print msg
- print """usage: %s [-d|-e|-u|-t] [file|-]
+ print(msg)
+ print("""usage: %s [-d|-e|-u|-t] [file|-]
-d, -u: decode
-e: encode (default)
- -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0]
+ -t: encode and decode string 'Aladdin:open sesame'"""%sys.argv[0])
sys.exit(2)
func = encode
for o, a in opts:
@@ -352,7 +350,7 @@
s0 = "Aladdin:open sesame"
s1 = encodestring(s0)
s2 = decodestring(s1)
- print s0, repr(s1), s2
+ print(s0, repr(s1), s2)
if __name__ == '__main__':
Modified: python/branches/p3yk-noslice/Lib/bdb.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bdb.py (original)
+++ python/branches/p3yk-noslice/Lib/bdb.py Fri Feb 23 18:29:35 2007
@@ -58,7 +58,7 @@
return self.trace_dispatch
if event == 'c_return':
return self.trace_dispatch
- print 'bdb.Bdb.dispatch: unknown debugging event:', repr(event)
+ print('bdb.Bdb.dispatch: unknown debugging event:', repr(event))
return self.trace_dispatch
def dispatch_line(self, frame):
@@ -483,17 +483,17 @@
disp = disp + 'yes '
else:
disp = disp + 'no '
- print >>out, '%-4dbreakpoint %s at %s:%d' % (self.number, disp,
- self.file, self.line)
+ print('%-4dbreakpoint %s at %s:%d' % (self.number, disp,
+ self.file, self.line), file=out)
if self.cond:
- print >>out, '\tstop only if %s' % (self.cond,)
+ print('\tstop only if %s' % (self.cond,), file=out)
if self.ignore:
- print >>out, '\tignore next %d hits' % (self.ignore)
+ print('\tignore next %d hits' % (self.ignore), file=out)
if (self.hits):
if (self.hits > 1): ss = 's'
else: ss = ''
- print >>out, ('\tbreakpoint already hit %d time%s' %
- (self.hits, ss))
+ print(('\tbreakpoint already hit %d time%s' %
+ (self.hits, ss)), file=out)
# -----------end of Breakpoint class----------
@@ -582,27 +582,27 @@
def user_call(self, frame, args):
name = frame.f_code.co_name
if not name: name = '???'
- print '+++ call', name, args
+ print('+++ call', name, args)
def user_line(self, frame):
import linecache
name = frame.f_code.co_name
if not name: name = '???'
fn = self.canonic(frame.f_code.co_filename)
line = linecache.getline(fn, frame.f_lineno)
- print '+++', fn, frame.f_lineno, name, ':', line.strip()
+ print('+++', fn, frame.f_lineno, name, ':', line.strip())
def user_return(self, frame, retval):
- print '+++ return', retval
+ print('+++ return', retval)
def user_exception(self, frame, exc_stuff):
- print '+++ exception', exc_stuff
+ print('+++ exception', exc_stuff)
self.set_continue()
def foo(n):
- print 'foo(', n, ')'
+ print('foo(', n, ')')
x = bar(n*10)
- print 'bar returned', x
+ print('bar returned', x)
def bar(a):
- print 'bar(', a, ')'
+ print('bar(', a, ')')
return a/2
def test():
Modified: python/branches/p3yk-noslice/Lib/bsddb/dbrecio.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/dbrecio.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/dbrecio.py Fri Feb 23 18:29:35 2007
@@ -39,7 +39,6 @@
self.len = None
self.pos = 0
self.closed = 0
- self.softspace = 0
def close(self):
if not self.closed:
Modified: python/branches/p3yk-noslice/Lib/bsddb/dbtables.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/dbtables.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/dbtables.py Fri Feb 23 18:29:35 2007
@@ -208,12 +208,12 @@
def _db_print(self) :
"""Print the database to stdout for debugging"""
- print "******** Printing raw database for debugging ********"
+ print("******** Printing raw database for debugging ********")
cur = self.db.cursor()
try:
key, data = cur.first()
while 1:
- print repr({key: data})
+ print(repr({key: data}))
next = cur.next()
if next:
key, data = next
@@ -546,7 +546,7 @@
self.__load_column_info(table)
if columns is None:
columns = self.tablecolumns[table]
- for column in (columns + conditions.keys()):
+ for column in (columns + list(conditions.keys())):
if not self.__tablecolumns[table].count(column):
raise TableDBError, "unknown column: %r" % (column,)
@@ -580,7 +580,7 @@
# leave all unknown condition callables alone as equals
return 0
- conditionlist = conditions.items()
+ conditionlist = list(conditions.items())
conditionlist.sort(cmp_conditions)
# Apply conditions to column data to find what we want
Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_all.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_all.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_all.py Fri Feb 23 18:29:35 2007
@@ -22,15 +22,15 @@
def print_versions():
- print
- print '-=' * 38
- print db.DB_VERSION_STRING
- print 'bsddb.db.version(): %s' % (db.version(), )
- print 'bsddb.db.__version__: %s' % db.__version__
- print 'bsddb.db.cvsid: %s' % db.cvsid
- print 'python version: %s' % sys.version
- print 'My pid: %s' % os.getpid()
- print '-=' * 38
+ print()
+ print('-=' * 38)
+ print(db.DB_VERSION_STRING)
+ print('bsddb.db.version(): %s' % (db.version(), ))
+ print('bsddb.db.__version__: %s' % db.__version__)
+ print('bsddb.db.cvsid: %s' % db.cvsid)
+ print('python version: %s' % sys.version)
+ print('My pid: %s' % os.getpid())
+ print('-=' * 38)
class PrintInfoFakeTest(unittest.TestCase):
Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_associate.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_associate.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_associate.py Fri Feb 23 18:29:35 2007
@@ -114,9 +114,9 @@
def test00_associateDBError(self):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test00_associateDBError..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test00_associateDBError..." % \
+ self.__class__.__name__)
dupDB = db.DB(self.env)
dupDB.set_flags(db.DB_DUP)
@@ -207,9 +207,9 @@
def test01_associateWithDB(self):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test01_associateWithDB..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test01_associateWithDB..." % \
+ self.__class__.__name__)
self.createDB()
@@ -227,9 +227,9 @@
def test02_associateAfterDB(self):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test02_associateAfterDB..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test02_associateAfterDB..." % \
+ self.__class__.__name__)
self.createDB()
self.addDataToDB(self.getDB())
@@ -257,7 +257,7 @@
vals[1].index('unknown')
if verbose:
- print "Primary key traversal:"
+ print("Primary key traversal:")
self.cur = self.getDB().cursor(txn)
count = 0
rec = self.cur.first()
@@ -268,13 +268,13 @@
assert rec[0] and type(rec[0]) == type(0)
count = count + 1
if verbose:
- print rec
+ print(rec)
rec = self.cur.next()
assert count == len(musicdata) # all items accounted for
if verbose:
- print "Secondary key traversal:"
+ print("Secondary key traversal:")
self.cur = secDB.cursor(txn)
count = 0
@@ -294,7 +294,7 @@
while rec is not None:
count = count + 1
if verbose:
- print rec
+ print(rec)
rec = self.cur.next()
# all items accounted for EXCEPT for 1 with "Blues" genre
assert count == len(musicdata)-1
@@ -304,7 +304,7 @@
def getGenre(self, priKey, priData):
assert type(priData) == type("")
if verbose:
- print 'getGenre key: %r data: %r' % (priKey, priData)
+ print('getGenre key: %r data: %r' % (priKey, priData))
genre = string.split(priData, '|')[2]
if genre == 'Blues':
return db.DB_DONOTINDEX
@@ -343,9 +343,9 @@
def test13_associate_in_transaction(self):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test13_associateAutoCommit..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test13_associateAutoCommit..." % \
+ self.__class__.__name__)
txn = self.env.txn_begin()
try:
@@ -389,7 +389,7 @@
def getGenre(self, priKey, priData):
assert type(priData) == type(())
if verbose:
- print 'getGenre key: %r data: %r' % (priKey, priData)
+ print('getGenre key: %r data: %r' % (priKey, priData))
genre = priData[2]
if genre == 'Blues':
return db.DB_DONOTINDEX
Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_basics.py Fri Feb 23 18:29:35 2007
@@ -31,10 +31,10 @@
def test00_version(self):
info = db.version()
if verbose:
- print '\n', '-=' * 20
- print 'bsddb.db.version(): %s' % (info, )
- print db.DB_VERSION_STRING
- print '-=' * 20
+ print('\n', '-=' * 20)
+ print('bsddb.db.version(): %s' % (info, ))
+ print(db.DB_VERSION_STRING)
+ print('-=' * 20)
assert info == (db.DB_VERSION_MAJOR, db.DB_VERSION_MINOR,
db.DB_VERSION_PATCH)
@@ -131,7 +131,7 @@
num = len(d)
if verbose:
- print "created %d records" % num
+ print("created %d records" % num)
def makeData(self, key):
@@ -145,13 +145,13 @@
d = self.d
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test01_GetsAndPuts..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test01_GetsAndPuts..." % self.__class__.__name__)
for key in ['0001', '0100', '0400', '0700', '0999']:
data = d.get(key)
if verbose:
- print data
+ print(data)
assert d.get('0321') == '0321-0321-0321-0321-0321'
@@ -164,7 +164,7 @@
d.delete('abcd')
except db.DBNotFoundError as val:
assert val[0] == db.DB_NOTFOUND
- if verbose: print val
+ if verbose: print(val)
else:
self.fail("expected exception")
@@ -183,7 +183,7 @@
d.put('abcd', 'this should fail', flags=db.DB_NOOVERWRITE)
except db.DBKeyExistError as val:
assert val[0] == db.DB_KEYEXIST
- if verbose: print val
+ if verbose: print(val)
else:
self.fail("expected exception")
@@ -212,7 +212,7 @@
rec = d.get_both('0555', '0555-0555-0555-0555-0555')
if verbose:
- print rec
+ print(rec)
assert d.get_both('0555', 'bad data') == None
@@ -227,7 +227,7 @@
s = d.stat()
assert type(s) == type({})
if verbose:
- print 'd.stat() returned this dictionary:'
+ print('d.stat() returned this dictionary:')
pprint(s)
@@ -237,15 +237,15 @@
d = self.d
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test02_DictionaryMethods..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test02_DictionaryMethods..." % \
+ self.__class__.__name__)
for key in ['0002', '0101', '0401', '0701', '0998']:
data = d[key]
assert data == self.makeData(key)
if verbose:
- print data
+ print(data)
assert len(d) == self._numKeys
keys = d.keys()
@@ -263,7 +263,7 @@
assert len(keys) == self._numKeys+1
if verbose:
- print "the first 10 keys are:"
+ print("the first 10 keys are:")
pprint(keys[:10])
assert d['new record'] == 'a replacement record'
@@ -278,7 +278,7 @@
assert len(items[0]) == 2
if verbose:
- print "the first 10 items are:"
+ print("the first 10 items are:")
pprint(items[:10])
values = d.values()
@@ -286,7 +286,7 @@
assert type(values) == type([])
if verbose:
- print "the first 10 values are:"
+ print("the first 10 values are:")
pprint(values[:10])
@@ -295,9 +295,9 @@
def test03_SimpleCursorStuff(self, get_raises_error=0, set_raises_error=0):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test03_SimpleCursorStuff (get_error %s, set_error %s)..." % \
- (self.__class__.__name__, get_raises_error, set_raises_error)
+ print('\n', '-=' * 30)
+ print("Running %s.test03_SimpleCursorStuff (get_error %s, set_error %s)..." % \
+ (self.__class__.__name__, get_raises_error, set_raises_error))
if self.env and self.dbopenflags & db.DB_AUTO_COMMIT:
txn = self.env.txn_begin()
@@ -310,13 +310,13 @@
while rec is not None:
count = count + 1
if verbose and count % 100 == 0:
- print rec
+ print(rec)
try:
rec = c.next()
except db.DBNotFoundError as val:
if get_raises_error:
assert val[0] == db.DB_NOTFOUND
- if verbose: print val
+ if verbose: print(val)
rec = None
else:
self.fail("unexpected DBNotFoundError")
@@ -330,13 +330,13 @@
while rec is not None:
count = count + 1
if verbose and count % 100 == 0:
- print rec
+ print(rec)
try:
rec = c.prev()
except db.DBNotFoundError as val:
if get_raises_error:
assert val[0] == db.DB_NOTFOUND
- if verbose: print val
+ if verbose: print(val)
rec = None
else:
self.fail("unexpected DBNotFoundError")
@@ -359,7 +359,7 @@
n = c.set('bad key')
except db.DBNotFoundError as val:
assert val[0] == db.DB_NOTFOUND
- if verbose: print val
+ if verbose: print(val)
else:
if set_raises_error:
self.fail("expected exception")
@@ -373,7 +373,7 @@
n = c.get_both('0404', 'bad data')
except db.DBNotFoundError as val:
assert val[0] == db.DB_NOTFOUND
- if verbose: print val
+ if verbose: print(val)
else:
if get_raises_error:
self.fail("expected exception")
@@ -383,16 +383,16 @@
if self.d.get_type() == db.DB_BTREE:
rec = c.set_range('011')
if verbose:
- print "searched for '011', found: ", rec
+ print("searched for '011', found: ", rec)
rec = c.set_range('011',dlen=0,doff=0)
if verbose:
- print "searched (partial) for '011', found: ", rec
+ print("searched (partial) for '011', found: ", rec)
if rec[1] != '': self.fail('expected empty data portion')
ev = c.set_range('empty value')
if verbose:
- print "search for 'empty value' returned", ev
+ print("search for 'empty value' returned", ev)
if ev[1] != '': self.fail('empty value lookup failed')
c.set('0499')
@@ -402,7 +402,7 @@
except db.DBKeyEmptyError as val:
if get_raises_error:
assert val[0] == db.DB_KEYEMPTY
- if verbose: print val
+ if verbose: print(val)
else:
self.fail("unexpected DBKeyEmptyError")
else:
@@ -441,13 +441,13 @@
for method, args in methods_to_test.items():
try:
if verbose:
- print "attempting to use a closed cursor's %s method" % \
- method
+ print("attempting to use a closed cursor's %s method" % \
+ method)
# a bug may cause a NULL pointer dereference...
getattr(c, method)(*args)
except db.DBError as val:
assert val[0] == 0
- if verbose: print val
+ if verbose: print(val)
else:
self.fail("no exception raised when using a buggy cursor's"
"%s method" % method)
@@ -466,9 +466,9 @@
def test03b_SimpleCursorWithoutGetReturnsNone0(self):
# same test but raise exceptions instead of returning None
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \
+ self.__class__.__name__)
old = self.d.set_get_returns_none(0)
assert old == 2
@@ -477,9 +477,9 @@
def test03b_SimpleCursorWithGetReturnsNone1(self):
# same test but raise exceptions instead of returning None
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test03b_SimpleCursorStuffWithoutGetReturnsNone..." % \
+ self.__class__.__name__)
old = self.d.set_get_returns_none(1)
self.test03_SimpleCursorStuff(get_raises_error=0, set_raises_error=1)
@@ -488,9 +488,9 @@
def test03c_SimpleCursorGetReturnsNone2(self):
# same test but raise exceptions instead of returning None
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test03c_SimpleCursorStuffWithoutSetReturnsNone..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test03c_SimpleCursorStuffWithoutSetReturnsNone..." % \
+ self.__class__.__name__)
old = self.d.set_get_returns_none(1)
assert old == 2
@@ -503,9 +503,9 @@
def test04_PartialGetAndPut(self):
d = self.d
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test04_PartialGetAndPut..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test04_PartialGetAndPut..." % \
+ self.__class__.__name__)
key = "partialTest"
data = "1" * 1000 + "2" * 1000
@@ -533,8 +533,8 @@
def test05_GetSize(self):
d = self.d
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test05_GetSize..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test05_GetSize..." % self.__class__.__name__)
for i in range(1, 50000, 500):
key = "size%s" % i
@@ -553,8 +553,8 @@
d = self.d
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test99_Truncate..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test99_Truncate..." % self.__class__.__name__)
d.put("abcde", "ABCDE");
num = d.truncate()
@@ -598,8 +598,8 @@
return
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test07_EnvRemoveAndRename..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test07_EnvRemoveAndRename..." % self.__class__.__name__)
# can't rename or remove an open DB
self.d.close()
@@ -647,8 +647,8 @@
def test06_Transactions(self):
d = self.d
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test06_Transactions..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test06_Transactions..." % self.__class__.__name__)
assert d.get('new rec', txn=self.txn) == None
d.put('new rec', 'this is a new record', self.txn)
@@ -671,7 +671,7 @@
while rec is not None:
count = count + 1
if verbose and count % 100 == 0:
- print rec
+ print(rec)
rec = c.next()
assert count == self._numKeys+1
@@ -696,7 +696,7 @@
assert logs != None
for log in logs:
if verbose:
- print 'log file: ' + log
+ print('log file: ' + log)
if db.version() >= (4,2):
logs = self.env.log_archive(db.DB_ARCH_REMOVE)
assert not logs
@@ -712,8 +712,8 @@
d = self.d
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test07_TxnTruncate..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test07_TxnTruncate..." % self.__class__.__name__)
d.put("abcde", "ABCDE");
txn = self.env.txn_begin()
@@ -762,21 +762,21 @@
def test07_RecnoInBTree(self):
d = self.d
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test07_RecnoInBTree..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test07_RecnoInBTree..." % self.__class__.__name__)
rec = d.get(200)
assert type(rec) == type(())
assert len(rec) == 2
if verbose:
- print "Record #200 is ", rec
+ print("Record #200 is ", rec)
c = d.cursor()
c.set('0200')
num = c.get_recno()
assert type(num) == type(1)
if verbose:
- print "recno of d['0200'] is ", num
+ print("recno of d['0200'] is ", num)
rec = c.current()
assert c.set_recno(num) == rec
@@ -796,9 +796,9 @@
def test08_DuplicateKeys(self):
d = self.d
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test08_DuplicateKeys..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test08_DuplicateKeys..." % \
+ self.__class__.__name__)
d.put("dup0", "before")
for x in "The quick brown fox jumped over the lazy dog.".split():
@@ -808,7 +808,7 @@
data = d.get("dup1")
assert data == "The"
if verbose:
- print data
+ print(data)
c = d.cursor()
rec = c.set("dup1")
@@ -827,14 +827,14 @@
rec = c.set('dup1')
while rec is not None:
if verbose:
- print rec
+ print(rec)
rec = c.next_dup()
c.set('dup1')
rec = c.next_nodup()
assert rec[0] != 'dup1'
if verbose:
- print rec
+ print(rec)
c.close()
@@ -869,8 +869,8 @@
def test09_MultiDB(self):
d1 = self.d
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test09_MultiDB..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test09_MultiDB..." % self.__class__.__name__)
d2 = db.DB(self.env)
d2.open(self.filename, "second", self.dbtype,
@@ -910,7 +910,7 @@
while rec is not None:
count = count + 1
if verbose and (count % 50) == 0:
- print rec
+ print(rec)
rec = c1.next()
assert count == self._numKeys
@@ -919,7 +919,7 @@
while rec is not None:
count = count + 1
if verbose:
- print rec
+ print(rec)
rec = c2.next()
assert count == 9
@@ -928,7 +928,7 @@
while rec is not None:
count = count + 1
if verbose:
- print rec
+ print(rec)
rec = c3.next()
assert count == 52
Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_compat.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_compat.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_compat.py Fri Feb 23 18:29:35 2007
@@ -37,7 +37,7 @@
def test03_rnopen(self):
data = string.split("The quick brown fox jumped over the lazy dog.")
if verbose:
- print "\nTesting: rnopen"
+ print("\nTesting: rnopen")
f = rnopen(self.filename, 'c')
for x in range(len(data)):
@@ -45,7 +45,7 @@
getTest = (f[1], f[2], f[3])
if verbose:
- print '%s %s %s' % getTest
+ print('%s %s %s' % getTest)
assert getTest[1] == 'quick', 'data mismatch!'
@@ -73,7 +73,7 @@
rec = f.first()
while rec:
if verbose:
- print rec
+ print(rec)
try:
rec = f.next()
except KeyError:
@@ -89,17 +89,17 @@
def do_bthash_test(self, factory, what):
if verbose:
- print '\nTesting: ', what
+ print('\nTesting: ', what)
f = factory(self.filename, 'c')
if verbose:
- print 'creation...'
+ print('creation...')
# truth test
if f:
- if verbose: print "truth test: true"
+ if verbose: print("truth test: true")
else:
- if verbose: print "truth test: false"
+ if verbose: print("truth test: false")
f['0'] = ''
f['a'] = 'Guido'
@@ -109,10 +109,10 @@
# 'e' intentionally left out
f['f'] = 'Python'
if verbose:
- print '%s %s %s' % (f['a'], f['b'], f['c'])
+ print('%s %s %s' % (f['a'], f['b'], f['c']))
if verbose:
- print 'key ordering...'
+ print('key ordering...')
start = f.set_location(f.first()[0])
if start != ('0', ''):
self.fail("incorrect first() result: "+repr(start))
@@ -124,7 +124,7 @@
f.previous()
break
if verbose:
- print rec
+ print(rec)
assert f.has_key('f'), 'Error, missing key!'
@@ -147,9 +147,9 @@
# truth test
try:
if f:
- if verbose: print "truth test: true"
+ if verbose: print("truth test: true")
else:
- if verbose: print "truth test: false"
+ if verbose: print("truth test: false")
except db.DBError:
pass
else:
@@ -158,16 +158,16 @@
del f
if verbose:
- print 'modification...'
+ print('modification...')
f = factory(self.filename, 'w')
f['d'] = 'discovered'
if verbose:
- print 'access...'
+ print('access...')
for key in f.keys():
word = f[key]
if verbose:
- print word
+ print(word)
def noRec(f):
rec = f['no such key']
Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_dbshelve.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_dbshelve.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_dbshelve.py Fri Feb 23 18:29:35 2007
@@ -79,8 +79,8 @@
def test01_basics(self):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test01_basics..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test01_basics..." % self.__class__.__name__)
self.populateDB(self.d)
self.d.sync()
@@ -94,9 +94,9 @@
f = d.fd()
if verbose:
- print "length:", l
- print "keys:", k
- print "stats:", s
+ print("length:", l)
+ print("keys:", k)
+ print("stats:", s)
assert 0 == d.has_key('bad key')
assert 1 == d.has_key('IA')
@@ -113,7 +113,7 @@
value = d[key]
values.append(value)
if verbose:
- print "%s: %s" % (key, value)
+ print("%s: %s" % (key, value))
self.checkrec(key, value)
dbvalues = sorted(d.values(), key=lambda x: (str(type(x)), x))
@@ -144,8 +144,8 @@
def test02_cursors(self):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test02_cursors..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test02_cursors..." % self.__class__.__name__)
self.populateDB(self.d)
d = self.d
@@ -156,7 +156,7 @@
while rec is not None:
count = count + 1
if verbose:
- print rec
+ print(rec)
key, value = rec
self.checkrec(key, value)
rec = c.next()
@@ -170,7 +170,7 @@
while rec is not None:
count = count + 1
if verbose:
- print rec
+ print(rec)
key, value = rec
self.checkrec(key, value)
rec = c.prev()
Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_dbtables.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_dbtables.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_dbtables.py Fri Feb 23 18:29:35 2007
@@ -76,6 +76,7 @@
values = self.tdb.Select(
tabname, [colname], conditions={colname: None})
+ values = list(values)
colval = pickle.loads(values[0][colname])
assert(colval > 3.141 and colval < 3.142)
@@ -102,6 +103,7 @@
values = self.tdb.Select(tabname, [col2],
conditions={col0: lambda x: pickle.loads(x) >= 8})
+ values = list(values)
assert len(values) == 2
if values[0]['Species'] == 'Penguin' :
@@ -110,7 +112,7 @@
assert values[1]['Species'] == 'Penguin'
else :
if verbose:
- print "values= %r" % (values,)
+ print("values= %r" % (values,))
raise "Wrong values returned!"
def test03(self):
@@ -120,15 +122,15 @@
except dbtables.TableDBError:
pass
if verbose:
- print '...before CreateTable...'
+ print('...before CreateTable...')
self.tdb._db_print()
self.tdb.CreateTable(tabname, ['a', 'b', 'c', 'd', 'e'])
if verbose:
- print '...after CreateTable...'
+ print('...after CreateTable...')
self.tdb._db_print()
self.tdb.Drop(tabname)
if verbose:
- print '...after Drop...'
+ print('...after Drop...')
self.tdb._db_print()
self.tdb.CreateTable(tabname, ['a', 'b', 'c', 'd', 'e'])
@@ -179,11 +181,13 @@
values = self.tdb.Select(
tabname, ['a', 'd', 'b'],
conditions={'e': dbtables.PrefixCond('Fuzzy')})
+ values = list(values)
assert len(values) == 1
assert values[0]['d'] == None
values = self.tdb.Select(tabname, ['b'],
conditions={'c': lambda c: c == 'meep'})
+ values = list(values)
assert len(values) == 1
assert values[0]['b'] == "bad"
@@ -272,6 +276,7 @@
values = self.tdb.Select(
tabname, ['p', 'e'],
conditions={'e': dbtables.PrefixCond('the l')})
+ values = list(values)
assert len(values) == 2, values
assert values[0]['e'] == values[1]['e'], values
assert values[0]['p'] != values[1]['p'], values
@@ -279,6 +284,7 @@
values = self.tdb.Select(
tabname, ['d', 'a'],
conditions={'a': dbtables.LikeCond('%aardvark%')})
+ values = list(values)
assert len(values) == 1, values
assert values[0]['d'] == "is for dog", values
assert values[0]['a'] == "is for aardvark", values
@@ -290,6 +296,7 @@
'd':dbtables.ExactCond('is for dog'),
'c':dbtables.PrefixCond('is for'),
'p':lambda s: not s})
+ values = list(values)
assert len(values) == 1, values
assert values[0]['d'] == "is for dog", values
assert values[0]['a'] == "is for aardvark", values
@@ -354,6 +361,7 @@
values = self.tdb.Select(
tabname, None,
conditions={'Type': dbtables.ExactCond('Unknown')})
+ values = list(values)
assert len(values) == 1, values
assert values[0]['Name'] == None, values
assert values[0]['Access'] == None, values
@@ -362,6 +370,7 @@
values = self.tdb.Select(
tabname, None,
conditions={'Name': dbtables.ExactCond('Nifty.MP3')})
+ values = list(values)
assert len(values) == 1, values
assert values[0]['Type'] == "MP3", values
assert values[0]['Access'] == "2", values
@@ -369,6 +378,7 @@
# Make sure change applied only to select conditions
values = self.tdb.Select(
tabname, None, conditions={'Name': dbtables.LikeCond('%doc%')})
+ values = list(values)
assert len(values) == 1, values
assert values[0]['Type'] == "Word", values
assert values[0]['Access'] == "9", values
Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_join.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_join.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_join.py Fri Feb 23 18:29:35 2007
@@ -65,9 +65,9 @@
def test01_join(self):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test01_join..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test01_join..." % \
+ self.__class__.__name__)
# create and populate primary index
priDB = db.DB(self.env)
Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_lock.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_lock.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_lock.py Fri Feb 23 18:29:35 2007
@@ -49,27 +49,27 @@
def test01_simple(self):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test01_simple..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test01_simple..." % self.__class__.__name__)
anID = self.env.lock_id()
if verbose:
- print "locker ID: %s" % anID
+ print("locker ID: %s" % anID)
lock = self.env.lock_get(anID, "some locked thing", db.DB_LOCK_WRITE)
if verbose:
- print "Aquired lock: %s" % lock
+ print("Aquired lock: %s" % lock)
time.sleep(1)
self.env.lock_put(lock)
if verbose:
- print "Released lock: %s" % lock
+ print("Released lock: %s" % lock)
def test02_threaded(self):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test02_threaded..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test02_threaded..." % self.__class__.__name__)
threads = []
threads.append(Thread(target = self.theThread,
@@ -113,17 +113,17 @@
anID = self.env.lock_id()
if verbose:
- print "%s: locker ID: %s" % (name, anID)
+ print("%s: locker ID: %s" % (name, anID))
lock = self.env.lock_get(anID, "some locked thing", lockType)
if verbose:
- print "%s: Aquired %s lock: %s" % (name, lt, lock)
+ print("%s: Aquired %s lock: %s" % (name, lt, lock))
time.sleep(sleepTime)
self.env.lock_put(lock)
if verbose:
- print "%s: Released %s lock: %s" % (name, lt, lock)
+ print("%s: Released %s lock: %s" % (name, lt, lock))
#----------------------------------------------------------------------
Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_queue.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_queue.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_queue.py Fri Feb 23 18:29:35 2007
@@ -34,15 +34,15 @@
# Basic Queue tests using the deprecated DBCursor.consume method.
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test01_basic..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test01_basic..." % self.__class__.__name__)
d = db.DB()
d.set_re_len(40) # Queues must be fixed length
d.open(self.filename, db.DB_QUEUE, db.DB_CREATE)
if verbose:
- print "before appends" + '-' * 30
+ print("before appends" + '-' * 30)
pprint(d.stat())
for x in string.letters:
@@ -58,7 +58,7 @@
assert len(d) == 55
if verbose:
- print "before close" + '-' * 30
+ print("before close" + '-' * 30)
pprint(d.stat())
d.close()
@@ -67,25 +67,25 @@
d.open(self.filename)
if verbose:
- print "after open" + '-' * 30
+ print("after open" + '-' * 30)
pprint(d.stat())
d.append("one more")
c = d.cursor()
if verbose:
- print "after append" + '-' * 30
+ print("after append" + '-' * 30)
pprint(d.stat())
rec = c.consume()
while rec:
if verbose:
- print rec
+ print(rec)
rec = c.consume()
c.close()
if verbose:
- print "after consume loop" + '-' * 30
+ print("after consume loop" + '-' * 30)
pprint(d.stat())
assert len(d) == 0, \
@@ -101,12 +101,12 @@
# (No cursor needed)
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test02_basicPost32..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test02_basicPost32..." % self.__class__.__name__)
if db.version() < (3, 2, 0):
if verbose:
- print "Test not run, DB not new enough..."
+ print("Test not run, DB not new enough...")
return
d = db.DB()
@@ -114,7 +114,7 @@
d.open(self.filename, db.DB_QUEUE, db.DB_CREATE)
if verbose:
- print "before appends" + '-' * 30
+ print("before appends" + '-' * 30)
pprint(d.stat())
for x in string.letters:
@@ -130,7 +130,7 @@
assert len(d) == 55
if verbose:
- print "before close" + '-' * 30
+ print("before close" + '-' * 30)
pprint(d.stat())
d.close()
@@ -140,23 +140,23 @@
#d.set_get_returns_none(true)
if verbose:
- print "after open" + '-' * 30
+ print("after open" + '-' * 30)
pprint(d.stat())
d.append("one more")
if verbose:
- print "after append" + '-' * 30
+ print("after append" + '-' * 30)
pprint(d.stat())
rec = d.consume()
while rec:
if verbose:
- print rec
+ print(rec)
rec = d.consume()
if verbose:
- print "after consume loop" + '-' * 30
+ print("after consume loop" + '-' * 30)
pprint(d.stat())
d.close()
Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_recno.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_recno.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_recno.py Fri Feb 23 18:29:35 2007
@@ -45,9 +45,9 @@
assert type(recno) == type(0)
assert recno >= 1
if verbose:
- print recno,
+ print(recno, end=' ')
- if verbose: print
+ if verbose: print()
stat = d.stat()
if verbose:
@@ -56,7 +56,7 @@
for recno in range(1, len(d)+1):
data = d[recno]
if verbose:
- print data
+ print(data)
assert type(data) == type("")
assert data == d.get(recno)
@@ -65,7 +65,7 @@
data = d[0] # This should raise a KeyError!?!?!
except db.DBInvalidArgError as val:
assert val[0] == db.EINVAL
- if verbose: print val
+ if verbose: print(val)
else:
self.fail("expected exception")
@@ -94,7 +94,7 @@
keys = d.keys()
if verbose:
- print keys
+ print(keys)
assert type(keys) == type([])
assert type(keys[0]) == type(123)
assert len(keys) == len(d)
@@ -120,23 +120,23 @@
data = d.get_both(26, "z" * 60)
assert data == "z" * 60
if verbose:
- print data
+ print(data)
fd = d.fd()
if verbose:
- print fd
+ print(fd)
c = d.cursor()
rec = c.first()
while rec:
if verbose:
- print rec
+ print(rec)
rec = c.next()
c.set(50)
rec = c.current()
if verbose:
- print rec
+ print(rec)
c.put(-1, "a replacement record", db.DB_CURRENT)
@@ -144,18 +144,18 @@
rec = c.current()
assert rec == (50, "a replacement record")
if verbose:
- print rec
+ print(rec)
rec = c.set_range(30)
if verbose:
- print rec
+ print(rec)
# test that non-existant key lookups work (and that
# DBC_set_range doesn't have a memleak under valgrind)
rec = c.set_range(999999)
assert rec == None
if verbose:
- print rec
+ print(rec)
c.close()
d.close()
@@ -182,7 +182,7 @@
self.fail("unexpected DBKeyEmptyError exception")
else:
assert val[0] == db.DB_KEYEMPTY
- if verbose: print val
+ if verbose: print(val)
else:
if not get_returns_none:
self.fail("expected exception")
@@ -190,7 +190,7 @@
rec = c.set(40)
while rec:
if verbose:
- print rec
+ print(rec)
rec = c.next()
c.close()
@@ -227,9 +227,9 @@
text = open(source, 'r').read()
text = text.strip()
if verbose:
- print text
- print data
- print text.split('\n')
+ print(text)
+ print(data)
+ print(text.split('\n'))
assert text.split('\n') == data
@@ -247,8 +247,8 @@
text = open(source, 'r').read()
text = text.strip()
if verbose:
- print text
- print text.split('\n')
+ print(text)
+ print(text.split('\n'))
assert text.split('\n') == \
"The quick reddish-brown fox jumped over the comatose dog".split()
@@ -269,7 +269,7 @@
d.append('bad' * 20)
except db.DBInvalidArgError as val:
assert val[0] == db.EINVAL
- if verbose: print val
+ if verbose: print(val)
else:
self.fail("expected exception")
@@ -277,7 +277,7 @@
rec = c.first()
while rec:
if verbose:
- print rec
+ print(rec)
rec = c.next()
c.close()
Modified: python/branches/p3yk-noslice/Lib/bsddb/test/test_thread.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/bsddb/test/test_thread.py (original)
+++ python/branches/p3yk-noslice/Lib/bsddb/test/test_thread.py Fri Feb 23 18:29:35 2007
@@ -93,9 +93,9 @@
def test01_1WriterMultiReaders(self):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test01_1WriterMultiReaders..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test01_1WriterMultiReaders..." % \
+ self.__class__.__name__)
threads = []
for x in range(self.writers):
@@ -123,17 +123,17 @@
start = howMany * writerNum
stop = howMany * (writerNum + 1) - 1
if verbose:
- print "%s: creating records %d - %d" % (name, start, stop)
+ print("%s: creating records %d - %d" % (name, start, stop))
for x in range(start, stop):
key = '%04d' % x
dbutils.DeadlockWrap(d.put, key, self.makeData(key),
max_retries=12)
if verbose and x % 100 == 0:
- print "%s: records %d - %d finished" % (name, start, x)
+ print("%s: records %d - %d finished" % (name, start, x))
if verbose:
- print "%s: finished creating records" % name
+ print("%s: finished creating records" % name)
## # Each write-cursor will be exclusive, the only one that can update the DB...
## if verbose: print "%s: deleting a few records" % name
@@ -147,7 +147,7 @@
## c.close()
if verbose:
- print "%s: thread finished" % name
+ print("%s: thread finished" % name)
def readerThread(self, d, readerNum):
time.sleep(0.01 * readerNum)
@@ -163,12 +163,12 @@
self.assertEqual(self.makeData(key), data)
rec = c.next()
if verbose:
- print "%s: found %d records" % (name, count)
+ print("%s: found %d records" % (name, count))
c.close()
time.sleep(0.05)
if verbose:
- print "%s: thread finished" % name
+ print("%s: thread finished" % name)
class BTreeConcurrentDataStore(ConcurrentDataStoreBase):
@@ -199,8 +199,8 @@
def test02_SimpleLocks(self):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test02_SimpleLocks..." % self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test02_SimpleLocks..." % self.__class__.__name__)
threads = []
for x in range(self.writers):
@@ -226,7 +226,7 @@
start = howMany * writerNum
stop = howMany * (writerNum + 1) - 1
if verbose:
- print "%s: creating records %d - %d" % (name, start, stop)
+ print("%s: creating records %d - %d" % (name, start, stop))
# create a bunch of records
for x in xrange(start, stop):
@@ -235,7 +235,7 @@
max_retries=12)
if verbose and x % 100 == 0:
- print "%s: records %d - %d finished" % (name, start, x)
+ print("%s: records %d - %d finished" % (name, start, x))
# do a bit or reading too
if random() <= 0.05:
@@ -249,22 +249,22 @@
dbutils.DeadlockWrap(d.sync, max_retries=12)
except db.DBIncompleteError as val:
if verbose:
- print "could not complete sync()..."
+ print("could not complete sync()...")
# read them back, deleting a few
for x in xrange(start, stop):
key = '%04d' % x
data = dbutils.DeadlockWrap(d.get, key, max_retries=12)
if verbose and x % 100 == 0:
- print "%s: fetched record (%s, %s)" % (name, key, data)
+ print("%s: fetched record (%s, %s)" % (name, key, data))
self.assertEqual(data, self.makeData(key))
if random() <= 0.10:
dbutils.DeadlockWrap(d.delete, key, max_retries=12)
if verbose:
- print "%s: deleted record %s" % (name, key)
+ print("%s: deleted record %s" % (name, key))
if verbose:
- print "%s: thread finished" % name
+ print("%s: thread finished" % name)
def readerThread(self, d, readerNum):
time.sleep(0.01 * readerNum)
@@ -280,12 +280,12 @@
self.assertEqual(self.makeData(key), data)
rec = dbutils.DeadlockWrap(c.next, max_retries=10)
if verbose:
- print "%s: found %d records" % (name, count)
+ print("%s: found %d records" % (name, count))
c.close()
time.sleep(0.05)
if verbose:
- print "%s: thread finished" % name
+ print("%s: thread finished" % name)
class BTreeSimpleThreaded(SimpleThreadedBase):
@@ -318,9 +318,9 @@
def test03_ThreadedTransactions(self):
if verbose:
- print '\n', '-=' * 30
- print "Running %s.test03_ThreadedTransactions..." % \
- self.__class__.__name__
+ print('\n', '-=' * 30)
+ print("Running %s.test03_ThreadedTransactions..." % \
+ self.__class__.__name__)
threads = []
for x in range(self.writers):
@@ -357,12 +357,12 @@
key = '%04d' % x
d.put(key, self.makeData(key), txn)
if verbose and x % 100 == 0:
- print "%s: records %d - %d finished" % (name, start, x)
+ print("%s: records %d - %d finished" % (name, start, x))
txn.commit()
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[1]))
txn.abort()
time.sleep(0.05)
@@ -371,16 +371,16 @@
start = howMany * writerNum
stop = howMany * (writerNum + 1) - 1
if verbose:
- print "%s: creating records %d - %d" % (name, start, stop)
+ print("%s: creating records %d - %d" % (name, start, stop))
step = 100
for x in range(start, stop, step):
self.doWrite(d, name, x, min(stop, x+step))
if verbose:
- print "%s: finished creating records" % name
+ print("%s: finished creating records" % name)
if verbose:
- print "%s: deleting a few records" % name
+ print("%s: deleting a few records" % name)
finished = False
while not finished:
@@ -397,15 +397,15 @@
txn.commit()
finished = True
if verbose:
- print "%s: deleted records %s" % (name, recs)
+ 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[1]))
txn.abort()
time.sleep(0.05)
if verbose:
- print "%s: thread finished" % name
+ print("%s: thread finished" % name)
def readerThread(self, d, readerNum):
time.sleep(0.01 * readerNum + 0.05)
@@ -424,13 +424,13 @@
key, data = rec
self.assertEqual(self.makeData(key), data)
rec = c.next()
- if verbose: print "%s: found %d records" % (name, count)
+ if verbose: print("%s: found %d records" % (name, count))
c.close()
txn.commit()
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[1]))
c.close()
txn.abort()
time.sleep(0.05)
@@ -438,7 +438,7 @@
time.sleep(0.05)
if verbose:
- print "%s: thread finished" % name
+ print("%s: thread finished" % name)
def deadlockThread(self):
self.doLockDetect = True
@@ -448,8 +448,8 @@
aborted = self.env.lock_detect(
db.DB_LOCK_RANDOM, db.DB_LOCK_CONFLICT)
if verbose and aborted:
- print "deadlock: Aborted %d deadlocked transaction(s)" \
- % aborted
+ print("deadlock: Aborted %d deadlocked transaction(s)" \
+ % aborted)
except db.DBError:
pass
@@ -497,7 +497,7 @@
suite.addTest(unittest.makeSuite(HashThreadedNoWaitTransactions))
else:
- print "Threads not available, skipping thread tests."
+ print("Threads not available, skipping thread tests.")
return suite
Modified: python/branches/p3yk-noslice/Lib/cProfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/cProfile.py (original)
+++ python/branches/p3yk-noslice/Lib/cProfile.py Fri Feb 23 18:29:35 2007
@@ -58,8 +58,8 @@
# Backwards compatibility.
def help():
- print "Documentation for the profile/cProfile modules can be found "
- print "in the Python Library Reference, section 'The Python Profiler'."
+ print("Documentation for the profile/cProfile modules can be found ")
+ print("in the Python Library Reference, section 'The Python Profiler'.")
# ____________________________________________________________
Modified: python/branches/p3yk-noslice/Lib/calendar.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/calendar.py (original)
+++ python/branches/p3yk-noslice/Lib/calendar.py Fri Feb 23 18:29:35 2007
@@ -261,7 +261,7 @@
"""
Print a single week (no newline).
"""
- print self.week(theweek, width),
+ print(self.week(theweek, width), end=' ')
def formatday(self, day, weekday, width):
"""
@@ -308,7 +308,7 @@
"""
Print a month's calendar.
"""
- print self.formatmonth(theyear, themonth, w, l),
+ print(self.formatmonth(theyear, themonth, w, l), end=' ')
def formatmonth(self, theyear, themonth, w=0, l=0):
"""
@@ -365,7 +365,7 @@
def pryear(self, theyear, w=0, l=0, c=6, m=3):
"""Print a year's calendar."""
- print self.formatyear(theyear, w, l, c, m)
+ print(self.formatyear(theyear, w, l, c, m))
class HTMLCalendar(Calendar):
@@ -584,7 +584,7 @@
def format(cols, colwidth=_colwidth, spacing=_spacing):
"""Prints multi-column formatting for year calendars"""
- print formatstring(cols, colwidth, spacing)
+ print(formatstring(cols, colwidth, spacing))
def formatstring(cols, colwidth=_colwidth, spacing=_spacing):
@@ -668,9 +668,9 @@
encoding = sys.getdefaultencoding()
optdict = dict(encoding=encoding, css=options.css)
if len(args) == 1:
- print cal.formatyearpage(datetime.date.today().year, **optdict)
+ print(cal.formatyearpage(datetime.date.today().year, **optdict))
elif len(args) == 2:
- print cal.formatyearpage(int(args[1]), **optdict)
+ print(cal.formatyearpage(int(args[1]), **optdict))
else:
parser.error("incorrect number of arguments")
sys.exit(1)
@@ -694,7 +694,7 @@
sys.exit(1)
if options.encoding:
result = result.encode(options.encoding)
- print result
+ print(result)
if __name__ == "__main__":
Modified: python/branches/p3yk-noslice/Lib/cgi.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/cgi.py (original)
+++ python/branches/p3yk-noslice/Lib/cgi.py Fri Feb 23 18:29:35 2007
@@ -901,8 +901,8 @@
the script in HTML form.
"""
- print "Content-type: text/html"
- print
+ print("Content-type: text/html")
+ print()
sys.stderr = sys.stdout
try:
form = FieldStorage() # Replace with other classes to test those
@@ -915,12 +915,12 @@
exec("testing print_exception() -- <I>italics?</I>")
def g(f=f):
f()
- print "<H3>What follows is a test, not an actual exception:</H3>"
+ print("<H3>What follows is a test, not an actual exception:</H3>")
g()
except:
print_exception()
- print "<H1>Second try with a small maxlen...</H1>"
+ print("<H1>Second try with a small maxlen...</H1>")
global maxlen
maxlen = 50
@@ -937,67 +937,67 @@
if type is None:
type, value, tb = sys.exc_info()
import traceback
- print
- print "<H3>Traceback (most recent call last):</H3>"
+ print()
+ print("<H3>Traceback (most recent call last):</H3>")
list = traceback.format_tb(tb, limit) + \
traceback.format_exception_only(type, value)
- print "<PRE>%s<B>%s</B></PRE>" % (
+ print("<PRE>%s<B>%s</B></PRE>" % (
escape("".join(list[:-1])),
escape(list[-1]),
- )
+ ))
del tb
def print_environ(environ=os.environ):
"""Dump the shell environment as HTML."""
keys = environ.keys()
keys.sort()
- print
- print "<H3>Shell Environment:</H3>"
- print "<DL>"
+ print()
+ print("<H3>Shell Environment:</H3>")
+ print("<DL>")
for key in keys:
- print "<DT>", escape(key), "<DD>", escape(environ[key])
- print "</DL>"
- print
+ print("<DT>", escape(key), "<DD>", escape(environ[key]))
+ print("</DL>")
+ print()
def print_form(form):
"""Dump the contents of a form as HTML."""
keys = form.keys()
keys.sort()
- print
- print "<H3>Form Contents:</H3>"
+ print()
+ print("<H3>Form Contents:</H3>")
if not keys:
- print "<P>No form fields."
- print "<DL>"
+ print("<P>No form fields.")
+ print("<DL>")
for key in keys:
- print "<DT>" + escape(key) + ":",
+ print("<DT>" + escape(key) + ":", end=' ')
value = form[key]
- print "<i>" + escape(repr(type(value))) + "</i>"
- print "<DD>" + escape(repr(value))
- print "</DL>"
- print
+ print("<i>" + escape(repr(type(value))) + "</i>")
+ print("<DD>" + escape(repr(value)))
+ print("</DL>")
+ print()
def print_directory():
"""Dump the current directory as HTML."""
- print
- print "<H3>Current Working Directory:</H3>"
+ print()
+ print("<H3>Current Working Directory:</H3>")
try:
pwd = os.getcwd()
except os.error as msg:
- print "os.error:", escape(str(msg))
+ print("os.error:", escape(str(msg)))
else:
- print escape(pwd)
- print
+ print(escape(pwd))
+ print()
def print_arguments():
- print
- print "<H3>Command Line Arguments:</H3>"
- print
- print sys.argv
- print
+ print()
+ print("<H3>Command Line Arguments:</H3>")
+ print()
+ print(sys.argv)
+ print()
def print_environ_usage():
"""Dump a list of environment variables used by CGI as HTML."""
- print """
+ print("""
<H3>These environment variables could have been set:</H3>
<UL>
<LI>AUTH_TYPE
@@ -1036,7 +1036,7 @@
<LI>HTTP_REFERER
<LI>HTTP_USER_AGENT
</UL>
-"""
+""")
# Utilities
Modified: python/branches/p3yk-noslice/Lib/code.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/code.py (original)
+++ python/branches/p3yk-noslice/Lib/code.py Fri Feb 23 18:29:35 2007
@@ -12,19 +12,6 @@
__all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact",
"compile_command"]
-def softspace(file, newvalue):
- oldvalue = 0
- try:
- oldvalue = file.softspace
- except AttributeError:
- pass
- try:
- file.softspace = newvalue
- except (AttributeError, TypeError):
- # "attribute-less object" or "read-only attributes"
- pass
- return oldvalue
-
class InteractiveInterpreter:
"""Base class for InteractiveConsole.
@@ -105,9 +92,6 @@
raise
except:
self.showtraceback()
- else:
- if softspace(sys.stdout, 0):
- print
def showsyntaxerror(self, filename=None):
"""Display the syntax error that just occurred.
Modified: python/branches/p3yk-noslice/Lib/compileall.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/compileall.py (original)
+++ python/branches/p3yk-noslice/Lib/compileall.py Fri Feb 23 18:29:35 2007
@@ -33,11 +33,11 @@
"""
if not quiet:
- print 'Listing', dir, '...'
+ print('Listing', dir, '...')
try:
names = os.listdir(dir)
except os.error:
- print "Can't list", dir
+ print("Can't list", dir)
names = []
names.sort()
success = 1
@@ -60,18 +60,18 @@
except os.error: ctime = 0
if (ctime > ftime) and not force: continue
if not quiet:
- print 'Compiling', fullname, '...'
+ print('Compiling', fullname, '...')
try:
ok = py_compile.compile(fullname, None, dfile, True)
except KeyboardInterrupt:
raise KeyboardInterrupt
except py_compile.PyCompileError as err:
if quiet:
- print 'Compiling', fullname, '...'
- print err.msg
+ print('Compiling', fullname, '...')
+ print(err.msg)
success = 0
except IOError as e:
- print "Sorry", e
+ print("Sorry", e)
success = 0
else:
if ok == 0:
@@ -98,7 +98,7 @@
success = 1
for dir in sys.path:
if (not dir or dir == os.curdir) and skip_curdir:
- print 'Skipping current directory'
+ print('Skipping current directory')
else:
success = success and compile_dir(dir, maxlevels, None,
force, quiet=quiet)
@@ -110,16 +110,16 @@
try:
opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:')
except getopt.error as msg:
- print msg
- print "usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \
- "[-x regexp] [directory ...]"
- print "-l: don't recurse down"
- print "-f: force rebuild even if timestamps are up-to-date"
- print "-q: quiet operation"
- print "-d destdir: purported directory name for error messages"
- print " if no directory arguments, -l sys.path is assumed"
- print "-x regexp: skip files matching the regular expression regexp"
- print " the regexp is search for in the full path of the file"
+ print(msg)
+ print("usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \
+ "[-x regexp] [directory ...]")
+ print("-l: don't recurse down")
+ print("-f: force rebuild even if timestamps are up-to-date")
+ print("-q: quiet operation")
+ print("-d destdir: purported directory name for error messages")
+ print(" if no directory arguments, -l sys.path is assumed")
+ print("-x regexp: skip files matching the regular expression regexp")
+ print(" the regexp is search for in the full path of the file")
sys.exit(2)
maxlevels = 10
ddir = None
@@ -136,7 +136,7 @@
rx = re.compile(a)
if ddir:
if len(args) != 1:
- print "-d destdir require exactly one directory argument"
+ print("-d destdir require exactly one directory argument")
sys.exit(2)
success = 1
try:
@@ -148,7 +148,7 @@
else:
success = compile_path()
except KeyboardInterrupt:
- print "\n[interrupt]"
+ print("\n[interrupt]")
success = 0
return success
Modified: python/branches/p3yk-noslice/Lib/compiler/ast.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/compiler/ast.py (original)
+++ python/branches/p3yk-noslice/Lib/compiler/ast.py Fri Feb 23 18:29:35 2007
@@ -998,50 +998,6 @@
def __repr__(self):
return "Power((%s, %s))" % (repr(self.left), repr(self.right))
-class Print(Node):
- def __init__(self, nodes, dest, lineno=None):
- self.nodes = nodes
- self.dest = dest
- self.lineno = lineno
-
- def getChildren(self):
- children = []
- children.extend(flatten(self.nodes))
- children.append(self.dest)
- return tuple(children)
-
- def getChildNodes(self):
- nodelist = []
- nodelist.extend(flatten_nodes(self.nodes))
- if self.dest is not None:
- nodelist.append(self.dest)
- return tuple(nodelist)
-
- def __repr__(self):
- return "Print(%s, %s)" % (repr(self.nodes), repr(self.dest))
-
-class Printnl(Node):
- def __init__(self, nodes, dest, lineno=None):
- self.nodes = nodes
- self.dest = dest
- self.lineno = lineno
-
- def getChildren(self):
- children = []
- children.extend(flatten(self.nodes))
- children.append(self.dest)
- return tuple(children)
-
- def getChildNodes(self):
- nodelist = []
- nodelist.extend(flatten_nodes(self.nodes))
- if self.dest is not None:
- nodelist.append(self.dest)
- return tuple(nodelist)
-
- def __repr__(self):
- return "Printnl(%s, %s)" % (repr(self.nodes), repr(self.dest))
-
class Raise(Node):
def __init__(self, expr1, expr2, expr3, lineno=None):
self.expr1 = expr1
@@ -1381,6 +1337,6 @@
def __repr__(self):
return "Yield(%s)" % (repr(self.value),)
-for name, obj in globals().items():
+for name, obj in list(globals().items()):
if isinstance(obj, type) and issubclass(obj, Node):
nodes[name.lower()] = obj
Modified: python/branches/p3yk-noslice/Lib/compiler/future.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/compiler/future.py (original)
+++ python/branches/p3yk-noslice/Lib/compiler/future.py Fri Feb 23 18:29:35 2007
@@ -65,9 +65,9 @@
from compiler import parseFile, walk
for file in sys.argv[1:]:
- print file
+ print(file)
tree = parseFile(file)
v = FutureParser()
walk(tree, v)
- print v.found
- print
+ print(v.found)
+ print()
Modified: python/branches/p3yk-noslice/Lib/compiler/misc.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/compiler/misc.py (original)
+++ python/branches/p3yk-noslice/Lib/compiler/misc.py Fri Feb 23 18:29:35 2007
@@ -18,7 +18,7 @@
def add(self, elt):
self.elts[elt] = elt
def elements(self):
- return self.elts.keys()
+ return list(self.elts.keys())
def has_elt(self, elt):
return elt in self.elts
def remove(self, elt):
Modified: python/branches/p3yk-noslice/Lib/compiler/pyassem.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/compiler/pyassem.py (original)
+++ python/branches/p3yk-noslice/Lib/compiler/pyassem.py Fri Feb 23 18:29:35 2007
@@ -19,10 +19,10 @@
def startBlock(self, block):
if self._debug:
if self.current:
- print "end", repr(self.current)
- print " next", self.current.next
- print " ", self.current.get_children()
- print repr(block)
+ print("end", repr(self.current))
+ print(" next", self.current.next)
+ print(" ", self.current.get_children())
+ print(repr(block))
self.current = block
def nextBlock(self, block=None):
@@ -68,7 +68,7 @@
def emit(self, *inst):
if self._debug:
- print "\t", inst
+ print("\t", inst)
if inst[0] in ['RETURN_VALUE', 'YIELD_VALUE']:
self.current.addOutEdge(self.exit)
if len(inst) == 2 and isinstance(inst[1], Block):
@@ -400,12 +400,12 @@
for t in self.insts:
opname = t[0]
if opname == "SET_LINENO":
- print
+ print()
if len(t) == 1:
- print "\t", "%3d" % pc, opname
+ print("\t", "%3d" % pc, opname)
pc = pc + 1
else:
- print "\t", "%3d" % pc, opname, t[1]
+ print("\t", "%3d" % pc, opname, t[1])
pc = pc + 3
if io:
sys.stdout = save
@@ -504,7 +504,7 @@
if name in cells]
for name in self.cellvars:
del cells[name]
- self.cellvars = self.cellvars + cells.keys()
+ self.cellvars = self.cellvars + list(cells.keys())
self.closure = self.cellvars + self.freevars
def _lookupName(self, name, list):
@@ -573,7 +573,7 @@
# similarly for other opcodes...
- for name, obj in locals().items():
+ for name, obj in list(locals().items()):
if name[:9] == "_convert_":
opname = name[9:]
_converters[opname] = obj
@@ -601,8 +601,8 @@
try:
lnotab.addCode(self.opnum[opname], lo, hi)
except ValueError:
- print opname, oparg
- print self.opnum[opname], lo, hi
+ print(opname, oparg)
+ print(self.opnum[opname], lo, hi)
raise
self.stage = DONE
@@ -744,7 +744,7 @@
for i in insts:
opname = i[0]
if debug:
- print i,
+ print(i, end=' ')
delta = self.effect.get(opname, None)
if delta is not None:
depth = depth + delta
@@ -763,7 +763,7 @@
if depth > maxDepth:
maxDepth = depth
if debug:
- print depth, maxDepth
+ print(depth, maxDepth)
return maxDepth
effect = {
@@ -772,8 +772,7 @@
'LIST_APPEND': -2,
'STORE_SUBSCR': -3,
'DELETE_SUBSCR': -2,
- # PRINT_EXPR?
- 'PRINT_ITEM': -1,
+ 'PRINT_EXPR': -1,
'RETURN_VALUE': -1,
'YIELD_VALUE': -1,
'BUILD_CLASS': -2,
Modified: python/branches/p3yk-noslice/Lib/compiler/pycodegen.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/compiler/pycodegen.py (original)
+++ python/branches/p3yk-noslice/Lib/compiler/pycodegen.py Fri Feb 23 18:29:35 2007
@@ -112,7 +112,7 @@
gen = ModuleCodeGenerator(tree)
if display:
import pprint
- print pprint.pprint(tree)
+ print(pprint.pprint(tree))
self.code = gen.getCode()
def dump(self, f):
@@ -914,6 +914,8 @@
self.emit('LOAD_CONST', None)
self.nextBlock(final)
self.setups.push((END_FINALLY, final))
+ self._implicitNameOp('LOAD', exitvar)
+ self._implicitNameOp('DELETE', exitvar)
self.emit('WITH_CLEANUP')
self.emit('END_FINALLY')
self.setups.pop()
@@ -1016,7 +1018,7 @@
self.set_lineno(node)
self.delName(node.name)
else:
- print "oops", node.flags
+ print("oops", node.flags)
def visitAssAttr(self, node):
self.visit(node.expr)
@@ -1025,8 +1027,8 @@
elif node.flags == 'OP_DELETE':
self.emit('DELETE_ATTR', self.mangle(node.attrname))
else:
- print "warning: unexpected flags:", node.flags
- print node
+ print("warning: unexpected flags:", node.flags)
+ print(node)
def _visitAssSequence(self, node, op='UNPACK_SEQUENCE'):
if findOp(node) != 'OP_DELETE':
@@ -1111,29 +1113,6 @@
opcode = callfunc_opcode_info[have_star, have_dstar]
self.emit(opcode, kw << 8 | pos)
- def visitPrint(self, node, newline=0):
- self.set_lineno(node)
- if node.dest:
- self.visit(node.dest)
- for child in node.nodes:
- if node.dest:
- self.emit('DUP_TOP')
- self.visit(child)
- if node.dest:
- self.emit('ROT_TWO')
- self.emit('PRINT_ITEM_TO')
- else:
- self.emit('PRINT_ITEM')
- if node.dest and not newline:
- self.emit('POP_TOP')
-
- def visitPrintnl(self, node):
- self.visitPrint(node, newline=1)
- if node.dest:
- self.emit('PRINT_NEWLINE_TO')
- else:
- self.emit('PRINT_NEWLINE')
-
def visitReturn(self, node):
self.set_lineno(node)
self.visit(node.value)
Modified: python/branches/p3yk-noslice/Lib/compiler/symbols.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/compiler/symbols.py (original)
+++ python/branches/p3yk-noslice/Lib/compiler/symbols.py Fri Feb 23 18:29:35 2007
@@ -76,12 +76,12 @@
return self.children
def DEBUG(self):
- print >> sys.stderr, self.name, self.nested and "nested" or ""
- print >> sys.stderr, "\tglobals: ", self.globals
- print >> sys.stderr, "\tcells: ", self.cells
- print >> sys.stderr, "\tdefs: ", self.defs
- print >> sys.stderr, "\tuses: ", self.uses
- print >> sys.stderr, "\tfrees:", self.frees
+ print(self.name, self.nested and "nested" or "", file=sys.stderr)
+ print("\tglobals: ", self.globals, file=sys.stderr)
+ print("\tcells: ", self.cells, file=sys.stderr)
+ print("\tdefs: ", self.defs, file=sys.stderr)
+ print("\tuses: ", self.uses, file=sys.stderr)
+ print("\tfrees:", self.frees, file=sys.stderr)
def check_name(self, name):
"""Return scope of name.
@@ -429,7 +429,7 @@
if not (s.startswith('_[') or s.startswith('.'))]
for file in sys.argv[1:]:
- print file
+ print(file)
f = open(file)
buf = f.read()
f.close()
@@ -443,10 +443,10 @@
names2 = s.scopes[tree].get_names()
if not list_eq(mod_names, names2):
- print
- print "oops", file
- print sorted(mod_names)
- print sorted(names2)
+ print()
+ print("oops", file)
+ print(sorted(mod_names))
+ print(sorted(names2))
sys.exit(-1)
d = {}
@@ -460,11 +460,11 @@
l = [sc for sc in scopes
if sc.name == s.get_name()]
if len(l) > 1:
- print "skipping", s.get_name()
+ print("skipping", s.get_name())
else:
if not list_eq(get_names(s.get_namespace()),
l[0].get_names()):
- print s.get_name()
- print sorted(get_names(s.get_namespace()))
- print sorted(l[0].get_names())
+ print(s.get_name())
+ print(sorted(get_names(s.get_namespace())))
+ print(sorted(l[0].get_names()))
sys.exit(-1)
Modified: python/branches/p3yk-noslice/Lib/compiler/syntax.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/compiler/syntax.py (original)
+++ python/branches/p3yk-noslice/Lib/compiler/syntax.py Fri Feb 23 18:29:35 2007
@@ -32,7 +32,7 @@
def error(self, node, msg):
self.errors = self.errors + 1
if self.multi is not None:
- print "%s:%s: %s" % (node.filename, node.lineno, msg)
+ print("%s:%s: %s" % (node.filename, node.lineno, msg))
else:
raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno)
Modified: python/branches/p3yk-noslice/Lib/compiler/transformer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/compiler/transformer.py (original)
+++ python/branches/p3yk-noslice/Lib/compiler/transformer.py Fri Feb 23 18:29:35 2007
@@ -86,7 +86,7 @@
try:
return nodes[kind](*args[1:])
except TypeError:
- print nodes[kind], len(args), args
+ print(nodes[kind], len(args), args)
raise
else:
raise WalkerError, "Can't find appropriate Node type: %s" % str(args)
@@ -387,26 +387,6 @@
return AugAssign(lval, op[1], exprNode, lineno=op[2])
raise WalkerError, "can't get here"
- def print_stmt(self, nodelist):
- # print ([ test (',' test)* [','] ] | '>>' test [ (',' test)+ [','] ])
- items = []
- if len(nodelist) == 1:
- start = 1
- dest = None
- elif nodelist[1][0] == token.RIGHTSHIFT:
- assert len(nodelist) == 3 \
- or nodelist[3][0] == token.COMMA
- dest = self.com_node(nodelist[2])
- start = 4
- else:
- dest = None
- start = 1
- for i in range(start, len(nodelist), 2):
- items.append(self.com_node(nodelist[i]))
- if nodelist[-1][0] == token.COMMA:
- return Print(items, dest, lineno=nodelist[0][2])
- return Printnl(items, dest, lineno=nodelist[0][2])
-
def del_stmt(self, nodelist):
return self.com_assign(nodelist[1], OP_DELETE)
@@ -1018,7 +998,7 @@
if nodelist[2][0] == token.COLON:
var = None
else:
- var = self.com_node(nodelist[2])
+ var = self.com_assign(nodelist[2][2], OP_ASSIGN)
return With(expr, var, body, lineno=nodelist[0][2])
def com_with_var(self, nodelist):
@@ -1458,7 +1438,6 @@
symbol.simple_stmt,
symbol.compound_stmt,
symbol.expr_stmt,
- symbol.print_stmt,
symbol.del_stmt,
symbol.pass_stmt,
symbol.break_stmt,
Modified: python/branches/p3yk-noslice/Lib/compiler/visitor.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/compiler/visitor.py (original)
+++ python/branches/p3yk-noslice/Lib/compiler/visitor.py Fri Feb 23 18:29:35 2007
@@ -79,20 +79,20 @@
meth = getattr(self.visitor, 'visit' + className, 0)
self._cache[node.__class__] = meth
if self.VERBOSE > 1:
- print "dispatch", className, (meth and meth.__name__ or '')
+ print("dispatch", className, (meth and meth.__name__ or ''))
if meth:
meth(node, *args)
elif self.VERBOSE > 0:
klass = node.__class__
if klass not in self.examples:
self.examples[klass] = klass
- print
- print self.visitor
- print klass
+ print()
+ print(self.visitor)
+ print(klass)
for attr in dir(node):
if attr[0] != '_':
- print "\t", "%-12.12s" % attr, getattr(node, attr)
- print
+ print("\t", "%-12.12s" % attr, getattr(node, attr))
+ print()
return self.default(node, *args)
# XXX this is an API change
@@ -107,7 +107,7 @@
return walker.visitor
def dumpNode(node):
- print node.__class__
+ print(node.__class__)
for attr in dir(node):
if attr[0] != '_':
- print "\t", "%-10.10s" % attr, getattr(node, attr)
+ print("\t", "%-10.10s" % attr, getattr(node, attr))
Modified: python/branches/p3yk-noslice/Lib/cookielib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/cookielib.py (original)
+++ python/branches/p3yk-noslice/Lib/cookielib.py Fri Feb 23 18:29:35 2007
@@ -1171,8 +1171,7 @@
def vals_sorted_by_key(adict):
- keys = adict.keys()
- keys.sort()
+ keys = sorted(adict.keys())
return map(adict.get, keys)
def deepvalues(mapping):
@@ -1318,26 +1317,26 @@
self._cookies_lock.acquire()
try:
- self._policy._now = self._now = int(time.time())
+ self._policy._now = self._now = int(time.time())
+
+ cookies = self._cookies_for_request(request)
- cookies = self._cookies_for_request(request)
+ attrs = self._cookie_attrs(cookies)
+ if attrs:
+ if not request.has_header("Cookie"):
+ request.add_unredirected_header(
+ "Cookie", "; ".join(attrs))
+
+ # if necessary, advertise that we know RFC 2965
+ if (self._policy.rfc2965 and not self._policy.hide_cookie2 and
+ not request.has_header("Cookie2")):
+ for cookie in cookies:
+ if cookie.version != 1:
+ request.add_unredirected_header("Cookie2", '$Version="1"')
+ break
- attrs = self._cookie_attrs(cookies)
- if attrs:
- if not request.has_header("Cookie"):
- request.add_unredirected_header(
- "Cookie", "; ".join(attrs))
-
- # if necessary, advertise that we know RFC 2965
- if (self._policy.rfc2965 and not self._policy.hide_cookie2 and
- not request.has_header("Cookie2")):
- for cookie in cookies:
- if cookie.version != 1:
- request.add_unredirected_header("Cookie2", '$Version="1"')
- break
-
finally:
- self._cookies_lock.release()
+ self._cookies_lock.release()
self.clear_expired_cookies()
@@ -1609,7 +1608,7 @@
if self._policy.set_ok(cookie, request):
self.set_cookie(cookie)
-
+
finally:
self._cookies_lock.release()
@@ -1632,14 +1631,14 @@
_debug("extract_cookies: %s", response.info())
self._cookies_lock.acquire()
try:
- self._policy._now = self._now = int(time.time())
+ self._policy._now = self._now = int(time.time())
- for cookie in self.make_cookies(response, request):
- if self._policy.set_ok(cookie, request):
- _debug(" setting cookie: %s", cookie)
- self.set_cookie(cookie)
+ for cookie in self.make_cookies(response, request):
+ if self._policy.set_ok(cookie, request):
+ _debug(" setting cookie: %s", cookie)
+ self.set_cookie(cookie)
finally:
- self._cookies_lock.release()
+ self._cookies_lock.release()
def clear(self, domain=None, path=None, name=None):
"""Clear some cookies.
@@ -1677,11 +1676,11 @@
"""
self._cookies_lock.acquire()
try:
- for cookie in self:
- if cookie.discard:
- self.clear(cookie.domain, cookie.path, cookie.name)
+ for cookie in self:
+ if cookie.discard:
+ self.clear(cookie.domain, cookie.path, cookie.name)
finally:
- self._cookies_lock.release()
+ self._cookies_lock.release()
def clear_expired_cookies(self):
"""Discard all expired cookies.
@@ -1695,12 +1694,12 @@
"""
self._cookies_lock.acquire()
try:
- now = time.time()
- for cookie in self:
- if cookie.is_expired(now):
- self.clear(cookie.domain, cookie.path, cookie.name)
+ now = time.time()
+ for cookie in self:
+ if cookie.is_expired(now):
+ self.clear(cookie.domain, cookie.path, cookie.name)
finally:
- self._cookies_lock.release()
+ self._cookies_lock.release()
def __iter__(self):
return deepvalues(self._cookies)
@@ -1774,16 +1773,16 @@
self._cookies_lock.acquire()
try:
- old_state = copy.deepcopy(self._cookies)
- self._cookies = {}
- try:
- self.load(filename, ignore_discard, ignore_expires)
- except (LoadError, IOError):
- self._cookies = old_state
- raise
+ old_state = copy.deepcopy(self._cookies)
+ self._cookies = {}
+ try:
+ self.load(filename, ignore_discard, ignore_expires)
+ except (LoadError, IOError):
+ self._cookies = old_state
+ raise
finally:
- self._cookies_lock.release()
+ self._cookies_lock.release()
from _LWPCookieJar import LWPCookieJar, lwp_cookie_str
from _MozillaCookieJar import MozillaCookieJar
Modified: python/branches/p3yk-noslice/Lib/copy.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/copy.py (original)
+++ python/branches/p3yk-noslice/Lib/copy.py Fri Feb 23 18:29:35 2007
@@ -99,7 +99,7 @@
def _copy_immutable(x):
return x
-for t in (type(None), int, long, float, bool, str, tuple,
+for t in (type(None), int, int, float, bool, str, tuple,
frozenset, type, xrange, types.ClassType,
types.BuiltinFunctionType,
types.FunctionType):
@@ -178,7 +178,7 @@
return x
d[type(None)] = _deepcopy_atomic
d[int] = _deepcopy_atomic
-d[long] = _deepcopy_atomic
+d[int] = _deepcopy_atomic
d[float] = _deepcopy_atomic
d[bool] = _deepcopy_atomic
try:
@@ -230,7 +230,7 @@
def _deepcopy_dict(x, memo):
y = {}
memo[id(x)] = y
- for key, value in x.iteritems():
+ for key, value in x.items():
y[deepcopy(key, memo)] = deepcopy(value, memo)
return y
d[dict] = _deepcopy_dict
@@ -302,7 +302,7 @@
if state is not None:
y.__dict__.update(state)
if slotstate is not None:
- for key, value in slotstate.iteritems():
+ for key, value in slotstate.items():
setattr(y, key, value)
return y
@@ -315,14 +315,14 @@
pass
def _test():
- l = [None, 1, 2L, 3.14, 'xyzzy', (1, 2L), [3.14, 'abc'],
+ l = [None, 1, 2, 3.14, 'xyzzy', (1, 2), [3.14, 'abc'],
{'abc': 'ABC'}, (), [], {}]
l1 = copy(l)
- print l1==l
+ print(l1==l)
l1 = map(copy, l)
- print l1==l
+ print(l1==l)
l1 = deepcopy(l)
- print l1==l
+ print(l1==l)
class C:
def __init__(self, arg=None):
self.a = 1
@@ -337,7 +337,7 @@
def __getstate__(self):
return {'a': self.a, 'arg': self.arg}
def __setstate__(self, state):
- for key, value in state.iteritems():
+ for key, value in state.items():
setattr(self, key, value)
def __deepcopy__(self, memo=None):
new = self.__class__(deepcopy(self.arg, memo))
@@ -346,26 +346,26 @@
c = C('argument sketch')
l.append(c)
l2 = copy(l)
- print l == l2
- print l
- print l2
+ print(l == l2)
+ print(l)
+ print(l2)
l2 = deepcopy(l)
- print l == l2
- print l
- print l2
+ print(l == l2)
+ print(l)
+ print(l2)
l.append({l[1]: l, 'xyz': l[2]})
l3 = copy(l)
import repr
- print map(repr.repr, l)
- print map(repr.repr, l1)
- print map(repr.repr, l2)
- print map(repr.repr, l3)
+ print(map(repr.repr, l))
+ print(map(repr.repr, l1))
+ print(map(repr.repr, l2))
+ print(map(repr.repr, l3))
l3 = deepcopy(l)
import repr
- print map(repr.repr, l)
- print map(repr.repr, l1)
- print map(repr.repr, l2)
- print map(repr.repr, l3)
+ print(map(repr.repr, l))
+ print(map(repr.repr, l1))
+ print(map(repr.repr, l2))
+ print(map(repr.repr, l3))
if __name__ == '__main__':
_test()
Modified: python/branches/p3yk-noslice/Lib/csv.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/csv.py (original)
+++ python/branches/p3yk-noslice/Lib/csv.py Fri Feb 23 18:29:35 2007
@@ -278,7 +278,7 @@
charFrequency[char] = metaFrequency
for char in charFrequency.keys():
- items = charFrequency[char].items()
+ items = list(charFrequency[char].items())
if len(items) == 1 and items[0][0] == 0:
continue
# get the mode of the frequencies
@@ -308,7 +308,7 @@
consistency -= 0.01
if len(delims) == 1:
- delim = delims.keys()[0]
+ delim = list(delims.keys())[0]
skipinitialspace = (data[0].count(delim) ==
data[0].count("%c " % delim))
return (delim, skipinitialspace)
@@ -367,9 +367,9 @@
if len(row) != columns:
continue # skip rows that have irregular number of columns
- for col in columnTypes.keys():
+ for col in list(columnTypes.keys()):
- for thisType in [int, long, float, complex]:
+ for thisType in [int, int, float, complex]:
try:
thisType(row[col])
break
@@ -380,7 +380,7 @@
thisType = len(row[col])
# treat longs as ints
- if thisType == long:
+ if thisType == int:
thisType = int
if thisType != columnTypes[col]:
Modified: python/branches/p3yk-noslice/Lib/ctypes/__init__.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/__init__.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/__init__.py Fri Feb 23 18:29:35 2007
@@ -5,7 +5,7 @@
import os as _os, sys as _sys
-__version__ = "1.0.1"
+__version__ = "1.1.0"
from _ctypes import Union, Structure, Array
from _ctypes import _Pointer
@@ -66,7 +66,7 @@
buf = buftype()
buf.value = init
return buf
- elif isinstance(init, (int, long)):
+ elif isinstance(init, (int, int)):
buftype = c_char * init
buf = buftype()
return buf
@@ -133,6 +133,18 @@
from _ctypes import sizeof, byref, addressof, alignment, resize
from _ctypes import _SimpleCData
+def _check_size(typ, typecode=None):
+ # Check if sizeof(ctypes_type) against struct.calcsize. This
+ # should protect somewhat against a misconfigured libffi.
+ from struct import calcsize
+ if typecode is None:
+ # Most _type_ codes are the same as used in struct
+ typecode = typ._type_
+ actual, required = sizeof(typ), calcsize(typecode)
+ if actual != required:
+ raise SystemError("sizeof(%s) wrong: %d instead of %d" % \
+ (typ, actual, required))
+
class py_object(_SimpleCData):
_type_ = "O"
def __repr__(self):
@@ -140,18 +152,23 @@
return super(py_object, self).__repr__()
except ValueError:
return "%s(<NULL>)" % type(self).__name__
+_check_size(py_object, "P")
class c_short(_SimpleCData):
_type_ = "h"
+_check_size(c_short)
class c_ushort(_SimpleCData):
_type_ = "H"
+_check_size(c_ushort)
class c_long(_SimpleCData):
_type_ = "l"
+_check_size(c_long)
class c_ulong(_SimpleCData):
_type_ = "L"
+_check_size(c_ulong)
if _calcsize("i") == _calcsize("l"):
# if int and long have the same size, make c_int an alias for c_long
@@ -160,15 +177,19 @@
else:
class c_int(_SimpleCData):
_type_ = "i"
+ _check_size(c_int)
class c_uint(_SimpleCData):
_type_ = "I"
+ _check_size(c_uint)
class c_float(_SimpleCData):
_type_ = "f"
+_check_size(c_float)
class c_double(_SimpleCData):
_type_ = "d"
+_check_size(c_double)
if _calcsize("l") == _calcsize("q"):
# if long and long long have the same size, make c_longlong an alias for c_long
@@ -177,33 +198,40 @@
else:
class c_longlong(_SimpleCData):
_type_ = "q"
+ _check_size(c_longlong)
class c_ulonglong(_SimpleCData):
_type_ = "Q"
## def from_param(cls, val):
## return ('d', float(val), val)
## from_param = classmethod(from_param)
+ _check_size(c_ulonglong)
class c_ubyte(_SimpleCData):
_type_ = "B"
c_ubyte.__ctype_le__ = c_ubyte.__ctype_be__ = c_ubyte
# backward compatibility:
##c_uchar = c_ubyte
+_check_size(c_ubyte)
class c_byte(_SimpleCData):
_type_ = "b"
c_byte.__ctype_le__ = c_byte.__ctype_be__ = c_byte
+_check_size(c_byte)
class c_char(_SimpleCData):
_type_ = "c"
c_char.__ctype_le__ = c_char.__ctype_be__ = c_char
+_check_size(c_char)
class c_char_p(_SimpleCData):
_type_ = "z"
+_check_size(c_char_p, "P")
class c_void_p(_SimpleCData):
_type_ = "P"
c_voidp = c_void_p # backwards compatibility (to a bug)
+_check_size(c_void_p)
# This cache maps types to pointers to them.
_pointer_type_cache = {}
@@ -257,7 +285,7 @@
buf = buftype()
buf.value = init
return buf
- elif isinstance(init, (int, long)):
+ elif isinstance(init, (int, int)):
buftype = c_wchar * init
buf = buftype()
return buf
@@ -328,7 +356,7 @@
def __getitem__(self, name_or_ordinal):
func = self._FuncPtr((name_or_ordinal, self))
- if not isinstance(name_or_ordinal, (int, long)):
+ if not isinstance(name_or_ordinal, (int, int)):
func.__name__ = name_or_ordinal
return func
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/__init__.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/__init__.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/__init__.py Fri Feb 23 18:29:35 2007
@@ -41,7 +41,7 @@
hasattr(package.__loader__, '_files')):
path = package.__name__.replace(".", os.path.sep)
mask = os.path.join(path, mask)
- for fnm in package.__loader__._files.iterkeys():
+ for fnm in package.__loader__._files.keys():
if fnmatch.fnmatchcase(fnm, mask):
yield os.path.splitext(fnm)[0].replace(os.path.sep, ".")
else:
@@ -60,10 +60,10 @@
except ResourceDenied as detail:
skipped.append(modname)
if verbosity > 1:
- print >> sys.stderr, "Skipped %s: %s" % (modname, detail)
+ print("Skipped %s: %s" % (modname, detail), file=sys.stderr)
continue
except Exception as detail:
- print >> sys.stderr, "Warning: could not import %s: %s" % (modname, detail)
+ print("Warning: could not import %s: %s" % (modname, detail), file=sys.stderr)
continue
for name in dir(mod):
if name.startswith("_"):
@@ -74,7 +74,7 @@
return skipped, tests
def usage():
- print __doc__
+ print(__doc__)
return 1
def test_with_refcounts(runner, verbosity, testcase):
@@ -106,9 +106,9 @@
cleanup()
refcounts[i] = sys.gettotalrefcount() - rc
if filter(None, refcounts):
- print "%s leaks:\n\t" % testcase, refcounts
+ print("%s leaks:\n\t" % testcase, refcounts)
elif verbosity:
- print "%s: ok." % testcase
+ print("%s: ok." % testcase)
class TestRunner(unittest.TextTestRunner):
def run(self, test, skipped):
@@ -166,7 +166,7 @@
try:
sys.gettotalrefcount
except AttributeError:
- print >> sys.stderr, "-r flag requires Python debug build"
+ print("-r flag requires Python debug build", file=sys.stderr)
return -1
search_leaks = True
elif flag == "-u":
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_as_parameter.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_as_parameter.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_as_parameter.py Fri Feb 23 18:29:35 2007
@@ -133,7 +133,7 @@
f.argtypes = [c_longlong, MyCallback]
def callback(value):
- self.failUnless(isinstance(value, (int, long)))
+ self.failUnless(isinstance(value, (int, int)))
return value & 0x7FFFFFFF
cb = MyCallback(callback)
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_byteswap.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_byteswap.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_byteswap.py Fri Feb 23 18:29:35 2007
@@ -15,7 +15,7 @@
class Test(unittest.TestCase):
def X_test(self):
- print >> sys.stderr, sys.byteorder
+ print(sys.byteorder, file=sys.stderr)
for i in range(32):
bits = BITS()
setattr(bits, "i%s" % i, 1)
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_find.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_find.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_find.py Fri Feb 23 18:29:35 2007
@@ -22,12 +22,12 @@
## print, for debugging
if is_resource_enabled("printing"):
if lib_gl or lib_glu or lib_glut or lib_gle:
- print "OpenGL libraries:"
+ print("OpenGL libraries:")
for item in (("GL", lib_gl),
("GLU", lib_glu),
("glut", lib_glut),
("gle", lib_gle)):
- print "\t", item
+ print("\t", item)
# On some systems, loading the OpenGL libraries needs the RTLD_GLOBAL mode.
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_functions.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_functions.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_functions.py Fri Feb 23 18:29:35 2007
@@ -291,7 +291,7 @@
f.argtypes = [c_longlong, MyCallback]
def callback(value):
- self.failUnless(isinstance(value, (int, long)))
+ self.failUnless(isinstance(value, (int, int)))
return value & 0x7FFFFFFF
cb = MyCallback(callback)
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_keeprefs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_keeprefs.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_keeprefs.py Fri Feb 23 18:29:35 2007
@@ -100,13 +100,13 @@
x = X()
i = c_char_p("abc def")
from sys import getrefcount as grc
- print "2?", grc(i)
+ print("2?", grc(i))
x.p = pointer(i)
- print "3?", grc(i)
+ print("3?", grc(i))
for i in range(320):
c_int(99)
x.p[0]
- print x.p[0]
+ print(x.p[0])
## del x
## print "2?", grc(i)
## del i
@@ -115,14 +115,14 @@
for i in range(320):
c_int(99)
x.p[0]
- print x.p[0]
- print x.p.contents
+ print(x.p[0])
+ print(x.p.contents)
## print x._objects
x.p[0] = "spam spam"
## print x.p[0]
- print "+" * 42
- print x._objects
+ print("+" * 42)
+ print(x._objects)
class PointerToStructure(unittest.TestCase):
def test(self):
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_loading.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_loading.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_loading.py Fri Feb 23 18:29:35 2007
@@ -15,7 +15,7 @@
libc_name = find_library("c")
if is_resource_enabled("printing"):
- print "libc_name is", libc_name
+ print("libc_name is", libc_name)
class LoaderTest(unittest.TestCase):
@@ -44,8 +44,8 @@
if os.name in ("nt", "ce"):
def test_load_library(self):
if is_resource_enabled("printing"):
- print find_library("kernel32")
- print find_library("user32")
+ print(find_library("kernel32"))
+ print(find_library("user32"))
if os.name == "nt":
windll.kernel32.GetModuleHandleW
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_numbers.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_numbers.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_numbers.py Fri Feb 23 18:29:35 2007
@@ -93,7 +93,7 @@
for t in float_types:
self.failUnlessEqual(t(2.0).value, 2.0)
self.failUnlessEqual(t(2).value, 2.0)
- self.failUnlessEqual(t(2L).value, 2.0)
+ self.failUnlessEqual(t(2).value, 2.0)
def test_integers(self):
# integers cannot be constructed from floats
@@ -192,7 +192,7 @@
for i in items:
func(); func(); func(); func(); func()
stop = clock()
- print "%15s: %.2f us" % (msg, ((stop-start)*1e6/5/rep))
+ print("%15s: %.2f us" % (msg, ((stop-start)*1e6/5/rep)))
def check_perf():
# Construct 5 objects
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_objects.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_objects.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_objects.py Fri Feb 23 18:29:35 2007
@@ -13,7 +13,7 @@
>>> from ctypes import *
>>> array = (c_char_p * 5)()
->>> print array._objects
+>>> print(array._objects)
None
>>>
@@ -34,14 +34,14 @@
... _fields_ = [("x", c_int), ("y", c_int), ("array", c_char_p * 5)]
...
>>> x = X()
->>> print x._objects
+>>> print(x._objects)
None
>>>
The'array' attribute of the 'x' object shares part of the memory buffer
of 'x' ('_b_base_' is either None, or the root object owning the memory block):
->>> print x.array._b_base_ # doctest: +ELLIPSIS
+>>> print(x.array._b_base_) # doctest: +ELLIPSIS
<ctypes.test.test_objects.X object at 0x...>
>>>
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_pointers.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_pointers.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_pointers.py Fri Feb 23 18:29:35 2007
@@ -5,8 +5,8 @@
ctype_types = [c_byte, c_ubyte, c_short, c_ushort, c_int, c_uint,
c_long, c_ulong, c_longlong, c_ulonglong, c_double, c_float]
-python_types = [int, int, int, int, int, long,
- int, long, long, long, float, float]
+python_types = [int, int, int, int, int, int,
+ int, int, int, int, float, float]
class PointersTestCase(unittest.TestCase):
@@ -160,16 +160,16 @@
def test_c_void_p(self):
# http://sourceforge.net/tracker/?func=detail&aid=1518190&group_id=5470&atid=105470
if sizeof(c_void_p) == 4:
- self.failUnlessEqual(c_void_p(0xFFFFFFFFL).value,
+ self.failUnlessEqual(c_void_p(0xFFFFFFFF).value,
c_void_p(-1).value)
- self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFFL).value,
+ self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFF).value,
c_void_p(-1).value)
elif sizeof(c_void_p) == 8:
- self.failUnlessEqual(c_void_p(0xFFFFFFFFL).value,
- 0xFFFFFFFFL)
- self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFFL).value,
+ self.failUnlessEqual(c_void_p(0xFFFFFFFF).value,
+ 0xFFFFFFFF)
+ self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFF).value,
c_void_p(-1).value)
- self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFFFFFFFFFFL).value,
+ self.failUnlessEqual(c_void_p(0xFFFFFFFFFFFFFFFFFFFFFFFF).value,
c_void_p(-1).value)
self.assertRaises(TypeError, c_void_p, 3.14) # make sure floats are NOT accepted
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_prototypes.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_prototypes.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_prototypes.py Fri Feb 23 18:29:35 2007
@@ -33,7 +33,7 @@
# View the bits in `a` as unsigned instead.
import struct
num_bits = struct.calcsize("P") * 8 # num bits in native machine address
- a += 1L << num_bits
+ a += 1 << num_bits
assert a >= 0
return a
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_strings.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_strings.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_strings.py Fri Feb 23 18:29:35 2007
@@ -189,7 +189,7 @@
for i in items:
func(arg); func(arg); func(arg); func(arg); func(arg)
stop = clock()
- print "%20s: %.2f us" % (msg, ((stop-start)*1e6/5/rep))
+ print("%20s: %.2f us" % (msg, ((stop-start)*1e6/5/rep)))
def check_perf():
# Construct 5 objects
Modified: python/branches/p3yk-noslice/Lib/ctypes/test/test_win32.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/test/test_win32.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/test/test_win32.py Fri Feb 23 18:29:35 2007
@@ -32,12 +32,32 @@
# or wrong calling convention
self.assertRaises(ValueError, IsWindow, None)
+if sys.platform == "win32":
+ class FunctionCallTestCase(unittest.TestCase):
+
if is_resource_enabled("SEH"):
def test_SEH(self):
- # Call functions with invalid arguments, and make sure that access violations
- # are trapped and raise an exception.
+ # Call functions with invalid arguments, and make sure
+ # that access violations are trapped and raise an
+ # exception.
self.assertRaises(WindowsError, windll.kernel32.GetModuleHandleA, 32)
+ def test_noargs(self):
+ # This is a special case on win32 x64
+ windll.user32.GetDesktopWindow()
+
+ class TestWintypes(unittest.TestCase):
+ def test_HWND(self):
+ from ctypes import wintypes
+ self.failUnlessEqual(sizeof(wintypes.HWND), sizeof(c_void_p))
+
+ def test_PARAM(self):
+ from ctypes import wintypes
+ self.failUnlessEqual(sizeof(wintypes.WPARAM),
+ sizeof(c_void_p))
+ self.failUnlessEqual(sizeof(wintypes.LPARAM),
+ sizeof(c_void_p))
+
class Structures(unittest.TestCase):
def test_struct_by_value(self):
Modified: python/branches/p3yk-noslice/Lib/ctypes/util.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/util.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/util.py Fri Feb 23 18:29:35 2007
@@ -46,24 +46,17 @@
import re, tempfile, errno
def _findLib_gcc(name):
- expr = '[^\(\)\s]*lib%s\.[^\(\)\s]*' % name
+ expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)
fdout, ccout = tempfile.mkstemp()
os.close(fdout)
- cmd = 'if type gcc &>/dev/null; then CC=gcc; else CC=cc; fi;' \
+ cmd = 'if type gcc >/dev/null 2>&1; then CC=gcc; else CC=cc; fi;' \
'$CC -Wl,-t -o ' + ccout + ' 2>&1 -l' + name
try:
- fdout, outfile = tempfile.mkstemp()
- os.close(fdout)
- fd = os.popen(cmd)
- trace = fd.read()
- err = fd.close()
+ f = os.popen(cmd)
+ trace = f.read()
+ f.close()
finally:
try:
- os.unlink(outfile)
- except OSError as e:
- if e.errno != errno.ENOENT:
- raise
- try:
os.unlink(ccout)
except OSError as e:
if e.errno != errno.ENOENT:
@@ -73,29 +66,58 @@
return None
return res.group(0)
- def _findLib_ld(name):
- expr = '/[^\(\)\s]*lib%s\.[^\(\)\s]*' % name
- res = re.search(expr, os.popen('/sbin/ldconfig -p 2>/dev/null').read())
- if not res:
- # Hm, this works only for libs needed by the python executable.
- cmd = 'ldd %s 2>/dev/null' % sys.executable
- res = re.search(expr, os.popen(cmd).read())
- if not res:
- 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)
- def find_library(name):
- lib = _findLib_ld(name) or _findLib_gcc(name)
- if not lib:
- return None
- return _get_soname(lib)
+ if (sys.platform.startswith("freebsd")
+ or sys.platform.startswith("openbsd")
+ or sys.platform.startswith("dragonfly")):
+
+ def _num_version(libname):
+ # "libxyz.so.MAJOR.MINOR" => [ MAJOR, MINOR ]
+ parts = libname.split(".")
+ nums = []
+ try:
+ while parts:
+ nums.insert(0, int(parts.pop()))
+ except ValueError:
+ pass
+ return nums or [ sys.maxint ]
+
+ def find_library(name):
+ ename = re.escape(name)
+ expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename, ename)
+ res = re.findall(expr,
+ os.popen('/sbin/ldconfig -r 2>/dev/null').read())
+ if not res:
+ return _get_soname(_findLib_gcc(name))
+ res.sort(cmp= lambda x,y: cmp(_num_version(x), _num_version(y)))
+ return res[-1]
+
+ else:
+
+ def _findLib_ldconfig(name):
+ # XXX assuming GLIBC's ldconfig (with option -p)
+ expr = r'/[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)
+ res = re.search(expr,
+ os.popen('/sbin/ldconfig -p 2>/dev/null').read())
+ if not res:
+ # Hm, this works only for libs needed by the python executable.
+ cmd = 'ldd %s 2>/dev/null' % sys.executable
+ res = re.search(expr, os.popen(cmd).read())
+ if not res:
+ return None
+ return res.group(0)
+
+ def find_library(name):
+ return _get_soname(_findLib_ldconfig(name) or _findLib_gcc(name))
################################################################
# test code
@@ -103,15 +125,15 @@
def test():
from ctypes import cdll
if os.name == "nt":
- print cdll.msvcrt
- print cdll.load("msvcrt")
- print find_library("msvcrt")
+ print(cdll.msvcrt)
+ print(cdll.load("msvcrt"))
+ print(find_library("msvcrt"))
if os.name == "posix":
# find and load_version
- print find_library("m")
- print find_library("c")
- print find_library("bz2")
+ print(find_library("m"))
+ print(find_library("c"))
+ print(find_library("bz2"))
# getattr
## print cdll.m
@@ -119,14 +141,14 @@
# load
if sys.platform == "darwin":
- print cdll.LoadLibrary("libm.dylib")
- print cdll.LoadLibrary("libcrypto.dylib")
- print cdll.LoadLibrary("libSystem.dylib")
- print cdll.LoadLibrary("System.framework/System")
+ print(cdll.LoadLibrary("libm.dylib"))
+ print(cdll.LoadLibrary("libcrypto.dylib"))
+ print(cdll.LoadLibrary("libSystem.dylib"))
+ print(cdll.LoadLibrary("System.framework/System"))
else:
- print cdll.LoadLibrary("libm.so")
- print cdll.LoadLibrary("libcrypt.so")
- print find_library("crypt")
+ print(cdll.LoadLibrary("libm.so"))
+ print(cdll.LoadLibrary("libcrypt.so"))
+ print(find_library("crypt"))
if __name__ == "__main__":
test()
Modified: python/branches/p3yk-noslice/Lib/ctypes/wintypes.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ctypes/wintypes.py (original)
+++ python/branches/p3yk-noslice/Lib/ctypes/wintypes.py Fri Feb 23 18:29:35 2007
@@ -34,8 +34,14 @@
LPCWSTR = LPWSTR = c_wchar_p
LPCSTR = LPSTR = c_char_p
-WPARAM = c_uint
-LPARAM = c_long
+# WPARAM is defined as UINT_PTR (unsigned type)
+# LPARAM is defined as LONG_PTR (signed type)
+if sizeof(c_long) == sizeof(c_void_p):
+ WPARAM = c_ulong
+ LPARAM = c_long
+elif sizeof(c_longlong) == sizeof(c_void_p):
+ WPARAM = c_ulonglong
+ LPARAM = c_longlong
ATOM = WORD
LANGID = WORD
@@ -48,7 +54,7 @@
################################################################
# HANDLE types
-HANDLE = c_ulong # in the header files: void *
+HANDLE = c_void_p # in the header files: void *
HACCEL = HANDLE
HBITMAP = HANDLE
Modified: python/branches/p3yk-noslice/Lib/curses/has_key.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/curses/has_key.py (original)
+++ python/branches/p3yk-noslice/Lib/curses/has_key.py Fri Feb 23 18:29:35 2007
@@ -189,4 +189,4 @@
% (_curses.keyname( key ), system, python) )
finally:
_curses.endwin()
- for i in L: print i
+ for i in L: print(i)
Modified: python/branches/p3yk-noslice/Lib/curses/textpad.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/curses/textpad.py (original)
+++ python/branches/p3yk-noslice/Lib/curses/textpad.py Fri Feb 23 18:29:35 2007
@@ -170,4 +170,4 @@
return Textbox(win).edit()
str = curses.wrapper(test_editbox)
- print 'Contents of text box:', repr(str)
+ print('Contents of text box:', repr(str))
Modified: python/branches/p3yk-noslice/Lib/decimal.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/decimal.py (original)
+++ python/branches/p3yk-noslice/Lib/decimal.py Fri Feb 23 18:29:35 2007
@@ -56,31 +56,31 @@
>>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
Decimal("-2.20")
>>> dig = Decimal(1)
->>> print dig / Decimal(3)
+>>> print(dig / Decimal(3))
0.333333333
>>> getcontext().prec = 18
->>> print dig / Decimal(3)
+>>> print(dig / Decimal(3))
0.333333333333333333
->>> print dig.sqrt()
+>>> print(dig.sqrt())
1
->>> print Decimal(3).sqrt()
+>>> print(Decimal(3).sqrt())
1.73205080756887729
->>> print Decimal(3) ** 123
+>>> print(Decimal(3) ** 123)
4.85192780976896427E+58
>>> inf = Decimal(1) / Decimal(0)
->>> print inf
+>>> print(inf)
Infinity
>>> neginf = Decimal(-1) / Decimal(0)
->>> print neginf
+>>> print(neginf)
-Infinity
->>> print neginf + inf
+>>> print(neginf + inf)
NaN
->>> print neginf * inf
+>>> print(neginf * inf)
-Infinity
->>> print dig / 0
+>>> print(dig / 0)
Infinity
>>> getcontext().traps[DivisionByZero] = 1
->>> print dig / 0
+>>> print(dig / 0)
Traceback (most recent call last):
...
...
@@ -88,29 +88,29 @@
decimal.DivisionByZero: x / 0
>>> c = Context()
>>> c.traps[InvalidOperation] = 0
->>> print c.flags[InvalidOperation]
+>>> print(c.flags[InvalidOperation])
0
>>> c.divide(Decimal(0), Decimal(0))
Decimal("NaN")
>>> c.traps[InvalidOperation] = 1
->>> print c.flags[InvalidOperation]
+>>> print(c.flags[InvalidOperation])
1
>>> c.flags[InvalidOperation] = 0
->>> print c.flags[InvalidOperation]
+>>> print(c.flags[InvalidOperation])
0
->>> print c.divide(Decimal(0), Decimal(0))
+>>> print(c.divide(Decimal(0), Decimal(0)))
Traceback (most recent call last):
...
...
...
decimal.InvalidOperation: 0 / 0
->>> print c.flags[InvalidOperation]
+>>> print(c.flags[InvalidOperation])
1
>>> c.flags[InvalidOperation] = 0
>>> c.traps[InvalidOperation] = 0
->>> print c.divide(Decimal(0), Decimal(0))
+>>> print(c.divide(Decimal(0), Decimal(0)))
NaN
->>> print c.flags[InvalidOperation]
+>>> print(c.flags[InvalidOperation])
1
>>>
"""
@@ -483,19 +483,19 @@
# as the doctest module doesn't understand __future__ statements
"""
>>> from __future__ import with_statement
- >>> print getcontext().prec
+ >>> print(getcontext().prec)
28
>>> with localcontext():
... ctx = getcontext()
- ... ctx.prec() += 2
- ... print ctx.prec
- ...
+ ... ctx.prec += 2
+ ... print(ctx.prec)
+ ...
30
>>> with localcontext(ExtendedContext):
- ... print getcontext().prec
- ...
+ ... print(getcontext().prec)
+ ...
9
- >>> print getcontext().prec
+ >>> print(getcontext().prec)
28
"""
if ctx is None: ctx = getcontext()
@@ -545,7 +545,7 @@
return self
# From an integer
- if isinstance(value, (int,long)):
+ if isinstance(value, (int,int)):
if value >= 0:
self._sign = 0
else:
@@ -561,7 +561,7 @@
if value[0] not in (0,1):
raise ValueError, 'Invalid sign'
for digit in value[1]:
- if not isinstance(digit, (int,long)) or digit < 0:
+ if not isinstance(digit, (int,int)) or digit < 0:
raise ValueError, "The second value in the tuple must be composed of non negative integer elements."
self._sign = value[0]
@@ -740,32 +740,32 @@
return 1
def __eq__(self, other):
- if not isinstance(other, (Decimal, int, long)):
+ if not isinstance(other, (Decimal, int, int)):
return NotImplemented
return self.__cmp__(other) == 0
def __ne__(self, other):
- if not isinstance(other, (Decimal, int, long)):
+ if not isinstance(other, (Decimal, int, int)):
return NotImplemented
return self.__cmp__(other) != 0
def __lt__(self, other):
- if not isinstance(other, (Decimal, int, long)):
+ if not isinstance(other, (Decimal, int, int)):
return NotImplemented
return self.__cmp__(other) < 0
def __le__(self, other):
- if not isinstance(other, (Decimal, int, long)):
+ if not isinstance(other, (Decimal, int, int)):
return NotImplemented
return self.__cmp__(other) <= 0
def __gt__(self, other):
- if not isinstance(other, (Decimal, int, long)):
+ if not isinstance(other, (Decimal, int, int)):
return NotImplemented
return self.__cmp__(other) > 0
def __ge__(self, other):
- if not isinstance(other, (Decimal, int, long)):
+ if not isinstance(other, (Decimal, int, int)):
return NotImplemented
return self.__cmp__(other) >= 0
@@ -1529,7 +1529,7 @@
Equivalent to long(int(self))
"""
- return long(self.__int__())
+ return int(self.__int__())
def _fix(self, context):
"""Round if it is necessary to keep self within prec precision.
@@ -2986,7 +2986,7 @@
"""
if isinstance(other, Decimal):
return other
- if isinstance(other, (int, long)):
+ if isinstance(other, (int, int)):
return Decimal(other)
return NotImplemented
Modified: python/branches/p3yk-noslice/Lib/difflib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/difflib.py (original)
+++ python/branches/p3yk-noslice/Lib/difflib.py Fri Feb 23 18:29:35 2007
@@ -76,7 +76,7 @@
sequences. As a rule of thumb, a .ratio() value over 0.6 means the
sequences are close matches:
- >>> print round(s.ratio(), 3)
+ >>> print(round(s.ratio(), 3))
0.866
>>>
@@ -84,7 +84,7 @@
.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 21 elements
a[29] and b[38] match for 0 elements
@@ -97,7 +97,7 @@
use .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:29] b[17:38]
@@ -331,7 +331,7 @@
junkdict = {}
if isjunk:
for d in populardict, b2j:
- for elt in d.keys():
+ for elt in list(d.keys()):
if isjunk(elt):
junkdict[elt] = 1
del d[elt]
@@ -545,8 +545,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)
@@ -832,7 +832,7 @@
As a single multi-line string it looks like this:
- >>> print ''.join(result),
+ >>> print(''.join(result), end="")
1. Beautiful is better than ugly.
- 2. Explicit is better than implicit.
- 3. Simple is better than complex.
@@ -889,8 +889,9 @@
Example:
- >>> print ''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
+ >>> print(''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1))),
+ ... end="")
- one
? ^
+ ore
@@ -950,7 +951,7 @@
>>> d = Differ()
>>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
... ['abcdefGhijkl\n'], 0, 1)
- >>> print ''.join(results),
+ >>> print(''.join(results), end="")
- abcDefghiJkl
? ^ ^ ^
+ abcdefGhijkl
@@ -1058,7 +1059,7 @@
>>> d = Differ()
>>> results = d._qformat('\tabcDefghiJkl\n', '\t\tabcdefGhijkl\n',
... ' ^ ^ ^ ', '+ ^ ^ ^ ')
- >>> for line in results: print repr(line)
+ >>> for line in results: print(repr(line))
...
'- \tabcDefghiJkl\n'
'? \t ^ ^ ^\n'
@@ -1164,7 +1165,7 @@
... 'zero one tree four'.split(), 'Original', 'Current',
... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003',
... lineterm=''):
- ... print line
+ ... print(line)
--- Original Sat Jan 26 23:30:50 1991
+++ Current Fri Jun 06 10:20:52 2003
@@ -1,4 +1,4 @@
@@ -1223,9 +1224,10 @@
Example:
- >>> print ''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
+ >>> print(''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current',
... 'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:22:46 2003')),
+ ... end="")
*** Original Sat Jan 26 23:30:50 1991
--- Current Fri Jun 06 10:22:46 2003
***************
@@ -1295,7 +1297,7 @@
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1))
- >>> print ''.join(diff),
+ >>> print(''.join(diff), end="")
- one
? ^
+ ore
@@ -1992,11 +1994,11 @@
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1))
>>> diff = list(diff)
- >>> 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
Modified: python/branches/p3yk-noslice/Lib/dis.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/dis.py (original)
+++ python/branches/p3yk-noslice/Lib/dis.py Fri Feb 23 18:29:35 2007
@@ -30,12 +30,12 @@
types.FunctionType,
types.CodeType,
types.ClassType):
- print "Disassembly of %s:" % name
+ print("Disassembly of %s:" % name)
try:
dis(x1)
except TypeError as msg:
- print "Sorry:", msg
- print
+ print("Sorry:", msg)
+ print()
elif hasattr(x, 'co_code'):
disassemble(x)
elif isinstance(x, str):
@@ -69,40 +69,40 @@
op = ord(c)
if i in linestarts:
if i > 0:
- print
- print "%3d" % linestarts[i],
+ print()
+ print("%3d" % linestarts[i], end=' ')
else:
- print ' ',
+ print(' ', end=' ')
- if i == lasti: print '-->',
- else: print ' ',
- if i in labels: print '>>',
- else: print ' ',
- print repr(i).rjust(4),
- print opname[op].ljust(20),
+ if i == lasti: print('-->', end=' ')
+ else: print(' ', end=' ')
+ if i in labels: print('>>', end=' ')
+ else: print(' ', end=' ')
+ print(repr(i).rjust(4), end=' ')
+ print(opname[op].ljust(20), end=' ')
i = i+1
if op >= HAVE_ARGUMENT:
oparg = ord(code[i]) + ord(code[i+1])*256 + extended_arg
extended_arg = 0
i = i+2
if op == EXTENDED_ARG:
- extended_arg = oparg*65536L
- print repr(oparg).rjust(5),
+ extended_arg = oparg*65536
+ print(repr(oparg).rjust(5), end=' ')
if op in hasconst:
- print '(' + repr(co.co_consts[oparg]) + ')',
+ print('(' + repr(co.co_consts[oparg]) + ')', end=' ')
elif op in hasname:
- print '(' + co.co_names[oparg] + ')',
+ print('(' + co.co_names[oparg] + ')', end=' ')
elif op in hasjrel:
- print '(to ' + repr(i + oparg) + ')',
+ print('(to ' + repr(i + oparg) + ')', end=' ')
elif op in haslocal:
- print '(' + co.co_varnames[oparg] + ')',
+ print('(' + co.co_varnames[oparg] + ')', end=' ')
elif op in hascompare:
- print '(' + cmp_op[oparg] + ')',
+ print('(' + cmp_op[oparg] + ')', end=' ')
elif op in hasfree:
if free is None:
free = co.co_cellvars + co.co_freevars
- print '(' + free[oparg] + ')',
- print
+ print('(' + free[oparg] + ')', end=' ')
+ print()
def disassemble_string(code, lasti=-1, varnames=None, names=None,
constants=None):
@@ -112,37 +112,37 @@
while i < n:
c = code[i]
op = ord(c)
- if i == lasti: print '-->',
- else: print ' ',
- if i in labels: print '>>',
- else: print ' ',
- print repr(i).rjust(4),
- print opname[op].ljust(15),
+ if i == lasti: print('-->', end=' ')
+ else: print(' ', end=' ')
+ if i in labels: print('>>', end=' ')
+ else: print(' ', end=' ')
+ print(repr(i).rjust(4), end=' ')
+ print(opname[op].ljust(15), end=' ')
i = i+1
if op >= HAVE_ARGUMENT:
oparg = ord(code[i]) + ord(code[i+1])*256
i = i+2
- print repr(oparg).rjust(5),
+ print(repr(oparg).rjust(5), end=' ')
if op in hasconst:
if constants:
- print '(' + repr(constants[oparg]) + ')',
+ print('(' + repr(constants[oparg]) + ')', end=' ')
else:
- print '(%d)'%oparg,
+ print('(%d)'%oparg, end=' ')
elif op in hasname:
if names is not None:
- print '(' + names[oparg] + ')',
+ print('(' + names[oparg] + ')', end=' ')
else:
- print '(%d)'%oparg,
+ print('(%d)'%oparg, end=' ')
elif op in hasjrel:
- print '(to ' + repr(i + oparg) + ')',
+ print('(to ' + repr(i + oparg) + ')', end=' ')
elif op in haslocal:
if varnames:
- print '(' + varnames[oparg] + ')',
+ print('(' + varnames[oparg] + ')', end=' ')
else:
- print '(%d)' % oparg,
+ print('(%d)' % oparg, end=' ')
elif op in hascompare:
- print '(' + cmp_op[oparg] + ')',
- print
+ print('(' + cmp_op[oparg] + ')', end=' ')
+ print()
disco = disassemble # XXX For backwards compatibility
Modified: python/branches/p3yk-noslice/Lib/distutils/bcppcompiler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/bcppcompiler.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/bcppcompiler.py Fri Feb 23 18:29:35 2007
@@ -392,7 +392,7 @@
try:
self.spawn(pp_args)
except DistutilsExecError as msg:
- print msg
+ print(msg)
raise CompileError, msg
# preprocess()
Modified: python/branches/p3yk-noslice/Lib/distutils/ccompiler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/ccompiler.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/ccompiler.py Fri Feb 23 18:29:35 2007
@@ -1026,7 +1026,7 @@
def debug_print (self, msg):
from distutils.debug import DEBUG
if DEBUG:
- print msg
+ print(msg)
def warn (self, msg):
sys.stderr.write ("warning: %s\n" % msg)
Modified: python/branches/p3yk-noslice/Lib/distutils/cmd.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/cmd.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/cmd.py Fri Feb 23 18:29:35 2007
@@ -163,14 +163,14 @@
from distutils.fancy_getopt import longopt_xlate
if header is None:
header = "command options for '%s':" % self.get_command_name()
- print indent + header
+ print(indent + header)
indent = indent + " "
for (option, _, _) in self.user_options:
option = string.translate(option, longopt_xlate)
if option[-1] == "=":
option = option[:-1]
value = getattr(self, option)
- print indent + "%s = %s" % (option, value)
+ print(indent + "%s = %s" % (option, value))
def run (self):
@@ -199,7 +199,7 @@
"""
from distutils.debug import DEBUG
if DEBUG:
- print msg
+ print(msg)
sys.stdout.flush()
@@ -475,4 +475,4 @@
if __name__ == "__main__":
- print "ok"
+ print("ok")
Modified: python/branches/p3yk-noslice/Lib/distutils/command/bdist_rpm.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/bdist_rpm.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/bdist_rpm.py Fri Feb 23 18:29:35 2007
@@ -267,11 +267,11 @@
def run (self):
if DEBUG:
- print "before _get_package_data():"
- print "vendor =", self.vendor
- print "packager =", self.packager
- print "doc_files =", self.doc_files
- print "changelog =", self.changelog
+ print("before _get_package_data():")
+ print("vendor =", self.vendor)
+ print("packager =", self.packager)
+ print("doc_files =", self.doc_files)
+ print("changelog =", self.changelog)
# make directories
if self.spec_only:
Modified: python/branches/p3yk-noslice/Lib/distutils/command/build_ext.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/build_ext.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/build_ext.py Fri Feb 23 18:29:35 2007
@@ -185,9 +185,7 @@
# for extensions under Cygwin and AtheOS Python's library directory must be
# appended to library_dirs
- if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos' or \
- ((sys.platform.startswith('linux') or sys.platform.startswith('gnu')) and
- sysconfig.get_config_var('Py_ENABLE_SHARED')):
+ if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos':
if string.find(sys.executable, sys.exec_prefix) != -1:
# building third party extensions
self.library_dirs.append(os.path.join(sys.prefix, "lib",
@@ -197,6 +195,17 @@
# building python standard extensions
self.library_dirs.append('.')
+ # for extensions under Linux with a shared Python library,
+ # Python's library directory must be appended to library_dirs
+ if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \
+ and sysconfig.get_config_var('Py_ENABLE_SHARED'):
+ if string.find(sys.executable, sys.exec_prefix) != -1:
+ # building third party extensions
+ self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
+ else:
+ # building python standard extensions
+ self.library_dirs.append('.')
+
# The argument parsing will result in self.define being a string, but
# it has to be a list of 2-tuples. All the preprocessor symbols
# specified by the 'define' option will be set to '1'. Multiple
Modified: python/branches/p3yk-noslice/Lib/distutils/command/config.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/config.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/config.py Fri Feb 23 18:29:35 2007
@@ -359,9 +359,9 @@
def dump_file (filename, head=None):
if head is None:
- print filename + ":"
+ print(filename + ":")
else:
- print head
+ print(head)
file = open(filename)
sys.stdout.write(file.read())
Modified: python/branches/p3yk-noslice/Lib/distutils/command/install.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/install.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/install.py Fri Feb 23 18:29:35 2007
@@ -292,7 +292,7 @@
if DEBUG:
from pprint import pprint
- print "config vars:"
+ print("config vars:")
pprint(self.config_vars)
# Expand "~" and configuration variables in the installation
@@ -347,7 +347,7 @@
def dump_dirs (self, msg):
if DEBUG:
from distutils.fancy_getopt import longopt_xlate
- print msg + ":"
+ print(msg + ":")
for opt in self.user_options:
opt_name = opt[0]
if opt_name[-1] == "=":
@@ -359,7 +359,7 @@
else:
opt_name = string.translate(opt_name, longopt_xlate)
val = getattr(self, opt_name)
- print " %s: %s" % (opt_name, val)
+ print(" %s: %s" % (opt_name, val))
def finalize_unix (self):
Modified: python/branches/p3yk-noslice/Lib/distutils/command/register.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/register.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/register.py Fri Feb 23 18:29:35 2007
@@ -86,14 +86,14 @@
''' Fetch the list of classifiers from the server.
'''
response = urllib2.urlopen(self.repository+'?:action=list_classifiers')
- print response.read()
+ print(response.read())
def verify_metadata(self):
''' Send the metadata to the package index server to be checked.
'''
# send the info to the server and report the result
(code, result) = self.post_to_server(self.build_post_data('verify'))
- print 'Server response (%s): %s'%(code, result)
+ print('Server response (%s): %s'%(code, result))
def send_metadata(self):
''' Send the metadata to the package index server.
@@ -128,7 +128,7 @@
if os.environ.has_key('HOME'):
rc = os.path.join(os.environ['HOME'], '.pypirc')
if os.path.exists(rc):
- print 'Using PyPI login from %s'%rc
+ print('Using PyPI login from %s'%rc)
config = ConfigParser.ConfigParser()
config.read(rc)
username = config.get('server-login', 'username')
@@ -138,17 +138,17 @@
# get the user's login info
choices = '1 2 3 4'.split()
while choice not in choices:
- print '''We need to know who you are, so please choose either:
+ print('''We need to know who you are, so please choose either:
1. use your existing login,
2. register as a new user,
3. have the server generate a new password for you (and email it to you), or
4. quit
-Your selection [default 1]: ''',
+Your selection [default 1]: ''', end=' ')
choice = raw_input()
if not choice:
choice = '1'
elif choice not in choices:
- print 'Please choose one of the four options!'
+ print('Please choose one of the four options!')
if choice == '1':
# get the username and password
@@ -165,13 +165,13 @@
# send the info to the server and report the result
code, result = self.post_to_server(self.build_post_data('submit'),
auth)
- print 'Server response (%s): %s'%(code, result)
+ print('Server response (%s): %s'%(code, result))
# possibly save the login
if os.environ.has_key('HOME') 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
+ print('I can store your PyPI login so future submissions will be faster.')
+ print('(the login will be stored in %s)'%rc)
choice = 'X'
while choice.lower() not in 'yn':
choice = raw_input('Save your login (y/N)?')
@@ -200,22 +200,22 @@
if data['password'] != data['confirm']:
data['password'] = ''
data['confirm'] = None
- print "Password and confirm don't match!"
+ print("Password and confirm don't match!")
while not data['email']:
data['email'] = raw_input(' EMail: ')
code, result = self.post_to_server(data)
if code != 200:
- print 'Server response (%s): %s'%(code, result)
+ print('Server response (%s): %s'%(code, result))
else:
- print 'You will receive an email shortly.'
- print 'Follow the instructions in it to complete registration.'
+ print('You will receive an email shortly.')
+ print('Follow the instructions in it to complete registration.')
elif choice == '3':
data = {':action': 'password_reset'}
data['email'] = ''
while not data['email']:
data['email'] = raw_input('Your email address: ')
code, result = self.post_to_server(data)
- print 'Server response (%s): %s'%(code, result)
+ print('Server response (%s): %s'%(code, result))
def build_post_data(self, action):
# figure the data to send - the metadata plus some additional
@@ -295,5 +295,5 @@
data = result.read()
result = 200, 'OK'
if self.show_response:
- print '-'*75, data, '-'*75
+ print('-'*75, data, '-'*75)
return result
Modified: python/branches/p3yk-noslice/Lib/distutils/command/upload.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/command/upload.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/command/upload.py Fri Feb 23 18:29:35 2007
@@ -196,4 +196,4 @@
self.announce('Upload failed (%s): %s' % (r.status, r.reason),
log.ERROR)
if self.show_response:
- print '-'*75, r.read(), '-'*75
+ print('-'*75, r.read(), '-'*75)
Modified: python/branches/p3yk-noslice/Lib/distutils/core.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/core.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/core.py Fri Feb 23 18:29:35 2007
@@ -125,7 +125,7 @@
dist.parse_config_files()
if DEBUG:
- print "options (after parsing config files):"
+ print("options (after parsing config files):")
dist.dump_option_dicts()
if _setup_stop_after == "config":
@@ -139,7 +139,7 @@
raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % msg
if DEBUG:
- print "options (after parsing command line):"
+ print("options (after parsing command line):")
dist.dump_option_dicts()
if _setup_stop_after == "commandline":
Modified: python/branches/p3yk-noslice/Lib/distutils/dist.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/dist.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/dist.py Fri Feb 23 18:29:35 2007
@@ -290,22 +290,22 @@
commands.sort()
if header is not None:
- print indent + header
+ print(indent + header)
indent = indent + " "
if not commands:
- print indent + "no commands known yet"
+ print(indent + "no commands known yet")
return
for cmd_name in commands:
opt_dict = self.command_options.get(cmd_name)
if opt_dict is None:
- print indent + "no option dict for '%s' command" % cmd_name
+ print(indent + "no option dict for '%s' command" % cmd_name)
else:
- print indent + "option dict for '%s' command:" % cmd_name
+ print(indent + "option dict for '%s' command:" % cmd_name)
out = pformat(opt_dict)
for line in string.split(out, "\n"):
- print indent + " " + line
+ print(indent + " " + line)
# dump_option_dicts ()
@@ -365,11 +365,11 @@
if filenames is None:
filenames = self.find_config_files()
- if DEBUG: print "Distribution.parse_config_files():"
+ if DEBUG: print("Distribution.parse_config_files():")
parser = ConfigParser()
for filename in filenames:
- if DEBUG: print " reading", filename
+ if DEBUG: print(" reading", filename)
parser.read(filename)
for section in parser.sections():
options = parser.options(section)
@@ -636,14 +636,14 @@
options = self.global_options
parser.set_option_table(options)
parser.print_help(self.common_usage + "\nGlobal options:")
- print
+ print()
if display_options:
parser.set_option_table(self.display_options)
parser.print_help(
"Information display options (just display " +
"information, ignore any commands)")
- print
+ print()
for command in self.commands:
if type(command) is ClassType and issubclass(command, Command):
@@ -657,9 +657,9 @@
else:
parser.set_option_table(klass.user_options)
parser.print_help("Options for '%s' command:" % klass.__name__)
- print
+ print()
- print gen_usage(self.script_name)
+ print(gen_usage(self.script_name))
return
# _show_help ()
@@ -678,8 +678,8 @@
# we ignore "foo bar").
if self.help_commands:
self.print_commands()
- print
- print gen_usage(self.script_name)
+ print()
+ print(gen_usage(self.script_name))
return 1
# If user supplied any of the "display metadata" options, then
@@ -695,12 +695,12 @@
opt = translate_longopt(opt)
value = getattr(self.metadata, "get_"+opt)()
if opt in ['keywords', 'platforms']:
- print string.join(value, ',')
+ print(string.join(value, ','))
elif opt in ('classifiers', 'provides', 'requires',
'obsoletes'):
- print string.join(value, '\n')
+ print(string.join(value, '\n'))
else:
- print value
+ print(value)
any_display_options = 1
return any_display_options
@@ -712,7 +712,7 @@
'print_commands()'.
"""
- print header + ":"
+ print(header + ":")
for cmd in commands:
klass = self.cmdclass.get(cmd)
@@ -723,7 +723,7 @@
except AttributeError:
description = "(no description available)"
- print " %-*s %s" % (max_length, cmd, description)
+ print(" %-*s %s" % (max_length, cmd, description))
# print_command_list ()
@@ -757,7 +757,7 @@
"Standard commands",
max_length)
if extra_commands:
- print
+ print()
self.print_command_list(extra_commands,
"Extra commands",
max_length)
@@ -862,8 +862,8 @@
cmd_obj = self.command_obj.get(command)
if not cmd_obj and create:
if DEBUG:
- print "Distribution.get_command_obj(): " \
- "creating '%s' command object" % command
+ print("Distribution.get_command_obj(): " \
+ "creating '%s' command object" % command)
klass = self.get_command_class(command)
cmd_obj = self.command_obj[command] = klass(self)
@@ -893,9 +893,9 @@
if option_dict is None:
option_dict = self.get_option_dict(command_name)
- if DEBUG: print " setting options for '%s' command:" % command_name
+ if DEBUG: print(" setting options for '%s' command:" % command_name)
for (option, (source, value)) in option_dict.items():
- if DEBUG: print " %s = %s (from %s)" % (option, value, source)
+ if DEBUG: print(" %s = %s (from %s)" % (option, value, source))
try:
bool_opts = map(translate_longopt, command_obj.boolean_options)
except AttributeError:
@@ -1219,4 +1219,4 @@
if __name__ == "__main__":
dist = Distribution()
- print "ok"
+ print("ok")
Modified: python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/fancy_getopt.py Fri Feb 23 18:29:35 2007
@@ -497,6 +497,6 @@
say, "How should I know?"].)"""
for w in (10, 20, 30, 40):
- print "width: %d" % w
- print string.join(wrap_text(text, w), "\n")
- print
+ print("width: %d" % w)
+ print(string.join(wrap_text(text, w), "\n"))
+ print()
Modified: python/branches/p3yk-noslice/Lib/distutils/filelist.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/filelist.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/filelist.py Fri Feb 23 18:29:35 2007
@@ -53,7 +53,7 @@
"""
from distutils.debug import DEBUG
if DEBUG:
- print msg
+ print(msg)
# -- List-like methods ---------------------------------------------
Modified: python/branches/p3yk-noslice/Lib/distutils/log.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/log.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/log.py Fri Feb 23 18:29:35 2007
@@ -23,9 +23,9 @@
if not args:
# msg may contain a '%'. If args is empty,
# don't even try to string-format
- print msg
+ print(msg)
else:
- print msg % args
+ print(msg % args)
sys.stdout.flush()
def log(self, level, msg, *args):
Modified: python/branches/p3yk-noslice/Lib/distutils/mwerkscompiler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/mwerkscompiler.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/mwerkscompiler.py Fri Feb 23 18:29:35 2007
@@ -160,9 +160,9 @@
settings['libraries'] = libraries
settings['extrasearchdirs'] = sourcefiledirs + include_dirs + library_dirs
if self.dry_run:
- print 'CALLING LINKER IN', os.getcwd()
+ print('CALLING LINKER IN', os.getcwd())
for key, value in settings.items():
- print '%20.20s %s'%(key, value)
+ print('%20.20s %s'%(key, value))
return
# Build the export file
exportfilename = os.path.join(build_temp, exportname)
Modified: python/branches/p3yk-noslice/Lib/distutils/spawn.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/spawn.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/spawn.py Fri Feb 23 18:29:35 2007
@@ -109,7 +109,7 @@
"command '%s' failed: %s" % (cmd[0], exc[-1])
if rc != 0:
# and this reflects the command running but failing
- print "command '%s' failed with exit status %d" % (cmd[0], rc)
+ print("command '%s' failed with exit status %d" % (cmd[0], rc))
raise DistutilsExecError, \
"command '%s' failed with exit status %d" % (cmd[0], rc)
Modified: python/branches/p3yk-noslice/Lib/distutils/sysconfig.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/sysconfig.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/sysconfig.py Fri Feb 23 18:29:35 2007
@@ -271,7 +271,7 @@
# do variable interpolation here
while notdone:
- for name in notdone.keys():
+ for name in list(notdone):
value = notdone[name]
m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
if m:
Modified: python/branches/p3yk-noslice/Lib/distutils/tests/test_dist.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/tests/test_dist.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/tests/test_dist.py Fri Feb 23 18:29:35 2007
@@ -74,8 +74,8 @@
sys.argv.append("build")
f = open(TESTFN, "w")
try:
- print >>f, "[global]"
- print >>f, "command_packages = foo.bar, splat"
+ print("[global]", file=f)
+ print("command_packages = foo.bar, splat", file=f)
f.close()
d = self.create_distribution([TESTFN])
self.assertEqual(d.get_command_packages(),
Modified: python/branches/p3yk-noslice/Lib/distutils/text_file.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/text_file.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/text_file.py Fri Feb 23 18:29:35 2007
@@ -342,13 +342,13 @@
result = file.readlines ()
# result = string.join (result, '')
if result == expected_result:
- print "ok %d (%s)" % (count, description)
+ print("ok %d (%s)" % (count, description))
else:
- print "not ok %d (%s):" % (count, description)
- print "** expected:"
- print expected_result
- print "** received:"
- print result
+ print("not ok %d (%s):" % (count, description))
+ print("** expected:")
+ print(expected_result)
+ print("** received:")
+ print(result)
filename = "test.txt"
Modified: python/branches/p3yk-noslice/Lib/distutils/versionpredicate.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/distutils/versionpredicate.py (original)
+++ python/branches/p3yk-noslice/Lib/distutils/versionpredicate.py Fri Feb 23 18:29:35 2007
@@ -40,7 +40,7 @@
The str() of a `VersionPredicate` provides a normalized
human-readable version of the expression::
- >>> print v
+ >>> print(v)
pyepat.abc (> 1.0, < 3333.3a1, != 1555.1b3)
The `satisfied_by()` method can be used to determine with a given
Modified: python/branches/p3yk-noslice/Lib/doctest.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/doctest.py (original)
+++ python/branches/p3yk-noslice/Lib/doctest.py Fri Feb 23 18:29:35 2007
@@ -240,16 +240,10 @@
# that a trailing newline is missing.
if result and not result.endswith("\n"):
result += "\n"
- # Prevent softspace from screwing up the next test case, in
- # case they used print with a trailing comma in an example.
- if hasattr(self, "softspace"):
- del self.softspace
return result
- def truncate(self, size=None):
+ def truncate(self, size=None):
StringIO.truncate(self, size)
- if hasattr(self, "softspace"):
- del self.softspace
# Worst-case linear-time ellipsis matching.
def _ellipsis_match(want, got):
@@ -855,7 +849,7 @@
add them to `tests`.
"""
if self._verbose:
- print 'Finding tests in %s' % name
+ print('Finding tests in %s' % name)
# If we've already processed this object, then ignore it.
if id(obj) in seen:
@@ -1012,7 +1006,7 @@
>>> runner = DocTestRunner(verbose=False)
>>> tests.sort(key = lambda test: test.name)
>>> for test in tests:
- ... print test.name, '->', runner.run(test)
+ ... print(test.name, '->', runner.run(test))
_TestClass -> (0, 2)
_TestClass.__init__ -> (0, 2)
_TestClass.get -> (0, 2)
@@ -1384,28 +1378,28 @@
failed.append(x)
if verbose:
if notests:
- print len(notests), "items had no tests:"
+ print(len(notests), "items had no tests:")
notests.sort()
for thing in notests:
- print " ", thing
+ print(" ", thing)
if passed:
- print len(passed), "items passed all tests:"
+ print(len(passed), "items passed all tests:")
passed.sort()
for thing, count in passed:
- print " %3d tests in %s" % (count, thing)
+ print(" %3d tests in %s" % (count, thing))
if failed:
- print self.DIVIDER
- print len(failed), "items had failures:"
+ print(self.DIVIDER)
+ print(len(failed), "items had failures:")
failed.sort()
for thing, (f, t) in failed:
- print " %3d of %3d in %s" % (f, t, thing)
+ print(" %3d of %3d in %s" % (f, t, thing))
if verbose:
- print totalt, "tests in", len(self._name2ft), "items."
- print totalt - totalf, "passed and", totalf, "failed."
+ print(totalt, "tests in", len(self._name2ft), "items.")
+ print(totalt - totalf, "passed and", totalf, "failed.")
if totalf:
- print "***Test Failed***", totalf, "failures."
+ print("***Test Failed***", totalf, "failures.")
elif verbose:
- print "Test passed."
+ print("Test passed.")
return totalf, totalt
#/////////////////////////////////////////////////////////////////
@@ -1415,8 +1409,8 @@
d = self._name2ft
for name, (f, t) in other._name2ft.items():
if name in d:
- print "*** DocTestRunner.merge: '" + name + "' in both" \
- " testers; summing outcomes."
+ print("*** DocTestRunner.merge: '" + name + "' in both" \
+ " testers; summing outcomes.")
f2, t2 = d[name]
f = f + f2
t = t + t2
@@ -1985,10 +1979,10 @@
def runstring(self, s, name):
test = DocTestParser().get_doctest(s, self.globs, name, None, None)
if self.verbose:
- print "Running string", name
+ print("Running string", name)
(f,t) = self.testrunner.run(test)
if self.verbose:
- print f, "of", t, "examples failed in string", name
+ print(f, "of", t, "examples failed in string", name)
return (f,t)
def rundoc(self, object, name=None, module=None):
@@ -2419,7 +2413,7 @@
... Ho hum
... '''
- >>> print script_from_examples(text)
+ >>> print(script_from_examples(text))
# Here are examples of simple math.
#
# Python has super accurate integer addition
@@ -2512,7 +2506,7 @@
try:
execfile(srcfilename, globs, globs)
except:
- print sys.exc_info()[1]
+ print(sys.exc_info()[1])
pdb.post_mortem(sys.exc_info()[2])
else:
# Note that %r is vital here. '%s' instead can, e.g., cause
@@ -2554,7 +2548,7 @@
"""val -> _TestClass object with associated value val.
>>> t = _TestClass(123)
- >>> print t.get()
+ >>> print(t.get())
123
"""
@@ -2574,7 +2568,7 @@
"""get() -> return TestClass's associated value.
>>> x = _TestClass(-42)
- >>> print x.get()
+ >>> print(x.get())
-42
"""
@@ -2606,7 +2600,7 @@
"blank lines": r"""
Blank lines can be marked with <BLANKLINE>:
- >>> print 'foo\n\nbar\n'
+ >>> print('foo\n\nbar\n')
foo
<BLANKLINE>
bar
@@ -2616,14 +2610,14 @@
"ellipsis": r"""
If the ellipsis flag is used, then '...' can be used to
elide substrings in the desired output:
- >>> print range(1000) #doctest: +ELLIPSIS
+ >>> print(range(1000)) #doctest: +ELLIPSIS
[0, 1, 2, ..., 999]
""",
"whitespace normalization": r"""
If the whitespace normalization flag is used, then
differences in whitespace are ignored.
- >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
+ >>> print(range(30)) #doctest: +NORMALIZE_WHITESPACE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29]
Modified: python/branches/p3yk-noslice/Lib/dumbdbm.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/dumbdbm.py (original)
+++ python/branches/p3yk-noslice/Lib/dumbdbm.py Fri Feb 23 18:29:35 2007
@@ -109,7 +109,7 @@
f = self._open(self._dirfile, 'w')
self._chmod(self._dirfile)
- for key, pos_and_siz_pair in self._index.iteritems():
+ for key, pos_and_siz_pair in self._index.items():
f.write("%r, %r\n" % (key, pos_and_siz_pair))
f.close()
@@ -202,7 +202,7 @@
return key in self._index
def iterkeys(self):
- return self._index.iterkeys()
+ return iter(self._index.keys())
__iter__ = iterkeys
def __len__(self):
@@ -243,5 +243,5 @@
else:
# Turn off any bits that are set in the umask
mode = mode & (~um)
-
+
return _Database(file, mode)
Modified: python/branches/p3yk-noslice/Lib/dummy_thread.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/dummy_thread.py (original)
+++ python/branches/p3yk-noslice/Lib/dummy_thread.py Fri Feb 23 18:29:35 2007
@@ -11,11 +11,8 @@
import dummy_thread as thread
"""
-__author__ = "Brett Cannon"
-__email__ = "brett at python.org"
-
-# Exports only things specified by thread documentation
-# (skipping obsolete synonyms allocate(), start_new(), exit_thread())
+# Exports only things specified by thread documentation;
+# skipping obsolete synonyms allocate(), start_new(), exit_thread().
__all__ = ['error', 'start_new_thread', 'exit', 'get_ident', 'allocate_lock',
'interrupt_main', 'LockType']
Modified: python/branches/p3yk-noslice/Lib/dummy_threading.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/dummy_threading.py (original)
+++ python/branches/p3yk-noslice/Lib/dummy_threading.py Fri Feb 23 18:29:35 2007
@@ -5,11 +5,6 @@
directly imported it would have made all subsequent imports succeed
regardless of whether ``thread`` was available which is not desired.
-:Author: Brett Cannon
-:Contact: brett at python.org
-
-XXX: Try to get rid of ``_dummy_threading``.
-
"""
from sys import modules as sys_modules
Modified: python/branches/p3yk-noslice/Lib/email/charset.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/charset.py (original)
+++ python/branches/p3yk-noslice/Lib/email/charset.py Fri Feb 23 18:29:35 2007
@@ -46,6 +46,7 @@
'iso-8859-13': (QP, QP, None),
'iso-8859-14': (QP, QP, None),
'iso-8859-15': (QP, QP, None),
+ 'iso-8859-16': (QP, QP, None),
'windows-1252':(QP, QP, None),
'viscii': (QP, QP, None),
'us-ascii': (None, None, None),
@@ -81,6 +82,8 @@
'latin-8': 'iso-8859-14',
'latin_9': 'iso-8859-15',
'latin-9': 'iso-8859-15',
+ 'latin_10':'iso-8859-16',
+ 'latin-10':'iso-8859-16',
'cp949': 'ks_c_5601-1987',
'euc_jp': 'euc-jp',
'euc_kr': 'euc-kr',
Modified: python/branches/p3yk-noslice/Lib/email/generator.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/generator.py (original)
+++ python/branches/p3yk-noslice/Lib/email/generator.py Fri Feb 23 18:29:35 2007
@@ -80,7 +80,7 @@
ufrom = msg.get_unixfrom()
if not ufrom:
ufrom = 'From nobody ' + time.ctime(time.time())
- print >> self._fp, ufrom
+ print(ufrom, file=self._fp)
self._write(msg)
def clone(self, fp):
@@ -140,13 +140,13 @@
def _write_headers(self, msg):
for h, v in msg.items():
- print >> self._fp, '%s:' % h,
+ print('%s:' % h, end=' ', file=self._fp)
if self._maxheaderlen == 0:
# Explicit no-wrapping
- print >> self._fp, v
+ print(v, file=self._fp)
elif isinstance(v, Header):
# Header instances know what to do
- print >> self._fp, v.encode()
+ print(v.encode(), file=self._fp)
elif _is8bitstring(v):
# If we have raw 8bit data in a byte string, we have no idea
# what the encoding is. There is no safe way to split this
@@ -154,14 +154,14 @@
# ascii split, but if it's multibyte then we could break the
# string. There's no way to know so the least harm seems to
# be to not split the string and risk it being too long.
- print >> self._fp, v
+ print(v, file=self._fp)
else:
# Header's got lots of smarts, so use it.
- print >> self._fp, Header(
+ print(Header(
v, maxlinelen=self._maxheaderlen,
- header_name=h, continuation_ws='\t').encode()
+ header_name=h, continuation_ws='\t').encode(), file=self._fp)
# A blank line always separates headers from body
- print >> self._fp
+ print(file=self._fp)
#
# Handlers for writing types and subtypes
@@ -215,9 +215,9 @@
msg.set_boundary(boundary)
# If there's a preamble, write it out, with a trailing CRLF
if msg.preamble is not None:
- print >> self._fp, msg.preamble
+ print(msg.preamble, file=self._fp)
# dash-boundary transport-padding CRLF
- print >> self._fp, '--' + boundary
+ print('--' + boundary, file=self._fp)
# body-part
if msgtexts:
self._fp.write(msgtexts.pop(0))
@@ -226,13 +226,13 @@
# --> CRLF body-part
for body_part in msgtexts:
# delimiter transport-padding CRLF
- print >> self._fp, '\n--' + boundary
+ print('\n--' + boundary, file=self._fp)
# body-part
self._fp.write(body_part)
# close-delimiter transport-padding
self._fp.write('\n--' + boundary + '--')
if msg.epilogue is not None:
- print >> self._fp
+ print(file=self._fp)
self._fp.write(msg.epilogue)
def _handle_message_delivery_status(self, msg):
@@ -308,12 +308,12 @@
for part in msg.walk():
maintype = part.get_content_maintype()
if maintype == 'text':
- print >> self, part.get_payload(decode=True)
+ print(part.get_payload(decode=True), file=self)
elif maintype == 'multipart':
# Just skip this
pass
else:
- print >> self, self._fmt % {
+ print(self._fmt % {
'type' : part.get_content_type(),
'maintype' : part.get_content_maintype(),
'subtype' : part.get_content_subtype(),
@@ -322,7 +322,7 @@
'[no description]'),
'encoding' : part.get('Content-Transfer-Encoding',
'[no encoding]'),
- }
+ }, file=self)
Modified: python/branches/p3yk-noslice/Lib/email/iterators.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/iterators.py (original)
+++ python/branches/p3yk-noslice/Lib/email/iterators.py Fri Feb 23 18:29:35 2007
@@ -63,11 +63,11 @@
if fp is None:
fp = sys.stdout
tab = ' ' * (level * 4)
- print >> fp, tab + msg.get_content_type(),
+ print(tab + msg.get_content_type(), end='', file=fp)
if include_default:
- print >> fp, '[%s]' % msg.get_default_type()
+ print(' [%s]' % msg.get_default_type(), file=fp)
else:
- print >> fp
+ print(file=fp)
if msg.is_multipart():
for subpart in msg.get_payload():
_structure(subpart, fp, level+1, include_default)
Modified: python/branches/p3yk-noslice/Lib/email/test/test_email.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/test/test_email.py (original)
+++ python/branches/p3yk-noslice/Lib/email/test/test_email.py Fri Feb 23 18:29:35 2007
@@ -54,10 +54,9 @@
if first != second:
sfirst = str(first)
ssecond = str(second)
- diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines())
- fp = StringIO()
- print >> fp, NL, NL.join(diff)
- raise self.failureException, fp.getvalue()
+ diff = difflib.ndiff(sfirst.splitlines(True),
+ ssecond.splitlines(True))
+ raise self.failureException(NL + "".join(diff))
def _msgobj(self, filename):
fp = openfile(findfile(filename))
Modified: python/branches/p3yk-noslice/Lib/email/test/test_email_codecs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/test/test_email_codecs.py (original)
+++ python/branches/p3yk-noslice/Lib/email/test/test_email_codecs.py Fri Feb 23 18:29:35 2007
@@ -41,8 +41,8 @@
[('Hello World!', None),
('\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'),
('Gr\xfc\xdf Gott!', 'iso-8859-1')])
- long = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9'
- h = Header(long, j, header_name="Subject")
+ int = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9'
+ h = Header(int, j, header_name="Subject")
# test a very long header
enc = h.encode()
# TK: splitting point may differ by codec design and/or Header encoding
@@ -50,7 +50,7 @@
=?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?=
=?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""")
# TK: full decode comparison
- eq(h.__unicode__().encode('euc-jp'), long)
+ eq(h.__unicode__().encode('euc-jp'), int)
def test_payload_encoding(self):
jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa'
Modified: python/branches/p3yk-noslice/Lib/email/test/test_email_codecs_renamed.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/test/test_email_codecs_renamed.py (original)
+++ python/branches/p3yk-noslice/Lib/email/test/test_email_codecs_renamed.py Fri Feb 23 18:29:35 2007
@@ -41,8 +41,8 @@
[('Hello World!', None),
('\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'),
('Gr\xfc\xdf Gott!', 'iso-8859-1')])
- long = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9'
- h = Header(long, j, header_name="Subject")
+ int = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9'
+ h = Header(int, j, header_name="Subject")
# test a very long header
enc = h.encode()
# TK: splitting point may differ by codec design and/or Header encoding
@@ -50,7 +50,7 @@
=?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?=
=?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""")
# TK: full decode comparison
- eq(h.__unicode__().encode('euc-jp'), long)
+ eq(h.__unicode__().encode('euc-jp'), int)
def test_payload_encoding(self):
jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa'
Modified: python/branches/p3yk-noslice/Lib/email/test/test_email_renamed.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/email/test/test_email_renamed.py (original)
+++ python/branches/p3yk-noslice/Lib/email/test/test_email_renamed.py Fri Feb 23 18:29:35 2007
@@ -55,10 +55,9 @@
if first != second:
sfirst = str(first)
ssecond = str(second)
- diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines())
- fp = StringIO()
- print >> fp, NL, NL.join(diff)
- raise self.failureException, fp.getvalue()
+ diff = difflib.ndiff(sfirst.splitlines(True),
+ ssecond.splitlines(True))
+ raise self.failureException(NL + "".join(diff))
def _msgobj(self, filename):
fp = openfile(findfile(filename))
Modified: python/branches/p3yk-noslice/Lib/encodings/__init__.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/encodings/__init__.py (original)
+++ python/branches/p3yk-noslice/Lib/encodings/__init__.py Fri Feb 23 18:29:35 2007
@@ -93,8 +93,10 @@
if not modname or '.' in modname:
continue
try:
- mod = __import__('encodings.' + modname,
- globals(), locals(), _import_tail)
+ # Import is absolute to prevent the possibly malicious import of a
+ # module with side-effects that is not in the 'encodings' package.
+ mod = __import__('encodings.' + modname, fromlist=_import_tail,
+ level=0)
except ImportError:
pass
else:
Modified: python/branches/p3yk-noslice/Lib/encodings/aliases.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/encodings/aliases.py (original)
+++ python/branches/p3yk-noslice/Lib/encodings/aliases.py Fri Feb 23 18:29:35 2007
@@ -301,6 +301,8 @@
# iso8859_13 codec
'iso_8859_13' : 'iso8859_13',
+ 'l7' : 'iso8859_13',
+ 'latin7' : 'iso8859_13',
# iso8859_14 codec
'iso_8859_14' : 'iso8859_14',
@@ -312,6 +314,8 @@
# iso8859_15 codec
'iso_8859_15' : 'iso8859_15',
+ 'l9' : 'iso8859_15',
+ 'latin9' : 'iso8859_15',
# iso8859_16 codec
'iso_8859_16' : 'iso8859_16',
Modified: python/branches/p3yk-noslice/Lib/encodings/punycode.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/encodings/punycode.py (original)
+++ python/branches/p3yk-noslice/Lib/encodings/punycode.py Fri Feb 23 18:29:35 2007
@@ -17,8 +17,7 @@
base.append(c)
else:
extended[c] = 1
- extended = extended.keys()
- extended.sort()
+ extended = sorted(extended.keys())
return "".join(base).encode("ascii"),extended
def selective_len(str, max):
Modified: python/branches/p3yk-noslice/Lib/filecmp.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/filecmp.py (original)
+++ python/branches/p3yk-noslice/Lib/filecmp.py Fri Feb 23 18:29:35 2007
@@ -187,44 +187,44 @@
def phase4_closure(self): # Recursively call phase4() on subdirectories
self.phase4()
- for sd in self.subdirs.itervalues():
+ for sd in self.subdirs.values():
sd.phase4_closure()
def report(self): # Print a report on the differences between a and b
# Output format is purposely lousy
- print 'diff', self.left, self.right
+ print('diff', self.left, self.right)
if self.left_only:
self.left_only.sort()
- print 'Only in', self.left, ':', self.left_only
+ print('Only in', self.left, ':', self.left_only)
if self.right_only:
self.right_only.sort()
- print 'Only in', self.right, ':', self.right_only
+ print('Only in', self.right, ':', self.right_only)
if self.same_files:
self.same_files.sort()
- print 'Identical files :', self.same_files
+ print('Identical files :', self.same_files)
if self.diff_files:
self.diff_files.sort()
- print 'Differing files :', self.diff_files
+ print('Differing files :', self.diff_files)
if self.funny_files:
self.funny_files.sort()
- print 'Trouble with common files :', self.funny_files
+ print('Trouble with common files :', self.funny_files)
if self.common_dirs:
self.common_dirs.sort()
- print 'Common subdirectories :', self.common_dirs
+ print('Common subdirectories :', self.common_dirs)
if self.common_funny:
self.common_funny.sort()
- print 'Common funny cases :', self.common_funny
+ print('Common funny cases :', self.common_funny)
def report_partial_closure(self): # Print reports on self and on subdirs
self.report()
- for sd in self.subdirs.itervalues():
- print
+ for sd in self.subdirs.values():
+ print()
sd.report()
def report_full_closure(self): # Report on self and subdirs recursively
self.report()
- for sd in self.subdirs.itervalues():
- print
+ for sd in self.subdirs.values():
+ print()
sd.report_full_closure()
methodmap = dict(subdirs=phase4,
Modified: python/branches/p3yk-noslice/Lib/fileinput.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/fileinput.py (original)
+++ python/branches/p3yk-noslice/Lib/fileinput.py Fri Feb 23 18:29:35 2007
@@ -405,9 +405,9 @@
for line in input(args, inplace=inplace, backup=backup):
if line[-1:] == '\n': line = line[:-1]
if line[-1:] == '\r': line = line[:-1]
- print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
- isfirstline() and "*" or "", line)
- print "%d: %s[%d]" % (lineno(), filename(), filelineno())
+ print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
+ isfirstline() and "*" or "", line))
+ print("%d: %s[%d]" % (lineno(), filename(), filelineno()))
if __name__ == '__main__':
_test()
Modified: python/branches/p3yk-noslice/Lib/formatter.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/formatter.py (original)
+++ python/branches/p3yk-noslice/Lib/formatter.py Fri Feb 23 18:29:35 2007
@@ -323,37 +323,37 @@
"""
def new_alignment(self, align):
- print "new_alignment(%r)" % (align,)
+ print("new_alignment(%r)" % (align,))
def new_font(self, font):
- print "new_font(%r)" % (font,)
+ print("new_font(%r)" % (font,))
def new_margin(self, margin, level):
- print "new_margin(%r, %d)" % (margin, level)
+ print("new_margin(%r, %d)" % (margin, level))
def new_spacing(self, spacing):
- print "new_spacing(%r)" % (spacing,)
+ print("new_spacing(%r)" % (spacing,))
def new_styles(self, styles):
- print "new_styles(%r)" % (styles,)
+ print("new_styles(%r)" % (styles,))
def send_paragraph(self, blankline):
- print "send_paragraph(%r)" % (blankline,)
+ print("send_paragraph(%r)" % (blankline,))
def send_line_break(self):
- print "send_line_break()"
+ print("send_line_break()")
def send_hor_rule(self, *args, **kw):
- print "send_hor_rule()"
+ print("send_hor_rule()")
def send_label_data(self, data):
- print "send_label_data(%r)" % (data,)
+ print("send_label_data(%r)" % (data,))
def send_flowing_data(self, data):
- print "send_flowing_data(%r)" % (data,)
+ print("send_flowing_data(%r)" % (data,))
def send_literal_data(self, data):
- print "send_literal_data(%r)" % (data,)
+ print("send_literal_data(%r)" % (data,))
class DumbWriter(NullWriter):
Modified: python/branches/p3yk-noslice/Lib/fpformat.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/fpformat.py (original)
+++ python/branches/p3yk-noslice/Lib/fpformat.py Fri Feb 23 18:29:35 2007
@@ -137,6 +137,6 @@
try:
while 1:
x, digs = input('Enter (x, digs): ')
- print x, fix(x, digs), sci(x, digs)
+ print(x, fix(x, digs), sci(x, digs))
except (EOFError, KeyboardInterrupt):
pass
Modified: python/branches/p3yk-noslice/Lib/ftplib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ftplib.py (original)
+++ python/branches/p3yk-noslice/Lib/ftplib.py Fri Feb 23 18:29:35 2007
@@ -119,7 +119,8 @@
try:
self.sock = socket.socket(af, socktype, proto)
self.sock.connect(sa)
- except socket.error as msg:
+ except socket.error as err:
+ msg = err
if self.sock:
self.sock.close()
self.sock = None
@@ -136,7 +137,7 @@
'''Get the welcome message from the server.
(this is read and squirreled away by connect())'''
if self.debugging:
- print '*welcome*', self.sanitize(self.welcome)
+ print('*welcome*', self.sanitize(self.welcome))
return self.welcome
def set_debuglevel(self, level):
@@ -166,12 +167,12 @@
# Internal: send one line to the server, appending CRLF
def putline(self, line):
line = line + CRLF
- if self.debugging > 1: print '*put*', self.sanitize(line)
+ if self.debugging > 1: print('*put*', self.sanitize(line))
self.sock.sendall(line)
# Internal: send one command to the server (through putline())
def putcmd(self, line):
- if self.debugging: print '*cmd*', self.sanitize(line)
+ if self.debugging: print('*cmd*', self.sanitize(line))
self.putline(line)
# Internal: return one line from the server, stripping CRLF.
@@ -179,7 +180,7 @@
def getline(self):
line = self.file.readline()
if self.debugging > 1:
- print '*get*', self.sanitize(line)
+ print('*get*', self.sanitize(line))
if not line: raise EOFError
if line[-2:] == CRLF: line = line[:-2]
elif line[-1:] in CRLF: line = line[:-1]
@@ -205,7 +206,7 @@
# Raise various errors if the response indicates an error
def getresp(self):
resp = self.getmultiline()
- if self.debugging: print '*resp*', self.sanitize(resp)
+ if self.debugging: print('*resp*', self.sanitize(resp))
self.lastresp = resp[:3]
c = resp[:1]
if c in ('1', '2', '3'):
@@ -229,7 +230,7 @@
IP and Synch; that doesn't seem to work with the servers I've
tried. Instead, just send the ABOR command as OOB data.'''
line = 'ABOR' + CRLF
- if self.debugging > 1: print '*put urgent*', self.sanitize(line)
+ if self.debugging > 1: print('*put urgent*', self.sanitize(line))
self.sock.sendall(line, MSG_OOB)
resp = self.getmultiline()
if resp[:3] not in ('426', '226'):
@@ -332,7 +333,7 @@
# 1xx or error messages for LIST), so we just discard
# this response.
if resp[0] == '2':
- resp = self.getresp()
+ resp = self.getresp()
if resp[0] != '1':
raise error_reply, resp
else:
@@ -342,7 +343,7 @@
resp = self.sendcmd(cmd)
# See above.
if resp[0] == '2':
- resp = self.getresp()
+ resp = self.getresp()
if resp[0] != '1':
raise error_reply, resp
conn, sockaddr = sock.accept()
@@ -408,7 +409,7 @@
fp = conn.makefile('rb')
while 1:
line = fp.readline()
- if self.debugging > 2: print '*retr*', repr(line)
+ if self.debugging > 2: print('*retr*', repr(line))
if not line:
break
if line[-2:] == CRLF:
@@ -513,7 +514,7 @@
try:
return int(s)
except (OverflowError, ValueError):
- return long(s)
+ return int(s)
def mkd(self, dirname):
'''Make a directory, return its full pathname.'''
@@ -563,7 +564,7 @@
try:
return int(s)
except (OverflowError, ValueError):
- return long(s)
+ return int(s)
_227_re = None
@@ -635,7 +636,7 @@
def print_line(line):
'''Default retrlines callback to print a line.'''
- print line
+ print(line)
def ftpcp(source, sourcename, target, targetname = '', type = 'I'):
@@ -774,7 +775,7 @@
'''
if len(sys.argv) < 2:
- print test.__doc__
+ print(test.__doc__)
sys.exit(0)
debugging = 0
Modified: python/branches/p3yk-noslice/Lib/getopt.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/getopt.py (original)
+++ python/branches/p3yk-noslice/Lib/getopt.py Fri Feb 23 18:29:35 2007
@@ -208,4 +208,4 @@
if __name__ == '__main__':
import sys
- print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])
+ print(getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]))
Modified: python/branches/p3yk-noslice/Lib/getpass.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/getpass.py (original)
+++ python/branches/p3yk-noslice/Lib/getpass.py Fri Feb 23 18:29:35 2007
@@ -67,7 +67,7 @@
def default_getpass(prompt='Password: ', stream=None):
- print >>sys.stderr, "Warning: Problem with getpass. Passwords may be echoed."
+ print("Warning: Problem with getpass. Passwords may be echoed.", file=sys.stderr)
return _raw_input(prompt, stream)
Modified: python/branches/p3yk-noslice/Lib/gettext.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/gettext.py (original)
+++ python/branches/p3yk-noslice/Lib/gettext.py Fri Feb 23 18:29:35 2007
@@ -256,8 +256,8 @@
class GNUTranslations(NullTranslations):
# Magic number of .mo files
- LE_MAGIC = 0x950412deL
- BE_MAGIC = 0xde120495L
+ LE_MAGIC = 0x950412de
+ BE_MAGIC = 0xde120495
def _parse(self, fp):
"""Override this method to support alternative .mo formats."""
Modified: python/branches/p3yk-noslice/Lib/gopherlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/gopherlib.py (original)
+++ python/branches/p3yk-noslice/Lib/gopherlib.py Fri Feb 23 18:29:35 2007
@@ -103,7 +103,7 @@
while 1:
line = f.readline()
if not line:
- print '(Unexpected EOF from server)'
+ print('(Unexpected EOF from server)')
break
if line[-2:] == CRLF:
line = line[:-2]
@@ -112,17 +112,17 @@
if line == '.':
break
if not line:
- print '(Empty line from server)'
+ print('(Empty line from server)')
continue
gtype = line[0]
parts = line[1:].split(TAB)
if len(parts) < 4:
- print '(Bad line from server: %r)' % (line,)
+ print('(Bad line from server: %r)' % (line,))
continue
if len(parts) > 4:
if parts[4:] != ['+']:
- print '(Extra info from server:',
- print parts[4:], ')'
+ print('(Extra info from server:', end=' ')
+ print(parts[4:], ')')
else:
parts.append('')
parts.insert(0, gtype)
@@ -140,7 +140,7 @@
while 1:
line = f.readline()
if not line:
- print '(Unexpected EOF from server)'
+ print('(Unexpected EOF from server)')
break
if line[-2:] == CRLF:
line = line[:-2]
@@ -196,13 +196,13 @@
f = send_selector(selector, host)
if type == A_TEXT:
lines = get_textfile(f)
- for item in lines: print item
+ for item in lines: print(item)
elif type in (A_MENU, A_INDEX):
entries = get_directory(f)
- for item in entries: print item
+ for item in entries: print(item)
else:
data = get_binary(f)
- print 'binary data:', len(data), 'bytes:', repr(data[:100])[:40]
+ print('binary data:', len(data), 'bytes:', repr(data[:100])[:40])
# Run the test when run as script
if __name__ == '__main__':
Modified: python/branches/p3yk-noslice/Lib/gzip.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/gzip.py (original)
+++ python/branches/p3yk-noslice/Lib/gzip.py Fri Feb 23 18:29:35 2007
@@ -21,12 +21,12 @@
If it's >= 2GB when viewed as a 32-bit unsigned int, return a long.
"""
if i < 0:
- i += 1L << 32
+ i += 1 << 32
return i
def LOWU32(i):
"""Return the low-order 32 bits of an int, as a non-negative int."""
- return i & 0xFFFFFFFFL
+ return i & 0xFFFFFFFF
def write32(output, value):
output.write(struct.pack("<l", value))
@@ -106,7 +106,7 @@
self._new_member = True
self.extrabuf = ""
self.extrasize = 0
- self.filename = filename
+ self.name = filename
# Starts small, scales exponentially
self.min_readsize = 100
@@ -127,14 +127,20 @@
if self.mode == WRITE:
self._write_gzip_header()
+ @property
+ def filename(self):
+ import warnings
+ warnings.warn("use the name attribute", DeprecationWarning)
+ if self.mode == WRITE and self.name[-3:] != ".gz":
+ return self.name + ".gz"
+ return self.name
+
def __repr__(self):
s = repr(self.fileobj)
return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
def _init_write(self, filename):
- if filename[-3:] != '.gz':
- filename = filename + '.gz'
- self.filename = filename
+ self.name = filename
self.crc = zlib.crc32("")
self.size = 0
self.writebuf = []
@@ -143,12 +149,14 @@
def _write_gzip_header(self):
self.fileobj.write('\037\213') # magic header
self.fileobj.write('\010') # compression method
- fname = self.filename[:-3]
+ fname = self.name
+ if fname.endswith(".gz"):
+ fname = fname[:-3]
flags = 0
if fname:
flags = FNAME
self.fileobj.write(chr(flags))
- write32u(self.fileobj, long(time.time()))
+ write32u(self.fileobj, int(time.time()))
self.fileobj.write('\002')
self.fileobj.write('\377')
if fname:
@@ -470,7 +478,7 @@
g = sys.stdout
else:
if arg[-3:] != ".gz":
- print "filename doesn't end in .gz:", repr(arg)
+ print("filename doesn't end in .gz:", repr(arg))
continue
f = open(arg, "rb")
g = __builtin__.open(arg[:-3], "wb")
Modified: python/branches/p3yk-noslice/Lib/heapq.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/heapq.py (original)
+++ python/branches/p3yk-noslice/Lib/heapq.py Fri Feb 23 18:29:35 2007
@@ -126,8 +126,8 @@
From all times, sorting has always been a Great Art! :-)
"""
-__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'nlargest',
- 'nsmallest']
+__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge',
+ 'nlargest', 'nsmallest']
from itertools import islice, repeat, count, imap, izip, tee
from operator import itemgetter, neg
@@ -308,6 +308,41 @@
except ImportError:
pass
+def merge(*iterables):
+ '''Merge multiple sorted inputs into a single sorted output.
+
+ Similar to sorted(itertools.chain(*iterables)) but returns an iterable,
+ does not pull the data into memory all at once, and assumes that each of
+ the input streams is already sorted (smallest to largest).
+
+ >>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
+ [0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
+
+ '''
+ _heappop, _heapreplace, _StopIteration = heappop, heapreplace, StopIteration
+
+ h = []
+ h_append = h.append
+ for itnum, it in enumerate(map(iter, iterables)):
+ try:
+ next = it.next
+ h_append([next(), itnum, next])
+ except _StopIteration:
+ pass
+ heapify(h)
+
+ while 1:
+ try:
+ while 1:
+ v, itnum, next = s = h[0] # raises IndexError when h is empty
+ yield v
+ s[0] = next() # raises StopIteration when exhausted
+ _heapreplace(h, s) # restore heap condition
+ except _StopIteration:
+ _heappop(h) # remove empty iterator
+ except IndexError:
+ return
+
# Extend the implementations of nsmallest and nlargest to use a key= argument
_nsmallest = nsmallest
def nsmallest(n, iterable, key=None):
@@ -340,4 +375,7 @@
sort = []
while heap:
sort.append(heappop(heap))
- print sort
+ print(sort)
+
+ import doctest
+ doctest.testmod()
Modified: python/branches/p3yk-noslice/Lib/hotshot/log.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/hotshot/log.py (original)
+++ python/branches/p3yk-noslice/Lib/hotshot/log.py Fri Feb 23 18:29:35 2007
@@ -159,7 +159,7 @@
try:
filename = self._filemap[fileno]
except KeyError:
- print "Could not identify fileId", fileno
+ print("Could not identify fileId", fileno)
return 1
if filename is None:
return 1
Modified: python/branches/p3yk-noslice/Lib/hotshot/stones.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/hotshot/stones.py (original)
+++ python/branches/p3yk-noslice/Lib/hotshot/stones.py Fri Feb 23 18:29:35 2007
@@ -10,9 +10,9 @@
benchtime, stones = p.runcall(test.pystone.pystones)
p.close()
- print "Pystone(%s) time for %d passes = %g" % \
- (test.pystone.__version__, test.pystone.LOOPS, benchtime)
- print "This machine benchmarks at %g pystones/second" % stones
+ print("Pystone(%s) time for %d passes = %g" % \
+ (test.pystone.__version__, test.pystone.LOOPS, benchtime))
+ print("This machine benchmarks at %g pystones/second" % stones)
stats = hotshot.stats.load(logfile)
stats.strip_dirs()
Modified: python/branches/p3yk-noslice/Lib/htmlentitydefs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/htmlentitydefs.py (original)
+++ python/branches/p3yk-noslice/Lib/htmlentitydefs.py Fri Feb 23 18:29:35 2007
@@ -263,7 +263,7 @@
# (or a character reference if the character is outside the Latin-1 range)
entitydefs = {}
-for (name, codepoint) in name2codepoint.iteritems():
+for (name, codepoint) in name2codepoint.items():
codepoint2name[codepoint] = name
if codepoint <= 0xff:
entitydefs[name] = chr(codepoint)
Modified: python/branches/p3yk-noslice/Lib/htmllib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/htmllib.py (original)
+++ python/branches/p3yk-noslice/Lib/htmllib.py Fri Feb 23 18:29:35 2007
@@ -464,7 +464,7 @@
try:
f = open(file, 'r')
except IOError as msg:
- print file, ":", msg
+ print(file, ":", msg)
sys.exit(1)
data = f.read()
Modified: python/branches/p3yk-noslice/Lib/httplib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/httplib.py (original)
+++ python/branches/p3yk-noslice/Lib/httplib.py Fri Feb 23 18:29:35 2007
@@ -342,7 +342,7 @@
# Initialize with Simple-Response defaults
line = self.fp.readline()
if self.debuglevel > 0:
- print "reply:", repr(line)
+ print("reply:", repr(line))
if not line:
# Presumably, the server closed the connection before
# sending a valid response.
@@ -391,7 +391,7 @@
if not skip:
break
if self.debuglevel > 0:
- print "header:", skip
+ print("header:", skip)
self.status = status
self.reason = reason.strip()
@@ -414,7 +414,7 @@
self.msg = HTTPMessage(self.fp, 0)
if self.debuglevel > 0:
for hdr in self.msg.headers:
- print "header:", hdr,
+ print("header:", hdr, end=' ')
# don't let the msg keep an fp
self.msg.fp = None
@@ -611,7 +611,7 @@
"""Return list of (header, value) tuples."""
if self.msg is None:
raise ResponseNotReady()
- return self.msg.items()
+ return list(self.msg.items())
class HTTPConnection:
@@ -665,11 +665,11 @@
try:
self.sock = socket.socket(af, socktype, proto)
if self.debuglevel > 0:
- print "connect: (%s, %s)" % (self.host, self.port)
+ print("connect: (%s, %s)" % (self.host, self.port))
self.sock.connect(sa)
except socket.error as msg:
if self.debuglevel > 0:
- print 'connect fail:', (self.host, self.port)
+ print('connect fail:', (self.host, self.port))
if self.sock:
self.sock.close()
self.sock = None
@@ -702,11 +702,11 @@
# NOTE: we DO propagate the error, though, because we cannot simply
# ignore the error... the caller will know if they can retry.
if self.debuglevel > 0:
- print "send:", repr(str)
+ print("send:", repr(str))
try:
blocksize=8192
if hasattr(str,'read') :
- if self.debuglevel > 0: print "sendIng a read()able"
+ if self.debuglevel > 0: print("sendIng a read()able")
data=str.read(blocksize)
while data:
self.sock.sendall(data)
@@ -898,11 +898,11 @@
thelen = str(os.fstat(body.fileno()).st_size)
except (AttributeError, OSError):
# Don't send a length if this failed
- if self.debuglevel > 0: print "Cannot stat!!"
-
+ if self.debuglevel > 0: print("Cannot stat!!")
+
if thelen is not None:
self.putheader('Content-Length',thelen)
- for hdr, value in headers.iteritems():
+ for hdr, value in headers.items():
self.putheader(hdr, value)
self.endheaders()
@@ -1408,13 +1408,13 @@
h.putrequest('GET', selector)
h.endheaders()
status, reason, headers = h.getreply()
- print 'status =', status
- print 'reason =', reason
- print "read", len(h.getfile().read())
- print
+ print('status =', status)
+ print('reason =', reason)
+ print("read", len(h.getfile().read()))
+ print()
if headers:
- for header in headers.headers: print header.strip()
- print
+ for header in headers.headers: print(header.strip())
+ print()
# minimal test that code to extract host from url works
class HTTP11(HTTP):
@@ -1431,20 +1431,20 @@
for host, selector in (('sourceforge.net', '/projects/python'),
):
- print "https://%s%s" % (host, selector)
+ print("https://%s%s" % (host, selector))
hs = HTTPS()
hs.set_debuglevel(dl)
hs.connect(host)
hs.putrequest('GET', selector)
hs.endheaders()
status, reason, headers = hs.getreply()
- print 'status =', status
- print 'reason =', reason
- print "read", len(hs.getfile().read())
- print
+ print('status =', status)
+ print('reason =', reason)
+ print("read", len(hs.getfile().read()))
+ print()
if headers:
- for header in headers.headers: print header.strip()
- print
+ for header in headers.headers: print(header.strip())
+ print()
if __name__ == '__main__':
test()
Modified: python/branches/p3yk-noslice/Lib/idlelib/AutoCompleteWindow.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/AutoCompleteWindow.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/AutoCompleteWindow.py Fri Feb 23 18:29:35 2007
@@ -10,13 +10,14 @@
KEYPRESS_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keypress>>"
# We need to bind event beyond <Key> so that the function will be called
# before the default specific IDLE function
-KEYPRESS_SEQUENCES = ("<Key>", "<Key-BackSpace>", "<Key-Return>",
- "<Key-Up>", "<Key-Down>", "<Key-Home>", "<Key-End>")
+KEYPRESS_SEQUENCES = ("<Key>", "<Key-BackSpace>", "<Key-Return>", "<Key-Tab>",
+ "<Key-Up>", "<Key-Down>", "<Key-Home>", "<Key-End>",
+ "<Key-Prior>", "<Key-Next>")
KEYRELEASE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keyrelease>>"
KEYRELEASE_SEQUENCE = "<KeyRelease>"
-LISTUPDATE_SEQUENCE = "<ButtonRelease>"
+LISTUPDATE_SEQUENCE = "<B1-ButtonRelease>"
WINCONFIG_SEQUENCE = "<Configure>"
-DOUBLECLICK_SEQUENCE = "<Double-ButtonRelease>"
+DOUBLECLICK_SEQUENCE = "<B1-Double-ButtonRelease>"
class AutoCompleteWindow:
@@ -49,6 +50,8 @@
# event ids
self.hideid = self.keypressid = self.listupdateid = self.winconfigid \
= self.keyreleaseid = self.doubleclickid = None
+ # Flag set if last keypress was a tab
+ self.lastkey_was_tab = False
def _change_start(self, newstart):
i = 0
@@ -118,11 +121,6 @@
i = 0
while i < len(lts) and i < len(selstart) and lts[i] == selstart[i]:
i += 1
- previous_completion = self.completions[cursel - 1]
- while cursel > 0 and selstart[:i] <= previous_completion:
- i += 1
- if selstart == previous_completion:
- break # maybe we have a duplicate?
newstart = selstart[:i]
self._change_start(newstart)
@@ -206,7 +204,7 @@
self.keyrelease_event)
self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE)
self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE,
- self.listupdate_event)
+ self.listselect_event)
self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event)
self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE,
self.doubleclick_event)
@@ -215,24 +213,34 @@
if not self.is_active():
return
# Position the completion list window
+ text = self.widget
+ text.see(self.startindex)
+ x, y, cx, cy = text.bbox(self.startindex)
acw = self.autocompletewindow
- self.widget.see(self.startindex)
- x, y, cx, cy = self.widget.bbox(self.startindex)
- acw.wm_geometry("+%d+%d" % (x + self.widget.winfo_rootx(),
- y + self.widget.winfo_rooty() \
- -acw.winfo_height()))
-
+ acw_width, acw_height = acw.winfo_width(), acw.winfo_height()
+ text_width, text_height = text.winfo_width(), text.winfo_height()
+ new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width))
+ new_y = text.winfo_rooty() + y
+ if (text_height - (y + cy) >= acw_height # enough height below
+ or y < acw_height): # not enough height above
+ # place acw below current line
+ new_y += cy
+ else:
+ # place acw above current line
+ new_y -= acw_height
+ acw.wm_geometry("+%d+%d" % (new_x, new_y))
def hide_event(self, event):
if not self.is_active():
return
self.hide_window()
- def listupdate_event(self, event):
+ def listselect_event(self, event):
if not self.is_active():
return
self.userwantswindow = True
- self._selection_changed()
+ cursel = int(self.listbox.curselection()[0])
+ self._change_start(self.completions[cursel])
def doubleclick_event(self, event):
# Put the selected completion in the text, and close the list
@@ -248,7 +256,8 @@
state = event.mc_state
else:
state = 0
-
+ if keysym != "Tab":
+ self.lastkey_was_tab = False
if (len(keysym) == 1 or keysym in ("underscore", "BackSpace")
or (self.mode==AutoComplete.COMPLETE_FILES and keysym in
("period", "minus"))) \
@@ -330,13 +339,21 @@
self.listbox.select_clear(cursel)
self.listbox.select_set(newsel)
self._selection_changed()
+ self._change_start(self.completions[newsel])
return "break"
elif (keysym == "Tab" and not state):
- # The user wants a completion, but it is handled by AutoComplete
- # (not AutoCompleteWindow), so ignore.
- self.userwantswindow = True
- return
+ if self.lastkey_was_tab:
+ # two tabs in a row; insert current selection and close acw
+ cursel = int(self.listbox.curselection()[0])
+ self._change_start(self.completions[cursel])
+ self.hide_window()
+ return "break"
+ else:
+ # first tab; let AutoComplete handle the completion
+ self.userwantswindow = True
+ self.lastkey_was_tab = True
+ return
elif any(s in keysym for s in ("Shift", "Control", "Alt",
"Meta", "Command", "Option")):
Modified: python/branches/p3yk-noslice/Lib/idlelib/CallTips.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/CallTips.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/CallTips.py Fri Feb 23 18:29:35 2007
@@ -3,7 +3,9 @@
Call Tips are floating windows which display function, class, and method
parameter and docstring information when you type an opening parenthesis, and
which disappear when you type a closing parenthesis.
+
"""
+import re
import sys
import types
@@ -89,6 +91,8 @@
two unrelated modules are being edited some calltips in the current
module may be inoperative if the module was not the last to run.
+ To find methods, fetch_tip must be fed a fully qualified name.
+
"""
try:
rpcclt = self.editwin.flist.pyshell.interp.rpcclt
@@ -108,7 +112,7 @@
namespace.update(__main__.__dict__)
try:
return eval(name, namespace)
- except:
+ except (NameError, AttributeError):
return None
def _find_constructor(class_ob):
@@ -124,39 +128,37 @@
def get_arg_text(ob):
"""Get a string describing the arguments for the given object"""
- argText = ""
+ arg_text = ""
if ob is not None:
- argOffset = 0
+ arg_offset = 0
if type(ob) in (types.ClassType, types.TypeType):
# Look for the highest __init__ in the class chain.
fob = _find_constructor(ob)
if fob is None:
fob = lambda: None
else:
- argOffset = 1
+ arg_offset = 1
elif type(ob)==types.MethodType:
# bit of a hack for methods - turn it into a function
# but we drop the "self" param.
fob = ob.im_func
- argOffset = 1
+ arg_offset = 1
else:
fob = ob
- # Try and build one for Python defined functions
+ # Try to build one for Python defined functions
if type(fob) in [types.FunctionType, types.LambdaType]:
- try:
- realArgs = fob.func_code.co_varnames[argOffset:fob.func_code.co_argcount]
- defaults = fob.func_defaults or []
- defaults = list(map(lambda name: "=%s" % repr(name), defaults))
- defaults = [""] * (len(realArgs)-len(defaults)) + defaults
- items = map(lambda arg, dflt: arg+dflt, realArgs, defaults)
- if fob.func_code.co_flags & 0x4:
- items.append("...")
- if fob.func_code.co_flags & 0x8:
- items.append("***")
- argText = ", ".join(items)
- argText = "(%s)" % argText
- except:
- pass
+ argcount = fob.func_code.co_argcount
+ real_args = fob.func_code.co_varnames[arg_offset:argcount]
+ defaults = fob.func_defaults or []
+ defaults = list(map(lambda name: "=%s" % repr(name), defaults))
+ defaults = [""] * (len(real_args) - len(defaults)) + defaults
+ items = map(lambda arg, dflt: arg + dflt, real_args, defaults)
+ if fob.func_code.co_flags & 0x4:
+ items.append("...")
+ if fob.func_code.co_flags & 0x8:
+ items.append("***")
+ arg_text = ", ".join(items)
+ arg_text = "(%s)" % re.sub("\.\d+", "<tuple>", arg_text)
# See if we can use the docstring
doc = getattr(ob, "__doc__", "")
if doc:
@@ -164,10 +166,10 @@
pos = doc.find("\n")
if pos < 0 or pos > 70:
pos = 70
- if argText:
- argText += "\n"
- argText += doc[:pos]
- return argText
+ if arg_text:
+ arg_text += "\n"
+ arg_text += doc[:pos]
+ return arg_text
#################################################
#
@@ -181,16 +183,18 @@
def t4(*args): "(...)"
def t5(a, *args): "(a, ...)"
def t6(a, b=None, *args, **kw): "(a, b=None, ..., ***)"
+ def t7((a, b), c, (d, e)): "(<tuple>, c, <tuple>)"
- class TC:
- "(a=None, ...)"
- def __init__(self, a=None, *b): "(a=None, ...)"
+ class TC(object):
+ "(ai=None, ...)"
+ def __init__(self, ai=None, *b): "(ai=None, ...)"
def t1(self): "()"
- def t2(self, a, b=None): "(a, b=None)"
- def t3(self, a, *args): "(a, ...)"
+ def t2(self, ai, b=None): "(ai, b=None)"
+ def t3(self, ai, *args): "(ai, ...)"
def t4(self, *args): "(...)"
- def t5(self, a, *args): "(a, ...)"
- def t6(self, a, b=None, *args, **kw): "(a, b=None, ..., ***)"
+ def t5(self, ai, *args): "(ai, ...)"
+ def t6(self, ai, b=None, *args, **kw): "(ai, b=None, ..., ***)"
+ def t7(self, (ai, b), c, (d, e)): "(<tuple>, c, <tuple>)"
def test(tests):
ct = CallTips()
@@ -198,15 +202,20 @@
for t in tests:
expected = t.__doc__ + "\n" + t.__doc__
name = t.__name__
- arg_text = ct.fetch_tip(name)
+ # exercise fetch_tip(), not just get_arg_text()
+ try:
+ qualified_name = "%s.%s" % (t.im_class.__name__, name)
+ except AttributeError:
+ qualified_name = name
+ arg_text = ct.fetch_tip(qualified_name)
if arg_text != expected:
failed.append(t)
- print "%s - expected %s, but got %s" % (t, expected,
- get_arg_text(entity))
- print "%d of %d tests failed" % (len(failed), len(tests))
+ fmt = "%s - expected %s, but got %s"
+ print(fmt % (t.__name__, expected, get_arg_text(t)))
+ print("%d of %d tests failed" % (len(failed), len(tests)))
tc = TC()
- tests = (t1, t2, t3, t4, t5, t6,
- TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6)
+ tests = (t1, t2, t3, t4, t5, t6, t7,
+ TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6, tc.t7)
test(tests)
Modified: python/branches/p3yk-noslice/Lib/idlelib/CodeContext.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/CodeContext.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/CodeContext.py Fri Feb 23 18:29:35 2007
@@ -10,6 +10,7 @@
"""
import Tkinter
+from Tkconstants import TOP, LEFT, X, W, SUNKEN
from configHandler import idleConf
import re
from sys import maxint as INFINITY
@@ -24,7 +25,6 @@
class CodeContext:
menudefs = [('options', [('!Code Conte_xt', '<<toggle-code-context>>')])]
-
context_depth = idleConf.GetOption("extensions", "CodeContext",
"numlines", type="int", default=3)
bgcolor = idleConf.GetOption("extensions", "CodeContext",
@@ -54,66 +54,33 @@
def toggle_code_context_event(self, event=None):
if not self.label:
- # The following code attempts to figure out the required border
- # width and vertical padding required for the CodeContext widget
- # to be perfectly aligned with the text in the main Text widget.
- # This is done by retrieving the appropriate attributes from the
- # editwin.text and editwin.text_frame widgets.
+ # Calculate the border width and horizontal padding required to
+ # align the context with the text in the main Text widget.
#
# All values are passed through int(str(<value>)), since some
- # values may be pixel objects, which can't simply be added added
- # to ints.
- #
- # This code is considered somewhat unstable since it relies on
- # some of Tk's inner workings. However its effect is merely
- # cosmetic; failure will only cause the CodeContext text to be
- # somewhat misaligned with the text in the main Text widget.
- #
- # To avoid possible errors, all references to the inner workings
- # of Tk are executed inside try/except blocks.
-
- widgets_for_width_calc = self.editwin.text, self.editwin.text_frame
-
- # calculate the required vertical padding
+ # values may be pixel objects, which can't simply be added to ints.
+ widgets = self.editwin.text, self.editwin.text_frame
+ # Calculate the required vertical padding
padx = 0
- for widget in widgets_for_width_calc:
- try:
- # retrieve the "padx" attribte from widget's pack info
- padx += int(str( widget.pack_info()['padx'] ))
- except:
- pass
- try:
- # retrieve the widget's "padx" attribte
- padx += int(str( widget.cget('padx') ))
- except:
- pass
-
- # calculate the required border width
- border_width = 0
- for widget in widgets_for_width_calc:
- try:
- # retrieve the widget's "border" attribte
- border_width += int(str( widget.cget('border') ))
- except:
- pass
-
+ for widget in widgets:
+ padx += int(str( widget.pack_info()['padx'] ))
+ padx += int(str( widget.cget('padx') ))
+ # Calculate the required border width
+ border = 0
+ for widget in widgets:
+ border += int(str( widget.cget('border') ))
self.label = Tkinter.Label(self.editwin.top,
text="\n" * (self.context_depth - 1),
- anchor="w", justify="left",
+ anchor=W, justify=LEFT,
font=self.textfont,
bg=self.bgcolor, fg=self.fgcolor,
width=1, #don't request more than we get
- padx=padx, #line up with text widget
- border=border_width, #match border width
- relief="sunken",
- )
-
- # CodeContext's label widget is packed before and above the
- # text_frame widget, thus ensuring that it will appear directly
- # above it.
- self.label.pack(side="top", fill="x", expand=False,
+ padx=padx, border=border,
+ relief=SUNKEN)
+ # Pack the label widget before and above the text_frame widget,
+ # thus ensuring that it will appear directly above text_frame
+ self.label.pack(side=TOP, fill=X, expand=False,
before=self.editwin.text_frame)
-
else:
self.label.destroy()
self.label = None
@@ -190,7 +157,6 @@
stopindent)
self.info.extend(lines)
self.topvisible = new_topvisible
-
# empty lines in context pane:
context_strings = [""] * max(0, self.context_depth - len(self.info))
# followed by the context hint lines:
Modified: python/branches/p3yk-noslice/Lib/idlelib/ColorDelegator.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/ColorDelegator.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/ColorDelegator.py Fri Feb 23 18:29:35 2007
@@ -72,7 +72,7 @@
"hit": idleConf.GetHighlight(theme, "hit"),
}
- if DEBUG: print 'tagdefs',self.tagdefs
+ if DEBUG: print('tagdefs',self.tagdefs)
def insert(self, index, chars, tags=None):
index = self.index(index)
@@ -91,13 +91,13 @@
def notify_range(self, index1, index2=None):
self.tag_add("TODO", index1, index2)
if self.after_id:
- if DEBUG: print "colorizing already scheduled"
+ if DEBUG: print("colorizing already scheduled")
return
if self.colorizing:
self.stop_colorizing = True
- if DEBUG: print "stop colorizing"
+ if DEBUG: print("stop colorizing")
if self.allow_colorizing:
- if DEBUG: print "schedule colorizing"
+ if DEBUG: print("schedule colorizing")
self.after_id = self.after(1, self.recolorize)
close_when_done = None # Window to be closed when done colorizing
@@ -106,7 +106,7 @@
if self.after_id:
after_id = self.after_id
self.after_id = None
- if DEBUG: print "cancel scheduled recolorizer"
+ if DEBUG: print("cancel scheduled recolorizer")
self.after_cancel(after_id)
self.allow_colorizing = False
self.stop_colorizing = True
@@ -120,42 +120,42 @@
if self.after_id:
after_id = self.after_id
self.after_id = None
- if DEBUG: print "cancel scheduled recolorizer"
+ if DEBUG: print("cancel scheduled recolorizer")
self.after_cancel(after_id)
if self.allow_colorizing and self.colorizing:
- if DEBUG: print "stop colorizing"
+ if DEBUG: print("stop colorizing")
self.stop_colorizing = True
self.allow_colorizing = not self.allow_colorizing
if self.allow_colorizing and not self.colorizing:
self.after_id = self.after(1, self.recolorize)
if DEBUG:
- print "auto colorizing turned",\
- self.allow_colorizing and "on" or "off"
+ print("auto colorizing turned",\
+ self.allow_colorizing and "on" or "off")
return "break"
def recolorize(self):
self.after_id = None
if not self.delegate:
- if DEBUG: print "no delegate"
+ if DEBUG: print("no delegate")
return
if not self.allow_colorizing:
- if DEBUG: print "auto colorizing is off"
+ if DEBUG: print("auto colorizing is off")
return
if self.colorizing:
- if DEBUG: print "already colorizing"
+ if DEBUG: print("already colorizing")
return
try:
self.stop_colorizing = False
self.colorizing = True
- if DEBUG: print "colorizing..."
+ if DEBUG: print("colorizing...")
t0 = time.clock()
self.recolorize_main()
t1 = time.clock()
- if DEBUG: print "%.3f seconds" % (t1-t0)
+ if DEBUG: print("%.3f seconds" % (t1-t0))
finally:
self.colorizing = False
if self.allow_colorizing and self.tag_nextrange("TODO", "1.0"):
- if DEBUG: print "reschedule colorizing"
+ if DEBUG: print("reschedule colorizing")
self.after_id = self.after(1, self.recolorize)
if self.close_when_done:
top = self.close_when_done
@@ -240,7 +240,7 @@
self.tag_add("TODO", next)
self.update()
if self.stop_colorizing:
- if DEBUG: print "colorizing stopped"
+ if DEBUG: print("colorizing stopped")
return
def removecolors(self):
Modified: python/branches/p3yk-noslice/Lib/idlelib/Delegator.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/Delegator.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/Delegator.py Fri Feb 23 18:29:35 2007
@@ -23,7 +23,7 @@
def cachereport(self):
keys = self.__cache.keys()
keys.sort()
- print keys
+ print(keys)
def setdelegate(self, delegate):
self.resetcache()
Modified: python/branches/p3yk-noslice/Lib/idlelib/EditorWindow.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/EditorWindow.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/EditorWindow.py Fri Feb 23 18:29:35 2007
@@ -819,7 +819,7 @@
def close(self):
reply = self.maybesave()
- if reply != "cancel":
+ if str(reply) != "cancel":
self._close()
return reply
@@ -859,7 +859,7 @@
try:
self.load_extension(name)
except:
- print "Failed to load extension", repr(name)
+ print("Failed to load extension", repr(name))
import traceback
traceback.print_exc()
@@ -870,7 +870,7 @@
try:
mod = __import__(name, globals(), locals(), [])
except ImportError:
- print "\nFailed to import extension: ", name
+ print("\nFailed to import extension: ", name)
return
cls = getattr(mod, name)
keydefs = idleConf.GetExtensionBindings(name)
Modified: python/branches/p3yk-noslice/Lib/idlelib/FileList.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/FileList.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/FileList.py Fri Feb 23 18:29:35 2007
@@ -54,7 +54,7 @@
try:
key = self.inversedict[edit]
except KeyError:
- print "Don't know this EditorWindow object. (close)"
+ print("Don't know this EditorWindow object. (close)")
return
if key:
del self.dict[key]
@@ -67,7 +67,7 @@
try:
key = self.inversedict[edit]
except KeyError:
- print "Don't know this EditorWindow object. (rename)"
+ print("Don't know this EditorWindow object. (rename)")
return
filename = edit.io.filename
if not filename:
Modified: python/branches/p3yk-noslice/Lib/idlelib/GrepDialog.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/GrepDialog.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/GrepDialog.py Fri Feb 23 18:29:35 2007
@@ -77,13 +77,13 @@
list.sort()
self.close()
pat = self.engine.getpat()
- print "Searching %r in %s ..." % (pat, path)
+ print("Searching %r in %s ..." % (pat, path))
hits = 0
for fn in list:
try:
f = open(fn)
except IOError as msg:
- print msg
+ print(msg)
continue
lineno = 0
while 1:
@@ -102,16 +102,16 @@
s = ""
else:
s = "s"
- print "Found", hits, "hit%s." % s
- print "(Hint: right-click to open locations.)"
+ print("Found", hits, "hit%s." % s)
+ print("(Hint: right-click to open locations.)")
else:
- print "No hits."
+ print("No hits.")
def findfiles(self, dir, base, rec):
try:
names = os.listdir(dir or os.curdir)
except os.error as msg:
- print msg
+ print(msg)
return []
list = []
subdirs = []
Modified: python/branches/p3yk-noslice/Lib/idlelib/IOBinding.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/IOBinding.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/IOBinding.py Fri Feb 23 18:29:35 2007
@@ -209,7 +209,7 @@
# gets set to "not modified" at every new prompt.
try:
interp = self.editwin.interp
- except:
+ except AttributeError:
interp = None
if not self.filename and self.get_saved() and not interp:
self.editwin.flist.open(filename, self.loadfile)
Modified: python/branches/p3yk-noslice/Lib/idlelib/MultiCall.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/MultiCall.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/MultiCall.py Fri Feb 23 18:29:35 2007
@@ -388,7 +388,7 @@
text.pack()
def bindseq(seq, n=[0]):
def handler(event):
- print seq
+ print(seq)
text.bind("<<handler%d>>"%n[0], handler)
text.event_add("<<handler%d>>"%n[0], seq)
n[0] += 1
Modified: python/branches/p3yk-noslice/Lib/idlelib/NEWS.txt
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/NEWS.txt (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/NEWS.txt Fri Feb 23 18:29:35 2007
@@ -3,6 +3,19 @@
*Release date: XX-XXX-200X*
+- Corrected some bugs in AutoComplete. Also, Page Up/Down in ACW implemented;
+ mouse and cursor selection in ACWindow implemented; double Tab inserts
+ current selection and closes ACW (similar to double-click and Return); scroll
+ wheel now works in ACW. Added AutoComplete instructions to IDLE Help.
+
+- AutoCompleteWindow moved below input line, will move above if there
+ isn't enough space. Patch 1621265 Tal Einat
+
+- Calltips now 'handle' tuples in the argument list (display '<tuple>' :)
+ Suggested solution by Christos Georgiou, Bug 791968.
+
+- Add 'raw' support to configHandler. Patch 1650174 Tal Einat.
+
- Avoid hang when encountering a duplicate in a completion list. Bug 1571112.
- Patch #1362975: Rework CodeContext indentation algorithm to
Modified: python/branches/p3yk-noslice/Lib/idlelib/Percolator.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/Percolator.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/Percolator.py Fri Feb 23 18:29:35 2007
@@ -58,10 +58,10 @@
self.name = name
Delegator.__init__(self, None)
def insert(self, *args):
- print self.name, ": insert", args
+ print(self.name, ": insert", args)
self.delegate.insert(*args)
def delete(self, *args):
- print self.name, ": delete", args
+ print(self.name, ": delete", args)
self.delegate.delete(*args)
root = Tk()
root.wm_protocol("WM_DELETE_WINDOW", root.quit)
Modified: python/branches/p3yk-noslice/Lib/idlelib/PyShell.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/PyShell.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/PyShell.py Fri Feb 23 18:29:35 2007
@@ -19,8 +19,8 @@
try:
from Tkinter import *
except ImportError:
- print>>sys.__stderr__, "** IDLE can't import Tkinter. " \
- "Your Python may not be configured for Tk. **"
+ print("** IDLE can't import Tkinter. " \
+ "Your Python may not be configured for Tk. **", file=sys.__stderr__)
sys.exit(1)
import tkMessageBox
@@ -504,14 +504,14 @@
console = self.tkconsole.console
if how == "OK":
if what is not None:
- print >>console, repr(what)
+ print(repr(what), file=console)
elif how == "EXCEPTION":
if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
self.remote_stack_viewer()
elif how == "ERROR":
errmsg = "PyShell.ModifiedInterpreter: Subprocess ERROR:\n"
- print >>sys.__stderr__, errmsg, what
- print >>console, errmsg, what
+ print(errmsg, what, file=sys.__stderr__)
+ print(errmsg, what, file=console)
# we received a response to the currently active seq number:
try:
self.tkconsole.endexecuting()
@@ -576,8 +576,8 @@
except (OverflowError, SyntaxError):
self.tkconsole.resetoutput()
tkerr = self.tkconsole.stderr
- print>>tkerr, '*** Error in script or command!\n'
- print>>tkerr, 'Traceback (most recent call last):'
+ print('*** Error in script or command!\n', file=tkerr)
+ print('Traceback (most recent call last):', file=tkerr)
InteractiveInterpreter.showsyntaxerror(self, filename)
self.tkconsole.showprompt()
else:
@@ -706,35 +706,36 @@
debugger = self.debugger
try:
self.tkconsole.beginexecuting()
- try:
- if not debugger and self.rpcclt is not None:
- self.active_seq = self.rpcclt.asyncqueue("exec", "runcode",
- (code,), {})
- elif debugger:
- debugger.run(code, self.locals)
- else:
- exec(code, self.locals)
- except SystemExit:
- if not self.tkconsole.closing:
- if tkMessageBox.askyesno(
- "Exit?",
- "Do you want to exit altogether?",
- default="yes",
- master=self.tkconsole.text):
- raise
- else:
- self.showtraceback()
- else:
+ if not debugger and self.rpcclt is not None:
+ self.active_seq = self.rpcclt.asyncqueue("exec", "runcode",
+ (code,), {})
+ elif debugger:
+ debugger.run(code, self.locals)
+ else:
+ exec(code, self.locals)
+ except SystemExit:
+ if not self.tkconsole.closing:
+ if tkMessageBox.askyesno(
+ "Exit?",
+ "Do you want to exit altogether?",
+ default="yes",
+ master=self.tkconsole.text):
raise
- except:
- if use_subprocess:
- # When run w/o subprocess, both user and IDLE errors
- # are printed here; skip message in that case.
- print >> self.tkconsole.stderr, \
- "IDLE internal error in runcode()"
+ else:
+ else:
+ raise
+ except:
+ if use_subprocess:
+ print("IDLE internal error in runcode()",
+ file=self.tkconsole.stderr)
self.showtraceback()
- if use_subprocess:
- self.tkconsole.endexecuting()
+ self.tkconsole.endexecuting()
+ else:
+ if self.tkconsole.canceled:
+ self.tkconsole.canceled = False
+ print("KeyboardInterrupt", file=self.tkconsole.stderr)
+ else:
+ self.showtraceback()
finally:
if not use_subprocess:
try:
@@ -1224,7 +1225,6 @@
self.text.insert("end-1c", "\n")
self.text.mark_set("iomark", "end-1c")
self.set_line_and_column()
- sys.stdout.softspace = 0
def write(self, s, tags=()):
try:
@@ -1243,7 +1243,6 @@
def __init__(self, shell, tags, encoding=None):
self.shell = shell
self.tags = tags
- self.softspace = 0
self.encoding = encoding
def write(self, s):
@@ -1349,7 +1348,7 @@
if os.path.isfile(script):
pass
else:
- print "No script file: ", script
+ print("No script file: ", script)
sys.exit()
enable_shell = True
if o == '-s':
Modified: python/branches/p3yk-noslice/Lib/idlelib/ScrolledList.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/ScrolledList.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/ScrolledList.py Fri Feb 23 18:29:35 2007
@@ -124,8 +124,8 @@
root.protocol("WM_DELETE_WINDOW", root.destroy)
class MyScrolledList(ScrolledList):
def fill_menu(self): self.menu.add_command(label="pass")
- def on_select(self, index): print "select", self.get(index)
- def on_double(self, index): print "double", self.get(index)
+ def on_select(self, index): print("select", self.get(index))
+ def on_double(self, index): print("double", self.get(index))
s = MyScrolledList(root)
for i in range(30):
s.append("item %02d" % i)
Modified: python/branches/p3yk-noslice/Lib/idlelib/UndoDelegator.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/UndoDelegator.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/UndoDelegator.py Fri Feb 23 18:29:35 2007
@@ -38,10 +38,10 @@
def dump_event(self, event):
from pprint import pprint
pprint(self.undolist[:self.pointer])
- print "pointer:", self.pointer,
- print "saved:", self.saved,
- print "can_merge:", self.can_merge,
- print "get_saved():", self.get_saved()
+ print("pointer:", self.pointer, end=' ')
+ print("saved:", self.saved, end=' ')
+ print("can_merge:", self.can_merge, end=' ')
+ print("get_saved():", self.get_saved())
pprint(self.undolist[self.pointer:])
return "break"
Modified: python/branches/p3yk-noslice/Lib/idlelib/WidgetRedirector.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/WidgetRedirector.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/WidgetRedirector.py Fri Feb 23 18:29:35 2007
@@ -83,7 +83,7 @@
redir = WidgetRedirector(text)
global orig_insert
def my_insert(*args):
- print "insert", args
+ print("insert", args)
orig_insert(*args)
orig_insert = redir.register("insert", my_insert)
root.mainloop()
Modified: python/branches/p3yk-noslice/Lib/idlelib/WindowList.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/WindowList.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/WindowList.py Fri Feb 23 18:29:35 2007
@@ -46,7 +46,7 @@
callback()
except:
t, v, tb = sys.exc_info()
- print "warning: callback failed in WindowList", t, ":", v
+ print("warning: callback failed in WindowList", t, ":", v)
registry = WindowList()
Modified: python/branches/p3yk-noslice/Lib/idlelib/configHandler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/configHandler.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/configHandler.py Fri Feb 23 18:29:35 2007
@@ -39,22 +39,19 @@
self.file=cfgFile
ConfigParser.__init__(self,defaults=cfgDefaults)
- def Get(self, section, option, type=None, default=None):
+ def Get(self, section, option, type=None, default=None, raw=False):
"""
Get an option value for given section/option or return default.
If type is specified, return as type.
"""
+ if not self.has_option(section, option):
+ return default
if type=='bool':
- getVal=self.getboolean
+ return self.getboolean(section, option)
elif type=='int':
- getVal=self.getint
- else:
- getVal=self.get
- if self.has_option(section,option):
- #return getVal(section, option, raw, vars, default)
- return getVal(section, option)
+ return self.getint(section, option)
else:
- return default
+ return self.get(section, option, raw=raw)
def GetOptionList(self,section):
"""
@@ -219,7 +216,7 @@
return userDir
def GetOption(self, configType, section, option, default=None, type=None,
- warn_on_default=True):
+ warn_on_default=True, raw=False):
"""
Get an option value for given config type and given general
configuration section/option or return a default. If type is specified,
@@ -233,9 +230,11 @@
"""
if self.userCfg[configType].has_option(section,option):
- return self.userCfg[configType].Get(section, option, type=type)
+ return self.userCfg[configType].Get(section, option,
+ type=type, raw=raw)
elif self.defaultCfg[configType].has_option(section,option):
- return self.defaultCfg[configType].Get(section, option, type=type)
+ return self.defaultCfg[configType].Get(section, option,
+ type=type, raw=raw)
else: #returning default, print warning
if warn_on_default:
warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n'
@@ -679,18 +678,18 @@
### module test
if __name__ == '__main__':
def dumpCfg(cfg):
- print '\n',cfg,'\n'
+ print('\n',cfg,'\n')
for key in cfg.keys():
sections=cfg[key].sections()
- print key
- print sections
+ print(key)
+ print(sections)
for section in sections:
options=cfg[key].options(section)
- print section
- print options
+ print(section)
+ print(options)
for option in options:
- print option, '=', cfg[key].Get(section,option)
+ print(option, '=', cfg[key].Get(section,option))
dumpCfg(idleConf.defaultCfg)
dumpCfg(idleConf.userCfg)
- print idleConf.userCfg['main'].Get('Theme','name')
+ print(idleConf.userCfg['main'].Get('Theme','name'))
#print idleConf.userCfg['highlight'].GetDefHighlight('Foo','normal')
Modified: python/branches/p3yk-noslice/Lib/idlelib/configHelpSourceEdit.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/configHelpSourceEdit.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/configHelpSourceEdit.py Fri Feb 23 18:29:35 2007
@@ -164,6 +164,6 @@
def run():
keySeq = ''
dlg = GetHelpSourceDialog(root, 'Get Help Source')
- print dlg.result
+ print(dlg.result)
Button(root,text='Dialog', command=run).pack()
root.mainloop()
Modified: python/branches/p3yk-noslice/Lib/idlelib/configSectionNameDialog.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/configSectionNameDialog.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/configSectionNameDialog.py Fri Feb 23 18:29:35 2007
@@ -92,6 +92,6 @@
keySeq=''
dlg=GetCfgSectionNameDialog(root,'Get Name',
'The information here should need to be word wrapped. Test.')
- print dlg.result
+ print(dlg.result)
Button(root,text='Dialog',command=run).pack()
root.mainloop()
Modified: python/branches/p3yk-noslice/Lib/idlelib/help.txt
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/help.txt (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/help.txt Fri Feb 23 18:29:35 2007
@@ -44,6 +44,10 @@
Find in Files... -- Open a search dialog box for searching files
Replace... -- Open a search-and-replace dialog box
Go to Line -- Ask for a line number and show that line
+ Show Calltip -- Open a small window with function param hints
+ Show Completions -- Open a scroll window allowing selection keywords
+ and attributes. (see '*TIPS*', below)
+ Show Parens -- Highlight the surrounding parenthesis
Expand Word -- Expand the word you have typed to match another
word in the same buffer; repeat to get a
different expansion
@@ -91,6 +95,7 @@
Code Context -- Open a pane at the top of the edit window which
shows the block context of the section of code
which is scrolling off the top or the window.
+ (Not present in Shell window.)
Windows Menu:
@@ -138,8 +143,11 @@
Control-left/right Arrow moves by words in a strange but useful way.
Home/End go to begin/end of line.
Control-Home/End go to begin/end of file.
- Some useful Emacs bindings (Control-a, Control-e, Control-k, etc.)
- are inherited from Tcl/Tk.
+ Some useful Emacs bindings are inherited from Tcl/Tk:
+ Control-a beginning of line
+ Control-e end of line
+ Control-k kill line (but doesn't put it in clipboard)
+ Control-l center window around the insertion point
Standard Windows bindings may work on that platform.
Keybindings are selected in the Settings Dialog, look there.
@@ -155,6 +163,52 @@
See also the indent/dedent region commands in the edit menu.
+Completions:
+
+ Completions are supplied for functions, classes, and attributes of
+ classes, both built-in and user-defined. Completions are also provided
+ for filenames.
+
+ The AutoCompleteWindow (ACW) will open after a predefined delay
+ (default is two seconds) after a '.' or (in a string) an os.sep is
+ typed. If after one of those characters (plus zero or more other
+ characters) you type a Tab the ACW will open immediately if a possible
+ continuation is found.
+
+ If there is only one possible completion for the characters entered, a
+ Tab will supply that completion without opening the ACW.
+
+ 'Show Completions' will force open a completions window. In an empty
+ string, this will contain the files in the current directory. On a
+ blank line, it will contain the built-in and user-defined functions and
+ classes in the current name spaces, plus any modules imported. If some
+ characters have been entered, the ACW will attempt to be more specific.
+
+ If string of characters is typed, the ACW selection will jump to the
+ entry most closely matching those characters. Entering a Tab will cause
+ the longest non-ambiguous match to be entered in the Edit window or
+ Shell. Two Tabs in a row will supply the current ACW selection, as
+ will Return or a double click. Cursor keys, Page Up/Down, mouse
+ selection, and the scrollwheel all operate on the ACW.
+
+ 'Hidden' attributes can be accessed by typing the beginning of hidden
+ name after a '.'. e.g. '_'. This allows access to modules with
+ '__all__' set, or to class-private attributes.
+
+ Completions and the 'Expand Word' facility can save a lot of typing!
+
+ Completions are currently limited to those in the namespaces. Names in
+ an Edit window which are not via __main__ or sys.modules will not be
+ found. Run the module once with your imports to correct this
+ situation. Note that IDLE itself places quite a few modules in
+ sys.modules, so much can be found by default, e.g. the re module.
+
+ If you don't like the ACW popping up unbidden, simply make the delay
+ longer or disable the extension. OTOH, you could make the delay zero.
+
+ You could also switch off the CallTips extension. (We will be adding
+ a delay to the call tip window.)
+
Python Shell window:
Control-c interrupts executing command.
@@ -165,7 +219,7 @@
Alt-p retrieves previous command matching what you have typed.
Alt-n retrieves next.
- (These are Control-p, Control-n on the Mac)
+ (These are Control-p, Control-n on the Mac)
Return while cursor is on a previous command retrieves that command.
Expand word is also useful to reduce typing.
@@ -196,7 +250,7 @@
be changed using the Settings dialog.
Command line usage:
-
+
Enter idle -h at the command prompt to get a usage message.
Running without a subprocess:
@@ -211,3 +265,18 @@
re-import any specific items (e.g. from foo import baz) if the changes
are to take effect. For these reasons, it is preferable to run IDLE
with the default subprocess if at all possible.
+
+Extensions:
+
+ IDLE contains an extension facility. See the beginning of
+ config-extensions.def in the idlelib directory for further information.
+ The default extensions are currently:
+
+ FormatParagraph
+ AutoExpand
+ ZoomHeight
+ ScriptBinding
+ CallTips
+ ParenMatch
+ AutoComplete
+ CodeContext
Modified: python/branches/p3yk-noslice/Lib/idlelib/keybindingDialog.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/keybindingDialog.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/keybindingDialog.py Fri Feb 23 18:29:35 2007
@@ -263,6 +263,6 @@
def run():
keySeq=''
dlg=GetKeysDialog(root,'Get Keys','find-again',[])
- print dlg.result
+ print(dlg.result)
Button(root,text='Dialog',command=run).pack()
root.mainloop()
Modified: python/branches/p3yk-noslice/Lib/idlelib/rpc.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/rpc.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/rpc.py Fri Feb 23 18:29:35 2007
@@ -104,14 +104,14 @@
raise
except:
erf = sys.__stderr__
- print>>erf, '\n' + '-'*40
- print>>erf, 'Unhandled server exception!'
- print>>erf, 'Thread: %s' % threading.currentThread().getName()
- print>>erf, 'Client Address: ', client_address
- print>>erf, 'Request: ', repr(request)
+ print('\n' + '-'*40, file=erf)
+ print('Unhandled server exception!', file=erf)
+ print('Thread: %s' % threading.currentThread().getName(), file=erf)
+ print('Client Address: ', client_address, file=erf)
+ print('Request: ', repr(request), file=erf)
traceback.print_exc(file=erf)
- print>>erf, '\n*** Unrecoverable, server exiting!'
- print>>erf, '-'*40
+ print('\n*** Unrecoverable, server exiting!', file=erf)
+ print('-'*40, file=erf)
os._exit(0)
#----------------- end class RPCServer --------------------
@@ -152,7 +152,7 @@
s = self.location + " " + str(threading.currentThread().getName())
for a in args:
s = s + " " + str(a)
- print>>sys.__stderr__, s
+ print(s, file=sys.__stderr__)
def register(self, oid, object):
self.objtable[oid] = object
@@ -201,7 +201,7 @@
except:
msg = "*** Internal Error: rpc.py:SocketIO.localcall()\n\n"\
" Object: %s \n Method: %s \n Args: %s\n"
- print>>sys.__stderr__, msg % (oid, method, args)
+ print(msg % (oid, method, args), file=sys.__stderr__)
traceback.print_exc(file=sys.__stderr__)
return ("EXCEPTION", None)
@@ -323,7 +323,7 @@
try:
s = pickle.dumps(message)
except pickle.PicklingError:
- print >>sys.__stderr__, "Cannot pickle:", repr(message)
+ print("Cannot pickle:", repr(message), file=sys.__stderr__)
raise
s = struct.pack("<i", len(s)) + s
while len(s) > 0:
@@ -379,10 +379,10 @@
try:
message = pickle.loads(packet)
except pickle.UnpicklingError:
- print >>sys.__stderr__, "-----------------------"
- print >>sys.__stderr__, "cannot unpickle packet:", repr(packet)
+ print("-----------------------", file=sys.__stderr__)
+ print("cannot unpickle packet:", repr(packet), file=sys.__stderr__)
traceback.print_stack(file=sys.__stderr__)
- print >>sys.__stderr__, "-----------------------"
+ print("-----------------------", file=sys.__stderr__)
raise
return message
@@ -526,11 +526,11 @@
def accept(self):
working_sock, address = self.listening_sock.accept()
if self.debugging:
- print>>sys.__stderr__, "****** Connection request from ", address
+ print("****** Connection request from ", address, file=sys.__stderr__)
if address[0] == LOCALHOST:
SocketIO.__init__(self, working_sock)
else:
- print>>sys.__stderr__, "** Invalid host: ", address
+ print("** Invalid host: ", address, file=sys.__stderr__)
raise socket.error
def get_remote_proxy(self, oid):
Modified: python/branches/p3yk-noslice/Lib/idlelib/run.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/idlelib/run.py (original)
+++ python/branches/p3yk-noslice/Lib/idlelib/run.py Fri Feb 23 18:29:35 2007
@@ -115,11 +115,11 @@
server = MyRPCServer(address, MyHandler)
break
except socket.error as err:
- print>>sys.__stderr__,"IDLE Subprocess: socket error: "\
- + err[1] + ", retrying...."
+ print("IDLE Subprocess: socket error: "\
+ + err[1] + ", retrying....", file=sys.__stderr__)
else:
- print>>sys.__stderr__, "IDLE Subprocess: Connection to "\
- "IDLE GUI failed, exiting."
+ print("IDLE Subprocess: Connection to "\
+ "IDLE GUI failed, exiting.", file=sys.__stderr__)
show_socket_error(err, address)
global exit_now
exit_now = True
@@ -149,14 +149,14 @@
typ, val, tb = excinfo = sys.exc_info()
sys.last_type, sys.last_value, sys.last_traceback = excinfo
tbe = traceback.extract_tb(tb)
- print>>efile, '\nTraceback (most recent call last):'
+ print('\nTraceback (most recent call last):', file=efile)
exclude = ("run.py", "rpc.py", "threading.py", "Queue.py",
"RemoteDebugger.py", "bdb.py")
cleanup_traceback(tbe, exclude)
traceback.print_list(tbe, file=efile)
lines = traceback.format_exception_only(typ, val)
for line in lines:
- print>>efile, line,
+ print(line, end=' ', file=efile)
def cleanup_traceback(tb, exclude):
"Remove excluded traces from beginning/end of tb; get cached lines"
@@ -178,7 +178,7 @@
if len(tb) == 0:
# exception was in IDLE internals, don't prune!
tb[:] = orig_tb[:]
- print>>sys.stderr, "** IDLE Internal Exception: "
+ print("** IDLE Internal Exception: ", file=sys.stderr)
rpchandler = rpc.objecttable['exec'].rpchandler
for i in range(len(tb)):
fn, ln, nm, line = tb[i]
@@ -190,12 +190,7 @@
tb[i] = fn, ln, nm, line
def flush_stdout():
- try:
- if sys.stdout.softspace:
- sys.stdout.softspace = 0
- sys.stdout.write("\n")
- except (AttributeError, EOFError):
- pass
+ """XXX How to do this now?"""
def exit():
"""Exit subprocess, possibly after first deleting sys.exitfunc
@@ -227,14 +222,14 @@
thread.interrupt_main()
except:
erf = sys.__stderr__
- print>>erf, '\n' + '-'*40
- print>>erf, 'Unhandled server exception!'
- print>>erf, 'Thread: %s' % threading.currentThread().getName()
- print>>erf, 'Client Address: ', client_address
- print>>erf, 'Request: ', repr(request)
+ print('\n' + '-'*40, file=erf)
+ print('Unhandled server exception!', file=erf)
+ print('Thread: %s' % threading.currentThread().getName(), file=erf)
+ print('Client Address: ', client_address, file=erf)
+ print('Request: ', repr(request), file=erf)
traceback.print_exc(file=erf)
- print>>erf, '\n*** Unrecoverable, server exiting!'
- print>>erf, '-'*40
+ print('\n*** Unrecoverable, server exiting!', file=erf)
+ print('-'*40, file=erf)
quitting = True
thread.interrupt_main()
Modified: python/branches/p3yk-noslice/Lib/ihooks.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ihooks.py (original)
+++ python/branches/p3yk-noslice/Lib/ihooks.py Fri Feb 23 18:29:35 2007
@@ -87,9 +87,9 @@
def message(self, format, *args):
if args:
- print format%args
+ print(format%args)
else:
- print format
+ print(format)
class BasicModuleLoader(_Verbose):
Modified: python/branches/p3yk-noslice/Lib/imaplib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/imaplib.py (original)
+++ python/branches/p3yk-noslice/Lib/imaplib.py Fri Feb 23 18:29:35 2007
@@ -1485,15 +1485,15 @@
run('uid', ('FETCH', '%s' % uid[-1],
'(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
- print '\nAll tests OK.'
+ print('\nAll tests OK.')
except:
- print '\nTests failed.'
+ print('\nTests failed.')
if not Debug:
- print '''
+ print('''
If you would like to see debugging output,
try: %s -d5
-''' % sys.argv[0]
+''' % sys.argv[0])
raise
Modified: python/branches/p3yk-noslice/Lib/imghdr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/imghdr.py (original)
+++ python/branches/p3yk-noslice/Lib/imghdr.py Fri Feb 23 18:29:35 2007
@@ -144,18 +144,18 @@
import os
for filename in list:
if os.path.isdir(filename):
- print filename + '/:',
+ print(filename + '/:', end=' ')
if recursive or toplevel:
- print 'recursing down:'
+ print('recursing down:')
import glob
names = glob.glob(os.path.join(filename, '*'))
testall(names, recursive, 0)
else:
- print '*** directory (use -r) ***'
+ print('*** directory (use -r) ***')
else:
- print filename + ':',
+ print(filename + ':', end=' ')
sys.stdout.flush()
try:
- print what(filename)
+ print(what(filename))
except IOError:
- print '*** not found ***'
+ print('*** not found ***')
Modified: python/branches/p3yk-noslice/Lib/imputil.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/imputil.py (original)
+++ python/branches/p3yk-noslice/Lib/imputil.py Fri Feb 23 18:29:35 2007
@@ -500,7 +500,7 @@
s = _os_stat(pathname)
except OSError:
return None
- return long(s.st_mtime)
+ return int(s.st_mtime)
######################################################################
@@ -552,6 +552,10 @@
# This method is only used when we look for a module within a package.
assert parent
+ for submodule_path in parent.__path__:
+ code = self._import_pathname(_os_path_join(submodule_path, modname), fqname)
+ if code is not None:
+ return code
return self._import_pathname(_os_path_join(parent.__pkgdir__, modname),
fqname)
@@ -583,7 +587,7 @@
def py_suffix_importer(filename, finfo, fqname):
file = filename[:-3] + _suffix
- t_py = long(finfo[8])
+ t_py = int(finfo[8])
t_pyc = _timestamp(file)
code = None
@@ -618,9 +622,9 @@
items.sort()
for name, module in items:
if module:
- print name, module.__dict__.get('__importer__', '-- no importer')
+ print(name, module.__dict__.get('__importer__', '-- no importer'))
else:
- print name, '-- non-existent module'
+ print(name, '-- non-existent module')
def _test_revamp():
ImportManager().install()
Modified: python/branches/p3yk-noslice/Lib/lib-tk/Dialog.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/lib-tk/Dialog.py (original)
+++ python/branches/p3yk-noslice/Lib/lib-tk/Dialog.py Fri Feb 23 18:29:35 2007
@@ -36,7 +36,7 @@
'strings': ('Save File',
'Discard Changes',
'Return to Editor')})
- print d.num
+ print(d.num)
if __name__ == '__main__':
Modified: python/branches/p3yk-noslice/Lib/lib-tk/FileDialog.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/lib-tk/FileDialog.py (original)
+++ python/branches/p3yk-noslice/Lib/lib-tk/FileDialog.py Fri Feb 23 18:29:35 2007
@@ -267,7 +267,7 @@
loadfile = fd.go(key="test")
fd = SaveFileDialog(root)
savefile = fd.go(key="test")
- print loadfile, savefile
+ print(loadfile, savefile)
if __name__ == '__main__':
Modified: python/branches/p3yk-noslice/Lib/lib-tk/SimpleDialog.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/lib-tk/SimpleDialog.py (original)
+++ python/branches/p3yk-noslice/Lib/lib-tk/SimpleDialog.py Fri Feb 23 18:29:35 2007
@@ -102,7 +102,7 @@
default=0,
cancel=2,
title="Test Dialog")
- print d.go()
+ print(d.go())
t = Button(root, text='Test', command=doit)
t.pack()
q = Button(root, text='Quit', command=t.quit)
Modified: python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py (original)
+++ python/branches/p3yk-noslice/Lib/lib-tk/Tkinter.py Fri Feb 23 18:29:35 2007
@@ -86,7 +86,7 @@
try:
cnf.update(c)
except (AttributeError, TypeError) as msg:
- print "_cnfmerge: fallback due to:", msg
+ print("_cnfmerge: fallback due to:", msg)
for k, v in c.items():
cnf[k] = v
return cnf
Modified: python/branches/p3yk-noslice/Lib/lib-tk/tkColorChooser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/lib-tk/tkColorChooser.py (original)
+++ python/branches/p3yk-noslice/Lib/lib-tk/tkColorChooser.py Fri Feb 23 18:29:35 2007
@@ -67,4 +67,4 @@
if __name__ == "__main__":
- print "color", askcolor()
+ print("color", askcolor())
Modified: python/branches/p3yk-noslice/Lib/lib-tk/tkFileDialog.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/lib-tk/tkFileDialog.py (original)
+++ python/branches/p3yk-noslice/Lib/lib-tk/tkFileDialog.py Fri Feb 23 18:29:35 2007
@@ -204,12 +204,12 @@
fp=open(openfilename,"r")
fp.close()
except:
- print "Could not open File: "
- print sys.exc_info()[1]
+ print("Could not open File: ")
+ print(sys.exc_info()[1])
- print "open", openfilename.encode(enc)
+ print("open", openfilename.encode(enc))
# dialog for saving files
saveasfilename=asksaveasfilename()
- print "saveas", saveasfilename.encode(enc)
+ print("saveas", saveasfilename.encode(enc))
Modified: python/branches/p3yk-noslice/Lib/lib-tk/tkFont.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/lib-tk/tkFont.py (original)
+++ python/branches/p3yk-noslice/Lib/lib-tk/tkFont.py Fri Feb 23 18:29:35 2007
@@ -185,22 +185,22 @@
# create a font
f = Font(family="times", size=30, weight=NORMAL)
- print f.actual()
- print f.actual("family")
- print f.actual("weight")
+ print(f.actual())
+ print(f.actual("family"))
+ print(f.actual("weight"))
- print f.config()
- print f.cget("family")
- print f.cget("weight")
+ print(f.config())
+ print(f.cget("family"))
+ print(f.cget("weight"))
- print names()
+ print(names())
- print f.measure("hello"), f.metrics("linespace")
+ print(f.measure("hello"), f.metrics("linespace"))
- print f.metrics()
+ print(f.metrics())
f = Font(font=("Courier", 20, "bold"))
- print f.measure("hello"), f.metrics("linespace")
+ print(f.measure("hello"), f.metrics("linespace"))
w = Tkinter.Label(root, text="Hello, world", font=f)
w.pack()
Modified: python/branches/p3yk-noslice/Lib/lib-tk/tkMessageBox.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/lib-tk/tkMessageBox.py (original)
+++ python/branches/p3yk-noslice/Lib/lib-tk/tkMessageBox.py Fri Feb 23 18:29:35 2007
@@ -122,11 +122,11 @@
if __name__ == "__main__":
- print "info", showinfo("Spam", "Egg Information")
- print "warning", showwarning("Spam", "Egg Warning")
- print "error", showerror("Spam", "Egg Alert")
- print "question", askquestion("Spam", "Question?")
- print "proceed", askokcancel("Spam", "Proceed?")
- print "yes/no", askyesno("Spam", "Got it?")
- print "yes/no/cancel", askyesnocancel("Spam", "Want it?")
- print "try again", askretrycancel("Spam", "Try again?")
+ print("info", showinfo("Spam", "Egg Information"))
+ print("warning", showwarning("Spam", "Egg Warning"))
+ print("error", showerror("Spam", "Egg Alert"))
+ print("question", askquestion("Spam", "Question?"))
+ print("proceed", askokcancel("Spam", "Proceed?"))
+ print("yes/no", askyesno("Spam", "Got it?"))
+ print("yes/no/cancel", askyesnocancel("Spam", "Want it?"))
+ print("try again", askretrycancel("Spam", "Try again?"))
Modified: python/branches/p3yk-noslice/Lib/lib-tk/tkSimpleDialog.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/lib-tk/tkSimpleDialog.py (original)
+++ python/branches/p3yk-noslice/Lib/lib-tk/tkSimpleDialog.py Fri Feb 23 18:29:35 2007
@@ -50,9 +50,9 @@
# If the master is not viewable, don't
# make the child transient, or else it
# would be opened withdrawn
- if parent.winfo_viewable():
+ if parent.winfo_viewable():
self.transient(parent)
-
+
if title:
self.title(title)
@@ -315,6 +315,6 @@
root = Tk()
root.update()
- print askinteger("Spam", "Egg count", initialvalue=12*12)
- print askfloat("Spam", "Egg weight\n(in tons)", minvalue=1, maxvalue=100)
- print askstring("Spam", "Egg label")
+ print(askinteger("Spam", "Egg count", initialvalue=12*12))
+ print(askfloat("Spam", "Egg weight\n(in tons)", minvalue=1, maxvalue=100))
+ print(askstring("Spam", "Egg label"))
Modified: python/branches/p3yk-noslice/Lib/locale.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/locale.py (original)
+++ python/branches/p3yk-noslice/Lib/locale.py Fri Feb 23 18:29:35 2007
@@ -262,10 +262,10 @@
setlocale(LC_ALL, "")
#do grouping
s1 = format("%d", 123456789,1)
- print s1, "is", atoi(s1)
+ print(s1, "is", atoi(s1))
#standard formatting
s1 = str(3.14)
- print s1, "is", atof(s1)
+ print(s1, "is", atof(s1))
### Locale name aliasing engine
@@ -1499,49 +1499,49 @@
_init_categories()
del categories['LC_ALL']
- print 'Locale defaults as determined by getdefaultlocale():'
- print '-'*72
+ print('Locale defaults as determined by getdefaultlocale():')
+ print('-'*72)
lang, enc = getdefaultlocale()
- print 'Language: ', lang or '(undefined)'
- print 'Encoding: ', enc or '(undefined)'
- print
+ print('Language: ', lang or '(undefined)')
+ print('Encoding: ', enc or '(undefined)')
+ print()
- print 'Locale settings on startup:'
- print '-'*72
+ print('Locale settings on startup:')
+ print('-'*72)
for name,category in categories.items():
- print name, '...'
+ print(name, '...')
lang, enc = getlocale(category)
- print ' Language: ', lang or '(undefined)'
- print ' Encoding: ', enc or '(undefined)'
- print
-
- print
- print 'Locale settings after calling resetlocale():'
- print '-'*72
+ print(' Language: ', lang or '(undefined)')
+ print(' Encoding: ', enc or '(undefined)')
+ print()
+
+ print()
+ print('Locale settings after calling resetlocale():')
+ print('-'*72)
resetlocale()
for name,category in categories.items():
- print name, '...'
+ print(name, '...')
lang, enc = getlocale(category)
- print ' Language: ', lang or '(undefined)'
- print ' Encoding: ', enc or '(undefined)'
- print
+ print(' Language: ', lang or '(undefined)')
+ print(' Encoding: ', enc or '(undefined)')
+ print()
try:
setlocale(LC_ALL, "")
except:
- print 'NOTE:'
- print 'setlocale(LC_ALL, "") does not support the default locale'
- print 'given in the OS environment variables.'
+ print('NOTE:')
+ print('setlocale(LC_ALL, "") does not support the default locale')
+ print('given in the OS environment variables.')
else:
- print
- print 'Locale settings after calling setlocale(LC_ALL, ""):'
- print '-'*72
+ print()
+ print('Locale settings after calling setlocale(LC_ALL, ""):')
+ print('-'*72)
for name,category in categories.items():
- print name, '...'
+ print(name, '...')
lang, enc = getlocale(category)
- print ' Language: ', lang or '(undefined)'
- print ' Encoding: ', enc or '(undefined)'
- print
+ print(' Language: ', lang or '(undefined)')
+ print(' Encoding: ', enc or '(undefined)')
+ print()
###
@@ -1553,10 +1553,10 @@
__all__.append("LC_MESSAGES")
if __name__=='__main__':
- print 'Locale aliasing:'
- print
+ print('Locale aliasing:')
+ print()
_print_locale()
- print
- print 'Number formatting:'
- print
+ print()
+ print('Number formatting:')
+ print()
_test()
Modified: python/branches/p3yk-noslice/Lib/logging/__init__.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/logging/__init__.py (original)
+++ python/branches/p3yk-noslice/Lib/logging/__init__.py Fri Feb 23 18:29:35 2007
@@ -1,4 +1,4 @@
-# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved.
+# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
@@ -21,7 +21,7 @@
Should work under Python versions >= 1.5.2, except that source line
information is not available unless 'sys._getframe()' is.
-Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
+Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging' and log away!
"""
@@ -41,8 +41,8 @@
__author__ = "Vinay Sajip <vinay_sajip at red-dove.com>"
__status__ = "production"
-__version__ = "0.5.0.0"
-__date__ = "08 January 2007"
+__version__ = "0.5.0.2"
+__date__ = "16 February 2007"
#---------------------------------------------------------------------------
# Miscellaneous module data
@@ -68,7 +68,7 @@
except:
return sys.exc_traceback.tb_frame.f_back
-if hasattr(sys, '_getframe'): currentframe = sys._getframe
+if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3)
# done filching
# _srcfile is only used in conjunction with sys._getframe().
@@ -251,7 +251,7 @@
self.lineno = lineno
self.funcName = func
self.created = ct
- self.msecs = (ct - long(ct)) * 1000
+ self.msecs = (ct - int(ct)) * 1000
self.relativeCreated = (self.created - _startTime) * 1000
if logThreads and thread:
self.thread = thread.get_ident()
@@ -764,17 +764,15 @@
"""
Open the specified file and use it as the stream for logging.
"""
- if codecs is None:
- encoding = None
- if encoding is None:
- stream = open(filename, mode)
- else:
- stream = codecs.open(filename, mode, encoding)
- StreamHandler.__init__(self, stream)
#keep the absolute path, otherwise derived classes which use this
#may come a cropper when the current directory changes
+ if codecs is None:
+ encoding = None
self.baseFilename = os.path.abspath(filename)
self.mode = mode
+ self.encoding = encoding
+ stream = self._open()
+ StreamHandler.__init__(self, stream)
def close(self):
"""
@@ -784,6 +782,17 @@
self.stream.close()
StreamHandler.close(self)
+ def _open(self):
+ """
+ Open the current base file with the (original) mode and encoding.
+ Return the resulting stream.
+ """
+ if self.encoding is None:
+ stream = open(self.baseFilename, self.mode)
+ else:
+ stream = codecs.open(self.baseFilename, self.mode, self.encoding)
+ return stream
+
#---------------------------------------------------------------------------
# Manager classes and functions
#---------------------------------------------------------------------------
Modified: python/branches/p3yk-noslice/Lib/logging/config.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/logging/config.py (original)
+++ python/branches/p3yk-noslice/Lib/logging/config.py Fri Feb 23 18:29:35 2007
@@ -202,7 +202,7 @@
#what's left in existing is the set of loggers
#which were in the previous configuration but
#which are not in the new configuration.
- existing = root.manager.loggerDict.keys()
+ existing = list(root.manager.loggerDict.keys())
#now set up the new ones...
for log in llist:
sectname = "logger_%s" % log
Modified: python/branches/p3yk-noslice/Lib/logging/handlers.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/logging/handlers.py (original)
+++ python/branches/p3yk-noslice/Lib/logging/handlers.py Fri Feb 23 18:29:35 2007
@@ -1,4 +1,4 @@
-# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved.
+# Copyright 2001-2007 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
@@ -22,7 +22,7 @@
Should work under Python versions >= 1.5.2, except that source line
information is not available unless 'sys._getframe()' is.
-Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved.
+Copyright (C) 2001-2007 Vinay Sajip. All Rights Reserved.
To use, simply 'import logging' and log away!
"""
@@ -32,6 +32,7 @@
import cPickle as pickle
except ImportError:
import pickle
+from stat import ST_DEV, ST_INO
try:
import codecs
@@ -134,10 +135,8 @@
os.remove(dfn)
os.rename(self.baseFilename, dfn)
#print "%s -> %s" % (self.baseFilename, dfn)
- if self.encoding:
- self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
- else:
- self.stream = open(self.baseFilename, 'w')
+ self.mode = 'w'
+ self.stream = self._open()
def shouldRollover(self, record):
"""
@@ -280,12 +279,58 @@
s.sort()
os.remove(s[0])
#print "%s -> %s" % (self.baseFilename, dfn)
- if self.encoding:
- self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
- else:
- self.stream = open(self.baseFilename, 'w')
+ self.mode = 'w'
+ self.stream = self._open()
self.rolloverAt = self.rolloverAt + self.interval
+class WatchedFileHandler(logging.FileHandler):
+ """
+ A handler for logging to a file, which watches the file
+ to see if it has changed while in use. This can happen because of
+ usage of programs such as newsyslog and logrotate which perform
+ log file rotation. This handler, intended for use under Unix,
+ watches the file to see if it has changed since the last emit.
+ (A file has changed if its device or inode have changed.)
+ If it has changed, the old file stream is closed, and the file
+ opened to get a new stream.
+
+ This handler is not appropriate for use under Windows, because
+ under Windows open files cannot be moved or renamed - logging
+ opens the files with exclusive locks - and so there is no need
+ for such a handler. Furthermore, ST_INO is not supported under
+ Windows; stat always returns zero for this value.
+
+ This handler is based on a suggestion and patch by Chad J.
+ Schroeder.
+ """
+ def __init__(self, filename, mode='a', encoding=None):
+ logging.FileHandler.__init__(self, filename, mode, encoding)
+ stat = os.stat(self.baseFilename)
+ self.dev, self.ino = stat[ST_DEV], stat[ST_INO]
+
+ def emit(self, record):
+ """
+ Emit a record.
+
+ First check if the underlying file has changed, and if it
+ has, close the old stream and reopen the file to get the
+ current stream.
+ """
+ if not os.path.exists(self.baseFilename):
+ stat = None
+ changed = 1
+ else:
+ stat = os.stat(self.baseFilename)
+ changed = (stat[ST_DEV] != self.dev) or (stat[ST_INO] != self.ino)
+ if changed:
+ self.stream.flush()
+ self.stream.close()
+ self.stream = self._open()
+ if stat is None:
+ stat = os.stat(self.baseFilename)
+ self.dev, self.ino = stat[ST_DEV], stat[ST_INO]
+ logging.FileHandler.emit(self, record)
+
class SocketHandler(logging.Handler):
"""
A handler class which writes logging records, in pickle format, to
@@ -737,7 +782,7 @@
try:
import smtplib
try:
- from email.Utils import formatdate
+ from email.utils import formatdate
except ImportError:
formatdate = self.date_time
port = self.mailport
@@ -789,8 +834,8 @@
logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
}
except ImportError:
- print "The Python Win32 extensions for NT (service, event "\
- "logging) appear not to be available."
+ print("The Python Win32 extensions for NT (service, event "\
+ "logging) appear not to be available.")
self._welu = None
def getMessageID(self, record):
Modified: python/branches/p3yk-noslice/Lib/macurl2path.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/macurl2path.py (original)
+++ python/branches/p3yk-noslice/Lib/macurl2path.py Fri Feb 23 18:29:35 2007
@@ -82,7 +82,7 @@
"/foo/bar/index.html",
"/foo/bar/",
"/"]:
- print '%r -> %r' % (url, url2pathname(url))
+ print('%r -> %r' % (url, url2pathname(url)))
for path in ["drive:",
"drive:dir:",
"drive:dir:file",
@@ -91,7 +91,7 @@
":file",
":dir:",
":dir:file"]:
- print '%r -> %r' % (path, pathname2url(path))
+ print('%r -> %r' % (path, pathname2url(path)))
if __name__ == '__main__':
test()
Modified: python/branches/p3yk-noslice/Lib/mailbox.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/mailbox.py (original)
+++ python/branches/p3yk-noslice/Lib/mailbox.py Fri Feb 23 18:29:35 2007
@@ -16,8 +16,8 @@
import errno
import copy
import email
-import email.Message
-import email.Generator
+import email.message
+import email.generator
import rfc822
import StringIO
try:
@@ -99,7 +99,7 @@
def itervalues(self):
"""Return an iterator over all messages."""
- for key in self.iterkeys():
+ for key in self.keys():
try:
value = self[key]
except KeyError:
@@ -107,7 +107,7 @@
yield value
def __iter__(self):
- return self.itervalues()
+ return self.values()
def values(self):
"""Return a list of messages. Memory intensive."""
@@ -115,7 +115,7 @@
def iteritems(self):
"""Return an iterator over (key, message) tuples."""
- for key in self.iterkeys():
+ for key in self.keys():
try:
value = self[key]
except KeyError:
@@ -136,7 +136,7 @@
def clear(self):
"""Delete all messages."""
- for key in self.iterkeys():
+ for key in self.keys():
self.discard(key)
def pop(self, key, default=None):
@@ -150,7 +150,7 @@
def popitem(self):
"""Delete an arbitrary (key, message) pair and return it."""
- for key in self.iterkeys():
+ for key in self.keys():
return (key, self.pop(key)) # This is only run once.
else:
raise KeyError('No messages in mailbox')
@@ -158,7 +158,7 @@
def update(self, arg=None):
"""Change the messages that correspond to certain keys."""
if hasattr(arg, 'iteritems'):
- source = arg.iteritems()
+ source = arg.items()
elif hasattr(arg, 'items'):
source = arg.items()
else:
@@ -193,9 +193,9 @@
# To get native line endings on disk, the user-friendly \n line endings
# used in strings and by email.Message are translated here.
"""Dump message contents to target file."""
- if isinstance(message, email.Message.Message):
+ if isinstance(message, email.message.Message):
buffer = StringIO.StringIO()
- gen = email.Generator.Generator(buffer, mangle_from_, 0)
+ gen = email.generator.Generator(buffer, mangle_from_, 0)
gen.flatten(message)
buffer.seek(0)
target.write(buffer.read().replace('\n', os.linesep))
@@ -477,7 +477,7 @@
def next(self):
"""Return the next message in a one-time iteration."""
if not hasattr(self, '_onetime_keys'):
- self._onetime_keys = self.iterkeys()
+ self._onetime_keys = iter(self.keys())
while True:
try:
return self[self._onetime_keys.next()]
@@ -569,7 +569,7 @@
# already have been generated (and presumably has been modified
# by adding or deleting an item).
assert self._toc is not None
-
+
# Check length of self._file; if it's changed, some other process
# has modified the mailbox since we scanned it.
self._file.seek(0, 2)
@@ -578,7 +578,7 @@
raise ExternalClashError('Size of mailbox file changed '
'(expected %i, found %i)' %
(self._file_length, cur_len))
-
+
new_file = _create_temporary(self._path)
try:
new_toc = {}
@@ -704,7 +704,7 @@
message = ''
elif isinstance(message, _mboxMMDFMessage):
from_line = 'From ' + message.get_from()
- elif isinstance(message, email.Message.Message):
+ elif isinstance(message, email.message.Message):
from_line = message.get_unixfrom() # May be None.
if from_line is None:
from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
@@ -950,7 +950,7 @@
def __len__(self):
"""Return a count of messages in the mailbox."""
- return len(list(self.iterkeys()))
+ return len(list(self.keys()))
def lock(self):
"""Lock the mailbox."""
@@ -1038,7 +1038,7 @@
f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
try:
os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
- for name, keys in sequences.iteritems():
+ for name, keys in sequences.items():
if len(keys) == 0:
continue
f.write('%s:' % name)
@@ -1067,7 +1067,7 @@
sequences = self.get_sequences()
prev = 0
changes = []
- for key in self.iterkeys():
+ for key in self.keys():
if key - 1 != prev:
changes.append((key, prev + 1))
if hasattr(os, 'link'):
@@ -1091,7 +1091,7 @@
"""Inspect a new MHMessage and update sequences appropriately."""
pending_sequences = message.get_sequences()
all_sequences = self.get_sequences()
- for name, key_list in all_sequences.iteritems():
+ for name, key_list in all_sequences.items():
if name in pending_sequences:
key_list.append(key)
elif key in key_list:
@@ -1219,7 +1219,7 @@
self._next_key = len(self._toc)
self._file.seek(0, 2)
self._file_length = self._file.tell()
-
+
def _pre_mailbox_hook(self, f):
"""Called before writing the mailbox to file f."""
f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' %
@@ -1254,9 +1254,9 @@
self._file.write(os.linesep)
else:
self._file.write('1,,' + os.linesep)
- if isinstance(message, email.Message.Message):
+ if isinstance(message, email.message.Message):
orig_buffer = StringIO.StringIO()
- orig_generator = email.Generator.Generator(orig_buffer, False, 0)
+ orig_generator = email.generator.Generator(orig_buffer, False, 0)
orig_generator.flatten(message)
orig_buffer.seek(0)
while True:
@@ -1267,7 +1267,7 @@
self._file.write('*** EOOH ***' + os.linesep)
if isinstance(message, BabylMessage):
vis_buffer = StringIO.StringIO()
- vis_generator = email.Generator.Generator(vis_buffer, False, 0)
+ vis_generator = email.generator.Generator(vis_buffer, False, 0)
vis_generator.flatten(message.get_visible())
while True:
line = vis_buffer.readline()
@@ -1323,12 +1323,12 @@
return (start, stop)
-class Message(email.Message.Message):
+class Message(email.message.Message):
"""Message with mailbox-format-specific properties."""
def __init__(self, message=None):
"""Initialize a Message instance."""
- if isinstance(message, email.Message.Message):
+ if isinstance(message, email.message.Message):
self._become_message(copy.deepcopy(message))
if isinstance(message, Message):
message._explain_to(self)
@@ -1337,7 +1337,7 @@
elif hasattr(message, "read"):
self._become_message(email.message_from_file(message))
elif message is None:
- email.Message.Message.__init__(self)
+ email.message.Message.__init__(self)
else:
raise TypeError('Invalid message type: %s' % type(message))
@@ -1468,7 +1468,7 @@
def __init__(self, message=None):
"""Initialize an mboxMMDFMessage instance."""
self.set_from('MAILER-DAEMON', True)
- if isinstance(message, email.Message.Message):
+ if isinstance(message, email.message.Message):
unixfrom = message.get_unixfrom()
if unixfrom is not None and unixfrom.startswith('From '):
self.set_from(unixfrom[5:])
@@ -1990,10 +1990,12 @@
# that the two characters preceding "From " are \n\n or the beginning of
# the file. Fixing this would require a more extensive rewrite than is
# necessary. For convenience, we've added a PortableUnixMailbox class
- # which uses the more lenient _fromlinepattern regular expression.
+ # which does no checking of the format of the 'From' line.
- _fromlinepattern = r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+" \
- r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*$"
+ _fromlinepattern = (r"From \s*[^\s]+\s+\w\w\w\s+\w\w\w\s+\d?\d\s+"
+ r"\d?\d:\d\d(:\d\d)?(\s+[^\s]+)?\s+\d\d\d\d\s*"
+ r"[^\s]*\s*"
+ "$")
_regexp = None
def _strict_isrealfromline(self, line):
@@ -2043,7 +2045,7 @@
# list = map(long, filter(pat.match, os.listdir(self.dirname)))
list = os.listdir(self.dirname)
list = filter(pat.match, list)
- list = map(long, list)
+ list = map(int, list)
list.sort()
# This only works in Python 1.6 or later;
# before that str() added 'L':
Modified: python/branches/p3yk-noslice/Lib/mailcap.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/mailcap.py (original)
+++ python/branches/p3yk-noslice/Lib/mailcap.py Fri Feb 23 18:29:35 2007
@@ -24,7 +24,7 @@
continue
morecaps = readmailcapfile(fp)
fp.close()
- for key, value in morecaps.iteritems():
+ for key, value in morecaps.items():
if not key in caps:
caps[key] = value
else:
@@ -219,37 +219,37 @@
for i in range(1, len(sys.argv), 2):
args = sys.argv[i:i+2]
if len(args) < 2:
- print "usage: mailcap [MIMEtype file] ..."
+ print("usage: mailcap [MIMEtype file] ...")
return
MIMEtype = args[0]
file = args[1]
command, e = findmatch(caps, MIMEtype, 'view', file)
if not command:
- print "No viewer found for", type
+ print("No viewer found for", type)
else:
- print "Executing:", command
+ print("Executing:", command)
sts = os.system(command)
if sts:
- print "Exit status:", sts
+ print("Exit status:", sts)
def show(caps):
- print "Mailcap files:"
- for fn in listmailcapfiles(): print "\t" + fn
- print
+ print("Mailcap files:")
+ for fn in listmailcapfiles(): print("\t" + fn)
+ print()
if not caps: caps = getcaps()
- print "Mailcap entries:"
- print
+ print("Mailcap entries:")
+ print()
ckeys = caps.keys()
ckeys.sort()
for type in ckeys:
- print type
+ print(type)
entries = caps[type]
for e in entries:
keys = e.keys()
keys.sort()
for k in keys:
- print " %-15s" % k, e[k]
- print
+ print(" %-15s" % k, e[k])
+ print()
if __name__ == '__main__':
test()
Modified: python/branches/p3yk-noslice/Lib/mhlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/mhlib.py (original)
+++ python/branches/p3yk-noslice/Lib/mhlib.py Fri Feb 23 18:29:35 2007
@@ -314,7 +314,7 @@
"""Write the set of sequences back to the folder."""
fullname = self.getsequencesfilename()
f = None
- for key, seq in sequences.iteritems():
+ for key, seq in sequences.items():
s = IntSet('', ' ')
s.fromlist(seq)
if not f: f = open(fullname, 'w')
@@ -959,7 +959,7 @@
global mh, f
os.system('rm -rf $HOME/Mail/@test')
mh = MH()
- def do(s): print s; print eval(s)
+ def do(s): print(s); print(eval(s))
do('mh.listfolders()')
do('mh.listallfolders()')
testfolders = ['@test', '@test/test1', '@test/test2',
@@ -974,7 +974,7 @@
do('f.getsequences()')
seqs = f.getsequences()
seqs['foo'] = IntSet('1-10 12-20', ' ').tolist()
- print seqs
+ print(seqs)
f.putsequences(seqs)
do('f.getsequences()')
for t in reversed(testfolders): do('mh.deletefolder(%r)' % (t,))
@@ -990,10 +990,10 @@
try:
do('f.parsesequence(%r)' % (seq,))
except Error as msg:
- print "Error:", msg
+ print("Error:", msg)
stuff = os.popen("pick %r 2>/dev/null" % (seq,)).read()
list = map(int, stuff.split())
- print list, "<-- pick"
+ print(list, "<-- pick")
do('f.listmessages()')
Modified: python/branches/p3yk-noslice/Lib/mimetypes.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/mimetypes.py (original)
+++ python/branches/p3yk-noslice/Lib/mimetypes.py Fri Feb 23 18:29:35 2007
@@ -503,8 +503,8 @@
"""
def usage(code, msg=''):
- print USAGE
- if msg: print msg
+ print(USAGE)
+ if msg: print(msg)
sys.exit(code)
try:
@@ -525,9 +525,9 @@
for gtype in args:
if extension:
guess = guess_extension(gtype, strict)
- if not guess: print "I don't know anything about type", gtype
- else: print guess
+ if not guess: print("I don't know anything about type", gtype)
+ else: print(guess)
else:
guess, encoding = guess_type(gtype, strict)
- if not guess: print "I don't know anything about type", gtype
- else: print 'type:', guess, 'encoding:', encoding
+ if not guess: print("I don't know anything about type", gtype)
+ else: print('type:', guess, 'encoding:', encoding)
Modified: python/branches/p3yk-noslice/Lib/mimify.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/mimify.py (original)
+++ python/branches/p3yk-noslice/Lib/mimify.py Fri Feb 23 18:29:35 2007
@@ -434,11 +434,11 @@
decode_base64 = 0
opts, args = getopt.getopt(sys.argv[1:], 'l:edb')
if len(args) not in (0, 1, 2):
- print usage
+ print(usage)
sys.exit(1)
if (('-e', '') in opts) == (('-d', '') in opts) or \
((('-b', '') in opts) and (('-d', '') not in opts)):
- print usage
+ print(usage)
sys.exit(1)
for o, a in opts:
if o == '-e':
@@ -449,7 +449,7 @@
try:
MAXLEN = int(a)
except (ValueError, OverflowError):
- print usage
+ print(usage)
sys.exit(1)
elif o == '-b':
decode_base64 = 1
Modified: python/branches/p3yk-noslice/Lib/modulefinder.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/modulefinder.py (original)
+++ python/branches/p3yk-noslice/Lib/modulefinder.py Fri Feb 23 18:29:35 2007
@@ -89,11 +89,11 @@
def msg(self, level, str, *args):
if level <= self.debug:
for i in range(self.indent):
- print " ",
- print str,
+ print(" ", end=' ')
+ print(str, end=' ')
for arg in args:
- print repr(arg),
- print
+ print(repr(arg), end=' ')
+ print()
def msgin(self, *args):
level = args[0]
@@ -482,38 +482,38 @@
"""Print a report to stdout, listing the found modules with their
paths, as well as modules that are missing, or seem to be missing.
"""
- print
- print " %-25s %s" % ("Name", "File")
- print " %-25s %s" % ("----", "----")
+ print()
+ print(" %-25s %s" % ("Name", "File"))
+ print(" %-25s %s" % ("----", "----"))
# Print modules found
keys = self.modules.keys()
keys.sort()
for key in keys:
m = self.modules[key]
if m.__path__:
- print "P",
+ print("P", end=' ')
else:
- print "m",
- print "%-25s" % key, m.__file__ or ""
+ print("m", end=' ')
+ print("%-25s" % key, m.__file__ or "")
# Print missing modules
missing, maybe = self.any_missing_maybe()
if missing:
- print
- print "Missing modules:"
+ print()
+ print("Missing modules:")
for name in missing:
mods = self.badmodules[name].keys()
mods.sort()
- print "?", name, "imported from", ', '.join(mods)
+ print("?", name, "imported from", ', '.join(mods))
# Print modules that may be missing, but then again, maybe not...
if maybe:
- print
- print "Submodules thay appear to be missing, but could also be",
- print "global names in the parent package:"
+ print()
+ print("Submodules thay appear to be missing, but could also be", end=' ')
+ print("global names in the parent package:")
for name in maybe:
mods = self.badmodules[name].keys()
mods.sort()
- print "?", name, "imported from", ', '.join(mods)
+ print("?", name, "imported from", ', '.join(mods))
def any_missing(self):
"""Return a list of modules that appear to be missing. Use
@@ -603,7 +603,7 @@
try:
opts, args = getopt.getopt(sys.argv[1:], "dmp:qx:")
except getopt.error as msg:
- print msg
+ print(msg)
return
# Process options
@@ -634,9 +634,9 @@
path[0] = os.path.dirname(script)
path = addpath + path
if debug > 1:
- print "path:"
+ print("path:")
for item in path:
- print " ", repr(item)
+ print(" ", repr(item))
# Create the module finder and turn its crank
mf = ModuleFinder(path, debug, exclude)
@@ -660,4 +660,4 @@
try:
mf = test()
except KeyboardInterrupt:
- print "\n[interrupt]"
+ print("\n[interrupt]")
Modified: python/branches/p3yk-noslice/Lib/msilib/__init__.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/msilib/__init__.py (original)
+++ python/branches/p3yk-noslice/Lib/msilib/__init__.py Fri Feb 23 18:29:35 2007
@@ -40,7 +40,7 @@
index -= 1
unk = type & ~knownbits
if unk:
- print "%s.%s unknown bits %x" % (self.name, name, unk)
+ print("%s.%s unknown bits %x" % (self.name, name, unk))
size = type & datasizemask
dtype = type & typemask
if dtype == type_string:
@@ -59,7 +59,7 @@
tname="OBJECT"
else:
tname="unknown"
- print "%s.%sunknown integer type %d" % (self.name, name, size)
+ print("%s.%sunknown integer type %d" % (self.name, name, size))
if type & type_nullable:
flags = ""
else:
@@ -99,7 +99,7 @@
assert len(value) == count, value
for i in range(count):
field = value[i]
- if isinstance(field, (int, long)):
+ if isinstance(field, (int, int)):
r.SetInteger(i+1,field)
elif isinstance(field, basestring):
r.SetString(i+1,field)
Modified: python/branches/p3yk-noslice/Lib/netrc.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/netrc.py (original)
+++ python/branches/p3yk-noslice/Lib/netrc.py Fri Feb 23 18:29:35 2007
@@ -108,4 +108,4 @@
return rep
if __name__ == '__main__':
- print netrc()
+ print(netrc())
Modified: python/branches/p3yk-noslice/Lib/nntplib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/nntplib.py (original)
+++ python/branches/p3yk-noslice/Lib/nntplib.py Fri Feb 23 18:29:35 2007
@@ -5,7 +5,7 @@
>>> from nntplib import NNTP
>>> s = NNTP('news')
>>> 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 51 articles, range 5770 to 5821
>>> resp, subs = s.xhdr('subject', first + '-' + last)
>>> resp = s.quit()
@@ -175,7 +175,7 @@
If the response code is 200, posting is allowed;
if it 201, posting is not allowed."""
- if self.debugging: print '*welcome*', repr(self.welcome)
+ if self.debugging: print('*welcome*', repr(self.welcome))
return self.welcome
def set_debuglevel(self, level):
@@ -190,12 +190,12 @@
def putline(self, line):
"""Internal: send one line to the server, appending CRLF."""
line = line + CRLF
- if self.debugging > 1: print '*put*', repr(line)
+ if self.debugging > 1: print('*put*', repr(line))
self.sock.sendall(line)
def putcmd(self, line):
"""Internal: send one command to the server (through putline())."""
- if self.debugging: print '*cmd*', repr(line)
+ if self.debugging: print('*cmd*', repr(line))
self.putline(line)
def getline(self):
@@ -203,7 +203,7 @@
Raise EOFError if the connection is closed."""
line = self.file.readline()
if self.debugging > 1:
- print '*get*', repr(line)
+ print('*get*', repr(line))
if not line: raise EOFError
if line[-2:] == CRLF: line = line[:-2]
elif line[-1:] in CRLF: line = line[:-1]
@@ -213,7 +213,7 @@
"""Internal: get a response from the server.
Raise various errors if the response indicates an error."""
resp = self.getline()
- if self.debugging: print '*resp*', repr(resp)
+ if self.debugging: print('*resp*', repr(resp))
c = resp[:1]
if c == '4':
raise NNTPTemporaryError(resp)
@@ -618,11 +618,11 @@
mode = None
s = NNTP(newshost, readermode=mode)
resp, count, first, last, name = s.group('comp.lang.python')
- print resp
- print 'Group', name, 'has', count, 'articles, range', first, 'to', last
+ print(resp)
+ print('Group', name, 'has', count, 'articles, range', first, 'to', last)
resp, subs = s.xhdr('subject', first + '-' + last)
- print resp
+ print(resp)
for item in subs:
- print "%7s %s" % item
+ print("%7s %s" % item)
resp = s.quit()
- print resp
+ print(resp)
Modified: python/branches/p3yk-noslice/Lib/ntpath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/ntpath.py (original)
+++ python/branches/p3yk-noslice/Lib/ntpath.py Fri Feb 23 18:29:35 2007
@@ -344,8 +344,10 @@
var = path[:index]
if var in os.environ:
res = res + os.environ[var]
+ else:
+ res = res + '${' + var + '}'
except ValueError:
- res = res + path
+ res = res + '${' + path
index = pathlen - 1
else:
var = ''
@@ -357,8 +359,10 @@
c = path[index:index + 1]
if var in os.environ:
res = res + os.environ[var]
+ else:
+ res = res + '$' + var
if c != '':
- res = res + c
+ index = index - 1
else:
res = res + c
index = index + 1
Modified: python/branches/p3yk-noslice/Lib/opcode.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/opcode.py (original)
+++ python/branches/p3yk-noslice/Lib/opcode.py Fri Feb 23 18:29:35 2007
@@ -86,10 +86,7 @@
def_op('GET_ITER', 68)
def_op('PRINT_EXPR', 70)
-def_op('PRINT_ITEM', 71)
-def_op('PRINT_NEWLINE', 72)
-def_op('PRINT_ITEM_TO', 73)
-def_op('PRINT_NEWLINE_TO', 74)
+
def_op('INPLACE_LSHIFT', 75)
def_op('INPLACE_RSHIFT', 76)
def_op('INPLACE_AND', 77)
Modified: python/branches/p3yk-noslice/Lib/optparse.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/optparse.py (original)
+++ python/branches/p3yk-noslice/Lib/optparse.py Fri Feb 23 18:29:35 2007
@@ -407,7 +407,7 @@
return _parse_num(val, int)
def _parse_long(val):
- return _parse_num(val, long)
+ return _parse_num(val, int)
_builtin_cvt = { "int" : (_parse_int, _("integer")),
"long" : (_parse_long, _("long integer")),
@@ -611,8 +611,7 @@
else:
setattr(self, attr, None)
if attrs:
- attrs = attrs.keys()
- attrs.sort()
+ attrs = sorted(attrs.keys())
raise OptionError(
"invalid keyword arguments: %s" % ", ".join(attrs),
self)
@@ -1578,7 +1577,7 @@
or not defined.
"""
if self.usage:
- print >>file, self.get_usage()
+ print(self.get_usage(), file=file)
def get_version(self):
if self.version:
@@ -1595,7 +1594,7 @@
name. Does nothing if self.version is empty or undefined.
"""
if self.version:
- print >>file, self.get_version()
+ print(self.get_version(), file=file)
def format_option_help(self, formatter=None):
if formatter is None:
Modified: python/branches/p3yk-noslice/Lib/pdb.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pdb.py (original)
+++ python/branches/p3yk-noslice/Lib/pdb.py Fri Feb 23 18:29:35 2007
@@ -135,7 +135,7 @@
if self._wait_for_mainpyfile:
return
if self.stop_here(frame):
- print >>self.stdout, '--Call--'
+ print('--Call--', file=self.stdout)
self.interaction(frame, None)
def user_line(self, frame):
@@ -171,7 +171,7 @@
def user_return(self, frame, return_value):
"""This function is called when a return trap is set here."""
frame.f_locals['__return__'] = return_value
- print >>self.stdout, '--Return--'
+ print('--Return--', file=self.stdout)
self.interaction(frame, None)
def user_exception(self, frame, (exc_type, exc_value, exc_traceback)):
@@ -181,7 +181,7 @@
if type(exc_type) == type(''):
exc_type_name = exc_type
else: exc_type_name = exc_type.__name__
- print >>self.stdout, exc_type_name + ':', _saferepr(exc_value)
+ print(exc_type_name + ':', _saferepr(exc_value), file=self.stdout)
self.interaction(frame, exc_traceback)
# General interaction function
@@ -204,7 +204,7 @@
if type(t) == type(''):
exc_type_name = t
else: exc_type_name = t.__name__
- print >>self.stdout, '***', exc_type_name + ':', v
+ print('***', exc_type_name + ':', v, file=self.stdout)
def precmd(self, line):
"""Handle alias expansion and ';;' separator."""
@@ -283,7 +283,7 @@
try:
bnum = int(arg)
except:
- print >>self.stdout, "Usage : commands [bnum]\n ...\n end"
+ print("Usage : commands [bnum]\n ...\n end", file=self.stdout)
return
self.commands_bnum = bnum
self.commands[bnum] = []
@@ -300,7 +300,7 @@
# break [ ([filename:]lineno | function) [, "condition"] ]
if not arg:
if self.breaks: # There's at least one
- print >>self.stdout, "Num Type Disp Enb Where"
+ print("Num Type Disp Enb Where", file=self.stdout)
for bp in bdb.Breakpoint.bpbynumber:
if bp:
bp.bpprint(self.stdout)
@@ -322,8 +322,8 @@
filename = arg[:colon].rstrip()
f = self.lookupmodule(filename)
if not f:
- print >>self.stdout, '*** ', repr(filename),
- print >>self.stdout, 'not found from sys.path'
+ print('*** ', repr(filename), end=' ', file=self.stdout)
+ print('not found from sys.path', file=self.stdout)
return
else:
filename = f
@@ -331,7 +331,7 @@
try:
lineno = int(arg)
except ValueError as msg:
- print >>self.stdout, '*** Bad lineno:', arg
+ print('*** Bad lineno:', arg, file=self.stdout)
return
else:
# no colon; can be lineno or function
@@ -357,10 +357,10 @@
# last thing to try
(ok, filename, ln) = self.lineinfo(arg)
if not ok:
- print >>self.stdout, '*** The specified object',
- print >>self.stdout, repr(arg),
- print >>self.stdout, 'is not a function'
- print >>self.stdout, 'or was not found along sys.path.'
+ print('*** The specified object', end=' ', file=self.stdout)
+ print(repr(arg), end=' ', file=self.stdout)
+ print('is not a function', file=self.stdout)
+ print('or was not found along sys.path.', file=self.stdout)
return
funcname = ok # ok contains a function name
lineno = int(ln)
@@ -371,12 +371,12 @@
if line:
# now set the break point
err = self.set_break(filename, line, temporary, cond, funcname)
- if err: print >>self.stdout, '***', err
+ if err: print('***', err, file=self.stdout)
else:
bp = self.get_breaks(filename, line)[-1]
- print >>self.stdout, "Breakpoint %d at %s:%d" % (bp.number,
+ print("Breakpoint %d at %s:%d" % (bp.number,
bp.file,
- bp.line)
+ bp.line), file=self.stdout)
# To be overridden in derived debuggers
def defaultFile(self):
@@ -432,13 +432,13 @@
"""
line = linecache.getline(filename, lineno)
if not line:
- print >>self.stdout, 'End of file'
+ print('End of file', file=self.stdout)
return 0
line = line.strip()
# Don't allow setting breakpoint at a blank line
if (not line or (line[0] == '#') or
(line[:3] == '"""') or line[:3] == "'''"):
- print >>self.stdout, '*** Blank or comment'
+ print('*** Blank or comment', file=self.stdout)
return 0
return lineno
@@ -448,11 +448,11 @@
try:
i = int(i)
except ValueError:
- print >>self.stdout, 'Breakpoint index %r is not a number' % i
+ print('Breakpoint index %r is not a number' % i, file=self.stdout)
continue
if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
- print >>self.stdout, 'No breakpoint numbered', i
+ print('No breakpoint numbered', i, file=self.stdout)
continue
bp = bdb.Breakpoint.bpbynumber[i]
@@ -465,11 +465,11 @@
try:
i = int(i)
except ValueError:
- print >>self.stdout, 'Breakpoint index %r is not a number' % i
+ print('Breakpoint index %r is not a number' % i, file=self.stdout)
continue
if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
- print >>self.stdout, 'No breakpoint numbered', i
+ print('No breakpoint numbered', i, file=self.stdout)
continue
bp = bdb.Breakpoint.bpbynumber[i]
@@ -479,7 +479,11 @@
def do_condition(self, arg):
# arg is breakpoint number and condition
args = arg.split(' ', 1)
- bpnum = int(args[0].strip())
+ try:
+ bpnum = int(args[0].strip())
+ except ValueError:
+ # something went wrong
+ print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
try:
cond = args[1]
except:
@@ -488,13 +492,17 @@
if bp:
bp.cond = cond
if not cond:
- print >>self.stdout, 'Breakpoint', bpnum,
- print >>self.stdout, 'is now unconditional.'
+ print('Breakpoint', bpnum, end=' ', file=self.stdout)
+ print('is now unconditional.', file=self.stdout)
def do_ignore(self,arg):
"""arg is bp number followed by ignore count."""
args = arg.split()
- bpnum = int(args[0].strip())
+ try:
+ bpnum = int(args[0].strip())
+ except ValueError:
+ # something went wrong
+ print('Breakpoint index %r is not a number' % args[0], file=self.stdout)
try:
count = int(args[1].strip())
except:
@@ -508,10 +516,10 @@
reply = reply + '%d crossings' % count
else:
reply = reply + '1 crossing'
- print >>self.stdout, reply + ' of breakpoint %d.' % bpnum
+ print(reply + ' of breakpoint %d.' % bpnum, file=self.stdout)
else:
- print >>self.stdout, 'Will stop next time breakpoint',
- print >>self.stdout, bpnum, 'is reached.'
+ print('Will stop next time breakpoint', end=' ', file=self.stdout)
+ print(bpnum, 'is reached.', file=self.stdout)
def do_clear(self, arg):
"""Three possibilities, tried in this order:
@@ -538,24 +546,24 @@
err = "Invalid line number (%s)" % arg
else:
err = self.clear_break(filename, lineno)
- if err: print >>self.stdout, '***', err
+ if err: print('***', err, file=self.stdout)
return
numberlist = arg.split()
for i in numberlist:
try:
i = int(i)
except ValueError:
- print >>self.stdout, 'Breakpoint index %r is not a number' % i
+ print('Breakpoint index %r is not a number' % i, file=self.stdout)
continue
if not (0 <= i < len(bdb.Breakpoint.bpbynumber)):
- print >>self.stdout, 'No breakpoint numbered', i
+ print('No breakpoint numbered', i, file=self.stdout)
continue
err = self.clear_bpbynumber(i)
if err:
- print >>self.stdout, '***', err
+ print('***', err, file=self.stdout)
else:
- print >>self.stdout, 'Deleted breakpoint', i
+ print('Deleted breakpoint', i, file=self.stdout)
do_cl = do_clear # 'c' is already an abbreviation for 'continue'
def do_where(self, arg):
@@ -565,7 +573,7 @@
def do_up(self, arg):
if self.curindex == 0:
- print >>self.stdout, '*** Oldest frame'
+ print('*** Oldest frame', file=self.stdout)
else:
self.curindex = self.curindex - 1
self.curframe = self.stack[self.curindex][0]
@@ -575,7 +583,7 @@
def do_down(self, arg):
if self.curindex + 1 == len(self.stack):
- print >>self.stdout, '*** Newest frame'
+ print('*** Newest frame', file=self.stdout)
else:
self.curindex = self.curindex + 1
self.curframe = self.stack[self.curindex][0]
@@ -605,12 +613,12 @@
def do_jump(self, arg):
if self.curindex + 1 != len(self.stack):
- print >>self.stdout, "*** You can only jump within the bottom frame"
+ print("*** You can only jump within the bottom frame", file=self.stdout)
return
try:
arg = int(arg)
except ValueError:
- print >>self.stdout, "*** The 'jump' command requires a line number."
+ print("*** The 'jump' command requires a line number.", file=self.stdout)
else:
try:
# Do the jump, fix up our copy of the stack, and display the
@@ -619,7 +627,7 @@
self.stack[self.curindex] = self.stack[self.curindex][0], arg
self.print_stack_entry(self.stack[self.curindex])
except ValueError as e:
- print >>self.stdout, '*** Jump failed:', e
+ print('*** Jump failed:', e, file=self.stdout)
do_j = do_jump
def do_debug(self, arg):
@@ -628,9 +636,9 @@
locals = self.curframe.f_locals
p = Pdb()
p.prompt = "(%s) " % self.prompt.strip()
- print >>self.stdout, "ENTERING RECURSIVE DEBUGGER"
+ print("ENTERING RECURSIVE DEBUGGER", file=self.stdout)
sys.call_tracing(p.run, (arg, globals, locals))
- print >>self.stdout, "LEAVING RECURSIVE DEBUGGER"
+ print("LEAVING RECURSIVE DEBUGGER", file=self.stdout)
sys.settrace(self.trace_dispatch)
self.lastcmd = p.lastcmd
@@ -643,7 +651,7 @@
do_exit = do_quit
def do_EOF(self, arg):
- print >>self.stdout
+ print(file=self.stdout)
self._user_requested_quit = 1
self.set_quit()
return 1
@@ -657,16 +665,16 @@
if co.co_flags & 8: n = n+1
for i in range(n):
name = co.co_varnames[i]
- print >>self.stdout, name, '=',
- if name in dict: print >>self.stdout, dict[name]
- else: print >>self.stdout, "*** undefined ***"
+ print(name, '=', end=' ', file=self.stdout)
+ if name in dict: print(dict[name], file=self.stdout)
+ else: print("*** undefined ***", file=self.stdout)
do_a = do_args
def do_retval(self, arg):
if '__return__' in self.curframe.f_locals:
- print >>self.stdout, self.curframe.f_locals['__return__']
+ print(self.curframe.f_locals['__return__'], file=self.stdout)
else:
- print >>self.stdout, '*** Not yet returned!'
+ print('*** Not yet returned!', file=self.stdout)
do_rv = do_retval
def _getval(self, arg):
@@ -678,12 +686,12 @@
if isinstance(t, str):
exc_type_name = t
else: exc_type_name = t.__name__
- print >>self.stdout, '***', exc_type_name + ':', repr(v)
+ print('***', exc_type_name + ':', repr(v), file=self.stdout)
raise
def do_p(self, arg):
try:
- print >>self.stdout, repr(self._getval(arg))
+ print(repr(self._getval(arg)), file=self.stdout)
except:
pass
@@ -709,7 +717,7 @@
else:
first = max(1, int(x) - 5)
except:
- print >>self.stdout, '*** Error in argument:', repr(arg)
+ print('*** Error in argument:', repr(arg), file=self.stdout)
return
elif self.lineno is None:
first = max(1, self.curframe.f_lineno - 5)
@@ -723,7 +731,7 @@
for lineno in range(first, last+1):
line = linecache.getline(filename, lineno)
if not line:
- print >>self.stdout, '[EOF]'
+ print('[EOF]', file=self.stdout)
break
else:
s = repr(lineno).rjust(3)
@@ -732,7 +740,7 @@
else: s = s + ' '
if lineno == self.curframe.f_lineno:
s = s + '->'
- print >>self.stdout, s + '\t' + line,
+ print(s + '\t' + line, end='', file=self.stdout)
self.lineno = lineno
except KeyboardInterrupt:
pass
@@ -747,23 +755,23 @@
if type(t) == type(''):
exc_type_name = t
else: exc_type_name = t.__name__
- print >>self.stdout, '***', exc_type_name + ':', repr(v)
+ print('***', exc_type_name + ':', repr(v), file=self.stdout)
return
code = None
# Is it a function?
try: code = value.func_code
except: pass
if code:
- print >>self.stdout, 'Function', code.co_name
+ print('Function', code.co_name, file=self.stdout)
return
# Is it an instance method?
try: code = value.im_func.func_code
except: pass
if code:
- print >>self.stdout, 'Method', code.co_name
+ print('Method', code.co_name, file=self.stdout)
return
# None of the above...
- print >>self.stdout, type(value)
+ print(type(value), file=self.stdout)
def do_alias(self, arg):
args = arg.split()
@@ -771,10 +779,10 @@
keys = self.aliases.keys()
keys.sort()
for alias in keys:
- print >>self.stdout, "%s = %s" % (alias, self.aliases[alias])
+ print("%s = %s" % (alias, self.aliases[alias]), file=self.stdout)
return
if args[0] in self.aliases and len(args) == 1:
- print >>self.stdout, "%s = %s" % (args[0], self.aliases[args[0]])
+ print("%s = %s" % (args[0], self.aliases[args[0]]), file=self.stdout)
else:
self.aliases[args[0]] = ' '.join(args[1:])
@@ -806,11 +814,11 @@
def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix):
frame, lineno = frame_lineno
if frame is self.curframe:
- print >>self.stdout, '>',
+ print('>', end=' ', file=self.stdout)
else:
- print >>self.stdout, ' ',
- print >>self.stdout, self.format_stack_entry(frame_lineno,
- prompt_prefix)
+ print(' ', end=' ', file=self.stdout)
+ print(self.format_stack_entry(frame_lineno,
+ prompt_prefix), file=self.stdout)
# Help methods (derived from pdb.doc)
@@ -819,20 +827,20 @@
self.help_h()
def help_h(self):
- print >>self.stdout, """h(elp)
+ print("""h(elp)
Without argument, print the list of available commands.
With a command name as argument, print help about that command
"help pdb" pipes the full documentation file to the $PAGER
-"help exec" gives help on the ! command"""
+"help exec" gives help on the ! command""", file=self.stdout)
def help_where(self):
self.help_w()
def help_w(self):
- print >>self.stdout, """w(here)
+ print("""w(here)
Print a stack trace, with the most recent frame at the bottom.
An arrow indicates the "current frame", which determines the
-context of most commands. 'bt' is an alias for this command."""
+context of most commands. 'bt' is an alias for this command.""", file=self.stdout)
help_bt = help_w
@@ -840,23 +848,23 @@
self.help_d()
def help_d(self):
- print >>self.stdout, """d(own)
+ print("""d(own)
Move the current frame one level down in the stack trace
-(to a newer frame)."""
+(to a newer frame).""", file=self.stdout)
def help_up(self):
self.help_u()
def help_u(self):
- print >>self.stdout, """u(p)
+ print("""u(p)
Move the current frame one level up in the stack trace
-(to an older frame)."""
+(to an older frame).""", file=self.stdout)
def help_break(self):
self.help_b()
def help_b(self):
- print >>self.stdout, """b(reak) ([file:]lineno | function) [, condition]
+ print("""b(reak) ([file:]lineno | function) [, condition]
With a line number argument, set a break there in the current
file. With a function name, set a break at first executable line
of that function. Without argument, list all breaks. If a second
@@ -866,14 +874,14 @@
The line number may be prefixed with a filename and a colon,
to specify a breakpoint in another file (probably one that
hasn't been loaded yet). The file is searched for on sys.path;
-the .py suffix may be omitted."""
+the .py suffix may be omitted.""", file=self.stdout)
def help_clear(self):
self.help_cl()
def help_cl(self):
- print >>self.stdout, "cl(ear) filename:lineno"
- print >>self.stdout, """cl(ear) [bpnumber [bpnumber...]]
+ print("cl(ear) filename:lineno", file=self.stdout)
+ print("""cl(ear) [bpnumber [bpnumber...]]
With a space separated list of breakpoint numbers, clear
those breakpoints. Without argument, clear all breaks (but
first ask confirmation). With a filename:lineno argument,
@@ -882,59 +890,59 @@
Note that the argument is different from previous versions of
the debugger (in python distributions 1.5.1 and before) where
a linenumber was used instead of either filename:lineno or
-breakpoint numbers."""
+breakpoint numbers.""", file=self.stdout)
def help_tbreak(self):
- print >>self.stdout, """tbreak same arguments as break, but breakpoint is
-removed when first hit."""
+ print("""tbreak same arguments as break, but breakpoint is
+removed when first hit.""", file=self.stdout)
def help_enable(self):
- print >>self.stdout, """enable bpnumber [bpnumber ...]
+ print("""enable bpnumber [bpnumber ...]
Enables the breakpoints given as a space separated list of
-bp numbers."""
+bp numbers.""", file=self.stdout)
def help_disable(self):
- print >>self.stdout, """disable bpnumber [bpnumber ...]
+ print("""disable bpnumber [bpnumber ...]
Disables the breakpoints given as a space separated list of
-bp numbers."""
+bp numbers.""", file=self.stdout)
def help_ignore(self):
- print >>self.stdout, """ignore bpnumber count
+ print("""ignore bpnumber count
Sets the ignore count for the given breakpoint number. A breakpoint
becomes active when the ignore count is zero. When non-zero, the
count is decremented each time the breakpoint is reached and the
breakpoint is not disabled and any associated condition evaluates
-to true."""
+to true.""", file=self.stdout)
def help_condition(self):
- print >>self.stdout, """condition bpnumber str_condition
+ print("""condition bpnumber str_condition
str_condition is a string specifying an expression which
must evaluate to true before the breakpoint is honored.
If str_condition is absent, any existing condition is removed;
-i.e., the breakpoint is made unconditional."""
+i.e., the breakpoint is made unconditional.""", file=self.stdout)
def help_step(self):
self.help_s()
def help_s(self):
- print >>self.stdout, """s(tep)
+ print("""s(tep)
Execute the current line, stop at the first possible occasion
-(either in a function that is called or in the current function)."""
+(either in a function that is called or in the current function).""", file=self.stdout)
def help_next(self):
self.help_n()
def help_n(self):
- print >>self.stdout, """n(ext)
+ print("""n(ext)
Continue execution until the next line in the current function
-is reached or it returns."""
+is reached or it returns.""", file=self.stdout)
def help_return(self):
self.help_r()
def help_r(self):
- print >>self.stdout, """r(eturn)
-Continue execution until the current function returns."""
+ print("""r(eturn)
+Continue execution until the current function returns.""", file=self.stdout)
def help_continue(self):
self.help_c()
@@ -943,51 +951,51 @@
self.help_c()
def help_c(self):
- print >>self.stdout, """c(ont(inue))
-Continue execution, only stop when a breakpoint is encountered."""
+ print("""c(ont(inue))
+Continue execution, only stop when a breakpoint is encountered.""", file=self.stdout)
def help_jump(self):
self.help_j()
def help_j(self):
- print >>self.stdout, """j(ump) lineno
-Set the next line that will be executed."""
+ print("""j(ump) lineno
+Set the next line that will be executed.""", file=self.stdout)
def help_debug(self):
- print >>self.stdout, """debug code
+ print("""debug code
Enter a recursive debugger that steps through the code argument
(which is an arbitrary expression or statement to be executed
-in the current environment)."""
+in the current environment).""", file=self.stdout)
def help_list(self):
self.help_l()
def help_l(self):
- print >>self.stdout, """l(ist) [first [,last]]
+ print("""l(ist) [first [,last]]
List source code for the current file.
Without arguments, list 11 lines around the current line
or continue the previous listing.
With one argument, list 11 lines starting at that line.
With two arguments, list the given range;
-if the second argument is less than the first, it is a count."""
+if the second argument is less than the first, it is a count.""", file=self.stdout)
def help_args(self):
self.help_a()
def help_a(self):
- print >>self.stdout, """a(rgs)
-Print the arguments of the current function."""
+ print("""a(rgs)
+Print the arguments of the current function.""", file=self.stdout)
def help_p(self):
- print >>self.stdout, """p expression
-Print the value of the expression."""
+ print("""p expression
+Print the value of the expression.""", file=self.stdout)
def help_pp(self):
- print >>self.stdout, """pp expression
-Pretty-print the value of the expression."""
+ print("""pp expression
+Pretty-print the value of the expression.""", file=self.stdout)
def help_exec(self):
- print >>self.stdout, """(!) statement
+ print("""(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
@@ -995,27 +1003,27 @@
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
-(Pdb)"""
+(Pdb)""", file=self.stdout)
def help_quit(self):
self.help_q()
def help_q(self):
- print >>self.stdout, """q(uit) or exit - Quit from the debugger.
-The program being executed is aborted."""
+ print("""q(uit) or exit - Quit from the debugger.
+The program being executed is aborted.""", file=self.stdout)
help_exit = help_q
def help_whatis(self):
- print >>self.stdout, """whatis arg
-Prints the type of the argument."""
+ print("""whatis arg
+Prints the type of the argument.""", file=self.stdout)
def help_EOF(self):
- print >>self.stdout, """EOF
-Handles the receipt of EOF as a command."""
+ print("""EOF
+Handles the receipt of EOF as a command.""", file=self.stdout)
def help_alias(self):
- print >>self.stdout, """alias [name [command [parameter parameter ...] ]]
+ print("""alias [name [command [parameter parameter ...] ]]
Creates an alias called 'name' the executes 'command'. The command
must *not* be enclosed in quotes. Replaceable parameters are
indicated by %1, %2, and so on, while %* is replaced by all the
@@ -1036,14 +1044,14 @@
#Print instance variables in self
alias ps pi self
-"""
+""", file=self.stdout)
def help_unalias(self):
- print >>self.stdout, """unalias name
-Deletes the specified alias."""
+ print("""unalias name
+Deletes the specified alias.""", file=self.stdout)
def help_commands(self):
- print >>self.stdout, """commands [bpnumber]
+ print("""commands [bpnumber]
(com) ...
(com) end
(Pdb)
@@ -1075,7 +1083,7 @@
be desirable for breakpoints 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.
-"""
+""", file=self.stdout)
def help_pdb(self):
help()
@@ -1166,20 +1174,20 @@
fullname = os.path.join(dirname, 'pdb.doc')
if os.path.exists(fullname):
sts = os.system('${PAGER-more} '+fullname)
- if sts: print '*** Pager exit status:', sts
+ if sts: print('*** Pager exit status:', sts)
break
else:
- print 'Sorry, can\'t find the help file "pdb.doc"',
- print 'along the Python search path'
+ print('Sorry, can\'t find the help file "pdb.doc"', end=' ')
+ print('along the Python search path')
def main():
if not sys.argv[1:]:
- print "usage: pdb.py scriptfile [arg] ..."
+ print("usage: pdb.py scriptfile [arg] ...")
sys.exit(2)
mainpyfile = sys.argv[1] # Get script filename
if not os.path.exists(mainpyfile):
- print 'Error:', mainpyfile, 'does not exist'
+ print('Error:', mainpyfile, 'does not exist')
sys.exit(1)
del sys.argv[0] # Hide "pdb.py" from argument list
@@ -1198,20 +1206,20 @@
pdb._runscript(mainpyfile)
if pdb._user_requested_quit:
break
- print "The program finished and will be restarted"
+ print("The program finished and will be restarted")
except SystemExit:
# In most cases SystemExit does not warrant a post-mortem session.
- print "The program exited via sys.exit(). Exit status: ",
- print sys.exc_info()[1]
+ print("The program exited via sys.exit(). Exit status: ", end=' ')
+ print(sys.exc_info()[1])
except:
traceback.print_exc()
- print "Uncaught exception. Entering post mortem debugging"
- print "Running 'cont' or 'step' will restart the program"
+ print("Uncaught exception. Entering post mortem debugging")
+ print("Running 'cont' or 'step' will restart the program")
t = sys.exc_info()[2]
while t.tb_next is not None:
t = t.tb_next
pdb.interaction(t.tb_frame,t)
- print "Post mortem debugger finished. The "+mainpyfile+" will be restarted"
+ print("Post mortem debugger finished. The "+mainpyfile+" will be restarted")
# When invoked as main program, invoke the debugger on a script
Modified: python/branches/p3yk-noslice/Lib/pickle.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pickle.py (original)
+++ python/branches/p3yk-noslice/Lib/pickle.py Fri Feb 23 18:29:35 2007
@@ -456,9 +456,29 @@
return
# Text pickle, or int too big to fit in signed 4-byte format.
self.write(INT + repr(obj) + '\n')
- dispatch[IntType] = save_int
+ # XXX save_int is merged into save_long
+ # dispatch[IntType] = save_int
def save_long(self, obj, pack=struct.pack):
+ if self.bin:
+ # If the int is small enough to fit in a signed 4-byte 2's-comp
+ # format, we can store it more efficiently than the general
+ # case.
+ # First one- and two-byte unsigned ints:
+ if obj >= 0:
+ if obj <= 0xff:
+ self.write(BININT1 + chr(obj))
+ return
+ if obj <= 0xffff:
+ self.write("%c%c%c" % (BININT2, obj&0xff, obj>>8))
+ return
+ # Next check for 4-byte signed ints:
+ high_bits = obj >> 31 # note that Python shift sign-extends
+ if high_bits == 0 or high_bits == -1:
+ # All high bits are copies of bit 2**31, so the value
+ # fits in a 4-byte signed int.
+ self.write(BININT + pack("<i", obj))
+ return
if self.proto >= 2:
bytes = encode_long(obj)
n = len(bytes)
@@ -646,7 +666,7 @@
write(MARK + DICT)
self.memoize(obj)
- self._batch_setitems(obj.iteritems())
+ self._batch_setitems(iter(obj.items()))
dispatch[DictionaryType] = save_dict
if not PyStringMap is None:
@@ -878,7 +898,7 @@
try:
val = int(data)
except ValueError:
- val = long(data)
+ val = int(data)
self.append(val)
dispatch[INT] = load_int
@@ -895,7 +915,7 @@
dispatch[BININT2] = load_binint2
def load_long(self):
- self.append(long(self.readline()[:-1], 0))
+ self.append(int(self.readline()[:-1], 0))
dispatch[LONG] = load_long
def load_long1(self):
@@ -1219,22 +1239,22 @@
def encode_long(x):
r"""Encode a long to a two's complement little-endian binary string.
- Note that 0L is a special case, returning an empty string, to save a
+ Note that 0 is a special case, returning an empty string, to save a
byte in the LONG1 pickling context.
- >>> encode_long(0L)
+ >>> encode_long(0)
''
- >>> encode_long(255L)
+ >>> encode_long(255)
'\xff\x00'
- >>> encode_long(32767L)
+ >>> encode_long(32767)
'\xff\x7f'
- >>> encode_long(-256L)
+ >>> encode_long(-256)
'\x00\xff'
- >>> encode_long(-32768L)
+ >>> encode_long(-32768)
'\x00\x80'
- >>> encode_long(-128L)
+ >>> encode_long(-128)
'\x80'
- >>> encode_long(127L)
+ >>> encode_long(127)
'\x7f'
>>>
"""
@@ -1264,7 +1284,7 @@
# Extend to a full byte.
nibbles += 1
nbits = nibbles * 4
- x += 1L << nbits
+ x += 1 << nbits
assert x > 0
ashex = hex(x)
njunkchars = 2 + ashex.endswith('L')
@@ -1304,11 +1324,11 @@
nbytes = len(data)
if nbytes == 0:
- return 0L
+ return 0
ashex = _binascii.hexlify(data[::-1])
- n = long(ashex, 16) # quadratic time before Python 2.3; linear now
+ n = int(ashex, 16) # quadratic time before Python 2.3; linear now
if data[-1] >= '\x80':
- n -= 1L << (nbytes * 8)
+ n -= 1 << (nbytes * 8)
return n
# Shorthands
Modified: python/branches/p3yk-noslice/Lib/pickletools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pickletools.py (original)
+++ python/branches/p3yk-noslice/Lib/pickletools.py Fri Feb 23 18:29:35 2007
@@ -511,7 +511,7 @@
try:
return int(s)
except OverflowError:
- return long(s)
+ return int(s)
def read_decimalnl_long(f):
r"""
@@ -525,7 +525,7 @@
"""
s = read_stringnl(f, decode=False, stripquotes=False)
- return long(s)
+ return int(s)
decimalnl_short = ArgumentDescriptor(
@@ -676,7 +676,7 @@
This first reads four bytes as a signed size (but requires the
size to be >= 0), then reads that many bytes and interprets them
as a little-endian 2's-complement long. If the size is 0, that's taken
- as a shortcut for the long 0L, although LONG1 should really be used
+ as a shortcut for the int 0, although LONG1 should really be used
then instead (and in any case where # of bytes < 256).
""")
@@ -724,12 +724,12 @@
pylong = StackObject(
name='long',
- obtype=long,
+ obtype=int,
doc="A long (as opposed to short) Python integer object.")
pyinteger_or_bool = StackObject(
name='int_or_bool',
- obtype=(int, long, bool),
+ obtype=(int, int, bool),
doc="A Python integer object (short or long), or "
"a Python bool.")
@@ -1757,18 +1757,18 @@
for name in pickle.__all__:
if not re.match("[A-Z][A-Z0-9_]+$", name):
if verbose:
- print "skipping %r: it doesn't look like an opcode name" % name
+ print("skipping %r: it doesn't look like an opcode name" % name)
continue
picklecode = getattr(pickle, name)
if not isinstance(picklecode, str) or len(picklecode) != 1:
if verbose:
- print ("skipping %r: value %r doesn't look like a pickle "
- "code" % (name, picklecode))
+ print(("skipping %r: value %r doesn't look like a pickle "
+ "code" % (name, picklecode)))
continue
if picklecode in copy:
if verbose:
- print "checking name %r w/ code %r for consistency" % (
- name, picklecode)
+ print("checking name %r w/ code %r for consistency" % (
+ name, picklecode))
d = copy[picklecode]
if d.name != name:
raise ValueError("for pickle code %r, pickle.py uses name %r "
@@ -1899,7 +1899,7 @@
errormsg = None
for opcode, arg, pos in genops(pickle):
if pos is not None:
- print >> out, "%5d:" % pos,
+ print("%5d:" % pos, end=' ', file=out)
line = "%-4s %s%s" % (repr(opcode.code)[1:-1],
indentchunk * len(markstack),
@@ -1964,7 +1964,7 @@
line += ' ' + repr(arg)
if markmsg:
line += ' ' + markmsg
- print >> out, line
+ print(line, file=out)
if errormsg:
# Note that we delayed complaining until the offending opcode
@@ -1983,7 +1983,7 @@
stack.extend(after)
- print >> out, "highest protocol among opcodes =", maxproto
+ print("highest protocol among opcodes =", maxproto, file=out)
if stack:
raise ValueError("stack not empty after STOP: %r" % stack)
@@ -2000,13 +2000,13 @@
0: ( MARK
1: l LIST (MARK at 0)
2: p PUT 0
- 5: I INT 1
+ 5: L LONG 1
8: a APPEND
- 9: I INT 2
+ 9: L LONG 2
12: a APPEND
13: ( MARK
- 14: I INT 3
- 17: I INT 4
+ 14: L LONG 3
+ 17: L LONG 4
20: t TUPLE (MARK at 13)
21: p PUT 1
24: a APPEND
@@ -2079,7 +2079,7 @@
93: p PUT 6
96: S STRING 'value'
105: p PUT 7
- 108: I INT 42
+ 108: L LONG 42
112: s SETITEM
113: b BUILD
114: a APPEND
Modified: python/branches/p3yk-noslice/Lib/pipes.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pipes.py (original)
+++ python/branches/p3yk-noslice/Lib/pipes.py Fri Feb 23 18:29:35 2007
@@ -188,7 +188,7 @@
def makepipeline(self, infile, outfile):
cmd = makepipeline(infile, self.steps, outfile)
if self.debugging:
- print cmd
+ print(cmd)
cmd = 'set -x; ' + cmd
return cmd
@@ -286,7 +286,7 @@
# Small test program and example
def test():
- print 'Testing...'
+ print('Testing...')
t = Template()
t.append('togif $IN $OUT', 'ff')
t.append('giftoppm', '--')
@@ -295,4 +295,4 @@
t.debug(1)
FILE = '/usr/local/images/rgb/rogues/guido.rgb'
t.copy(FILE, '@temp')
- print 'Done.'
+ print('Done.')
Modified: python/branches/p3yk-noslice/Lib/plat-aix3/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-aix3/IN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-aix3/IN.py Fri Feb 23 18:29:35 2007
@@ -86,30 +86,30 @@
IPPORT_RESERVED = 1024
IPPORT_USERRESERVED = 5000
IPPORT_TIMESERVER = 37
-def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0)
+def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0)
IN_CLASSA_NET = 0xff000000
IN_CLASSA_NSHIFT = 24
IN_CLASSA_HOST = 0x00ffffff
IN_CLASSA_MAX = 128
-def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000)
+def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000)
IN_CLASSB_NET = 0xffff0000
IN_CLASSB_NSHIFT = 16
IN_CLASSB_HOST = 0x0000ffff
IN_CLASSB_MAX = 65536
-def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000)
+def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000)
IN_CLASSC_NET = 0xffffff00
IN_CLASSC_NSHIFT = 8
IN_CLASSC_HOST = 0x000000ff
-def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000)
+def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000)
def IN_MULTICAST(i): return IN_CLASSD(i)
-def IN_EXPERIMENTAL(i): return (((long)(i) & 0xe0000000) == 0xe0000000)
+def IN_EXPERIMENTAL(i): return (((int)(i) & 0xe0000000) == 0xe0000000)
-def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000)
+def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000)
INADDR_ANY = 0x00000000
INADDR_LOOPBACK = 0x7f000001
Modified: python/branches/p3yk-noslice/Lib/plat-aix4/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-aix4/IN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-aix4/IN.py Fri Feb 23 18:29:35 2007
@@ -111,24 +111,24 @@
IPPORT_RESERVED = 1024
IPPORT_USERRESERVED = 5000
IPPORT_TIMESERVER = 37
-def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0)
+def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0)
IN_CLASSA_NET = 0xff000000
IN_CLASSA_NSHIFT = 24
IN_CLASSA_HOST = 0x00ffffff
IN_CLASSA_MAX = 128
-def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000)
+def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000)
IN_CLASSB_NET = 0xffff0000
IN_CLASSB_NSHIFT = 16
IN_CLASSB_HOST = 0x0000ffff
IN_CLASSB_MAX = 65536
-def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000)
+def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000)
IN_CLASSC_NET = 0xffffff00
IN_CLASSC_NSHIFT = 8
IN_CLASSC_HOST = 0x000000ff
-def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000)
+def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000)
def IN_MULTICAST(i): return IN_CLASSD(i)
@@ -138,9 +138,9 @@
INADDR_UNSPEC_GROUP = 0xe0000000
INADDR_ALLHOSTS_GROUP = 0xe0000001
INADDR_MAX_LOCAL_GROUP = 0xe00000ff
-def IN_EXPERIMENTAL(i): return (((long)(i) & 0xe0000000) == 0xe0000000)
+def IN_EXPERIMENTAL(i): return (((int)(i) & 0xe0000000) == 0xe0000000)
-def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000)
+def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000)
INADDR_ANY = 0x00000000
INADDR_BROADCAST = 0xffffffff
Modified: python/branches/p3yk-noslice/Lib/plat-atheos/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-atheos/IN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-atheos/IN.py Fri Feb 23 18:29:35 2007
@@ -7,7 +7,7 @@
__FAVOR_BSD = 1
_ISOC9X_SOURCE = 1
_POSIX_SOURCE = 1
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
_XOPEN_SOURCE = 500
_XOPEN_SOURCE_EXTENDED = 1
_LARGEFILE64_SOURCE = 1
@@ -18,7 +18,7 @@
__USE_ISOC9X = 1
_POSIX_SOURCE = 1
_POSIX_C_SOURCE = 2
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
__USE_POSIX = 1
__USE_POSIX2 = 1
__USE_POSIX199309 = 1
@@ -110,8 +110,8 @@
CHAR_MIN = (-128)
INT_MAX = 2147483647
INT_MIN = (-2147483647-1)
-LONG_MAX = 2147483647L
-LONG_MIN = (-2147483647L-1L)
+LONG_MAX = 2147483647
+LONG_MIN = (-2147483647-1)
SCHAR_MAX = 127
SCHAR_MIN = (-128)
SHRT_MAX = 32767
@@ -206,10 +206,10 @@
INT_MIN = (-INT_MAX - 1)
INT_MAX = 2147483647
UINT_MAX = 4294967295
-LONG_MAX = 9223372036854775807L
-LONG_MAX = 2147483647L
-LONG_MIN = (-LONG_MAX - 1L)
-ULONG_MAX = 4294967295L
+LONG_MAX = 9223372036854775807
+LONG_MAX = 2147483647
+LONG_MIN = (-LONG_MAX - 1)
+ULONG_MAX = 4294967295
# Included from stdint.h
_STDINT_H = 1
@@ -243,27 +243,27 @@
INT_LEAST64_MAX = (__INT64_C(9223372036854775807))
UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615))
INT_FAST8_MIN = (-128)
-INT_FAST16_MIN = (-9223372036854775807L-1)
-INT_FAST32_MIN = (-9223372036854775807L-1)
+INT_FAST16_MIN = (-9223372036854775807-1)
+INT_FAST32_MIN = (-9223372036854775807-1)
INT_FAST16_MIN = (-2147483647-1)
INT_FAST32_MIN = (-2147483647-1)
INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1)
INT_FAST8_MAX = (127)
-INT_FAST16_MAX = (9223372036854775807L)
-INT_FAST32_MAX = (9223372036854775807L)
+INT_FAST16_MAX = (9223372036854775807)
+INT_FAST32_MAX = (9223372036854775807)
INT_FAST16_MAX = (2147483647)
INT_FAST32_MAX = (2147483647)
INT_FAST64_MAX = (__INT64_C(9223372036854775807))
UINT_FAST64_MAX = (__UINT64_C(18446744073709551615))
-INTPTR_MIN = (-9223372036854775807L-1)
-INTPTR_MAX = (9223372036854775807L)
+INTPTR_MIN = (-9223372036854775807-1)
+INTPTR_MAX = (9223372036854775807)
INTPTR_MIN = (-2147483647-1)
INTPTR_MAX = (2147483647)
INTMAX_MIN = (-__INT64_C(9223372036854775807)-1)
INTMAX_MAX = (__INT64_C(9223372036854775807))
UINTMAX_MAX = (__UINT64_C(18446744073709551615))
-PTRDIFF_MIN = (-9223372036854775807L-1)
-PTRDIFF_MAX = (9223372036854775807L)
+PTRDIFF_MIN = (-9223372036854775807-1)
+PTRDIFF_MAX = (9223372036854775807)
PTRDIFF_MIN = (-2147483647-1)
PTRDIFF_MAX = (2147483647)
SIG_ATOMIC_MIN = (-2147483647-1)
@@ -684,7 +684,7 @@
INADDR_ANY = 0x00000000
INADDR_BROADCAST = 0xffffffff
INADDR_LOOPBACK = 0x7f000001
-def CMSG_ALIGN(len): return ( ((len)+sizeof(long)-1) & ~(sizeof(long)-1) )
+def CMSG_ALIGN(len): return ( ((len)+sizeof(int)-1) & ~(sizeof(int)-1) )
PROT_SOCK = 1024
SHUTDOWN_MASK = 3
Modified: python/branches/p3yk-noslice/Lib/plat-atheos/TYPES.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-atheos/TYPES.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-atheos/TYPES.py Fri Feb 23 18:29:35 2007
@@ -7,7 +7,7 @@
__FAVOR_BSD = 1
_ISOC9X_SOURCE = 1
_POSIX_SOURCE = 1
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
_XOPEN_SOURCE = 500
_XOPEN_SOURCE_EXTENDED = 1
_LARGEFILE64_SOURCE = 1
@@ -18,7 +18,7 @@
__USE_ISOC9X = 1
_POSIX_SOURCE = 1
_POSIX_C_SOURCE = 2
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
__USE_POSIX = 1
__USE_POSIX2 = 1
__USE_POSIX199309 = 1
Modified: python/branches/p3yk-noslice/Lib/plat-beos5/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-beos5/IN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-beos5/IN.py Fri Feb 23 18:29:35 2007
@@ -34,7 +34,7 @@
# Included from null.h
NULL = (0)
-NULL = 0L
+NULL = 0
# Included from size_t.h
@@ -100,8 +100,8 @@
MB_LEN_MAX = (1)
SHRT_MIN = (-32767-1)
SHRT_MAX = (32767)
-LONG_MIN = (-2147483647L-1)
-LONG_MAX = (2147483647L)
+LONG_MIN = (-2147483647-1)
+LONG_MAX = (2147483647)
INT_MIN = LONG_MIN
INT_MAX = LONG_MAX
ARG_MAX = (32768)
@@ -118,7 +118,7 @@
OPEN_MAX = (128)
PATH_MAX = (1024)
PIPE_MAX = (512)
-SSIZE_MAX = (2147483647L)
+SSIZE_MAX = (2147483647)
TTY_NAME_MAX = (256)
TZNAME_MAX = (32)
SYMLINKS_MAX = (16)
@@ -133,7 +133,7 @@
_POSIX_OPEN_MAX = (128)
_POSIX_PATH_MAX = (1024)
_POSIX_PIPE_BUF = (512)
-_POSIX_SSIZE_MAX = (2147483647L)
+_POSIX_SSIZE_MAX = (2147483647)
_POSIX_STREAM_MAX = (8)
_POSIX_TTY_NAME_MAX = (256)
_POSIX_TZNAME_MAX = (3)
Modified: python/branches/p3yk-noslice/Lib/plat-freebsd2/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-freebsd2/IN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-freebsd2/IN.py Fri Feb 23 18:29:35 2007
@@ -101,33 +101,33 @@
IPPORT_HIFIRSTAUTO = 40000
IPPORT_HILASTAUTO = 44999
IPPORT_RESERVEDSTART = 600
-def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0)
+def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0)
IN_CLASSA_NET = 0xff000000
IN_CLASSA_NSHIFT = 24
IN_CLASSA_HOST = 0x00ffffff
IN_CLASSA_MAX = 128
-def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000)
+def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000)
IN_CLASSB_NET = 0xffff0000
IN_CLASSB_NSHIFT = 16
IN_CLASSB_HOST = 0x0000ffff
IN_CLASSB_MAX = 65536
-def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000)
+def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000)
IN_CLASSC_NET = 0xffffff00
IN_CLASSC_NSHIFT = 8
IN_CLASSC_HOST = 0x000000ff
-def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000)
+def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000)
IN_CLASSD_NET = 0xf0000000
IN_CLASSD_NSHIFT = 28
IN_CLASSD_HOST = 0x0fffffff
def IN_MULTICAST(i): return IN_CLASSD(i)
-def IN_EXPERIMENTAL(i): return (((long)(i) & 0xf0000000) == 0xf0000000)
+def IN_EXPERIMENTAL(i): return (((int)(i) & 0xf0000000) == 0xf0000000)
-def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000)
+def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000)
INADDR_ANY = 0x00000000
INADDR_BROADCAST = 0xffffffff
Modified: python/branches/p3yk-noslice/Lib/plat-freebsd3/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-freebsd3/IN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-freebsd3/IN.py Fri Feb 23 18:29:35 2007
@@ -101,33 +101,33 @@
IPPORT_HIFIRSTAUTO = 49152
IPPORT_HILASTAUTO = 65535
IPPORT_RESERVEDSTART = 600
-def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0)
+def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0)
IN_CLASSA_NET = 0xff000000
IN_CLASSA_NSHIFT = 24
IN_CLASSA_HOST = 0x00ffffff
IN_CLASSA_MAX = 128
-def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000)
+def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000)
IN_CLASSB_NET = 0xffff0000
IN_CLASSB_NSHIFT = 16
IN_CLASSB_HOST = 0x0000ffff
IN_CLASSB_MAX = 65536
-def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000)
+def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000)
IN_CLASSC_NET = 0xffffff00
IN_CLASSC_NSHIFT = 8
IN_CLASSC_HOST = 0x000000ff
-def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000)
+def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000)
IN_CLASSD_NET = 0xf0000000
IN_CLASSD_NSHIFT = 28
IN_CLASSD_HOST = 0x0fffffff
def IN_MULTICAST(i): return IN_CLASSD(i)
-def IN_EXPERIMENTAL(i): return (((long)(i) & 0xf0000000) == 0xf0000000)
+def IN_EXPERIMENTAL(i): return (((int)(i) & 0xf0000000) == 0xf0000000)
-def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000)
+def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000)
INADDR_ANY = 0x00000000
INADDR_LOOPBACK = 0x7f000001
Modified: python/branches/p3yk-noslice/Lib/plat-irix5/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-irix5/IN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-irix5/IN.py Fri Feb 23 18:29:35 2007
@@ -61,33 +61,33 @@
IPPORT_RESERVED = 1024
IPPORT_USERRESERVED = 5000
IPPORT_MAXPORT = 65535
-def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0)
+def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0)
IN_CLASSA_NET = 0xff000000
IN_CLASSA_NSHIFT = 24
IN_CLASSA_HOST = 0x00ffffff
IN_CLASSA_MAX = 128
-def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000)
+def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000)
IN_CLASSB_NET = 0xffff0000
IN_CLASSB_NSHIFT = 16
IN_CLASSB_HOST = 0x0000ffff
IN_CLASSB_MAX = 65536
-def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000)
+def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000)
IN_CLASSC_NET = 0xffffff00
IN_CLASSC_NSHIFT = 8
IN_CLASSC_HOST = 0x000000ff
-def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000)
+def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000)
IN_CLASSD_NET = 0xf0000000
IN_CLASSD_NSHIFT = 28
IN_CLASSD_HOST = 0x0fffffff
def IN_MULTICAST(i): return IN_CLASSD(i)
-def IN_EXPERIMENTAL(i): return (((long)(i) & 0xf0000000) == 0xf0000000)
+def IN_EXPERIMENTAL(i): return (((int)(i) & 0xf0000000) == 0xf0000000)
-def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000)
+def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000)
INADDR_ANY = 0x00000000
INADDR_BROADCAST = 0xffffffff
Modified: python/branches/p3yk-noslice/Lib/plat-irix5/cddb.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-irix5/cddb.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-irix5/cddb.py Fri Feb 23 18:29:35 2007
@@ -89,7 +89,7 @@
break
match = reg.match(line)
if not match:
- print 'syntax error in ' + file
+ print('syntax error in ' + file)
continue
name1, name2, value = match.group(1, 2, 3)
if name1 == 'album':
@@ -101,17 +101,17 @@
if not self.toc:
self.toc = value
if self.toc != value:
- print 'toc\'s don\'t match'
+ print('toc\'s don\'t match')
elif name2 == 'notes':
self.notes.append(value)
elif name1[:5] == 'track':
try:
trackno = int(name1[5:])
except strings.atoi_error:
- print 'syntax error in ' + file
+ print('syntax error in ' + file)
continue
if trackno > ntracks:
- print 'track number %r in file %r out of range' % (trackno, file)
+ print('track number %r in file %r out of range' % (trackno, file))
continue
if name2 == 'title':
self.track[trackno] = value
Modified: python/branches/p3yk-noslice/Lib/plat-irix5/cdplayer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-irix5/cdplayer.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-irix5/cdplayer.py Fri Feb 23 18:29:35 2007
@@ -51,7 +51,7 @@
line = line[l:]
match = reg.match(line)
if not match:
- print 'syntax error in ~/' + cdplayerrc
+ print('syntax error in ~/' + cdplayerrc)
continue
name, value = match.group(1, 2)
if name == 'title':
Modified: python/branches/p3yk-noslice/Lib/plat-irix5/flp.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-irix5/flp.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-irix5/flp.py Fri Feb 23 18:29:35 2007
@@ -66,7 +66,7 @@
return None
try:
if fp.read(4) != MAGIC:
- print 'flp: bad magic word in cache file', cachename
+ print('flp: bad magic word in cache file', cachename)
return None
cache_mtime = rdlong(fp)
file_mtime = getmtime(filename)
@@ -122,7 +122,7 @@
try:
fp = open(cachename, 'w')
except IOError:
- print 'flp: can\'t create cache file', cachename
+ print('flp: can\'t create cache file', cachename)
return # Never mind
fp.write('\0\0\0\0') # Seek back and write MAGIC when done
wrlong(fp, getmtime(filename))
@@ -145,8 +145,8 @@
def freeze(filename):
forms = parse_forms(filename)
altforms = _pack_cache(forms)
- print 'import flp'
- print 'flp._internal_cache[', repr(filename), '] =', altforms
+ print('import flp')
+ print('flp._internal_cache[', repr(filename), '] =', altforms)
#
# Internal: create the data structure to be placed in the cache
@@ -426,7 +426,7 @@
if len(sys.argv) == 2:
forms = parse_forms(sys.argv[1])
t1 = time.time()
- print 'parse time:', 0.001*(t1-t0), 'sec.'
+ print('parse time:', 0.001*(t1-t0), 'sec.')
keys = forms.keys()
keys.sort()
for i in keys:
@@ -434,18 +434,18 @@
elif len(sys.argv) == 3:
form = parse_form(sys.argv[1], sys.argv[2])
t1 = time.time()
- print 'parse time:', round(t1-t0, 3), 'sec.'
+ print('parse time:', round(t1-t0, 3), 'sec.')
_printform(form)
else:
- print 'Usage: test fdfile [form]'
+ print('Usage: test fdfile [form]')
def _printform(form):
f = form[0]
objs = form[1]
- print 'Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects
+ print('Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects)
for i in objs:
- print ' Obj ', i.Name, ' type ', i.Class, i.Type
- print ' Box ', i.Box, ' btype ', i.Boxtype
- print ' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment
- print ' cols ', i.Colors
- print ' cback ', i.Callback, i.Argument
+ print(' Obj ', i.Name, ' type ', i.Class, i.Type)
+ print(' Box ', i.Box, ' btype ', i.Boxtype)
+ print(' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment)
+ print(' cols ', i.Colors)
+ print(' cback ', i.Callback, i.Argument)
Modified: python/branches/p3yk-noslice/Lib/plat-irix5/panel.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-irix5/panel.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-irix5/panel.py Fri Feb 23 18:29:35 2007
@@ -62,18 +62,18 @@
def show_actuator(prefix, a):
for item in a:
if not is_list(item):
- print prefix, item
+ print(prefix, item)
elif item and item[0] == 'al':
- print prefix, 'Subactuator list:'
+ print(prefix, 'Subactuator list:')
for a in item[1:]:
show_actuator(prefix + ' ', a)
elif len(item) == 2:
- print prefix, item[0], '=>', item[1]
+ print(prefix, item[0], '=>', item[1])
elif len(item) == 3 and item[0] == 'prop':
- print prefix, 'Prop', item[1], '=>',
- print item[2]
+ print(prefix, 'Prop', item[1], '=>', end=' ')
+ print(item[2])
else:
- print prefix, '?', item
+ print(prefix, '?', item)
# Neatly display a panel.
@@ -81,18 +81,18 @@
def show_panel(prefix, p):
for item in p:
if not is_list(item):
- print prefix, item
+ print(prefix, item)
elif item and item[0] == 'al':
- print prefix, 'Actuator list:'
+ print(prefix, 'Actuator list:')
for a in item[1:]:
show_actuator(prefix + ' ', a)
elif len(item) == 2:
- print prefix, item[0], '=>', item[1]
+ print(prefix, item[0], '=>', item[1])
elif len(item) == 3 and item[0] == 'prop':
- print prefix, 'Prop', item[1], '=>',
- print item[2]
+ print(prefix, 'Prop', item[1], '=>', end=' ')
+ print(item[2])
else:
- print prefix, '?', item
+ print(prefix, '?', item)
# Exception raised by build_actuator or build_panel.
@@ -123,18 +123,18 @@
# Strange default set by Panel Editor...
ok = 0
else:
- print 'unknown value', value, 'for', name
+ print('unknown value', value, 'for', name)
ok = 0
if ok:
lhs = 'target.' + prefix + name
stmt = lhs + '=' + repr(value)
- if debug: print 'exec', stmt
+ if debug: print('exec', stmt)
try:
exec(stmt + '\n')
except KeyboardInterrupt: # Don't catch this!
raise KeyboardInterrupt
except:
- print 'assign failed:', stmt
+ print('assign failed:', stmt)
# Build a real actuator from an actuator description.
@@ -185,7 +185,7 @@
act.addsubact(super_act)
if name:
stmt = 'panel.' + name + ' = act'
- if debug: print 'exec', stmt
+ if debug: print('exec', stmt)
exec(stmt + '\n')
if is_endgroup(a):
panel.endgroup()
Modified: python/branches/p3yk-noslice/Lib/plat-irix6/FILE.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-irix6/FILE.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-irix6/FILE.py Fri Feb 23 18:29:35 2007
@@ -43,7 +43,7 @@
__NBBY = 8
# Included from string.h
-NULL = 0L
+NULL = 0
NBBY = 8
# Included from sys/cpumask.h
@@ -332,9 +332,9 @@
SV_ONSTACK = 0x0001
SV_INTERRUPT = 0x0002
NUMBSDSIGS = (32)
-def sigmask(sig): return (1L << ((sig)-1))
+def sigmask(sig): return (1 << ((sig)-1))
-def sigmask(sig): return (1L << ((sig)-1))
+def sigmask(sig): return (1 << ((sig)-1))
SIG_ERR = (-1)
SIG_IGN = (1)
@@ -356,7 +356,7 @@
BRK_PSEUDO_OP_MAX = 0x3
BRK_CACHE_SYNC = 0x80
BRK_MULOVF = 1023
-_POSIX_VERSION = 199506L
+_POSIX_VERSION = 199506
_POSIX_VERSION = 199506
_POSIX_VDISABLE = 0
MAX_INPUT = 512
@@ -414,7 +414,7 @@
CPSSHIFT = 12
CPSSHIFT = 11
BPSSHIFT = (BPCSHIFT+CPSSHIFT)
-NULL = 0L
+NULL = 0
CMASK = 022
NODEV = (-1)
NOPAGE = (-1)
@@ -464,7 +464,7 @@
def DELAYBUS(n): return us_delaybus(n)
-TIMEPOKE_NOW = -100L
+TIMEPOKE_NOW = -100
MUTEX_DEFAULT = 0x0
METER_NAMSZ = 16
METER_NO_SEQ = -1
Modified: python/branches/p3yk-noslice/Lib/plat-irix6/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-irix6/IN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-irix6/IN.py Fri Feb 23 18:29:35 2007
@@ -37,7 +37,7 @@
__NBBY = 8
# Included from string.h
-NULL = 0L
+NULL = 0
NBBY = 8
# Included from sys/endian.h
Modified: python/branches/p3yk-noslice/Lib/plat-irix6/WAIT.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-irix6/WAIT.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-irix6/WAIT.py Fri Feb 23 18:29:35 2007
@@ -68,7 +68,7 @@
__NBBY = 8
# Included from string.h
-NULL = 0L
+NULL = 0
NBBY = 8
# Included from sys/procset.h
@@ -286,9 +286,9 @@
SV_ONSTACK = 0x0001
SV_INTERRUPT = 0x0002
NUMBSDSIGS = (32)
-def sigmask(sig): return (1L << ((sig)-1))
+def sigmask(sig): return (1 << ((sig)-1))
-def sigmask(sig): return (1L << ((sig)-1))
+def sigmask(sig): return (1 << ((sig)-1))
SIG_ERR = (-1)
SIG_IGN = (1)
Modified: python/branches/p3yk-noslice/Lib/plat-irix6/cddb.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-irix6/cddb.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-irix6/cddb.py Fri Feb 23 18:29:35 2007
@@ -89,7 +89,7 @@
break
match = reg.match(line)
if not match:
- print 'syntax error in ' + file
+ print('syntax error in ' + file)
continue
name1, name2, value = match.group(1, 2, 3)
if name1 == 'album':
@@ -101,17 +101,17 @@
if not self.toc:
self.toc = value
if self.toc != value:
- print 'toc\'s don\'t match'
+ print('toc\'s don\'t match')
elif name2 == 'notes':
self.notes.append(value)
elif name1[:5] == 'track':
try:
trackno = int(name1[5:])
except ValueError:
- print 'syntax error in ' + file
+ print('syntax error in ' + file)
continue
if trackno > ntracks:
- print 'track number %r in file %s out of range' % (trackno, file)
+ print('track number %r in file %s out of range' % (trackno, file))
continue
if name2 == 'title':
self.track[trackno] = value
Modified: python/branches/p3yk-noslice/Lib/plat-irix6/cdplayer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-irix6/cdplayer.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-irix6/cdplayer.py Fri Feb 23 18:29:35 2007
@@ -51,7 +51,7 @@
line = line[l:]
match = reg.match(line)
if not match:
- print 'syntax error in ~/' + cdplayerrc
+ print('syntax error in ~/' + cdplayerrc)
continue
name, value = match.group(1, 2)
if name == 'title':
Modified: python/branches/p3yk-noslice/Lib/plat-irix6/flp.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-irix6/flp.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-irix6/flp.py Fri Feb 23 18:29:35 2007
@@ -65,7 +65,7 @@
return None
try:
if fp.read(4) != MAGIC:
- print 'flp: bad magic word in cache file', cachename
+ print('flp: bad magic word in cache file', cachename)
return None
cache_mtime = rdlong(fp)
file_mtime = getmtime(filename)
@@ -121,7 +121,7 @@
try:
fp = open(cachename, 'w')
except IOError:
- print 'flp: can\'t create cache file', cachename
+ print('flp: can\'t create cache file', cachename)
return # Never mind
fp.write('\0\0\0\0') # Seek back and write MAGIC when done
wrlong(fp, getmtime(filename))
@@ -144,8 +144,8 @@
def freeze(filename):
forms = parse_forms(filename)
altforms = _pack_cache(forms)
- print 'import flp'
- print 'flp._internal_cache[', repr(filename), '] =', altforms
+ print('import flp')
+ print('flp._internal_cache[', repr(filename), '] =', altforms)
#
# Internal: create the data structure to be placed in the cache
@@ -425,7 +425,7 @@
if len(sys.argv) == 2:
forms = parse_forms(sys.argv[1])
t1 = time.time()
- print 'parse time:', 0.001*(t1-t0), 'sec.'
+ print('parse time:', 0.001*(t1-t0), 'sec.')
keys = forms.keys()
keys.sort()
for i in keys:
@@ -433,18 +433,18 @@
elif len(sys.argv) == 3:
form = parse_form(sys.argv[1], sys.argv[2])
t1 = time.time()
- print 'parse time:', round(t1-t0, 3), 'sec.'
+ print('parse time:', round(t1-t0, 3), 'sec.')
_printform(form)
else:
- print 'Usage: test fdfile [form]'
+ print('Usage: test fdfile [form]')
def _printform(form):
f = form[0]
objs = form[1]
- print 'Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects
+ print('Form ', f.Name, ', size: ', f.Width, f.Height, ' Nobj ', f.Numberofobjects)
for i in objs:
- print ' Obj ', i.Name, ' type ', i.Class, i.Type
- print ' Box ', i.Box, ' btype ', i.Boxtype
- print ' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment
- print ' cols ', i.Colors
- print ' cback ', i.Callback, i.Argument
+ print(' Obj ', i.Name, ' type ', i.Class, i.Type)
+ print(' Box ', i.Box, ' btype ', i.Boxtype)
+ print(' Label ', i.Label, ' size/style/col/align ', i.Size,i.Style, i.Lcol, i.Alignment)
+ print(' cols ', i.Colors)
+ print(' cback ', i.Callback, i.Argument)
Modified: python/branches/p3yk-noslice/Lib/plat-irix6/panel.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-irix6/panel.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-irix6/panel.py Fri Feb 23 18:29:35 2007
@@ -62,18 +62,18 @@
def show_actuator(prefix, a):
for item in a:
if not is_list(item):
- print prefix, item
+ print(prefix, item)
elif item and item[0] == 'al':
- print prefix, 'Subactuator list:'
+ print(prefix, 'Subactuator list:')
for a in item[1:]:
show_actuator(prefix + ' ', a)
elif len(item) == 2:
- print prefix, item[0], '=>', item[1]
+ print(prefix, item[0], '=>', item[1])
elif len(item) == 3 and item[0] == 'prop':
- print prefix, 'Prop', item[1], '=>',
- print item[2]
+ print(prefix, 'Prop', item[1], '=>', end=' ')
+ print(item[2])
else:
- print prefix, '?', item
+ print(prefix, '?', item)
# Neatly display a panel.
@@ -81,18 +81,18 @@
def show_panel(prefix, p):
for item in p:
if not is_list(item):
- print prefix, item
+ print(prefix, item)
elif item and item[0] == 'al':
- print prefix, 'Actuator list:'
+ print(prefix, 'Actuator list:')
for a in item[1:]:
show_actuator(prefix + ' ', a)
elif len(item) == 2:
- print prefix, item[0], '=>', item[1]
+ print(prefix, item[0], '=>', item[1])
elif len(item) == 3 and item[0] == 'prop':
- print prefix, 'Prop', item[1], '=>',
- print item[2]
+ print(prefix, 'Prop', item[1], '=>', end=' ')
+ print(item[2])
else:
- print prefix, '?', item
+ print(prefix, '?', item)
# Exception raised by build_actuator or build_panel.
@@ -123,18 +123,18 @@
# Strange default set by Panel Editor...
ok = 0
else:
- print 'unknown value', value, 'for', name
+ print('unknown value', value, 'for', name)
ok = 0
if ok:
lhs = 'target.' + prefix + name
stmt = lhs + '=' + repr(value)
- if debug: print 'exec', stmt
+ if debug: print('exec', stmt)
try:
exec(stmt + '\n')
except KeyboardInterrupt: # Don't catch this!
raise KeyboardInterrupt
except:
- print 'assign failed:', stmt
+ print('assign failed:', stmt)
# Build a real actuator from an actuator description.
@@ -185,7 +185,7 @@
act.addsubact(super_act)
if name:
stmt = 'panel.' + name + ' = act'
- if debug: print 'exec', stmt
+ if debug: print('exec', stmt)
exec(stmt + '\n')
if is_endgroup(a):
panel.endgroup()
Modified: python/branches/p3yk-noslice/Lib/plat-linux2/DLFCN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-linux2/DLFCN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-linux2/DLFCN.py Fri Feb 23 18:29:35 2007
@@ -7,7 +7,7 @@
__FAVOR_BSD = 1
_ISOC99_SOURCE = 1
_POSIX_SOURCE = 1
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
_XOPEN_SOURCE = 600
_XOPEN_SOURCE_EXTENDED = 1
_LARGEFILE64_SOURCE = 1
@@ -18,7 +18,7 @@
__USE_ISOC99 = 1
_POSIX_SOURCE = 1
_POSIX_C_SOURCE = 2
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
__USE_POSIX = 1
__USE_POSIX2 = 1
__USE_POSIX199309 = 1
@@ -40,7 +40,7 @@
__USE_REENTRANT = 1
__STDC_IEC_559__ = 1
__STDC_IEC_559_COMPLEX__ = 1
-__STDC_ISO_10646__ = 200009L
+__STDC_ISO_10646__ = 200009
__GNU_LIBRARY__ = 6
__GLIBC__ = 2
__GLIBC_MINOR__ = 2
Modified: python/branches/p3yk-noslice/Lib/plat-linux2/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-linux2/IN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-linux2/IN.py Fri Feb 23 18:29:35 2007
@@ -7,7 +7,7 @@
__FAVOR_BSD = 1
_ISOC99_SOURCE = 1
_POSIX_SOURCE = 1
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
_XOPEN_SOURCE = 600
_XOPEN_SOURCE_EXTENDED = 1
_LARGEFILE64_SOURCE = 1
@@ -18,7 +18,7 @@
__USE_ISOC99 = 1
_POSIX_SOURCE = 1
_POSIX_C_SOURCE = 2
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
__USE_POSIX = 1
__USE_POSIX2 = 1
__USE_POSIX199309 = 1
@@ -40,7 +40,7 @@
__USE_REENTRANT = 1
__STDC_IEC_559__ = 1
__STDC_IEC_559_COMPLEX__ = 1
-__STDC_ISO_10646__ = 200009L
+__STDC_ISO_10646__ = 200009
__GNU_LIBRARY__ = 6
__GLIBC__ = 2
__GLIBC_MINOR__ = 2
@@ -78,8 +78,8 @@
# Included from bits/wchar.h
_BITS_WCHAR_H = 1
-__WCHAR_MIN = (-2147483647l - 1l)
-__WCHAR_MAX = (2147483647l)
+__WCHAR_MIN = (-2147483647 - 1)
+__WCHAR_MAX = (2147483647)
# Included from bits/wordsize.h
__WORDSIZE = 32
@@ -114,28 +114,28 @@
UINT_LEAST16_MAX = (65535)
UINT_LEAST64_MAX = (__UINT64_C(18446744073709551615))
INT_FAST8_MIN = (-128)
-INT_FAST16_MIN = (-9223372036854775807L-1)
-INT_FAST32_MIN = (-9223372036854775807L-1)
+INT_FAST16_MIN = (-9223372036854775807-1)
+INT_FAST32_MIN = (-9223372036854775807-1)
INT_FAST16_MIN = (-2147483647-1)
INT_FAST32_MIN = (-2147483647-1)
INT_FAST64_MIN = (-__INT64_C(9223372036854775807)-1)
INT_FAST8_MAX = (127)
-INT_FAST16_MAX = (9223372036854775807L)
-INT_FAST32_MAX = (9223372036854775807L)
+INT_FAST16_MAX = (9223372036854775807)
+INT_FAST32_MAX = (9223372036854775807)
INT_FAST16_MAX = (2147483647)
INT_FAST32_MAX = (2147483647)
INT_FAST64_MAX = (__INT64_C(9223372036854775807))
UINT_FAST8_MAX = (255)
UINT_FAST64_MAX = (__UINT64_C(18446744073709551615))
-INTPTR_MIN = (-9223372036854775807L-1)
-INTPTR_MAX = (9223372036854775807L)
+INTPTR_MIN = (-9223372036854775807-1)
+INTPTR_MAX = (9223372036854775807)
INTPTR_MIN = (-2147483647-1)
INTPTR_MAX = (2147483647)
INTMAX_MIN = (-__INT64_C(9223372036854775807)-1)
INTMAX_MAX = (__INT64_C(9223372036854775807))
UINTMAX_MAX = (__UINT64_C(18446744073709551615))
-PTRDIFF_MIN = (-9223372036854775807L-1)
-PTRDIFF_MAX = (9223372036854775807L)
+PTRDIFF_MIN = (-9223372036854775807-1)
+PTRDIFF_MAX = (9223372036854775807)
PTRDIFF_MIN = (-2147483647-1)
PTRDIFF_MAX = (2147483647)
SIG_ATOMIC_MIN = (-2147483647-1)
@@ -238,9 +238,9 @@
SHRT_MAX = 32767
USHRT_MAX = 65535
INT_MAX = 2147483647
-LONG_MAX = 9223372036854775807L
-LONG_MAX = 2147483647L
-LONG_MIN = (-LONG_MAX - 1L)
+LONG_MAX = 9223372036854775807
+LONG_MAX = 2147483647
+LONG_MIN = (-LONG_MAX - 1)
# Included from bits/posix1_lim.h
_BITS_POSIX1_LIM_H = 1
Modified: python/branches/p3yk-noslice/Lib/plat-linux2/TYPES.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-linux2/TYPES.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-linux2/TYPES.py Fri Feb 23 18:29:35 2007
@@ -7,7 +7,7 @@
__FAVOR_BSD = 1
_ISOC99_SOURCE = 1
_POSIX_SOURCE = 1
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
_XOPEN_SOURCE = 600
_XOPEN_SOURCE_EXTENDED = 1
_LARGEFILE64_SOURCE = 1
@@ -18,7 +18,7 @@
__USE_ISOC99 = 1
_POSIX_SOURCE = 1
_POSIX_C_SOURCE = 2
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
__USE_POSIX = 1
__USE_POSIX2 = 1
__USE_POSIX199309 = 1
@@ -40,7 +40,7 @@
__USE_REENTRANT = 1
__STDC_IEC_559__ = 1
__STDC_IEC_559_COMPLEX__ = 1
-__STDC_ISO_10646__ = 200009L
+__STDC_ISO_10646__ = 200009
__GNU_LIBRARY__ = 6
__GLIBC__ = 2
__GLIBC_MINOR__ = 2
@@ -99,7 +99,7 @@
# Included from bits/time.h
_BITS_TIME_H = 1
-CLOCKS_PER_SEC = 1000000l
+CLOCKS_PER_SEC = 1000000
CLOCK_REALTIME = 0
CLOCK_PROCESS_CPUTIME_ID = 2
CLOCK_THREAD_CPUTIME_ID = 3
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Audio_mac.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Audio_mac.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Audio_mac.py Fri Feb 23 18:29:35 2007
@@ -104,7 +104,7 @@
fn = EasyDialogs.AskFileForOpen(message="Select an AIFF soundfile", typeList=("AIFF",))
if not fn: return
af = aifc.open(fn, 'r')
- print af.getparams()
+ print(af.getparams())
p = Play_Audio_mac()
p.setoutrate(af.getframerate())
p.setsampwidth(af.getsampwidth())
@@ -114,7 +114,7 @@
data = af.readframes(BUFSIZ)
if not data: break
p.writeframes(data)
- print 'wrote', len(data), 'space', p.getfillable()
+ print('wrote', len(data), 'space', p.getfillable())
p.wait()
if __name__ == '__main__':
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/CarbonEvents.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/CarbonEvents.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/CarbonEvents.py Fri Feb 23 18:29:35 2007
@@ -74,8 +74,8 @@
kEventHotKeyReleased = 6
kEventKeyModifierNumLockBit = 16
kEventKeyModifierFnBit = 17
-kEventKeyModifierNumLockMask = 1L << kEventKeyModifierNumLockBit
-kEventKeyModifierFnMask = 1L << kEventKeyModifierFnBit
+kEventKeyModifierNumLockMask = 1 << kEventKeyModifierNumLockBit
+kEventKeyModifierFnMask = 1 << kEventKeyModifierFnBit
kEventAppActivated = 1
kEventAppDeactivated = 2
kEventAppQuit = 3
@@ -221,9 +221,9 @@
kHICommandPrint = FOUR_CHAR_CODE('prnt')
kHICommandPageSetup = FOUR_CHAR_CODE('page')
kHICommandAppHelp = FOUR_CHAR_CODE('ahlp')
-kHICommandFromMenu = (1L << 0)
-kHICommandFromControl = (1L << 1)
-kHICommandFromWindow = (1L << 2)
+kHICommandFromMenu = (1 << 0)
+kHICommandFromControl = (1 << 1)
+kHICommandFromWindow = (1 << 2)
kEventControlInitialize = 1000
kEventControlDispose = 1001
kEventControlGetOptimalBounds = 1003
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Components.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Components.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Components.py Fri Feb 23 18:29:35 2007
@@ -8,8 +8,8 @@
kAnyComponentSubType = 0
kAnyComponentManufacturer = 0
kAnyComponentFlagsMask = 0
-cmpIsMissing = 1L << 29
-cmpWantsRegisterMessage = 1L << 31
+cmpIsMissing = 1 << 29
+cmpWantsRegisterMessage = 1 << 31
kComponentOpenSelect = -1
kComponentCloseSelect = -2
kComponentCanDoSelect = -3
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Controls.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Controls.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Controls.py Fri Feb 23 18:29:35 2007
@@ -18,7 +18,7 @@
controlNotifyClick = FOUR_CHAR_CODE('clik')
controlNotifyFocus = FOUR_CHAR_CODE('focu')
controlNotifyKey = FOUR_CHAR_CODE('key ')
-kControlCanAutoInvalidate = 1L << 0
+kControlCanAutoInvalidate = 1 << 0
staticTextProc = 256
editTextProc = 272
iconProc = 288
@@ -529,7 +529,7 @@
kDataBrowserOrderUndefined = 0
kDataBrowserOrderIncreasing = 1
kDataBrowserOrderDecreasing = 2
-kDataBrowserNoItem = 0L
+kDataBrowserNoItem = 0
kDataBrowserItemNoState = 0
# kDataBrowserItemAnyState = (unsigned long)(-1)
kDataBrowserItemIsSelected = 1 << 0
@@ -569,18 +569,18 @@
kDataBrowserTargetChanged = 15
kDataBrowserUserStateChanged = 13
kDataBrowserSelectionSetChanged = 14
-kDataBrowserItemNoProperty = 0L
-kDataBrowserItemIsActiveProperty = 1L
-kDataBrowserItemIsSelectableProperty = 2L
-kDataBrowserItemIsEditableProperty = 3L
-kDataBrowserItemIsContainerProperty = 4L
-kDataBrowserContainerIsOpenableProperty = 5L
-kDataBrowserContainerIsClosableProperty = 6L
-kDataBrowserContainerIsSortableProperty = 7L
-kDataBrowserItemSelfIdentityProperty = 8L
-kDataBrowserContainerAliasIDProperty = 9L
-kDataBrowserColumnViewPreviewProperty = 10L
-kDataBrowserItemParentContainerProperty = 11L
+kDataBrowserItemNoProperty = 0
+kDataBrowserItemIsActiveProperty = 1
+kDataBrowserItemIsSelectableProperty = 2
+kDataBrowserItemIsEditableProperty = 3
+kDataBrowserItemIsContainerProperty = 4
+kDataBrowserContainerIsOpenableProperty = 5
+kDataBrowserContainerIsClosableProperty = 6
+kDataBrowserContainerIsSortableProperty = 7
+kDataBrowserItemSelfIdentityProperty = 8
+kDataBrowserContainerAliasIDProperty = 9
+kDataBrowserColumnViewPreviewProperty = 10
+kDataBrowserItemParentContainerProperty = 11
kDataBrowserCustomType = 0x3F3F3F3F
kDataBrowserIconType = FOUR_CHAR_CODE('icnr')
kDataBrowserTextType = FOUR_CHAR_CODE('text')
@@ -591,7 +591,7 @@
kDataBrowserRelevanceRankType = FOUR_CHAR_CODE('rank')
kDataBrowserPopupMenuType = FOUR_CHAR_CODE('menu')
kDataBrowserIconAndTextType = FOUR_CHAR_CODE('ticn')
-kDataBrowserPropertyEnclosingPart = 0L
+kDataBrowserPropertyEnclosingPart = 0
kDataBrowserPropertyContentPart = FOUR_CHAR_CODE('----')
kDataBrowserPropertyDisclosurePart = FOUR_CHAR_CODE('disc')
kDataBrowserPropertyTextPart = kDataBrowserTextType
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Dragconst.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Dragconst.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Dragconst.py Fri Feb 23 18:29:35 2007
@@ -14,16 +14,16 @@
flavorSenderTranslated = (1 << 1)
flavorNotSaved = (1 << 2)
flavorSystemTranslated = (1 << 8)
-kDragHasLeftSenderWindow = (1L << 0)
-kDragInsideSenderApplication = (1L << 1)
-kDragInsideSenderWindow = (1L << 2)
+kDragHasLeftSenderWindow = (1 << 0)
+kDragInsideSenderApplication = (1 << 1)
+kDragInsideSenderWindow = (1 << 2)
kDragBehaviorNone = 0
-kDragBehaviorZoomBackAnimation = (1L << 0)
-kDragRegionAndImage = (1L << 4)
-kDragStandardTranslucency = 0L
-kDragDarkTranslucency = 1L
-kDragDarkerTranslucency = 2L
-kDragOpaqueTranslucency = 3L
+kDragBehaviorZoomBackAnimation = (1 << 0)
+kDragRegionAndImage = (1 << 4)
+kDragStandardTranslucency = 0
+kDragDarkTranslucency = 1
+kDragDarkerTranslucency = 2
+kDragOpaqueTranslucency = 3
kDragRegionBegin = 1
kDragRegionDraw = 2
kDragRegionHide = 3
@@ -56,13 +56,13 @@
kDragTrackingInWindow = 3
kDragTrackingLeaveWindow = 4
kDragTrackingLeaveHandler = 5
-kDragActionNothing = 0L
-kDragActionCopy = 1L
-kDragActionAlias = (1L << 1)
-kDragActionGeneric = (1L << 2)
-kDragActionPrivate = (1L << 3)
-kDragActionMove = (1L << 4)
-kDragActionDelete = (1L << 5)
+kDragActionNothing = 0
+kDragActionCopy = 1
+kDragActionAlias = (1 << 1)
+kDragActionGeneric = (1 << 2)
+kDragActionPrivate = (1 << 3)
+kDragActionMove = (1 << 4)
+kDragActionDelete = (1 << 5)
# kDragActionAll = (long)0xFFFFFFFF
dragHasLeftSenderWindow = kDragHasLeftSenderWindow
dragInsideSenderApplication = kDragInsideSenderApplication
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Folders.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Folders.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Folders.py Fri Feb 23 18:29:35 2007
@@ -3,7 +3,7 @@
def FOUR_CHAR_CODE(x): return x
true = True
false = False
-kOnSystemDisk = -32768L
+kOnSystemDisk = -32768
kOnAppropriateDisk = -32767
kSystemDomain = -32766
kLocalDomain = -32765
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Fonts.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Fonts.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Fonts.py Fri Feb 23 18:29:35 2007
@@ -17,15 +17,15 @@
checkMark = 18
diamondMark = 19
appleMark = 20
-propFont = 36864L
-prpFntH = 36865L
-prpFntW = 36866L
-prpFntHW = 36867L
-fixedFont = 45056L
-fxdFntH = 45057L
-fxdFntW = 45058L
-fxdFntHW = 45059L
-fontWid = 44208L
+propFont = 36864
+prpFntH = 36865
+prpFntW = 36866
+prpFntHW = 36867
+fixedFont = 45056
+fxdFntH = 45057
+fxdFntW = 45058
+fxdFntHW = 45059
+fontWid = 44208
kFMUseGlobalScopeOption = 0x00000001
kFontIDNewYork = 2
kFontIDGeneva = 3
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Icons.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Icons.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Icons.py Fri Feb 23 18:29:35 2007
@@ -375,7 +375,7 @@
kRightContainerArrowIcon = FOUR_CHAR_CODE('rcar')
kIconServicesNormalUsageFlag = 0
kIconServicesCatalogInfoMask = (kFSCatInfoNodeID | kFSCatInfoParentDirID | kFSCatInfoVolume | kFSCatInfoNodeFlags | kFSCatInfoFinderInfo | kFSCatInfoFinderXInfo | kFSCatInfoUserAccess)
-kPlotIconRefNormalFlags = 0L
+kPlotIconRefNormalFlags = 0
kPlotIconRefNoImage = (1 << 1)
kPlotIconRefNoMask = (1 << 2)
kIconFamilyType = FOUR_CHAR_CODE('icns')
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/MacTextEditor.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/MacTextEditor.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/MacTextEditor.py Fri Feb 23 18:29:35 2007
@@ -17,18 +17,18 @@
normal = 0
kTXNWillDefaultToATSUIBit = 0
kTXNWillDefaultToCarbonEventBit = 1
-kTXNWillDefaultToATSUIMask = 1L << kTXNWillDefaultToATSUIBit
-kTXNWillDefaultToCarbonEventMask = 1L << kTXNWillDefaultToCarbonEventBit
+kTXNWillDefaultToATSUIMask = 1 << kTXNWillDefaultToATSUIBit
+kTXNWillDefaultToCarbonEventMask = 1 << kTXNWillDefaultToCarbonEventBit
kTXNWantMoviesBit = 0
kTXNWantSoundBit = 1
kTXNWantGraphicsBit = 2
kTXNAlwaysUseQuickDrawTextBit = 3
kTXNUseTemporaryMemoryBit = 4
-kTXNWantMoviesMask = 1L << kTXNWantMoviesBit
-kTXNWantSoundMask = 1L << kTXNWantSoundBit
-kTXNWantGraphicsMask = 1L << kTXNWantGraphicsBit
-kTXNAlwaysUseQuickDrawTextMask = 1L << kTXNAlwaysUseQuickDrawTextBit
-kTXNUseTemporaryMemoryMask = 1L << kTXNUseTemporaryMemoryBit
+kTXNWantMoviesMask = 1 << kTXNWantMoviesBit
+kTXNWantSoundMask = 1 << kTXNWantSoundBit
+kTXNWantGraphicsMask = 1 << kTXNWantGraphicsBit
+kTXNAlwaysUseQuickDrawTextMask = 1 << kTXNAlwaysUseQuickDrawTextBit
+kTXNUseTemporaryMemoryMask = 1 << kTXNUseTemporaryMemoryBit
kTXNDrawGrowIconBit = 0
kTXNShowWindowBit = 1
kTXNWantHScrollBarBit = 2
@@ -46,23 +46,23 @@
kTXNSingleLineOnlyBit = 14
kTXNDisableDragAndDropBit = 15
kTXNUseQDforImagingBit = 16
-kTXNDrawGrowIconMask = 1L << kTXNDrawGrowIconBit
-kTXNShowWindowMask = 1L << kTXNShowWindowBit
-kTXNWantHScrollBarMask = 1L << kTXNWantHScrollBarBit
-kTXNWantVScrollBarMask = 1L << kTXNWantVScrollBarBit
-kTXNNoTSMEverMask = 1L << kTXNNoTSMEverBit
-kTXNReadOnlyMask = 1L << kTXNReadOnlyBit
-kTXNNoKeyboardSyncMask = 1L << kTXNNoKeyboardSyncBit
-kTXNNoSelectionMask = 1L << kTXNNoSelectionBit
-kTXNSaveStylesAsSTYLResourceMask = 1L << kTXNSaveStylesAsSTYLResourceBit
-kOutputTextInUnicodeEncodingMask = 1L << kOutputTextInUnicodeEncodingBit
-kTXNDoNotInstallDragProcsMask = 1L << kTXNDoNotInstallDragProcsBit
-kTXNAlwaysWrapAtViewEdgeMask = 1L << kTXNAlwaysWrapAtViewEdgeBit
-kTXNDontDrawCaretWhenInactiveMask = 1L << kTXNDontDrawCaretWhenInactiveBit
-kTXNDontDrawSelectionWhenInactiveMask = 1L << kTXNDontDrawSelectionWhenInactiveBit
-kTXNSingleLineOnlyMask = 1L << kTXNSingleLineOnlyBit
-kTXNDisableDragAndDropMask = 1L << kTXNDisableDragAndDropBit
-kTXNUseQDforImagingMask = 1L << kTXNUseQDforImagingBit
+kTXNDrawGrowIconMask = 1 << kTXNDrawGrowIconBit
+kTXNShowWindowMask = 1 << kTXNShowWindowBit
+kTXNWantHScrollBarMask = 1 << kTXNWantHScrollBarBit
+kTXNWantVScrollBarMask = 1 << kTXNWantVScrollBarBit
+kTXNNoTSMEverMask = 1 << kTXNNoTSMEverBit
+kTXNReadOnlyMask = 1 << kTXNReadOnlyBit
+kTXNNoKeyboardSyncMask = 1 << kTXNNoKeyboardSyncBit
+kTXNNoSelectionMask = 1 << kTXNNoSelectionBit
+kTXNSaveStylesAsSTYLResourceMask = 1 << kTXNSaveStylesAsSTYLResourceBit
+kOutputTextInUnicodeEncodingMask = 1 << kOutputTextInUnicodeEncodingBit
+kTXNDoNotInstallDragProcsMask = 1 << kTXNDoNotInstallDragProcsBit
+kTXNAlwaysWrapAtViewEdgeMask = 1 << kTXNAlwaysWrapAtViewEdgeBit
+kTXNDontDrawCaretWhenInactiveMask = 1 << kTXNDontDrawCaretWhenInactiveBit
+kTXNDontDrawSelectionWhenInactiveMask = 1 << kTXNDontDrawSelectionWhenInactiveBit
+kTXNSingleLineOnlyMask = 1 << kTXNSingleLineOnlyBit
+kTXNDisableDragAndDropMask = 1 << kTXNDisableDragAndDropBit
+kTXNUseQDforImagingMask = 1 << kTXNUseQDforImagingBit
kTXNSetFlushnessBit = 0
kTXNSetJustificationBit = 1
kTXNUseFontFallBackBit = 2
@@ -73,29 +73,29 @@
kTXNUseCGContextRefBit = 7
kTXNImageWithQDBit = 8
kTXNDontWrapTextBit = 9
-kTXNSetFlushnessMask = 1L << kTXNSetFlushnessBit
-kTXNSetJustificationMask = 1L << kTXNSetJustificationBit
-kTXNUseFontFallBackMask = 1L << kTXNUseFontFallBackBit
-kTXNRotateTextMask = 1L << kTXNRotateTextBit
-kTXNUseVerticalTextMask = 1L << kTXNUseVerticalTextBit
-kTXNDontUpdateBoxRectMask = 1L << kTXNDontUpdateBoxRectBit
-kTXNDontDrawTextMask = 1L << kTXNDontDrawTextBit
-kTXNUseCGContextRefMask = 1L << kTXNUseCGContextRefBit
-kTXNImageWithQDMask = 1L << kTXNImageWithQDBit
-kTXNDontWrapTextMask = 1L << kTXNDontWrapTextBit
+kTXNSetFlushnessMask = 1 << kTXNSetFlushnessBit
+kTXNSetJustificationMask = 1 << kTXNSetJustificationBit
+kTXNUseFontFallBackMask = 1 << kTXNUseFontFallBackBit
+kTXNRotateTextMask = 1 << kTXNRotateTextBit
+kTXNUseVerticalTextMask = 1 << kTXNUseVerticalTextBit
+kTXNDontUpdateBoxRectMask = 1 << kTXNDontUpdateBoxRectBit
+kTXNDontDrawTextMask = 1 << kTXNDontDrawTextBit
+kTXNUseCGContextRefMask = 1 << kTXNUseCGContextRefBit
+kTXNImageWithQDMask = 1 << kTXNImageWithQDBit
+kTXNDontWrapTextMask = 1 << kTXNDontWrapTextBit
kTXNFontContinuousBit = 0
kTXNSizeContinuousBit = 1
kTXNStyleContinuousBit = 2
kTXNColorContinuousBit = 3
-kTXNFontContinuousMask = 1L << kTXNFontContinuousBit
-kTXNSizeContinuousMask = 1L << kTXNSizeContinuousBit
-kTXNStyleContinuousMask = 1L << kTXNStyleContinuousBit
-kTXNColorContinuousMask = 1L << kTXNColorContinuousBit
+kTXNFontContinuousMask = 1 << kTXNFontContinuousBit
+kTXNSizeContinuousMask = 1 << kTXNSizeContinuousBit
+kTXNStyleContinuousMask = 1 << kTXNStyleContinuousBit
+kTXNColorContinuousMask = 1 << kTXNColorContinuousBit
kTXNIgnoreCaseBit = 0
kTXNEntireWordBit = 1
kTXNUseEncodingWordRulesBit = 31
-kTXNIgnoreCaseMask = 1L << kTXNIgnoreCaseBit
-kTXNEntireWordMask = 1L << kTXNEntireWordBit
+kTXNIgnoreCaseMask = 1 << kTXNIgnoreCaseBit
+kTXNEntireWordMask = 1 << kTXNEntireWordBit
# kTXNUseEncodingWordRulesMask = (unsigned long)(1L << kTXNUseEncodingWordRulesBit)
kTXNTextensionFile = FOUR_CHAR_CODE('txtn')
kTXNTextFile = FOUR_CHAR_CODE('TEXT')
@@ -216,8 +216,8 @@
kTXNBackgroundTypeRGB = 1
kTXNTextInputCountBit = 0
kTXNRunCountBit = 1
-kTXNTextInputCountMask = 1L << kTXNTextInputCountBit
-kTXNRunCountMask = 1L << kTXNRunCountBit
+kTXNTextInputCountMask = 1 << kTXNTextInputCountBit
+kTXNRunCountMask = 1 << kTXNRunCountBit
kTXNAllCountMask = kTXNTextInputCountMask | kTXNRunCountMask
kTXNNoAppleEventHandlersBit = 0
kTXNRestartAppleEventHandlersBit = 1
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/OSAconst.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/OSAconst.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/OSAconst.py Fri Feb 23 18:29:35 2007
@@ -19,7 +19,7 @@
keyOSADialectCode = FOUR_CHAR_CODE('dcod')
keyOSADialectLangCode = FOUR_CHAR_CODE('dlcd')
keyOSADialectScriptCode = FOUR_CHAR_CODE('dscd')
-kOSANullScript = 0L
+kOSANullScript = 0
kOSANullMode = 0
kOSAModeNull = 0
kOSASupportsCompiling = 0x0002
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QDOffscreen.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QDOffscreen.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QDOffscreen.py Fri Feb 23 18:29:35 2007
@@ -18,30 +18,30 @@
stretchPixBit = 29
ditherPixBit = 30
gwFlagErrBit = 31
-pixPurge = 1L << pixPurgeBit
-noNewDevice = 1L << noNewDeviceBit
-useTempMem = 1L << useTempMemBit
-keepLocal = 1L << keepLocalBit
-useDistantHdwrMem = 1L << useDistantHdwrMemBit
-useLocalHdwrMem = 1L << useLocalHdwrMemBit
-pixelsPurgeable = 1L << pixelsPurgeableBit
-pixelsLocked = 1L << pixelsLockedBit
-kAllocDirectDrawSurface = 1L << 14
-mapPix = 1L << mapPixBit
-newDepth = 1L << newDepthBit
-alignPix = 1L << alignPixBit
-newRowBytes = 1L << newRowBytesBit
-reallocPix = 1L << reallocPixBit
-clipPix = 1L << clipPixBit
-stretchPix = 1L << stretchPixBit
-ditherPix = 1L << ditherPixBit
-gwFlagErr = 1L << gwFlagErrBit
-deviceIsIndirect = (1L << 0)
-deviceNeedsLock = (1L << 1)
-deviceIsStatic = (1L << 2)
-deviceIsExternalBuffer = (1L << 3)
-deviceIsDDSurface = (1L << 4)
-deviceIsDCISurface = (1L << 5)
-deviceIsGDISurface = (1L << 6)
-deviceIsAScreen = (1L << 7)
-deviceIsOverlaySurface = (1L << 8)
+pixPurge = 1 << pixPurgeBit
+noNewDevice = 1 << noNewDeviceBit
+useTempMem = 1 << useTempMemBit
+keepLocal = 1 << keepLocalBit
+useDistantHdwrMem = 1 << useDistantHdwrMemBit
+useLocalHdwrMem = 1 << useLocalHdwrMemBit
+pixelsPurgeable = 1 << pixelsPurgeableBit
+pixelsLocked = 1 << pixelsLockedBit
+kAllocDirectDrawSurface = 1 << 14
+mapPix = 1 << mapPixBit
+newDepth = 1 << newDepthBit
+alignPix = 1 << alignPixBit
+newRowBytes = 1 << newRowBytesBit
+reallocPix = 1 << reallocPixBit
+clipPix = 1 << clipPixBit
+stretchPix = 1 << stretchPixBit
+ditherPix = 1 << ditherPixBit
+gwFlagErr = 1 << gwFlagErrBit
+deviceIsIndirect = (1 << 0)
+deviceNeedsLock = (1 << 1)
+deviceIsStatic = (1 << 2)
+deviceIsExternalBuffer = (1 << 3)
+deviceIsDDSurface = (1 << 4)
+deviceIsDCISurface = (1 << 5)
+deviceIsGDISurface = (1 << 6)
+deviceIsAScreen = (1 << 7)
+deviceIsOverlaySurface = (1 << 8)
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickDraw.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickDraw.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickDraw.py Fri Feb 23 18:29:35 2007
@@ -160,11 +160,11 @@
kXFerConvertPixelToRGB32 = 0x00000002
kCursorComponentsVersion = 0x00010001
kCursorComponentType = FOUR_CHAR_CODE('curs')
-cursorDoesAnimate = 1L << 0
-cursorDoesHardware = 1L << 1
-cursorDoesUnreadableScreenBits = 1L << 2
-kRenderCursorInHardware = 1L << 0
-kRenderCursorInSoftware = 1L << 1
+cursorDoesAnimate = 1 << 0
+cursorDoesHardware = 1 << 1
+cursorDoesUnreadableScreenBits = 1 << 2
+kRenderCursorInHardware = 1 << 0
+kRenderCursorInSoftware = 1 << 1
kCursorComponentInit = 0x0001
kCursorComponentGetInfo = 0x0002
kCursorComponentSetOutputMode = 0x0003
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickTime.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickTime.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/QuickTime.py Fri Feb 23 18:29:35 2007
@@ -94,14 +94,14 @@
kUserDataTextWriter = FOUR_CHAR_CODE('\xa9wrt')
kUserDataTextURLLink = FOUR_CHAR_CODE('\xa9url')
kUserDataTextEditDate1 = FOUR_CHAR_CODE('\xa9ed1')
-kUserDataUnicodeBit = 1L << 7
+kUserDataUnicodeBit = 1 << 7
DoTheRightThing = 0
kQTNetworkStatusNoNetwork = -2
kQTNetworkStatusUncertain = -1
kQTNetworkStatusNotConnected = 0
kQTNetworkStatusConnected = 1
-kMusicFlagDontPlay2Soft = 1L << 0
-kMusicFlagDontSlaveToMovie = 1L << 1
+kMusicFlagDontPlay2Soft = 1 << 0
+kMusicFlagDontSlaveToMovie = 1 << 1
dfDontDisplay = 1 << 0
dfDontAutoScale = 1 << 1
dfClipToTextBox = 1 << 2
@@ -119,10 +119,10 @@
dfKeyedText = 1 << 14
dfInverseHilite = 1 << 15
dfTextColorHilite = 1 << 16
-searchTextDontGoToFoundTime = 1L << 16
-searchTextDontHiliteFoundText = 1L << 17
-searchTextOneTrackOnly = 1L << 18
-searchTextEnabledTracksOnly = 1L << 19
+searchTextDontGoToFoundTime = 1 << 16
+searchTextDontHiliteFoundText = 1 << 17
+searchTextOneTrackOnly = 1 << 18
+searchTextEnabledTracksOnly = 1 << 19
kTextTextHandle = 1
kTextTextPtr = 2
kTextTEStyle = 3
@@ -167,7 +167,7 @@
mediaQualityNormal = 0x0040
mediaQualityBetter = 0x0080
mediaQualityBest = 0x00C0
-kQTEventPayloadIsQTList = 1L << 0
+kQTEventPayloadIsQTList = 1 << 0
kActionMovieSetVolume = 1024
kActionMovieSetRate = 1025
kActionMovieSetLoopingFlags = 1026
@@ -509,19 +509,19 @@
kQTEventRequestToModifyMovie = FOUR_CHAR_CODE('reqm')
kQTEventListReceived = FOUR_CHAR_CODE('list')
kQTEventKeyUp = FOUR_CHAR_CODE('keyU')
-kActionFlagActionIsDelta = 1L << 1
-kActionFlagParameterWrapsAround = 1L << 2
-kActionFlagActionIsToggle = 1L << 3
-kStatusStringIsURLLink = 1L << 1
-kStatusStringIsStreamingStatus = 1L << 2
-kStatusHasCodeNumber = 1L << 3
-kStatusIsError = 1L << 4
-kScriptIsUnknownType = 1L << 0
-kScriptIsJavaScript = 1L << 1
-kScriptIsLingoEvent = 1L << 2
-kScriptIsVBEvent = 1L << 3
-kScriptIsProjectorCommand = 1L << 4
-kScriptIsAppleScript = 1L << 5
+kActionFlagActionIsDelta = 1 << 1
+kActionFlagParameterWrapsAround = 1 << 2
+kActionFlagActionIsToggle = 1 << 3
+kStatusStringIsURLLink = 1 << 1
+kStatusStringIsStreamingStatus = 1 << 2
+kStatusHasCodeNumber = 1 << 3
+kStatusIsError = 1 << 4
+kScriptIsUnknownType = 1 << 0
+kScriptIsJavaScript = 1 << 1
+kScriptIsLingoEvent = 1 << 2
+kScriptIsVBEvent = 1 << 3
+kScriptIsProjectorCommand = 1 << 4
+kScriptIsAppleScript = 1 << 5
kQTRegistrationDialogTimeOutFlag = 1 << 0
kQTRegistrationDialogShowDialog = 1 << 1
kQTRegistrationDialogForceDialog = 1 << 2
@@ -605,16 +605,16 @@
nextTimeStep = 1 << 4
nextTimeEdgeOK = 1 << 14
nextTimeIgnoreActiveSegment = 1 << 15
-createMovieFileDeleteCurFile = 1L << 31
-createMovieFileDontCreateMovie = 1L << 30
-createMovieFileDontOpenFile = 1L << 29
-createMovieFileDontCreateResFile = 1L << 28
-flattenAddMovieToDataFork = 1L << 0
-flattenActiveTracksOnly = 1L << 2
-flattenDontInterleaveFlatten = 1L << 3
-flattenFSSpecPtrIsDataRefRecordPtr = 1L << 4
-flattenCompressMovieResource = 1L << 5
-flattenForceMovieResourceBeforeMovieData = 1L << 6
+createMovieFileDeleteCurFile = 1 << 31
+createMovieFileDontCreateMovie = 1 << 30
+createMovieFileDontOpenFile = 1 << 29
+createMovieFileDontCreateResFile = 1 << 28
+flattenAddMovieToDataFork = 1 << 0
+flattenActiveTracksOnly = 1 << 2
+flattenDontInterleaveFlatten = 1 << 3
+flattenFSSpecPtrIsDataRefRecordPtr = 1 << 4
+flattenCompressMovieResource = 1 << 5
+flattenForceMovieResourceBeforeMovieData = 1 << 6
movieInDataForkResID = -1
mcTopLeftMovie = 1 << 0
mcScaleMovieToFit = 1 << 1
@@ -645,17 +645,17 @@
hintsSingleField = 1 << 20
hintsNoRenderingTimeOut = 1 << 21
hintsFlushVideoInsteadOfDirtying = 1 << 22
-hintsEnableSubPixelPositioning = 1L << 23
+hintsEnableSubPixelPositioning = 1 << 23
mediaHandlerFlagBaseClient = 1
movieTrackMediaType = 1 << 0
movieTrackCharacteristic = 1 << 1
movieTrackEnabledOnly = 1 << 2
-kMovieControlOptionHideController = (1L << 0)
-kMovieControlOptionLocateTopLeft = (1L << 1)
-kMovieControlOptionEnableEditing = (1L << 2)
-kMovieControlOptionHandleEditingHI = (1L << 3)
-kMovieControlOptionSetKeysEnabled = (1L << 4)
-kMovieControlOptionManuallyIdled = (1L << 5)
+kMovieControlOptionHideController = (1 << 0)
+kMovieControlOptionLocateTopLeft = (1 << 1)
+kMovieControlOptionEnableEditing = (1 << 2)
+kMovieControlOptionHandleEditingHI = (1 << 3)
+kMovieControlOptionSetKeysEnabled = (1 << 4)
+kMovieControlOptionManuallyIdled = (1 << 5)
kMovieControlDataMovieController = FOUR_CHAR_CODE('mc ')
kMovieControlDataMovie = FOUR_CHAR_CODE('moov')
kMovieControlDataManualIdling = FOUR_CHAR_CODE('manu')
@@ -663,33 +663,33 @@
movieDrawingCallAlways = 1
kQTCloneShareSamples = 1 << 0
kQTCloneDontCopyEdits = 1 << 1
-kGetMovieImporterValidateToFind = 1L << 0
-kGetMovieImporterAllowNewFile = 1L << 1
-kGetMovieImporterDontConsiderGraphicsImporters = 1L << 2
-kGetMovieImporterDontConsiderFileOnlyImporters = 1L << 6
-kGetMovieImporterAutoImportOnly = 1L << 10
+kGetMovieImporterValidateToFind = 1 << 0
+kGetMovieImporterAllowNewFile = 1 << 1
+kGetMovieImporterDontConsiderGraphicsImporters = 1 << 2
+kGetMovieImporterDontConsiderFileOnlyImporters = 1 << 6
+kGetMovieImporterAutoImportOnly = 1 << 10
kQTGetMIMETypeInfoIsQuickTimeMovieType = FOUR_CHAR_CODE('moov')
kQTGetMIMETypeInfoIsUnhelpfulType = FOUR_CHAR_CODE('dumb')
kQTCopyUserDataReplace = FOUR_CHAR_CODE('rplc')
kQTCopyUserDataMerge = FOUR_CHAR_CODE('merg')
-kMovieLoadStateError = -1L
+kMovieLoadStateError = -1
kMovieLoadStateLoading = 1000
kMovieLoadStateLoaded = 2000
kMovieLoadStatePlayable = 10000
kMovieLoadStatePlaythroughOK = 20000
-kMovieLoadStateComplete = 100000L
-kQTDontUseDataToFindImporter = 1L << 0
-kQTDontLookForMovieImporterIfGraphicsImporterFound = 1L << 1
-kQTAllowOpeningStillImagesAsMovies = 1L << 2
-kQTAllowImportersThatWouldCreateNewFile = 1L << 3
-kQTAllowAggressiveImporters = 1L << 4
-preloadAlways = 1L << 0
-preloadOnlyIfEnabled = 1L << 1
-fullScreenHideCursor = 1L << 0
-fullScreenAllowEvents = 1L << 1
-fullScreenDontChangeMenuBar = 1L << 2
-fullScreenPreflightSize = 1L << 3
-movieExecuteWiredActionDontExecute = 1L << 0
+kMovieLoadStateComplete = 100000
+kQTDontUseDataToFindImporter = 1 << 0
+kQTDontLookForMovieImporterIfGraphicsImporterFound = 1 << 1
+kQTAllowOpeningStillImagesAsMovies = 1 << 2
+kQTAllowImportersThatWouldCreateNewFile = 1 << 3
+kQTAllowAggressiveImporters = 1 << 4
+preloadAlways = 1 << 0
+preloadOnlyIfEnabled = 1 << 1
+fullScreenHideCursor = 1 << 0
+fullScreenAllowEvents = 1 << 1
+fullScreenDontChangeMenuBar = 1 << 2
+fullScreenPreflightSize = 1 << 3
+movieExecuteWiredActionDontExecute = 1 << 0
kRefConNavigationNext = 0
kRefConNavigationPrevious = 1
kRefConPropertyCanHaveFocus = 1
@@ -728,19 +728,19 @@
kSpriteHitTestTreatAllSpritesAsHitTestableMode = 1
kSpriteHitTestTreatAllSpritesAsNotHitTestableMode = 2
kNoQTIdleEvents = -1
-kGetSpriteWorldInvalidRegionAndLeaveIntact = -1L
-kGetSpriteWorldInvalidRegionAndThenSetEmpty = -2L
-kOnlyDrawToSpriteWorld = 1L << 0
-kSpriteWorldPreflight = 1L << 1
-kSpriteWorldDidDraw = 1L << 0
-kSpriteWorldNeedsToDraw = 1L << 1
-kKeyFrameAndSingleOverride = 1L << 1
-kKeyFrameAndAllOverrides = 1L << 2
-kScaleSpritesToScaleWorld = 1L << 1
-kSpriteWorldHighQuality = 1L << 2
-kSpriteWorldDontAutoInvalidate = 1L << 3
-kSpriteWorldInvisible = 1L << 4
-kSpriteWorldDirtyInsteadOfFlush = 1L << 5
+kGetSpriteWorldInvalidRegionAndLeaveIntact = -1
+kGetSpriteWorldInvalidRegionAndThenSetEmpty = -2
+kOnlyDrawToSpriteWorld = 1 << 0
+kSpriteWorldPreflight = 1 << 1
+kSpriteWorldDidDraw = 1 << 0
+kSpriteWorldNeedsToDraw = 1 << 1
+kKeyFrameAndSingleOverride = 1 << 1
+kKeyFrameAndAllOverrides = 1 << 2
+kScaleSpritesToScaleWorld = 1 << 1
+kSpriteWorldHighQuality = 1 << 2
+kSpriteWorldDontAutoInvalidate = 1 << 3
+kSpriteWorldInvisible = 1 << 4
+kSpriteWorldDirtyInsteadOfFlush = 1 << 5
kParentAtomIsContainer = 0
kTweenRecordNoFlags = 0
kTweenRecordIsAtInterruptTime = 0x00000001
@@ -796,19 +796,19 @@
pdOptionsHidePreview = 0x00000010
effectIsRealtime = 0
kAccessKeyAtomType = FOUR_CHAR_CODE('acky')
-kAccessKeySystemFlag = 1L << 0
+kAccessKeySystemFlag = 1 << 0
ConnectionSpeedPrefsType = FOUR_CHAR_CODE('cspd')
BandwidthManagementPrefsType = FOUR_CHAR_CODE('bwmg')
kQTIdlePriority = 10
kQTNonRealTimePriority = 20
kQTRealTimeSharedPriority = 25
kQTRealTimePriority = 30
-kQTBandwidthNotifyNeedToStop = 1L << 0
-kQTBandwidthNotifyGoodToGo = 1L << 1
-kQTBandwidthChangeRequest = 1L << 2
-kQTBandwidthQueueRequest = 1L << 3
-kQTBandwidthScheduledRequest = 1L << 4
-kQTBandwidthVoluntaryRelease = 1L << 5
+kQTBandwidthNotifyNeedToStop = 1 << 0
+kQTBandwidthNotifyGoodToGo = 1 << 1
+kQTBandwidthChangeRequest = 1 << 2
+kQTBandwidthQueueRequest = 1 << 3
+kQTBandwidthScheduledRequest = 1 << 4
+kQTBandwidthVoluntaryRelease = 1 << 5
kITextRemoveEverythingBut = 0 << 1
kITextRemoveLeaveSuggestedAlternate = 1 << 1
kITextAtomType = FOUR_CHAR_CODE('itxt')
@@ -908,20 +908,20 @@
kNameAtom = FOUR_CHAR_CODE('name')
kInitialRotationAtom = FOUR_CHAR_CODE('inro')
kNonLinearTweenHeader = FOUR_CHAR_CODE('nlth')
-kTweenReturnDelta = 1L << 0
+kTweenReturnDelta = 1 << 0
kQTRestrictionClassSave = FOUR_CHAR_CODE('save')
-kQTRestrictionSaveDontAddMovieResource = (1L << 0)
-kQTRestrictionSaveDontFlatten = (1L << 1)
-kQTRestrictionSaveDontExport = (1L << 2)
-kQTRestrictionSaveDontExtract = (1L << 3)
+kQTRestrictionSaveDontAddMovieResource = (1 << 0)
+kQTRestrictionSaveDontFlatten = (1 << 1)
+kQTRestrictionSaveDontExport = (1 << 2)
+kQTRestrictionSaveDontExtract = (1 << 3)
kQTRestrictionClassEdit = FOUR_CHAR_CODE('edit')
-kQTRestrictionEditDontCopy = (1L << 0)
-kQTRestrictionEditDontCut = (1L << 1)
-kQTRestrictionEditDontPaste = (1L << 2)
-kQTRestrictionEditDontClear = (1L << 3)
-kQTRestrictionEditDontModify = (1L << 4)
-kQTRestrictionEditDontExtract = (1L << 5)
-videoFlagDontLeanAhead = 1L << 0
+kQTRestrictionEditDontCopy = (1 << 0)
+kQTRestrictionEditDontCut = (1 << 1)
+kQTRestrictionEditDontPaste = (1 << 2)
+kQTRestrictionEditDontClear = (1 << 3)
+kQTRestrictionEditDontModify = (1 << 4)
+kQTRestrictionEditDontExtract = (1 << 5)
+videoFlagDontLeanAhead = 1 << 0
txtProcDefaultDisplay = 0
txtProcDontDisplay = 1
txtProcDoDisplay = 2
@@ -932,12 +932,12 @@
findTextUseOffset = 1 << 4
dropShadowOffsetType = FOUR_CHAR_CODE('drpo')
dropShadowTranslucencyType = FOUR_CHAR_CODE('drpt')
-spriteHitTestBounds = 1L << 0
-spriteHitTestImage = 1L << 1
-spriteHitTestInvisibleSprites = 1L << 2
-spriteHitTestIsClick = 1L << 3
-spriteHitTestLocInDisplayCoordinates = 1L << 4
-spriteHitTestTreatAllSpritesAsHitTestable = 1L << 5
+spriteHitTestBounds = 1 << 0
+spriteHitTestImage = 1 << 1
+spriteHitTestInvisibleSprites = 1 << 2
+spriteHitTestIsClick = 1 << 3
+spriteHitTestLocInDisplayCoordinates = 1 << 4
+spriteHitTestTreatAllSpritesAsHitTestable = 1 << 5
kSpriteAtomType = FOUR_CHAR_CODE('sprt')
kSpriteImagesContainerAtomType = FOUR_CHAR_CODE('imct')
kSpriteImageAtomType = FOUR_CHAR_CODE('imag')
@@ -1363,68 +1363,68 @@
k4444YpCbCrA8PixelFormat = FOUR_CHAR_CODE('v408')
k4444YpCbCrA8RPixelFormat = FOUR_CHAR_CODE('r408')
kYUV420PixelFormat = FOUR_CHAR_CODE('y420')
-codecInfoDoes1 = (1L << 0)
-codecInfoDoes2 = (1L << 1)
-codecInfoDoes4 = (1L << 2)
-codecInfoDoes8 = (1L << 3)
-codecInfoDoes16 = (1L << 4)
-codecInfoDoes32 = (1L << 5)
-codecInfoDoesDither = (1L << 6)
-codecInfoDoesStretch = (1L << 7)
-codecInfoDoesShrink = (1L << 8)
-codecInfoDoesMask = (1L << 9)
-codecInfoDoesTemporal = (1L << 10)
-codecInfoDoesDouble = (1L << 11)
-codecInfoDoesQuad = (1L << 12)
-codecInfoDoesHalf = (1L << 13)
-codecInfoDoesQuarter = (1L << 14)
-codecInfoDoesRotate = (1L << 15)
-codecInfoDoesHorizFlip = (1L << 16)
-codecInfoDoesVertFlip = (1L << 17)
-codecInfoHasEffectParameterList = (1L << 18)
-codecInfoDoesBlend = (1L << 19)
-codecInfoDoesWarp = (1L << 20)
-codecInfoDoesRecompress = (1L << 21)
-codecInfoDoesSpool = (1L << 22)
-codecInfoDoesRateConstrain = (1L << 23)
-codecInfoDepth1 = (1L << 0)
-codecInfoDepth2 = (1L << 1)
-codecInfoDepth4 = (1L << 2)
-codecInfoDepth8 = (1L << 3)
-codecInfoDepth16 = (1L << 4)
-codecInfoDepth32 = (1L << 5)
-codecInfoDepth24 = (1L << 6)
-codecInfoDepth33 = (1L << 7)
-codecInfoDepth34 = (1L << 8)
-codecInfoDepth36 = (1L << 9)
-codecInfoDepth40 = (1L << 10)
-codecInfoStoresClut = (1L << 11)
-codecInfoDoesLossless = (1L << 12)
-codecInfoSequenceSensitive = (1L << 13)
-codecFlagUseImageBuffer = (1L << 0)
-codecFlagUseScreenBuffer = (1L << 1)
-codecFlagUpdatePrevious = (1L << 2)
-codecFlagNoScreenUpdate = (1L << 3)
-codecFlagWasCompressed = (1L << 4)
-codecFlagDontOffscreen = (1L << 5)
-codecFlagUpdatePreviousComp = (1L << 6)
-codecFlagForceKeyFrame = (1L << 7)
-codecFlagOnlyScreenUpdate = (1L << 8)
-codecFlagLiveGrab = (1L << 9)
-codecFlagDiffFrame = (1L << 9)
-codecFlagDontUseNewImageBuffer = (1L << 10)
-codecFlagInterlaceUpdate = (1L << 11)
-codecFlagCatchUpDiff = (1L << 12)
-codecFlagSupportDisable = (1L << 13)
-codecFlagReenable = (1L << 14)
-codecFlagOutUpdateOnNextIdle = (1L << 9)
-codecFlagOutUpdateOnDataSourceChange = (1L << 10)
-codecFlagSequenceSensitive = (1L << 11)
-codecFlagOutUpdateOnTimeChange = (1L << 12)
-codecFlagImageBufferNotSourceImage = (1L << 13)
-codecFlagUsedNewImageBuffer = (1L << 14)
-codecFlagUsedImageBuffer = (1L << 15)
-codecMinimumDataSize = 32768L
+codecInfoDoes1 = (1 << 0)
+codecInfoDoes2 = (1 << 1)
+codecInfoDoes4 = (1 << 2)
+codecInfoDoes8 = (1 << 3)
+codecInfoDoes16 = (1 << 4)
+codecInfoDoes32 = (1 << 5)
+codecInfoDoesDither = (1 << 6)
+codecInfoDoesStretch = (1 << 7)
+codecInfoDoesShrink = (1 << 8)
+codecInfoDoesMask = (1 << 9)
+codecInfoDoesTemporal = (1 << 10)
+codecInfoDoesDouble = (1 << 11)
+codecInfoDoesQuad = (1 << 12)
+codecInfoDoesHalf = (1 << 13)
+codecInfoDoesQuarter = (1 << 14)
+codecInfoDoesRotate = (1 << 15)
+codecInfoDoesHorizFlip = (1 << 16)
+codecInfoDoesVertFlip = (1 << 17)
+codecInfoHasEffectParameterList = (1 << 18)
+codecInfoDoesBlend = (1 << 19)
+codecInfoDoesWarp = (1 << 20)
+codecInfoDoesRecompress = (1 << 21)
+codecInfoDoesSpool = (1 << 22)
+codecInfoDoesRateConstrain = (1 << 23)
+codecInfoDepth1 = (1 << 0)
+codecInfoDepth2 = (1 << 1)
+codecInfoDepth4 = (1 << 2)
+codecInfoDepth8 = (1 << 3)
+codecInfoDepth16 = (1 << 4)
+codecInfoDepth32 = (1 << 5)
+codecInfoDepth24 = (1 << 6)
+codecInfoDepth33 = (1 << 7)
+codecInfoDepth34 = (1 << 8)
+codecInfoDepth36 = (1 << 9)
+codecInfoDepth40 = (1 << 10)
+codecInfoStoresClut = (1 << 11)
+codecInfoDoesLossless = (1 << 12)
+codecInfoSequenceSensitive = (1 << 13)
+codecFlagUseImageBuffer = (1 << 0)
+codecFlagUseScreenBuffer = (1 << 1)
+codecFlagUpdatePrevious = (1 << 2)
+codecFlagNoScreenUpdate = (1 << 3)
+codecFlagWasCompressed = (1 << 4)
+codecFlagDontOffscreen = (1 << 5)
+codecFlagUpdatePreviousComp = (1 << 6)
+codecFlagForceKeyFrame = (1 << 7)
+codecFlagOnlyScreenUpdate = (1 << 8)
+codecFlagLiveGrab = (1 << 9)
+codecFlagDiffFrame = (1 << 9)
+codecFlagDontUseNewImageBuffer = (1 << 10)
+codecFlagInterlaceUpdate = (1 << 11)
+codecFlagCatchUpDiff = (1 << 12)
+codecFlagSupportDisable = (1 << 13)
+codecFlagReenable = (1 << 14)
+codecFlagOutUpdateOnNextIdle = (1 << 9)
+codecFlagOutUpdateOnDataSourceChange = (1 << 10)
+codecFlagSequenceSensitive = (1 << 11)
+codecFlagOutUpdateOnTimeChange = (1 << 12)
+codecFlagImageBufferNotSourceImage = (1 << 13)
+codecFlagUsedNewImageBuffer = (1 << 14)
+codecFlagUsedImageBuffer = (1 << 15)
+codecMinimumDataSize = 32768
compressorComponentType = FOUR_CHAR_CODE('imco')
decompressorComponentType = FOUR_CHAR_CODE('imdc')
codecLosslessQuality = 0x00000400
@@ -1466,11 +1466,11 @@
oddField2ToEvenFieldOut = 1 << 6
oddField2ToOddFieldOut = 1 << 7
icmFrameTimeHasVirtualStartTimeAndDuration = 1 << 0
-codecDSequenceDisableOverlaySurface = (1L << 5)
-codecDSequenceSingleField = (1L << 6)
-codecDSequenceBidirectionalPrediction = (1L << 7)
-codecDSequenceFlushInsteadOfDirtying = (1L << 8)
-codecDSequenceEnableSubPixelPositioning = (1L << 9)
+codecDSequenceDisableOverlaySurface = (1 << 5)
+codecDSequenceSingleField = (1 << 6)
+codecDSequenceBidirectionalPrediction = (1 << 7)
+codecDSequenceFlushInsteadOfDirtying = (1 << 8)
+codecDSequenceEnableSubPixelPositioning = (1 << 9)
kICMSequenceTaskWeight = FOUR_CHAR_CODE('twei')
kICMSequenceTaskName = FOUR_CHAR_CODE('tnam')
kICMSequenceUserPreferredCodecs = FOUR_CHAR_CODE('punt')
@@ -1487,19 +1487,19 @@
sfpItemCreatePreviewButton = 14
sfpItemShowPreviewButton = 15
kICMPixelFormatIsPlanarMask = 0x0F
-kICMPixelFormatIsIndexed = (1L << 4)
-kICMPixelFormatIsSupportedByQD = (1L << 5)
-kICMPixelFormatIsMonochrome = (1L << 6)
-kICMPixelFormatHasAlphaChannel = (1L << 7)
+kICMPixelFormatIsIndexed = (1 << 4)
+kICMPixelFormatIsSupportedByQD = (1 << 5)
+kICMPixelFormatIsMonochrome = (1 << 6)
+kICMPixelFormatHasAlphaChannel = (1 << 7)
kICMGetChainUltimateParent = 0
kICMGetChainParent = 1
kICMGetChainChild = 2
kICMGetChainUltimateChild = 3
-kDontUseValidateToFindGraphicsImporter = 1L << 0
-kICMTempThenAppMemory = 1L << 12
-kICMAppThenTempMemory = 1L << 13
+kDontUseValidateToFindGraphicsImporter = 1 << 0
+kICMTempThenAppMemory = 1 << 12
+kICMAppThenTempMemory = 1 << 13
kQTUsePlatformDefaultGammaLevel = 0
-kQTUseSourceGammaLevel = -1L
+kQTUseSourceGammaLevel = -1
kQTCCIR601VideoGammaLevel = 0x00023333
identityMatrixType = 0x00
translateMatrixType = 0x01
@@ -1509,7 +1509,7 @@
linearTranslateMatrixType = 0x05
perspectiveMatrixType = 0x06
GraphicsImporterComponentType = FOUR_CHAR_CODE('grip')
-graphicsImporterUsesImageDecompressor = 1L << 23
+graphicsImporterUsesImageDecompressor = 1 << 23
quickTimeImageFileImageDescriptionAtom = FOUR_CHAR_CODE('idsc')
quickTimeImageFileImageDataAtom = FOUR_CHAR_CODE('idat')
quickTimeImageFileMetaDataAtom = FOUR_CHAR_CODE('meta')
@@ -1517,9 +1517,9 @@
graphicsImporterDrawsAllPixels = 0
graphicsImporterDoesntDrawAllPixels = 1
graphicsImporterDontKnowIfDrawAllPixels = 2
-kGraphicsImporterDontDoGammaCorrection = 1L << 0
-kGraphicsImporterTrustResolutionFromFile = 1L << 1
-kGraphicsImporterEnableSubPixelPositioning = 1L << 2
+kGraphicsImporterDontDoGammaCorrection = 1 << 0
+kGraphicsImporterTrustResolutionFromFile = 1 << 1
+kGraphicsImporterEnableSubPixelPositioning = 1 << 2
kGraphicsExportGroup = FOUR_CHAR_CODE('expo')
kGraphicsExportFileType = FOUR_CHAR_CODE('ftyp')
kGraphicsExportMIMEType = FOUR_CHAR_CODE('mime')
@@ -1624,9 +1624,9 @@
kQTExifUserDataGPSDestDistance = 0x0677001A
GraphicsExporterComponentType = FOUR_CHAR_CODE('grex')
kBaseGraphicsExporterSubType = FOUR_CHAR_CODE('base')
-graphicsExporterIsBaseExporter = 1L << 0
-graphicsExporterCanTranscode = 1L << 1
-graphicsExporterUsesImageCompressor = 1L << 2
+graphicsExporterIsBaseExporter = 1 << 0
+graphicsExporterCanTranscode = 1 << 1
+graphicsExporterUsesImageCompressor = 1 << 2
kQTResolutionSettings = FOUR_CHAR_CODE('reso')
kQTTargetDataSize = FOUR_CHAR_CODE('dasz')
kQTDontRecompress = FOUR_CHAR_CODE('dntr')
@@ -1637,7 +1637,7 @@
kQTMetaData = FOUR_CHAR_CODE('meta')
kQTTIFFCompressionMethod = FOUR_CHAR_CODE('tifc')
kQTTIFFCompression_None = 1
-kQTTIFFCompression_PackBits = 32773L
+kQTTIFFCompression_PackBits = 32773
kQTTIFFLittleEndian = FOUR_CHAR_CODE('tife')
kQTPNGFilterPreference = FOUR_CHAR_CODE('pngf')
kQTPNGFilterBestForColorType = FOUR_CHAR_CODE('bflt')
@@ -1802,13 +1802,13 @@
StandardCompressionType = FOUR_CHAR_CODE('scdi')
StandardCompressionSubType = FOUR_CHAR_CODE('imag')
StandardCompressionSubTypeSound = FOUR_CHAR_CODE('soun')
-scListEveryCodec = 1L << 1
-scAllowZeroFrameRate = 1L << 2
-scAllowZeroKeyFrameRate = 1L << 3
-scShowBestDepth = 1L << 4
-scUseMovableModal = 1L << 5
-scDisableFrameRateItem = 1L << 6
-scShowDataRateAsKilobits = 1L << 7
+scListEveryCodec = 1 << 1
+scAllowZeroFrameRate = 1 << 2
+scAllowZeroKeyFrameRate = 1 << 3
+scShowBestDepth = 1 << 4
+scUseMovableModal = 1 << 5
+scDisableFrameRateItem = 1 << 6
+scShowDataRateAsKilobits = 1 << 7
scPreferCropping = 1 << 0
scPreferScaling = 1 << 1
scPreferScalingAndCropping = scPreferScaling | scPreferCropping
@@ -1863,7 +1863,7 @@
scSoundSampleRateChangeOK = FOUR_CHAR_CODE('rcok')
scAvailableCompressionListType = FOUR_CHAR_CODE('avai')
scGetCompression = 1
-scShowMotionSettings = 1L << 0
+scShowMotionSettings = 1 << 0
scSettingsChangedItem = -1
scCompressFlagIgnoreIdenticalFrames = 1
kQTSettingsVideo = FOUR_CHAR_CODE('vide')
@@ -1897,14 +1897,14 @@
hasMovieImportMIMEList = 1 << 14
canMovieImportAvoidBlocking = 1 << 15
canMovieExportFromProcedures = 1 << 15
-canMovieExportValidateMovie = 1L << 16
-movieImportMustGetDestinationMediaType = 1L << 16
-movieExportNeedsResourceFork = 1L << 17
-canMovieImportDataReferences = 1L << 18
-movieExportMustGetSourceMediaType = 1L << 19
-canMovieImportWithIdle = 1L << 20
-canMovieImportValidateDataReferences = 1L << 21
-reservedForUseByGraphicsImporters = 1L << 23
+canMovieExportValidateMovie = 1 << 16
+movieImportMustGetDestinationMediaType = 1 << 16
+movieExportNeedsResourceFork = 1 << 17
+canMovieImportDataReferences = 1 << 18
+movieExportMustGetSourceMediaType = 1 << 19
+canMovieImportWithIdle = 1 << 20
+canMovieImportValidateDataReferences = 1 << 21
+reservedForUseByGraphicsImporters = 1 << 23
movieImportCreateTrack = 1
movieImportInParallel = 2
movieImportMustUseTrack = 4
@@ -1925,20 +1925,20 @@
kQTMediaGroupResourceVersion = 1
kQTBrowserInfoResourceType = FOUR_CHAR_CODE('brws')
kQTBrowserInfoResourceVersion = 1
-kQTMediaMIMEInfoHasChanged = (1L << 1)
-kQTMediaFileInfoHasChanged = (1L << 2)
-kQTMediaConfigCanUseApp = (1L << 18)
-kQTMediaConfigCanUsePlugin = (1L << 19)
-kQTMediaConfigUNUSED = (1L << 20)
-kQTMediaConfigBinaryFile = (1L << 23)
+kQTMediaMIMEInfoHasChanged = (1 << 1)
+kQTMediaFileInfoHasChanged = (1 << 2)
+kQTMediaConfigCanUseApp = (1 << 18)
+kQTMediaConfigCanUsePlugin = (1 << 19)
+kQTMediaConfigUNUSED = (1 << 20)
+kQTMediaConfigBinaryFile = (1 << 23)
kQTMediaConfigTextFile = 0
-kQTMediaConfigMacintoshFile = (1L << 24)
-kQTMediaConfigAssociateByDefault = (1L << 27)
-kQTMediaConfigUseAppByDefault = (1L << 28)
-kQTMediaConfigUsePluginByDefault = (1L << 29)
+kQTMediaConfigMacintoshFile = (1 << 24)
+kQTMediaConfigAssociateByDefault = (1 << 27)
+kQTMediaConfigUseAppByDefault = (1 << 28)
+kQTMediaConfigUsePluginByDefault = (1 << 29)
kQTMediaConfigDefaultsMask = (kQTMediaConfigUseAppByDefault | kQTMediaConfigUsePluginByDefault)
kQTMediaConfigDefaultsShift = 12
-kQTMediaConfigHasFileHasQTAtoms = (1L << 30)
+kQTMediaConfigHasFileHasQTAtoms = (1 << 30)
kQTMediaConfigStreamGroupID = FOUR_CHAR_CODE('strm')
kQTMediaConfigInteractiveGroupID = FOUR_CHAR_CODE('intr')
kQTMediaConfigVideoGroupID = FOUR_CHAR_CODE('eyes')
@@ -2013,17 +2013,17 @@
kQTPresetsPlatformListResourceType = FOUR_CHAR_CODE('stgp')
kQTPresetInfoIsDivider = 1
kQTMovieExportSourceInfoResourceType = FOUR_CHAR_CODE('src#')
-kQTMovieExportSourceInfoIsMediaType = 1L << 0
-kQTMovieExportSourceInfoIsMediaCharacteristic = 1L << 1
-kQTMovieExportSourceInfoIsSourceType = 1L << 2
+kQTMovieExportSourceInfoIsMediaType = 1 << 0
+kQTMovieExportSourceInfoIsMediaCharacteristic = 1 << 1
+kQTMovieExportSourceInfoIsSourceType = 1 << 2
movieExportUseConfiguredSettings = FOUR_CHAR_CODE('ucfg')
movieExportWidth = FOUR_CHAR_CODE('wdth')
movieExportHeight = FOUR_CHAR_CODE('hegt')
movieExportDuration = FOUR_CHAR_CODE('dura')
movieExportVideoFilter = FOUR_CHAR_CODE('iflt')
movieExportTimeScale = FOUR_CHAR_CODE('tmsc')
-kQTBrowserInfoCanUseSystemFolderPlugin = (1L << 0)
-kQTPreFlightOpenComponent = (1L << 1)
+kQTBrowserInfoCanUseSystemFolderPlugin = (1 << 0)
+kQTPreFlightOpenComponent = (1 << 1)
pnotComponentWantsEvents = 1
pnotComponentNeedsNoCache = 2
ShowFilePreviewComponentType = FOUR_CHAR_CODE('pnot')
@@ -2032,10 +2032,10 @@
DataDecompressorComponentType = FOUR_CHAR_CODE('ddec')
AppleDataCompressorSubType = FOUR_CHAR_CODE('adec')
zlibDataCompressorSubType = FOUR_CHAR_CODE('zlib')
-kDataHCanRead = 1L << 0
-kDataHSpecialRead = 1L << 1
-kDataHSpecialReadFile = 1L << 2
-kDataHCanWrite = 1L << 3
+kDataHCanRead = 1 << 0
+kDataHSpecialRead = 1 << 1
+kDataHSpecialReadFile = 1 << 2
+kDataHCanWrite = 1 << 3
kDataHSpecialWrite = 1 << 4
kDataHSpecialWriteFile = 1 << 5
kDataHCanStreamingWrite = 1 << 6
@@ -2055,12 +2055,12 @@
kDataHFileTypeMacOSFileType = FOUR_CHAR_CODE('ftyp')
kDataHFileTypeExtension = FOUR_CHAR_CODE('fext')
kDataHFileTypeMIME = FOUR_CHAR_CODE('mime')
-kDataHCreateFileButDontCreateResFile = (1L << 0)
-kDataHMovieUsageDoAppendMDAT = 1L << 0
-kDataHTempUseSameDirectory = 1L << 0
-kDataHTempUseSameVolume = 1L << 1
-kDataHTempCreateFile = 1L << 2
-kDataHTempOpenFile = 1L << 3
+kDataHCreateFileButDontCreateResFile = (1 << 0)
+kDataHMovieUsageDoAppendMDAT = 1 << 0
+kDataHTempUseSameDirectory = 1 << 0
+kDataHTempUseSameVolume = 1 << 1
+kDataHTempCreateFile = 1 << 2
+kDataHTempOpenFile = 1 << 3
kDataHGetDataRateInfiniteRate = 0x7FFFFFFF
kDataHSetTimeHintsSkipBandwidthRequest = 1 << 0
videoDigitizerComponentType = FOUR_CHAR_CODE('vdig')
@@ -2091,48 +2091,48 @@
vdTypeAlpha = 1
vdTypeMask = 2
vdTypeKey = 3
-digiInDoesNTSC = 1L << 0
-digiInDoesPAL = 1L << 1
-digiInDoesSECAM = 1L << 2
-digiInDoesGenLock = 1L << 7
-digiInDoesComposite = 1L << 8
-digiInDoesSVideo = 1L << 9
-digiInDoesComponent = 1L << 10
-digiInVTR_Broadcast = 1L << 11
-digiInDoesColor = 1L << 12
-digiInDoesBW = 1L << 13
-digiInSignalLock = 1L << 31
-digiOutDoes1 = 1L << 0
-digiOutDoes2 = 1L << 1
-digiOutDoes4 = 1L << 2
-digiOutDoes8 = 1L << 3
-digiOutDoes16 = 1L << 4
-digiOutDoes32 = 1L << 5
-digiOutDoesDither = 1L << 6
-digiOutDoesStretch = 1L << 7
-digiOutDoesShrink = 1L << 8
-digiOutDoesMask = 1L << 9
-digiOutDoesDouble = 1L << 11
-digiOutDoesQuad = 1L << 12
-digiOutDoesQuarter = 1L << 13
-digiOutDoesSixteenth = 1L << 14
-digiOutDoesRotate = 1L << 15
-digiOutDoesHorizFlip = 1L << 16
-digiOutDoesVertFlip = 1L << 17
-digiOutDoesSkew = 1L << 18
-digiOutDoesBlend = 1L << 19
-digiOutDoesWarp = 1L << 20
-digiOutDoesHW_DMA = 1L << 21
-digiOutDoesHWPlayThru = 1L << 22
-digiOutDoesILUT = 1L << 23
-digiOutDoesKeyColor = 1L << 24
-digiOutDoesAsyncGrabs = 1L << 25
-digiOutDoesUnreadableScreenBits = 1L << 26
-digiOutDoesCompress = 1L << 27
-digiOutDoesCompressOnly = 1L << 28
-digiOutDoesPlayThruDuringCompress = 1L << 29
-digiOutDoesCompressPartiallyVisible = 1L << 30
-digiOutDoesNotNeedCopyOfCompressData = 1L << 31
+digiInDoesNTSC = 1 << 0
+digiInDoesPAL = 1 << 1
+digiInDoesSECAM = 1 << 2
+digiInDoesGenLock = 1 << 7
+digiInDoesComposite = 1 << 8
+digiInDoesSVideo = 1 << 9
+digiInDoesComponent = 1 << 10
+digiInVTR_Broadcast = 1 << 11
+digiInDoesColor = 1 << 12
+digiInDoesBW = 1 << 13
+digiInSignalLock = 1 << 31
+digiOutDoes1 = 1 << 0
+digiOutDoes2 = 1 << 1
+digiOutDoes4 = 1 << 2
+digiOutDoes8 = 1 << 3
+digiOutDoes16 = 1 << 4
+digiOutDoes32 = 1 << 5
+digiOutDoesDither = 1 << 6
+digiOutDoesStretch = 1 << 7
+digiOutDoesShrink = 1 << 8
+digiOutDoesMask = 1 << 9
+digiOutDoesDouble = 1 << 11
+digiOutDoesQuad = 1 << 12
+digiOutDoesQuarter = 1 << 13
+digiOutDoesSixteenth = 1 << 14
+digiOutDoesRotate = 1 << 15
+digiOutDoesHorizFlip = 1 << 16
+digiOutDoesVertFlip = 1 << 17
+digiOutDoesSkew = 1 << 18
+digiOutDoesBlend = 1 << 19
+digiOutDoesWarp = 1 << 20
+digiOutDoesHW_DMA = 1 << 21
+digiOutDoesHWPlayThru = 1 << 22
+digiOutDoesILUT = 1 << 23
+digiOutDoesKeyColor = 1 << 24
+digiOutDoesAsyncGrabs = 1 << 25
+digiOutDoesUnreadableScreenBits = 1 << 26
+digiOutDoesCompress = 1 << 27
+digiOutDoesCompressOnly = 1 << 28
+digiOutDoesPlayThruDuringCompress = 1 << 29
+digiOutDoesCompressPartiallyVisible = 1 << 30
+digiOutDoesNotNeedCopyOfCompressData = 1 << 31
dmaDepth1 = 1
dmaDepth2 = 2
dmaDepth4 = 4
@@ -2160,19 +2160,19 @@
xmlContentTypeInvalid = 0
xmlContentTypeElement = 1
xmlContentTypeCharData = 2
-elementFlagAlwaysSelfContained = 1L << 0
-elementFlagPreserveWhiteSpace = 1L << 1
-xmlParseFlagAllowUppercase = 1L << 0
-xmlParseFlagAllowUnquotedAttributeValues = 1L << 1
-xmlParseFlagEventParseOnly = 1L << 2
+elementFlagAlwaysSelfContained = 1 << 0
+elementFlagPreserveWhiteSpace = 1 << 1
+xmlParseFlagAllowUppercase = 1 << 0
+xmlParseFlagAllowUnquotedAttributeValues = 1 << 1
+xmlParseFlagEventParseOnly = 1 << 2
attributeValueKindCharString = 0
-attributeValueKindInteger = 1L << 0
-attributeValueKindPercent = 1L << 1
-attributeValueKindBoolean = 1L << 2
-attributeValueKindOnOff = 1L << 3
-attributeValueKindColor = 1L << 4
-attributeValueKindEnum = 1L << 5
-attributeValueKindCaseSensEnum = 1L << 6
+attributeValueKindInteger = 1 << 0
+attributeValueKindPercent = 1 << 1
+attributeValueKindBoolean = 1 << 2
+attributeValueKindOnOff = 1 << 3
+attributeValueKindColor = 1 << 4
+attributeValueKindEnum = 1 << 5
+attributeValueKindCaseSensEnum = 1 << 6
MAX_ATTRIBUTE_VALUE_KIND = attributeValueKindCaseSensEnum
nameSpaceIDNone = 0
element_xml = 1
@@ -2267,7 +2267,7 @@
sgcVideoDigitizerType = FOUR_CHAR_CODE('vdig')
QTVideoOutputComponentType = FOUR_CHAR_CODE('vout')
QTVideoOutputComponentBaseSubType = FOUR_CHAR_CODE('base')
-kQTVideoOutputDontDisplayToUser = 1L << 0
+kQTVideoOutputDontDisplayToUser = 1 << 0
kQTVODisplayModeItem = FOUR_CHAR_CODE('qdmi')
kQTVODimensions = FOUR_CHAR_CODE('dimn')
kQTVOResolution = FOUR_CHAR_CODE('resl')
@@ -2801,12 +2801,12 @@
mWantIdleActions = 1 << 5
forceUpdateRedraw = 1 << 0
forceUpdateNewBuffer = 1 << 1
-mHitTestBounds = 1L << 0
-mHitTestImage = 1L << 1
-mHitTestInvisible = 1L << 2
-mHitTestIsClick = 1L << 3
-mOpaque = 1L << 0
-mInvisible = 1L << 1
+mHitTestBounds = 1 << 0
+mHitTestImage = 1 << 1
+mHitTestInvisible = 1 << 2
+mHitTestIsClick = 1 << 3
+mOpaque = 1 << 0
+mInvisible = 1 << 1
kMediaQTIdleFrequencySelector = FOUR_CHAR_CODE('idfq')
kMediaVideoParamBrightness = 1
kMediaVideoParamContrast = 2
@@ -3244,8 +3244,8 @@
kGeneralEventType = 0x0000000F
kXEventLengthBits = 0x00000002
kGeneralEventLengthBits = 0x00000003
-kEventLen = 1L
-kXEventLen = 2L
+kEventLen = 1
+kXEventLen = 2
kRestEventLen = kEventLen
kNoteEventLen = kEventLen
kControlEventLen = kEventLen
@@ -3265,7 +3265,7 @@
kXEventPartFieldWidth = 12
kRestEventDurationFieldPos = 0
kRestEventDurationFieldWidth = 24
-kRestEventDurationMax = ((1L << kRestEventDurationFieldWidth) - 1)
+kRestEventDurationMax = ((1 << kRestEventDurationFieldWidth) - 1)
kNoteEventPitchFieldPos = 18
kNoteEventPitchFieldWidth = 6
kNoteEventPitchOffset = 32
@@ -3274,12 +3274,12 @@
kNoteEventVolumeOffset = 0
kNoteEventDurationFieldPos = 0
kNoteEventDurationFieldWidth = 11
-kNoteEventDurationMax = ((1L << kNoteEventDurationFieldWidth) - 1)
+kNoteEventDurationMax = ((1 << kNoteEventDurationFieldWidth) - 1)
kXNoteEventPitchFieldPos = 0
kXNoteEventPitchFieldWidth = 16
kXNoteEventDurationFieldPos = 0
kXNoteEventDurationFieldWidth = 22
-kXNoteEventDurationMax = ((1L << kXNoteEventDurationFieldWidth) - 1)
+kXNoteEventDurationMax = ((1 << kXNoteEventDurationFieldWidth) - 1)
kXNoteEventVolumeFieldPos = 22
kXNoteEventVolumeFieldWidth = 7
kControlEventControllerFieldPos = 16
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Sound.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Sound.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Sound.py Fri Feb 23 18:29:35 2007
@@ -300,15 +300,15 @@
k8BitTwosOut = (1 << 9)
k16BitOut = (1 << 10)
kStereoOut = (1 << 11)
-kReverse = (1L << 16)
-kRateConvert = (1L << 17)
-kCreateSoundSource = (1L << 18)
-kVMAwareness = (1L << 21)
-kHighQuality = (1L << 22)
-kNonRealTime = (1L << 23)
+kReverse = (1 << 16)
+kRateConvert = (1 << 17)
+kCreateSoundSource = (1 << 18)
+kVMAwareness = (1 << 21)
+kHighQuality = (1 << 22)
+kNonRealTime = (1 << 23)
kSourcePaused = (1 << 0)
-kPassThrough = (1L << 16)
-kNoSoundComponentChain = (1L << 17)
+kPassThrough = (1 << 16)
+kNoSoundComponentChain = (1 << 17)
kNoMixing = (1 << 0)
kNoSampleRateConversion = (1 << 1)
kNoSampleSizeConversion = (1 << 2)
@@ -343,9 +343,9 @@
audioRightChannel = 2
audioUnmuted = 0
audioMuted = 1
-audioDoesMono = (1L << 0)
-audioDoesStereo = (1L << 1)
-audioDoesIndependentChannels = (1L << 2)
+audioDoesMono = (1 << 0)
+audioDoesStereo = (1 << 1)
+audioDoesIndependentChannels = (1 << 2)
siCDQuality = FOUR_CHAR_CODE('cd ')
siBestQuality = FOUR_CHAR_CODE('best')
siBetterQuality = FOUR_CHAR_CODE('betr')
@@ -358,8 +358,8 @@
siWritePermission = 1
kSoundConverterDidntFillBuffer = (1 << 0)
kSoundConverterHasLeftOverData = (1 << 1)
-kExtendedSoundSampleCountNotValid = 1L << 0
-kExtendedSoundBufferSizeValid = 1L << 1
+kExtendedSoundSampleCountNotValid = 1 << 0
+kExtendedSoundBufferSizeValid = 1 << 1
kScheduledSoundDoScheduled = 1 << 0
kScheduledSoundDoCallBack = 1 << 1
kScheduledSoundExtendedHdr = 1 << 2
Modified: python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Windows.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Windows.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/Carbon/Windows.py Fri Feb 23 18:29:35 2007
@@ -20,24 +20,24 @@
kAltPlainWindowClass = 16
kDrawerWindowClass = 20
# kAllWindowClasses = (unsigned long)0xFFFFFFFF
-kWindowNoAttributes = 0L
-kWindowCloseBoxAttribute = (1L << 0)
-kWindowHorizontalZoomAttribute = (1L << 1)
-kWindowVerticalZoomAttribute = (1L << 2)
+kWindowNoAttributes = 0
+kWindowCloseBoxAttribute = (1 << 0)
+kWindowHorizontalZoomAttribute = (1 << 1)
+kWindowVerticalZoomAttribute = (1 << 2)
kWindowFullZoomAttribute = (kWindowVerticalZoomAttribute | kWindowHorizontalZoomAttribute)
-kWindowCollapseBoxAttribute = (1L << 3)
-kWindowResizableAttribute = (1L << 4)
-kWindowSideTitlebarAttribute = (1L << 5)
-kWindowToolbarButtonAttribute = (1L << 6)
-kWindowNoUpdatesAttribute = (1L << 16)
-kWindowNoActivatesAttribute = (1L << 17)
-kWindowOpaqueForEventsAttribute = (1L << 18)
-kWindowNoShadowAttribute = (1L << 21)
-kWindowHideOnSuspendAttribute = (1L << 24)
-kWindowStandardHandlerAttribute = (1L << 25)
-kWindowHideOnFullScreenAttribute = (1L << 26)
-kWindowInWindowMenuAttribute = (1L << 27)
-kWindowLiveResizeAttribute = (1L << 28)
+kWindowCollapseBoxAttribute = (1 << 3)
+kWindowResizableAttribute = (1 << 4)
+kWindowSideTitlebarAttribute = (1 << 5)
+kWindowToolbarButtonAttribute = (1 << 6)
+kWindowNoUpdatesAttribute = (1 << 16)
+kWindowNoActivatesAttribute = (1 << 17)
+kWindowOpaqueForEventsAttribute = (1 << 18)
+kWindowNoShadowAttribute = (1 << 21)
+kWindowHideOnSuspendAttribute = (1 << 24)
+kWindowStandardHandlerAttribute = (1 << 25)
+kWindowHideOnFullScreenAttribute = (1 << 26)
+kWindowInWindowMenuAttribute = (1 << 27)
+kWindowLiveResizeAttribute = (1 << 28)
# kWindowNoConstrainAttribute = (unsigned long)((1L << 31))
kWindowStandardDocumentAttributes = (kWindowCloseBoxAttribute | kWindowFullZoomAttribute | kWindowCollapseBoxAttribute | kWindowResizableAttribute)
kWindowStandardFloatingAttributes = (kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute)
@@ -225,7 +225,7 @@
# kMouseUpOutOfSlop = (long)0x80008000
kWindowDefinitionVersionOne = 1
kWindowDefinitionVersionTwo = 2
-kWindowIsCollapsedState = (1 << 0L)
+kWindowIsCollapsedState = (1 << 0)
kStoredWindowSystemTag = FOUR_CHAR_CODE('appl')
kStoredBasicWindowDescriptionID = FOUR_CHAR_CODE('sbas')
kStoredWindowPascalTitleID = FOUR_CHAR_CODE('s255')
@@ -251,8 +251,8 @@
kWindowGroupContentsVisible = 1 << 2
kWindowPaintProcOptionsNone = 0
kScrollWindowNoOptions = 0
-kScrollWindowInvalidate = (1L << 0)
-kScrollWindowEraseToPortBackground = (1L << 1)
+kScrollWindowInvalidate = (1 << 0)
+kScrollWindowEraseToPortBackground = (1 << 1)
kWindowMenuIncludeRotate = 1 << 0
kWindowZoomTransitionEffect = 1
kWindowSheetTransitionEffect = 2
@@ -261,11 +261,11 @@
kWindowHideTransitionAction = 2
kWindowMoveTransitionAction = 3
kWindowResizeTransitionAction = 4
-kWindowConstrainMayResize = (1L << 0)
-kWindowConstrainMoveRegardlessOfFit = (1L << 1)
-kWindowConstrainAllowPartial = (1L << 2)
-kWindowConstrainCalcOnly = (1L << 3)
-kWindowConstrainUseTransitionWindow = (1L << 4)
+kWindowConstrainMayResize = (1 << 0)
+kWindowConstrainMoveRegardlessOfFit = (1 << 1)
+kWindowConstrainAllowPartial = (1 << 2)
+kWindowConstrainCalcOnly = (1 << 3)
+kWindowConstrainUseTransitionWindow = (1 << 4)
kWindowConstrainStandardOptions = kWindowConstrainMoveRegardlessOfFit
kWindowLatentVisibleFloater = 1 << 0
kWindowLatentVisibleSuspend = 1 << 1
Modified: python/branches/p3yk-noslice/Lib/plat-mac/EasyDialogs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/EasyDialogs.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/EasyDialogs.py Fri Feb 23 18:29:35 2007
@@ -75,7 +75,7 @@
_interact()
d = GetNewDialog(id, -1)
if not d:
- print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
+ print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)")
return
h = d.GetDialogItemAsControl(2)
SetDialogItemText(h, lf2cr(msg))
@@ -108,7 +108,7 @@
_interact()
d = GetNewDialog(id, -1)
if not d:
- print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
+ print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)")
return
h = d.GetDialogItemAsControl(3)
SetDialogItemText(h, lf2cr(prompt))
@@ -150,7 +150,7 @@
_interact()
d = GetNewDialog(id, -1)
if not d:
- print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
+ print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)")
return
h = d.GetDialogItemAsControl(3)
SetDialogItemText(h, lf2cr(prompt))
@@ -194,7 +194,7 @@
_interact()
d = GetNewDialog(id, -1)
if not d:
- print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
+ print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)")
return
# Button assignments:
# 1 = default (invisible)
@@ -429,7 +429,7 @@
_interact()
d = GetNewDialog(id, -1)
if not d:
- print "EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)"
+ print("EasyDialogs: Can't get DLOG resource with id =", id, " (missing resource file?)")
return
# h = d.GetDialogItemAsControl(3)
# SetDialogItemText(h, lf2cr(prompt))
@@ -791,7 +791,7 @@
argv = GetArgv(optionlist=optionlist, commandlist=commandlist, addoldfile=0)
Message("Command line: %s"%' '.join(argv))
for i in range(len(argv)):
- print 'arg[%d] = %r' % (i, argv[i])
+ print('arg[%d] = %r' % (i, argv[i]))
ok = AskYesNoCancel("Do you want to proceed?")
ok = AskYesNoCancel("Do you want to identify?", yes="Identify", no="No")
if ok > 0:
Modified: python/branches/p3yk-noslice/Lib/plat-mac/FrameWork.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/FrameWork.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/FrameWork.py Fri Feb 23 18:29:35 2007
@@ -250,7 +250,7 @@
if window in self._windows:
self._windows[window].do_itemhit(item, event)
else:
- print 'Dialog event for unknown dialog'
+ print('Dialog event for unknown dialog')
return 1
return 0
@@ -323,14 +323,14 @@
def do_unknownpartcode(self, partcode, window, event):
(what, message, when, where, modifiers) = event
- if DEBUG: print "Mouse down at global:", where
- if DEBUG: print "\tUnknown part code:", partcode
- if DEBUG: print "\tEvent:", self.printevent(event)
+ if DEBUG: print("Mouse down at global:", where)
+ if DEBUG: print("\tUnknown part code:", partcode)
+ if DEBUG: print("\tEvent:", self.printevent(event))
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
def do_unknownwindow(self, partcode, window, event):
- if DEBUG: print 'Unknown window:', window
+ if DEBUG: print('Unknown window:', window)
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
@@ -373,7 +373,7 @@
# else it wasn't for us, sigh...
def do_char(self, c, event):
- if DEBUG: print "Character", repr(c)
+ if DEBUG: print("Character", repr(c))
def do_updateEvt(self, event):
(what, message, when, where, modifiers) = event
@@ -402,7 +402,7 @@
self.do_suspendresume(event)
else:
if DEBUG:
- print 'unknown osEvt:',
+ print('unknown osEvt:', end=' ')
self.printevent(event)
def do_suspendresume(self, event):
@@ -415,7 +415,7 @@
def do_kHighLevelEvent(self, event):
(what, message, when, where, modifiers) = event
if DEBUG:
- print "High Level Event:",
+ print("High Level Event:", end=' ')
self.printevent(event)
try:
AEProcessAppleEvent(event)
@@ -426,7 +426,7 @@
def do_unknownevent(self, event):
if DEBUG:
- print "Unhandled event:",
+ print("Unhandled event:", end=' ')
self.printevent(event)
def printevent(self, event):
@@ -434,13 +434,13 @@
nicewhat = repr(what)
if what in eventname:
nicewhat = eventname[what]
- print nicewhat,
+ print(nicewhat, end=' ')
if what == kHighLevelEvent:
h, v = where
- print repr(ostypecode(message)), hex(when), repr(ostypecode(h | (v<<16))),
+ print(repr(ostypecode(message)), hex(when), repr(ostypecode(h | (v<<16))), end=' ')
else:
- print hex(message), hex(when), where,
- print hex(modifiers)
+ print(hex(message), hex(when), where, end=' ')
+ print(hex(modifiers))
class MenuBar:
@@ -477,7 +477,7 @@
def addmenu(self, title, after = 0, id=None):
if id == None:
id = self.getnextid()
- if DEBUG: print 'Newmenu', title, id # XXXX
+ if DEBUG: print('Newmenu', title, id) # XXXX
m = NewMenu(id, title)
m.InsertMenu(after)
if after >= 0:
@@ -488,7 +488,7 @@
return id, m
def delmenu(self, id):
- if DEBUG: print 'Delmenu', id # XXXX
+ if DEBUG: print('Delmenu', id) # XXXX
DeleteMenu(id)
def addpopup(self, title = ''):
@@ -531,8 +531,8 @@
if id in self.menus:
self.menus[id].dispatch(id, item, window, event)
else:
- if DEBUG: print "MenuBar.dispatch(%d, %d, %s, %s)" % \
- (id, item, window, event)
+ if DEBUG: print("MenuBar.dispatch(%d, %d, %s, %s)" % \
+ (id, item, window, event))
# XXX Need a way to get menus as resources and bind them to callbacks
@@ -837,10 +837,10 @@
def do_contentclick(self, local, modifiers, event):
if DEBUG:
- print 'Click in contents at %s, modifiers %s'%(local, modifiers)
+ print('Click in contents at %s, modifiers %s'%(local, modifiers))
def do_rawupdate(self, window, event):
- if DEBUG: print "raw update for", window
+ if DEBUG: print("raw update for", window)
SetPort(window)
window.BeginUpdate()
self.do_update(window, event)
@@ -857,12 +857,12 @@
EraseRgn(window.GetWindowPort().visRgn)
def do_activate(self, activate, event):
- if DEBUG: print 'Activate %d for %s'%(activate, self.wid)
+ if DEBUG: print('Activate %d for %s'%(activate, self.wid))
class ControlsWindow(Window):
def do_rawupdate(self, window, event):
- if DEBUG: print "raw update for", window
+ if DEBUG: print("raw update for", window)
SetPort(window)
window.BeginUpdate()
self.do_update(window, event)
@@ -872,7 +872,7 @@
window.EndUpdate()
def do_controlhit(self, window, control, pcode, event):
- if DEBUG: print "control hit in", window, "on", control, "; pcode =", pcode
+ if DEBUG: print("control hit in", window, "on", control, "; pcode =", pcode)
def do_inContent(self, partcode, window, event):
if MyFrontWindow() != window:
@@ -885,8 +885,8 @@
if pcode and control:
self.do_rawcontrolhit(window, control, pcode, local, event)
else:
- if DEBUG: print "FindControl(%s, %s) -> (%s, %s)" % \
- (local, window, pcode, control)
+ if DEBUG: print("FindControl(%s, %s) -> (%s, %s)" % \
+ (local, window, pcode, control))
self.do_contentclick(local, modifiers, event)
def do_rawcontrolhit(self, window, control, pcode, local, event):
@@ -975,11 +975,11 @@
pcode = control.TrackControl(local)
if pcode == inThumb:
value = control.GetControlValue()
- print 'setbars', which, value #DBG
+ print('setbars', which, value) #DBG
self.scrollbar_callback(which, 'set', value)
self.updatescrollbars()
else:
- print 'funny part', pcode #DBG
+ print('funny part', pcode) #DBG
return 1
def do_controltrack(self, control, pcode):
@@ -1045,7 +1045,7 @@
return 0, 0
def scrollbar_callback(self, which, what, value):
- print 'scroll', which, what, value
+ print('scroll', which, what, value)
class DialogWindow(Window):
"""A modeless dialog window"""
@@ -1063,7 +1063,7 @@
Window.do_postclose(self)
def do_itemhit(self, item, event):
- print 'Dialog %s, item %d hit'%(self.dlg, item)
+ print('Dialog %s, item %d hit'%(self.dlg, item))
def do_rawupdate(self, window, event):
pass
@@ -1096,7 +1096,7 @@
self.quititem = MenuItem(m, "Quit", "Q", self.quit)
def save(self, *args):
- print "Save"
+ print("Save")
def quit(self, *args):
raise self
@@ -1106,7 +1106,7 @@
self.nohelpitem = MenuItem(hm, "There isn't any", None, self.nohelp)
def nohelp(self, *args):
- print "I told you there isn't any!"
+ print("I told you there isn't any!")
def debug(self, *args):
import pdb
Modified: python/branches/p3yk-noslice/Lib/plat-mac/MiniAEFrame.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/MiniAEFrame.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/MiniAEFrame.py Fri Feb 23 18:29:35 2007
@@ -71,8 +71,8 @@
try:
AE.AEProcessAppleEvent(event)
except AE.Error as err:
- print 'AE error: ', err
- print 'in', msg
+ print('AE error: ', err)
+ print('in', msg)
traceback.print_exc()
return
elif what == keyDown:
@@ -107,7 +107,7 @@
if hasattr(MacOS, 'HandleEvent'):
MacOS.HandleEvent(event)
else:
- print "Unhandled event:", event
+ print("Unhandled event:", event)
def getabouttext(self):
return self.__class__.__name__
@@ -191,7 +191,7 @@
pass
def other(self, _object=None, _class=None, _type=None, **args):
- print 'AppleEvent', (_class, _type), 'for', _object, 'Other args:', args
+ print('AppleEvent', (_class, _type), 'for', _object, 'Other args:', args)
if __name__ == '__main__':
Modified: python/branches/p3yk-noslice/Lib/plat-mac/aepack.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/aepack.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/aepack.py Fri Feb 23 18:29:35 2007
@@ -189,13 +189,13 @@
return struct.unpack('l', desc.data)[0]
if t == typeLongDateTime:
a, b = struct.unpack('lL', desc.data)
- return (long(a) << 32) + b
+ return (int(a) << 32) + b
if t == typeNull:
return None
if t == typeMagnitude:
v = struct.unpack('l', desc.data)
if v < 0:
- v = 0x100000000L + v
+ v = 0x100000000 + v
return v
if t == typeObjectSpecifier:
record = desc.AECoerceDesc('reco')
Modified: python/branches/p3yk-noslice/Lib/plat-mac/aetools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/aetools.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/aetools.py Fri Feb 23 18:29:35 2007
@@ -349,15 +349,15 @@
target = AE.AECreateDesc('sign', 'quil')
ae = AE.AECreateAppleEvent('aevt', 'oapp', target, -1, 0)
- print unpackevent(ae)
+ print(unpackevent(ae))
raw_input(":")
ae = AE.AECreateAppleEvent('core', 'getd', target, -1, 0)
obj = Character(2, Word(1, Document(1)))
- print obj
- print repr(obj)
+ print(obj)
+ print(repr(obj))
packevent(ae, {'----': obj})
params, attrs = unpackevent(ae)
- print params['----']
+ print(params['----'])
raw_input(":")
if __name__ == '__main__':
Modified: python/branches/p3yk-noslice/Lib/plat-mac/applesingle.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/applesingle.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/applesingle.py Fri Feb 23 18:29:35 2007
@@ -51,9 +51,9 @@
except ValueError as arg:
raise Error, "Unpack header error: %s" % (arg,)
if verbose:
- print 'Magic: 0x%8.8x' % (magic,)
- print 'Version: 0x%8.8x' % (version,)
- print 'Entries: %d' % (nentry,)
+ print('Magic: 0x%8.8x' % (magic,))
+ print('Version: 0x%8.8x' % (version,))
+ print('Entries: %d' % (nentry,))
if magic != AS_MAGIC:
raise Error, "Unknown AppleSingle magic number 0x%8.8x" % (magic,)
if version != AS_VERSION:
@@ -68,7 +68,7 @@
except ValueError as arg:
raise Error, "Unpack entry error: %s" % (arg,)
if verbose:
- print "Fork %d, offset %d, length %d" % (restype, offset, length)
+ print("Fork %d, offset %d, length %d" % (restype, offset, length))
fileobj.seek(offset)
data = fileobj.read(length)
if len(data) != length:
@@ -124,7 +124,7 @@
def _test():
if len(sys.argv) < 3 or sys.argv[1] == '-r' and len(sys.argv) != 4:
- print 'Usage: applesingle.py [-r] applesinglefile decodedfile'
+ print('Usage: applesingle.py [-r] applesinglefile decodedfile')
sys.exit(1)
if sys.argv[1] == '-r':
resonly = True
Modified: python/branches/p3yk-noslice/Lib/plat-mac/argvemulator.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/argvemulator.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/argvemulator.py Fri Feb 23 18:29:35 2007
@@ -37,7 +37,7 @@
self._dooneevent(mask, timeout)
if not self.quitting:
- print "argvemulator: timeout waiting for arguments"
+ print("argvemulator: timeout waiting for arguments")
self.close()
@@ -54,12 +54,12 @@
AE.AEProcessAppleEvent(event)
except AE.Error as err:
msg = "High Level Event: %r %r" % (hex(message), hex(h | (v<<16)))
- print 'AE error: ', err
- print 'in', msg
+ print('AE error: ', err)
+ print('in', msg)
traceback.print_exc()
return
else:
- print "Unhandled event:", event
+ print("Unhandled event:", event)
def _quit(self):
@@ -78,7 +78,7 @@
pathname = fsref.as_pathname()
sys.argv.append(pathname)
except Exception as e:
- print "argvemulator.py warning: can't unpack an open document event"
+ print("argvemulator.py warning: can't unpack an open document event")
import traceback
traceback.print_exc()
@@ -86,4 +86,4 @@
if __name__ == '__main__':
ArgvCollector().mainloop()
- print "sys.argv=", sys.argv
+ print("sys.argv=", sys.argv)
Modified: python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/bundlebuilder.py Fri Feb 23 18:29:35 2007
@@ -831,8 +831,8 @@
def usage(msg=None):
if msg:
- print msg
- print cmdline_doc
+ print(msg)
+ print(cmdline_doc)
sys.exit(1)
def main(builder=None):
Modified: python/branches/p3yk-noslice/Lib/plat-mac/findertools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/findertools.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/findertools.py Fri Feb 23 18:29:35 2007
@@ -695,76 +695,76 @@
def _test():
import EasyDialogs
- print 'Original findertools functionality test...'
- print 'Testing launch...'
+ print('Original findertools functionality test...')
+ print('Testing launch...')
pathname = EasyDialogs.AskFileForOpen('File to launch:')
if pathname:
result = launch(pathname)
if result:
- print 'Result: ', result
- print 'Press return-',
+ print('Result: ', result)
+ print('Press return-', end=' ')
sys.stdin.readline()
- print 'Testing print...'
+ print('Testing print...')
pathname = EasyDialogs.AskFileForOpen('File to print:')
if pathname:
result = Print(pathname)
if result:
- print 'Result: ', result
- print 'Press return-',
+ print('Result: ', result)
+ print('Press return-', end=' ')
sys.stdin.readline()
- print 'Testing copy...'
+ print('Testing copy...')
pathname = EasyDialogs.AskFileForOpen('File to copy:')
if pathname:
destdir = EasyDialogs.AskFolder('Destination:')
if destdir:
result = copy(pathname, destdir)
if result:
- print 'Result:', result
- print 'Press return-',
+ print('Result:', result)
+ print('Press return-', end=' ')
sys.stdin.readline()
- print 'Testing move...'
+ print('Testing move...')
pathname = EasyDialogs.AskFileForOpen('File to move:')
if pathname:
destdir = EasyDialogs.AskFolder('Destination:')
if destdir:
result = move(pathname, destdir)
if result:
- print 'Result:', result
- print 'Press return-',
+ print('Result:', result)
+ print('Press return-', end=' ')
sys.stdin.readline()
- print 'Testing sleep...'
+ print('Testing sleep...')
if EasyDialogs.AskYesNoCancel('Sleep?') > 0:
result = sleep()
if result:
- print 'Result:', result
- print 'Press return-',
+ print('Result:', result)
+ print('Press return-', end=' ')
sys.stdin.readline()
- print 'Testing shutdown...'
+ print('Testing shutdown...')
if EasyDialogs.AskYesNoCancel('Shut down?') > 0:
result = shutdown()
if result:
- print 'Result:', result
- print 'Press return-',
+ print('Result:', result)
+ print('Press return-', end=' ')
sys.stdin.readline()
- print 'Testing restart...'
+ print('Testing restart...')
if EasyDialogs.AskYesNoCancel('Restart?') > 0:
result = restart()
if result:
- print 'Result:', result
- print 'Press return-',
+ print('Result:', result)
+ print('Press return-', end=' ')
sys.stdin.readline()
def _test2():
- print '\nmorefindertools version %s\nTests coming up...' %__version__
+ print('\nmorefindertools version %s\nTests coming up...' %__version__)
import os
import random
# miscellaneous
- print '\tfilesharing on?', filesharing() # is file sharing on, off, starting up?
- print '\tOS version', OSversion() # the version of the system software
+ print('\tfilesharing on?', filesharing()) # is file sharing on, off, starting up?
+ print('\tOS version', OSversion()) # the version of the system software
# set the soundvolume in a simple way
- print '\tSystem beep volume'
+ print('\tSystem beep volume')
for i in range(0, 7):
volumelevel(i)
MacOS.SysBeep()
@@ -781,10 +781,10 @@
windowview(base, 1) # set the view by list
label(f, 2) # set the label of this file to something orange
- print '\tlabel', label(f) # get the label of this file
+ print('\tlabel', label(f)) # get the label of this file
# the file location only works in a window with icon view!
- print 'Random locations for an icon'
+ print('Random locations for an icon')
windowview(base, 0) # set the view by icon
windowsize(base, (600, 600))
for i in range(50):
@@ -794,36 +794,36 @@
windowview(base, 1) # set the view by icon
orgpos = windowposition(base)
- print 'Animated window location'
+ print('Animated window location')
for i in range(10):
pos = (100+i*10, 100+i*10)
windowposition(base, pos)
- print '\twindow position', pos
+ print('\twindow position', pos)
windowposition(base, orgpos) # park it where it was before
- print 'Put a comment in file', f, ':'
- print '\t', comment(f) # print the Finder comment this file has
+ print('Put a comment in file', f, ':')
+ print('\t', comment(f)) # print the Finder comment this file has
s = 'This is a comment no one reads!'
comment(f, s) # set the Finder comment
def _test3():
- print 'MacOS9 or better specific functions'
+ print('MacOS9 or better specific functions')
# processes
pr = processes() # return a list of tuples with (active_processname, creatorcode)
- print 'Return a list of current active processes:'
+ print('Return a list of current active processes:')
for p in pr:
- print '\t', p
+ print('\t', p)
# get attributes of the first process in the list
- print 'Attributes of the first process in the list:'
+ print('Attributes of the first process in the list:')
pinfo = processinfo(pr[0][0])
- print '\t', pr[0][0]
- print '\t\tmemory partition', pinfo.partition # the memory allocated to this process
- print '\t\tmemory used', pinfo.used # the memory actuall used by this process
- print '\t\tis visible', pinfo.visible # is the process visible to the user
- print '\t\tis frontmost', pinfo.frontmost # is the process the front most one?
- print '\t\thas scripting', pinfo.hasscripting # is the process scriptable?
- print '\t\taccepts high level events', pinfo.accepthighlevel # does the process accept high level appleevents?
+ print('\t', pr[0][0])
+ print('\t\tmemory partition', pinfo.partition) # the memory allocated to this process
+ print('\t\tmemory used', pinfo.used) # the memory actuall used by this process
+ print('\t\tis visible', pinfo.visible) # is the process visible to the user
+ print('\t\tis frontmost', pinfo.frontmost) # is the process the front most one?
+ print('\t\thas scripting', pinfo.hasscripting) # is the process scriptable?
+ print('\t\taccepts high level events', pinfo.accepthighlevel) # does the process accept high level appleevents?
if __name__ == '__main__':
_test()
Modified: python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/gensuitemodule.py Fri Feb 23 18:29:35 2007
@@ -115,8 +115,8 @@
processfile(filename, edit_modnames=edit_modnames, basepkgname=basepkgname,
verbose=sys.stderr)
except MacOS.Error as arg:
- print "Error getting terminology:", arg
- print "Retry, manually parsing resources"
+ print("Error getting terminology:", arg)
+ print("Retry, manually parsing resources")
processfile_fromresource(filename, edit_modnames=edit_modnames,
basepkgname=basepkgname, verbose=sys.stderr)
@@ -145,10 +145,10 @@
edit_modnames=None, creatorsignature=None, dump=None, verbose=None):
"""Process all resources in a single file"""
if not is_scriptable(fullname) and verbose:
- print >>verbose, "Warning: app does not seem scriptable: %s" % fullname
+ print("Warning: app does not seem scriptable: %s" % fullname, file=verbose)
cur = CurResFile()
if verbose:
- print >>verbose, "Processing", fullname
+ print("Processing", fullname, file=verbose)
rf = macresource.open_pathname(fullname)
try:
UseResFile(rf)
@@ -160,11 +160,11 @@
res = Get1IndResource('aeut', 1+i)
resources.append(res)
if verbose:
- print >>verbose, "\nLISTING aete+aeut RESOURCES IN", repr(fullname)
+ print("\nLISTING aete+aeut RESOURCES IN", repr(fullname), file=verbose)
aetelist = []
for res in resources:
if verbose:
- print >>verbose, "decoding", res.GetResInfo(), "..."
+ print("decoding", res.GetResInfo(), "...", file=verbose)
data = res.data
aete = decode(data, verbose)
aetelist.append((aete, res.GetResInfo()))
@@ -185,15 +185,15 @@
verbose=None):
"""Ask an application for its terminology and process that"""
if not is_scriptable(fullname) and verbose:
- print >>verbose, "Warning: app does not seem scriptable: %s" % fullname
+ print("Warning: app does not seem scriptable: %s" % fullname, file=verbose)
if verbose:
- print >>verbose, "\nASKING FOR aete DICTIONARY IN", repr(fullname)
+ print("\nASKING FOR aete DICTIONARY IN", repr(fullname), file=verbose)
try:
aedescobj, launched = OSATerminology.GetAppTerminology(fullname)
except MacOS.Error as arg:
if arg[0] in (-1701, -192): # errAEDescNotFound, resNotFound
if verbose:
- print >>verbose, "GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually"
+ print("GetAppTerminology failed with errAEDescNotFound/resNotFound, trying manually", file=verbose)
aedata, sig = getappterminology(fullname, verbose=verbose)
if not creatorsignature:
creatorsignature = sig
@@ -202,15 +202,15 @@
else:
if launched:
if verbose:
- print >>verbose, "Launched", fullname
+ print("Launched", fullname, file=verbose)
raw = aetools.unpack(aedescobj)
if not raw:
if verbose:
- print >>verbose, 'Unpack returned empty value:', raw
+ print('Unpack returned empty value:', raw, file=verbose)
return
if not raw[0].data:
if verbose:
- print >>verbose, 'Unpack returned value without data:', raw
+ print('Unpack returned value without data:', raw, file=verbose)
return
aedata = raw[0]
aete = decode(aedata.data, verbose)
@@ -246,7 +246,7 @@
talker._start()
except (MacOS.Error, aetools.Error) as arg:
if verbose:
- print >>verbose, 'Warning: start() failed, continuing anyway:', arg
+ print('Warning: start() failed, continuing anyway:', arg, file=verbose)
reply = talker.send("ascr", "gdte")
#reply2 = talker.send("ascr", "gdut")
# Now pick the bits out of the return that we need.
@@ -344,9 +344,9 @@
return list
def alt_generic(what, f, *args):
- print "generic", repr(what), args
+ print("generic", repr(what), args)
res = vageneric(what, f, args)
- print '->', repr(res)
+ print('->', repr(res))
return res
def generic(what, f, *args):
@@ -940,14 +940,14 @@
for mapper in self.othernamemappers:
if mapper.hasname(name) and mapper.modulename != self.modulename:
if self.verbose:
- print >>self.verbose, "Duplicate Python identifier:", name, self.modulename, mapper.modulename
+ print("Duplicate Python identifier:", name, self.modulename, mapper.modulename, file=self.verbose)
return True
return False
def askdefinitionmodule(self, type, code):
if not self.can_interact:
if self.verbose:
- print >>self.verbose, "** No definition for %s '%s' found" % (type, code)
+ print("** No definition for %s '%s' found" % (type, code), file=self.verbose)
return None
path = EasyDialogs.AskFileForSave(message='Where is %s %s declared?'%(type, code))
if not path: return
@@ -1018,7 +1018,7 @@
if self.fp and (elements or len(properties) > 1 or (len(properties) == 1 and
properties[0][1] != 'c@#!')):
if self.verbose:
- print >>self.verbose, '** Skip multiple %s of %s (code %r)' % (cname, self.namemappers[0].findcodename('class', code)[0], code)
+ print('** Skip multiple %s of %s (code %r)' % (cname, self.namemappers[0].findcodename('class', code)[0], code), file=self.verbose)
raise RuntimeError, "About to skip non-empty class"
return
plist = []
Modified: python/branches/p3yk-noslice/Lib/plat-mac/ic.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/ic.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/ic.py Fri Feb 23 18:29:35 2007
@@ -94,7 +94,7 @@
chr(0) + _code_default(name)
def _code_boolean(data, key):
- print 'XXXX boolean:', repr(data)
+ print('XXXX boolean:', repr(data))
return chr(data)
def _code_text(data, key):
@@ -258,7 +258,7 @@
v = ic[k]
except error:
v = '????'
- print k, '\t', v
+ print(k, '\t', v)
sys.exit(1)
if __name__ == '__main__':
Modified: python/branches/p3yk-noslice/Lib/plat-mac/macfs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/macfs.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/macfs.py Fri Feb 23 18:29:35 2007
@@ -28,24 +28,24 @@
# Find the epoch conversion for file dates in a way that works on OS9 and OSX
import time
if time.gmtime(0)[0] == 1970:
- _EPOCHCONVERT = -((1970-1904)*365 + 17) * (24*60*60) + 0x100000000L
+ _EPOCHCONVERT = -((1970-1904)*365 + 17) * (24*60*60) + 0x100000000
def _utc2time(utc):
t = utc[1] + _EPOCHCONVERT
return int(t)
def _time2utc(t):
t = int(t) - _EPOCHCONVERT
if t < -0x7fffffff:
- t = t + 0x10000000L
+ t = t + 0x10000000
return (0, int(t), 0)
else:
def _utc2time(utc):
t = utc[1]
if t < 0:
- t = t + 0x100000000L
+ t = t + 0x100000000
return t
def _time2utc(t):
if t > 0x7fffffff:
- t = t - 0x100000000L
+ t = t - 0x100000000
return (0, int(t), 0)
# The old name of the error object:
Modified: python/branches/p3yk-noslice/Lib/plat-mac/macresource.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/macresource.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/macresource.py Fri Feb 23 18:29:35 2007
@@ -140,7 +140,7 @@
import tempfile
fd, newpathname = tempfile.mkstemp(".rsrc")
if verbose:
- print 'Decoding', pathname, 'to', newpathname
+ print('Decoding', pathname, 'to', newpathname)
import applesingle
applesingle.decode(pathname, newpathname, resonly=1)
return newpathname
Modified: python/branches/p3yk-noslice/Lib/plat-mac/pimp.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/pimp.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/pimp.py Fri Feb 23 18:29:35 2007
@@ -148,7 +148,7 @@
keepgoing = True
download = urllib2.urlopen(url)
if "content-length" in download.headers:
- length = long(download.headers['content-length'])
+ length = int(download.headers['content-length'])
else:
length = -1
@@ -229,7 +229,7 @@
#print 'SKIP', member.name
else:
member.name = newprefix + member.name[len(oldprefix):]
- print ' ', member.name
+ print(' ', member.name)
break
elif oldprefix2 and member.name[:len(oldprefix2)] == oldprefix2:
if newprefix is None:
@@ -1020,8 +1020,8 @@
elif mode =='list':
if not args:
args = db.listnames()
- print "%-20.20s\t%s" % ("Package", "Description")
- print
+ print("%-20.20s\t%s" % ("Package", "Description"))
+ print()
for pkgname in args:
pkg = db.find(pkgname)
if pkg:
@@ -1029,21 +1029,21 @@
pkgname = pkg.fullname()
else:
description = 'Error: no such package'
- print "%-20.20s\t%s" % (pkgname, description)
+ print("%-20.20s\t%s" % (pkgname, description))
if verbose:
- print "\tHome page:\t", pkg.homepage()
+ print("\tHome page:\t", pkg.homepage())
try:
- print "\tDownload URL:\t", pkg.downloadURL()
+ print("\tDownload URL:\t", pkg.downloadURL())
except KeyError:
pass
description = pkg.description()
description = '\n\t\t\t\t\t'.join(description.splitlines())
- print "\tDescription:\t%s" % description
+ print("\tDescription:\t%s" % description)
elif mode =='status':
if not args:
args = db.listnames()
- print "%-20.20s\t%s\t%s" % ("Package", "Installed", "Message")
- print
+ print("%-20.20s\t%s\t%s" % ("Package", "Installed", "Message"))
+ print()
for pkgname in args:
pkg = db.find(pkgname)
if pkg:
@@ -1052,7 +1052,7 @@
else:
status = 'error'
msg = 'No such package'
- print "%-20.20s\t%-9.9s\t%s" % (pkgname, status, msg)
+ print("%-20.20s\t%-9.9s\t%s" % (pkgname, status, msg))
if verbose and status == "no":
prereq = pkg.prerequisites()
for pkg, msg in prereq:
@@ -1060,22 +1060,22 @@
pkg = ''
else:
pkg = pkg.fullname()
- print "%-20.20s\tRequirement: %s %s" % ("", pkg, msg)
+ print("%-20.20s\tRequirement: %s %s" % ("", pkg, msg))
elif mode == 'install':
if not args:
- print 'Please specify packages to install'
+ print('Please specify packages to install')
sys.exit(1)
inst = PimpInstaller(db)
for pkgname in args:
pkg = db.find(pkgname)
if not pkg:
- print '%s: No such package' % pkgname
+ print('%s: No such package' % pkgname)
continue
list, messages = inst.prepareInstall(pkg, force)
if messages and not force:
- print "%s: Not installed:" % pkgname
+ print("%s: Not installed:" % pkgname)
for m in messages:
- print "\t", m
+ print("\t", m)
else:
if verbose:
output = sys.stdout
@@ -1083,26 +1083,26 @@
output = None
messages = inst.install(list, output)
if messages:
- print "%s: Not installed:" % pkgname
+ print("%s: Not installed:" % pkgname)
for m in messages:
- print "\t", m
+ print("\t", m)
def main():
"""Minimal commandline tool to drive pimp."""
import getopt
def _help():
- print "Usage: pimp [options] -s [package ...] List installed status"
- print " pimp [options] -l [package ...] Show package information"
- print " pimp [options] -i package ... Install packages"
- print " pimp -d Dump database to stdout"
- print " pimp -V Print version number"
- print "Options:"
- print " -v Verbose"
- print " -f Force installation"
- print " -D dir Set destination directory"
- print " (default: %s)" % DEFAULT_INSTALLDIR
- print " -u url URL for database"
+ print("Usage: pimp [options] -s [package ...] List installed status")
+ print(" pimp [options] -l [package ...] Show package information")
+ print(" pimp [options] -i package ... Install packages")
+ print(" pimp -d Dump database to stdout")
+ print(" pimp -V Print version number")
+ print("Options:")
+ print(" -v Verbose")
+ print(" -f Force installation")
+ print(" -D dir Set destination directory")
+ print(" (default: %s)" % DEFAULT_INSTALLDIR)
+ print(" -u url URL for database")
sys.exit(1)
class _Watcher:
@@ -1152,7 +1152,7 @@
if not mode:
_help()
if mode == 'version':
- print 'Pimp version %s; module name is %s' % (PIMP_VERSION, __name__)
+ print('Pimp version %s; module name is %s' % (PIMP_VERSION, __name__))
else:
_run(mode, verbose, force, args, prefargs, watcher)
Modified: python/branches/p3yk-noslice/Lib/plat-mac/plistlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/plistlib.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/plistlib.py Fri Feb 23 18:29:35 2007
@@ -268,8 +268,7 @@
def writeDict(self, d):
self.beginElement("dict")
- items = d.items()
- items.sort()
+ items = sorted(d.items())
for key, value in items:
if not isinstance(key, (str, unicode)):
raise TypeError("keys must be strings")
Modified: python/branches/p3yk-noslice/Lib/plat-mac/videoreader.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-mac/videoreader.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-mac/videoreader.py Fri Feb 23 18:29:35 2007
@@ -272,8 +272,8 @@
fname = 'frame%04.4d.jpg'%num
num = num+1
pname = os.path.join(dstdir, fname)
- if not img: print 'Not',
- print 'Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data))
+ if not img: print('Not', end=' ')
+ print('Writing %s, size %dx%d, %d bytes'%(fname, imgw, imgh, len(data)))
if img:
wrt = img.writer(imgfmt, pname)
wrt.width = imgw
@@ -282,9 +282,9 @@
timestamp, data = rdr.ReadVideo()
MacOS.SetCreatorAndType(pname, 'ogle', 'JPEG')
if num > 20:
- print 'stopping at 20 frames so your disk does not fill up:-)'
+ print('stopping at 20 frames so your disk does not fill up:-)')
break
- print 'Total frames:', num
+ print('Total frames:', num)
if __name__ == '__main__':
_test()
Modified: python/branches/p3yk-noslice/Lib/plat-os2emx/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-os2emx/IN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-os2emx/IN.py Fri Feb 23 18:29:35 2007
@@ -28,33 +28,33 @@
IPPROTO_MAX = 256
IPPORT_RESERVED = 1024
IPPORT_USERRESERVED = 5000
-def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0)
+def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0)
IN_CLASSA_NET = 0xff000000
IN_CLASSA_NSHIFT = 24
IN_CLASSA_HOST = 0x00ffffff
IN_CLASSA_MAX = 128
-def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000)
+def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000)
IN_CLASSB_NET = 0xffff0000
IN_CLASSB_NSHIFT = 16
IN_CLASSB_HOST = 0x0000ffff
IN_CLASSB_MAX = 65536
-def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000)
+def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000)
IN_CLASSC_NET = 0xffffff00
IN_CLASSC_NSHIFT = 8
IN_CLASSC_HOST = 0x000000ff
-def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000)
+def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000)
IN_CLASSD_NET = 0xf0000000
IN_CLASSD_NSHIFT = 28
IN_CLASSD_HOST = 0x0fffffff
def IN_MULTICAST(i): return IN_CLASSD(i)
-def IN_EXPERIMENTAL(i): return (((long)(i) & 0xe0000000) == 0xe0000000)
+def IN_EXPERIMENTAL(i): return (((int)(i) & 0xe0000000) == 0xe0000000)
-def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000)
+def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000)
INADDR_ANY = 0x00000000
INADDR_LOOPBACK = 0x7f000001
Modified: python/branches/p3yk-noslice/Lib/plat-os2emx/_emx_link.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-os2emx/_emx_link.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-os2emx/_emx_link.py Fri Feb 23 18:29:35 2007
@@ -74,6 +74,6 @@
try:
link(sys.argv[1], sys.argv[2])
except IndexError:
- print 'Usage: emx_link <source> <target>'
+ print('Usage: emx_link <source> <target>')
except OSError:
- print 'emx_link: %s' % str(sys.exc_info()[1])
+ print('emx_link: %s' % str(sys.exc_info()[1]))
Modified: python/branches/p3yk-noslice/Lib/plat-riscos/rourl2path.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-riscos/rourl2path.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-riscos/rourl2path.py Fri Feb 23 18:29:35 2007
@@ -60,12 +60,12 @@
"/foo/bar/index.html",
"/foo/bar/",
"/"]:
- print '%r -> %r' % (url, url2pathname(url))
- print "*******************************************************"
+ print('%r -> %r' % (url, url2pathname(url)))
+ print("*******************************************************")
for path in ["SCSI::SCSI4.$.Anwendung",
"PythonApp:Lib",
"PythonApp:Lib.rourl2path/py"]:
- print '%r -> %r' % (path, pathname2url(path))
+ print('%r -> %r' % (path, pathname2url(path)))
if __name__ == '__main__':
test()
Modified: python/branches/p3yk-noslice/Lib/plat-sunos5/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-sunos5/IN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-sunos5/IN.py Fri Feb 23 18:29:35 2007
@@ -42,7 +42,7 @@
_LARGEFILE_SOURCE = 1
_FILE_OFFSET_BITS = 64
_FILE_OFFSET_BITS = 32
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
_POSIX_PTHREAD_SEMANTICS = 1
_XOPEN_VERSION = 500
_XOPEN_VERSION = 4
@@ -95,10 +95,10 @@
NGROUPS_UMAX = 32
NGROUPS_MAX_DEFAULT = 16
NZERO = 20
-NULL = 0L
+NULL = 0
NULL = 0
CMASK = 022
-CDLIMIT = (1L<<11)
+CDLIMIT = (1<<11)
NBPS = 0x20000
NBPSCTR = 512
UBSIZE = 512
@@ -117,9 +117,9 @@
DEV_BSHIFT = 9
MAXFRAG = 8
MAXOFF32_T = 0x7fffffff
-MAXOFF_T = 0x7fffffffffffffffl
-MAXOFFSET_T = 0x7fffffffffffffffl
-MAXOFF_T = 0x7fffffffl
+MAXOFF_T = 0x7fffffffffffffff
+MAXOFFSET_T = 0x7fffffffffffffff
+MAXOFF_T = 0x7fffffff
MAXOFFSET_T = 0x7fffffff
def btodb(bytes): return \
@@ -312,9 +312,9 @@
_PC_SYNC_IO = 12
_PC_FILESIZEBITS = 67
_PC_LAST = 67
-_POSIX_VERSION = 199506L
-_POSIX2_VERSION = 199209L
-_POSIX2_C_VERSION = 199209L
+_POSIX_VERSION = 199506
+_POSIX2_VERSION = 199209
+_POSIX2_C_VERSION = 199209
_XOPEN_XCU_VERSION = 4
_XOPEN_REALTIME = 1
_XOPEN_ENH_I18N = 1
@@ -431,7 +431,7 @@
from TYPES import *
# Included from iso/time_iso.h
-NULL = 0L
+NULL = 0
NULL = 0
CLOCKS_PER_SEC = 1000000
@@ -869,9 +869,9 @@
RLIMIT_VMEM = 6
RLIMIT_AS = RLIMIT_VMEM
RLIM_NLIMITS = 7
-RLIM_INFINITY = (-3l)
-RLIM_SAVED_MAX = (-2l)
-RLIM_SAVED_CUR = (-1l)
+RLIM_INFINITY = (-3)
+RLIM_SAVED_MAX = (-2)
+RLIM_SAVED_CUR = (-1)
RLIM_INFINITY = 0x7fffffff
RLIM_SAVED_MAX = 0x7ffffffe
RLIM_SAVED_CUR = 0x7ffffffd
@@ -1063,7 +1063,7 @@
POLLCLOSED = 0x8000
# Included from sys/strmdep.h
-def str_aligned(X): return (((ulong_t)(X) & (sizeof (long) - 1)) == 0)
+def str_aligned(X): return (((ulong_t)(X) & (sizeof (int) - 1)) == 0)
# Included from sys/strft.h
Modified: python/branches/p3yk-noslice/Lib/plat-sunos5/STROPTS.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-sunos5/STROPTS.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-sunos5/STROPTS.py Fri Feb 23 18:29:35 2007
@@ -42,7 +42,7 @@
_LARGEFILE_SOURCE = 1
_FILE_OFFSET_BITS = 64
_FILE_OFFSET_BITS = 32
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
_POSIX_PTHREAD_SEMANTICS = 1
_XOPEN_VERSION = 500
_XOPEN_VERSION = 4
@@ -92,10 +92,10 @@
NGROUPS_UMAX = 32
NGROUPS_MAX_DEFAULT = 16
NZERO = 20
-NULL = 0L
+NULL = 0
NULL = 0
CMASK = 022
-CDLIMIT = (1L<<11)
+CDLIMIT = (1<<11)
NBPS = 0x20000
NBPSCTR = 512
UBSIZE = 512
@@ -114,9 +114,9 @@
DEV_BSHIFT = 9
MAXFRAG = 8
MAXOFF32_T = 0x7fffffff
-MAXOFF_T = 0x7fffffffffffffffl
-MAXOFFSET_T = 0x7fffffffffffffffl
-MAXOFF_T = 0x7fffffffl
+MAXOFF_T = 0x7fffffffffffffff
+MAXOFFSET_T = 0x7fffffffffffffff
+MAXOFF_T = 0x7fffffff
MAXOFFSET_T = 0x7fffffff
def btodb(bytes): return \
@@ -309,9 +309,9 @@
_PC_SYNC_IO = 12
_PC_FILESIZEBITS = 67
_PC_LAST = 67
-_POSIX_VERSION = 199506L
-_POSIX2_VERSION = 199209L
-_POSIX2_C_VERSION = 199209L
+_POSIX_VERSION = 199506
+_POSIX2_VERSION = 199209
+_POSIX2_C_VERSION = 199209
_XOPEN_XCU_VERSION = 4
_XOPEN_REALTIME = 1
_XOPEN_ENH_I18N = 1
@@ -428,7 +428,7 @@
from TYPES import *
# Included from iso/time_iso.h
-NULL = 0L
+NULL = 0
NULL = 0
CLOCKS_PER_SEC = 1000000
@@ -872,9 +872,9 @@
RLIMIT_VMEM = 6
RLIMIT_AS = RLIMIT_VMEM
RLIM_NLIMITS = 7
-RLIM_INFINITY = (-3l)
-RLIM_SAVED_MAX = (-2l)
-RLIM_SAVED_CUR = (-1l)
+RLIM_INFINITY = (-3)
+RLIM_SAVED_MAX = (-2)
+RLIM_SAVED_CUR = (-1)
RLIM_INFINITY = 0x7fffffff
RLIM_SAVED_MAX = 0x7ffffffe
RLIM_SAVED_CUR = 0x7ffffffd
Modified: python/branches/p3yk-noslice/Lib/plat-sunos5/TYPES.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-sunos5/TYPES.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-sunos5/TYPES.py Fri Feb 23 18:29:35 2007
@@ -42,7 +42,7 @@
_LARGEFILE_SOURCE = 1
_FILE_OFFSET_BITS = 64
_FILE_OFFSET_BITS = 32
-_POSIX_C_SOURCE = 199506L
+_POSIX_C_SOURCE = 199506
_POSIX_PTHREAD_SEMANTICS = 1
_XOPEN_VERSION = 500
_XOPEN_VERSION = 4
@@ -216,10 +216,10 @@
USHRT_MAX = 65535
INT_MIN = (-2147483647-1)
INT_MAX = 2147483647
-LONG_MIN = (-9223372036854775807L-1L)
-LONG_MAX = 9223372036854775807L
-LONG_MIN = (-2147483647L-1L)
-LONG_MAX = 2147483647L
+LONG_MIN = (-9223372036854775807-1)
+LONG_MAX = 9223372036854775807
+LONG_MIN = (-2147483647-1)
+LONG_MAX = 2147483647
P_MYID = (-1)
# Included from sys/select.h
@@ -303,7 +303,7 @@
from TYPES import *
# Included from iso/time_iso.h
-NULL = 0L
+NULL = 0
NULL = 0
CLOCKS_PER_SEC = 1000000
FD_SETSIZE = 65536
Modified: python/branches/p3yk-noslice/Lib/plat-unixware7/IN.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-unixware7/IN.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-unixware7/IN.py Fri Feb 23 18:29:35 2007
@@ -1,33 +1,33 @@
# Generated by h2py from /usr/include/netinet/in.h
# Included from netinet/in_f.h
-def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0)
+def IN_CLASSA(i): return (((int)(i) & 0x80000000) == 0)
IN_CLASSA_NET = 0xff000000
IN_CLASSA_NSHIFT = 24
IN_CLASSA_HOST = 0x00ffffff
IN_CLASSA_MAX = 128
-def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000)
+def IN_CLASSB(i): return (((int)(i) & 0xc0000000) == 0x80000000)
IN_CLASSB_NET = 0xffff0000
IN_CLASSB_NSHIFT = 16
IN_CLASSB_HOST = 0x0000ffff
IN_CLASSB_MAX = 65536
-def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000)
+def IN_CLASSC(i): return (((int)(i) & 0xe0000000) == 0xc0000000)
IN_CLASSC_NET = 0xffffff00
IN_CLASSC_NSHIFT = 8
IN_CLASSC_HOST = 0x000000ff
-def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000)
+def IN_CLASSD(i): return (((int)(i) & 0xf0000000) == 0xe0000000)
IN_CLASSD_NET = 0xf0000000
IN_CLASSD_NSHIFT = 28
IN_CLASSD_HOST = 0x0fffffff
def IN_MULTICAST(i): return IN_CLASSD(i)
-def IN_EXPERIMENTAL(i): return (((long)(i) & 0xe0000000) == 0xe0000000)
+def IN_EXPERIMENTAL(i): return (((int)(i) & 0xe0000000) == 0xe0000000)
-def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000)
+def IN_BADCLASS(i): return (((int)(i) & 0xf0000000) == 0xf0000000)
INADDR_ANY = 0x00000000
INADDR_LOOPBACK = 0x7f000001
@@ -330,7 +330,7 @@
MSG_EOR = 0x30
MSG_WAITALL = 0x20
MSG_MAXIOVLEN = 16
-def OPTLEN(x): return ((((x) + sizeof(long) - 1) / sizeof(long)) * sizeof(long))
+def OPTLEN(x): return ((((x) + sizeof(int) - 1) / sizeof(int)) * sizeof(int))
GIARG = 0x1
CONTI = 0x2
@@ -715,7 +715,7 @@
STRHIGH = 5120
STRLOW = 1024
MAXIOCBSZ = 1024
-def straln(a): return (caddr_t)((long)(a) & ~(sizeof(int)-1))
+def straln(a): return (caddr_t)((int)(a) & ~(sizeof(int)-1))
IPM_ID = 200
ICMPM_ID = 201
Modified: python/branches/p3yk-noslice/Lib/plat-unixware7/STROPTS.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/plat-unixware7/STROPTS.py (original)
+++ python/branches/p3yk-noslice/Lib/plat-unixware7/STROPTS.py Fri Feb 23 18:29:35 2007
@@ -213,7 +213,7 @@
_PC_VDISABLE = 8
_PC_CHOWN_RESTRICTED = 9
_PC_FILESIZEBITS = 10
-_POSIX_VERSION = 199009L
+_POSIX_VERSION = 199009
_XOPEN_VERSION = 4
GF_PATH = "/etc/group"
PF_PATH = "/etc/passwd"
@@ -231,8 +231,8 @@
_XOPEN_UNIX = 1
_XOPEN_ENH_I18N = 1
_XOPEN_XPG4 = 1
-_POSIX2_C_VERSION = 199209L
-_POSIX2_VERSION = 199209L
+_POSIX2_C_VERSION = 199209
+_POSIX2_VERSION = 199209
_XOPEN_XCU_VERSION = 4
_POSIX_SEMAPHORES = 1
_POSIX_THREADS = 1
Modified: python/branches/p3yk-noslice/Lib/platform.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/platform.py (original)
+++ python/branches/p3yk-noslice/Lib/platform.py Fri Feb 23 18:29:35 2007
@@ -28,12 +28,15 @@
# Betancourt, Randall Hopper, Karl Putland, John Farrell, Greg
# Andruk, Just van Rossum, Thomas Heller, Mark R. Levinson, Mark
# Hammond, Bill Tutt, Hans Nowak, Uwe Zessin (OpenVMS support),
-# Colin Kong, Trent Mick, Guido van Rossum
+# Colin Kong, Trent Mick, Guido van Rossum, Anthony Baxter
#
# History:
#
# <see CVS and SVN checkin messages for history>
#
+# 1.0.6 - added linux_distribution()
+# 1.0.5 - fixed Java support to allow running the module on Jython
+# 1.0.4 - added IronPython support
# 1.0.3 - added normalization of Windows system name
# 1.0.2 - added more Windows support
# 1.0.1 - reformatted to make doc.py happy
@@ -88,7 +91,7 @@
__copyright__ = """
Copyright (c) 1999-2000, Marc-Andre Lemburg; mailto:mal at lemburg.com
- Copyright (c) 2000-2003, eGenix.com Software GmbH; mailto:info at egenix.com
+ Copyright (c) 2000-2007, eGenix.com Software GmbH; mailto:info at egenix.com
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee or royalty is hereby granted,
@@ -107,7 +110,7 @@
"""
-__version__ = '1.0.4'
+__version__ = '1.0.6'
import sys,string,os,re
@@ -136,6 +139,11 @@
The file is read and scanned in chunks of chunksize bytes.
"""
+ if hasattr(os.path, 'realpath'):
+ # Python 2.2 introduced os.path.realpath(); it is used
+ # here to work around problems with Cygwin not being
+ # able to open symlinks for reading
+ executable = os.path.realpath(executable)
f = open(executable,'rb')
binary = f.read(chunksize)
pos = 0
@@ -218,14 +226,69 @@
return distname,version,id
_release_filename = re.compile(r'(\w+)[-_](release|version)')
-_release_version = re.compile(r'([\d.]+)[^(]*(?:\((.+)\))?')
+_lsb_release_version = re.compile(r'(.+)'
+ ' release '
+ '([\d.]+)'
+ '[^(]*(?:\((.+)\))?')
+_release_version = re.compile(r'([^0-9]+)'
+ '(?: release )?'
+ '([\d.]+)'
+ '[^(]*(?:\((.+)\))?')
+
+# See also http://www.novell.com/coolsolutions/feature/11251.html
+# and http://linuxmafia.com/faq/Admin/release-files.html
+# and http://data.linux-ntfs.org/rpm/whichrpm
+# and http://www.die.net/doc/linux/man/man1/lsb_release.1.html
+
+_supported_dists = ('SuSE', 'debian', 'fedora', 'redhat', 'centos',
+ 'mandrake', 'rocks', 'slackware', 'yellowdog',
+ 'gentoo', 'UnitedLinux')
+
+def _parse_release_file(firstline):
+
+ # Parse the first line
+ m = _lsb_release_version.match(firstline)
+ if m is not None:
+ # LSB format: "distro release x.x (codename)"
+ return tuple(m.groups())
+
+ # Pre-LSB format: "distro x.x (codename)"
+ m = _release_version.match(firstline)
+ if m is not None:
+ return tuple(m.groups())
+
+ # Unkown format... take the first two words
+ l = string.split(string.strip(firstline))
+ if l:
+ version = l[0]
+ if len(l) > 1:
+ id = l[1]
+ else:
+ id = ''
+ return '', version, id
-# Note:In supported_dists below we need 'fedora' before 'redhat' as in
-# Fedora redhat-release is a link to fedora-release.
+def _test_parse_release_file():
-def dist(distname='',version='',id='',
+ for input, output in (
+ # Examples of release file contents:
+ ('SuSE Linux 9.3 (x86-64)', ('SuSE Linux ', '9.3', 'x86-64'))
+ ('SUSE LINUX 10.1 (X86-64)', ('SUSE LINUX ', '10.1', 'X86-64'))
+ ('SUSE LINUX 10.1 (i586)', ('SUSE LINUX ', '10.1', 'i586'))
+ ('Fedora Core release 5 (Bordeaux)', ('Fedora Core', '5', 'Bordeaux'))
+ ('Red Hat Linux release 8.0 (Psyche)', ('Red Hat Linux', '8.0', 'Psyche'))
+ ('Red Hat Linux release 9 (Shrike)', ('Red Hat Linux', '9', 'Shrike'))
+ ('Red Hat Enterprise Linux release 4 (Nahant)', ('Red Hat Enterprise Linux', '4', 'Nahant'))
+ ('CentOS release 4', ('CentOS', '4', None))
+ ('Rocks release 4.2.1 (Cydonia)', ('Rocks', '4.2.1', 'Cydonia'))
+ ):
+ parsed = _parse_release_file(input)
+ if parsed != output:
+ print((input, parsed))
- supported_dists=('SuSE', 'debian', 'fedora', 'redhat', 'mandrake')):
+def linux_distribution(distname='', version='', id='',
+
+ supported_dists=_supported_dists,
+ full_distribution_name=1):
""" Tries to determine the name of the Linux OS distribution name.
@@ -233,6 +296,15 @@
/etc and then reverts to _dist_try_harder() in case no
suitable files are found.
+ supported_dists may be given to define the set of Linux
+ distributions to look for. It defaults to a list of currently
+ supported Linux distributions identified by their release file
+ name.
+
+ If full_distribution_name is true (default), the full
+ distribution read from the OS is returned. Otherwise the short
+ name taken from supported_dists is used.
+
Returns a tuple (distname,version,id) which default to the
args given as parameters.
@@ -242,33 +314,50 @@
except os.error:
# Probably not a Unix system
return distname,version,id
+ etc.sort()
for file in etc:
m = _release_filename.match(file)
- if m:
+ if m is not None:
_distname,dummy = m.groups()
if _distname in supported_dists:
distname = _distname
break
else:
return _dist_try_harder(distname,version,id)
- f = open('/etc/'+file,'r')
+
+ # Read the first line
+ f = open('/etc/'+file, 'r')
firstline = f.readline()
f.close()
- m = _release_version.search(firstline)
- if m:
- _version,_id = m.groups()
- if _version:
- version = _version
- if _id:
- id = _id
- else:
- # Unkown format... take the first two words
- l = string.split(string.strip(firstline))
- if l:
- version = l[0]
- if len(l) > 1:
- id = l[1]
- return distname,version,id
+ _distname, _version, _id = _parse_release_file(firstline)
+
+ if _distname and full_distribution_name:
+ distname = _distname
+ if _version:
+ version = _version
+ if _id:
+ id = _id
+ return distname, version, id
+
+# To maintain backwards compatibility:
+
+def dist(distname='',version='',id='',
+
+ supported_dists=_supported_dists):
+
+ """ Tries to determine the name of the Linux OS distribution name.
+
+ The function first looks for a distribution release file in
+ /etc and then reverts to _dist_try_harder() in case no
+ suitable files are found.
+
+ Returns a tuple (distname,version,id) which default to the
+ args given as parameters.
+
+ """
+ return linux_distribution(distname, version, id,
+ supported_dists=supported_dists,
+ full_distribution_name=0)
class _popen:
@@ -357,7 +446,7 @@
else:
return popen(cmd,mode,bufsize)
-def _norm_version(version,build=''):
+def _norm_version(version, build=''):
""" Normalize the version and build strings and return a single
version string using the format major.minor.build (or patchlevel).
@@ -378,7 +467,7 @@
'.*'
'Version ([\d.]+))')
-def _syscmd_ver(system='',release='',version='',
+def _syscmd_ver(system='', release='', version='',
supported_platforms=('win32','win16','dos','os2')):
@@ -418,7 +507,7 @@
# Parse the output
info = string.strip(info)
m = _ver_output.match(info)
- if m:
+ if m is not None:
system,release,version = m.groups()
# Strip trailing dots from version and release
if release[-1] == '.':
@@ -593,7 +682,7 @@
patch = (sysv & 0x000F)
release = '%s.%i.%i' % (_bcd2str(major),minor,patch)
if sysu:
- major = int((sysu & 0xFF000000L) >> 24)
+ major = int((sysu & 0xFF000000) >> 24)
minor = (sysu & 0x00F00000) >> 20
bugfix = (sysu & 0x000F0000) >> 16
stage = (sysu & 0x0000FF00) >> 8
@@ -615,8 +704,11 @@
from java.lang import System
try:
- return System.getProperty(name)
- except:
+ value = System.getProperty(name)
+ if value is None:
+ return default
+ return value
+ except AttributeError:
return default
def java_ver(release='',vendor='',vminfo=('','',''),osinfo=('','','')):
@@ -637,20 +729,20 @@
except ImportError:
return release,vendor,vminfo,osinfo
- vendor = _java_getprop('java.vendor',vendor)
- release = _java_getprop('java.version',release)
- vm_name,vm_release,vm_vendor = vminfo
- vm_name = _java_getprop('java.vm.name',vm_name)
- vm_vendor = _java_getprop('java.vm.vendor',vm_vendor)
- vm_release = _java_getprop('java.vm.version',vm_release)
- vminfo = vm_name,vm_release,vm_vendor
- os_name,os_version,os_arch = osinfo
- os_arch = _java_getprop('java.os.arch',os_arch)
- os_name = _java_getprop('java.os.name',os_name)
- os_version = _java_getprop('java.os.version',os_version)
- osinfo = os_name,os_version,os_arch
+ vendor = _java_getprop('java.vendor', vendor)
+ release = _java_getprop('java.version', release)
+ vm_name, vm_release, vm_vendor = vminfo
+ vm_name = _java_getprop('java.vm.name', vm_name)
+ vm_vendor = _java_getprop('java.vm.vendor', vm_vendor)
+ vm_release = _java_getprop('java.vm.version', vm_release)
+ vminfo = vm_name, vm_release, vm_vendor
+ os_name, os_version, os_arch = osinfo
+ os_arch = _java_getprop('java.os.arch', os_arch)
+ os_name = _java_getprop('java.os.name', os_name)
+ os_version = _java_getprop('java.os.version', os_version)
+ osinfo = os_name, os_version, os_arch
- return release,vendor,vminfo,osinfo
+ return release, vendor, vminfo, osinfo
### System name aliasing
@@ -716,7 +808,7 @@
# Format the platform string
platform = string.join(
map(string.strip,
- filter(len,args)),
+ filter(len, args)),
'-')
# Cleanup some possible filename obstacles...
@@ -871,7 +963,10 @@
bits = str(size*8) + 'bit'
# Get data from the 'file' system command
- output = _syscmd_file(executable,'')
+ if executable:
+ output = _syscmd_file(executable, '')
+ else:
+ output = ''
if not output and \
executable == sys.executable:
@@ -960,6 +1055,10 @@
release,version,csd,ptype = win32_ver()
if release and version:
use_syscmd_ver = 0
+ # XXX Should try to parse the PROCESSOR_* environment variables
+ # available on Win XP and later; see
+ # http://support.microsoft.com/kb/888731 and
+ # http://www.geocities.com/rick_lively/MANUALS/ENV/MSWIN/PROCESSI.HTM
# Try the 'ver' system command available on some
# platforms
@@ -1092,36 +1191,136 @@
### Various APIs for extracting information from sys.version
-_sys_version_parser = re.compile(r'([\w.+]+)\s*'
- '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
- '\[([^\]]+)\]?')
-_sys_version_cache = None
+_sys_version_parser = re.compile(
+ r'([\w.+]+)\s*'
+ '\(#?([^,]+),\s*([\w ]+),\s*([\w :]+)\)\s*'
+ '\[([^\]]+)\]?')
+
+_jython_sys_version_parser = re.compile(
+ r'([\d\.]+)')
+
+_ironpython_sys_version_parser = re.compile(
+ r'IronPython\s*'
+ '([\d\.]+)'
+ '(?: \(([\d\.]+)\))?'
+ ' on (.NET [\d\.]+)')
+
+_sys_version_cache = {}
-def _sys_version():
+def _sys_version(sys_version=None):
""" Returns a parsed version of Python's sys.version as tuple
- (version, buildno, builddate, compiler) referring to the Python
- version, build number, build date/time as string and the compiler
- identification string.
+ (name, version, branch, revision, buildno, builddate, compiler)
+ referring to the Python implementation name, version, branch,
+ revision, build number, build date/time as string and the compiler
+ identification string.
Note that unlike the Python sys.version, the returned value
for the Python version will always include the patchlevel (it
defaults to '.0').
+ The function returns empty strings for tuple entries that
+ cannot be determined.
+
+ sys_version may be given to parse an alternative version
+ string, e.g. if the version was read from a different Python
+ interpreter.
+
"""
- global _sys_version_cache
+ # Get the Python version
+ if sys_version is None:
+ sys_version = sys.version
+
+ # Try the cache first
+ result = _sys_version_cache.get(sys_version, None)
+ if result is not None:
+ return result
+
+ # Parse it
+ if sys_version[:10] == 'IronPython':
+ # IronPython
+ name = 'IronPython'
+ match = _ironpython_sys_version_parser.match(sys_version)
+ if match is None:
+ raise ValueError(
+ 'failed to parse IronPython sys.version: %s' %
+ repr(sys_version))
+ version, alt_version, compiler = match.groups()
+ branch = ''
+ revision = ''
+ buildno = ''
+ builddate = ''
+
+ elif sys.platform[:4] == 'java':
+ # Jython
+ name = 'Jython'
+ match = _jython_sys_version_parser.match(sys_version)
+ if match is None:
+ raise ValueError(
+ 'failed to parse Jython sys.version: %s' %
+ repr(sys_version))
+ version, = match.groups()
+ branch = ''
+ revision = ''
+ compiler = sys.platform
+ buildno = ''
+ builddate = ''
+
+ else:
+ # CPython
+ match = _sys_version_parser.match(sys_version)
+ if match is None:
+ raise ValueError(
+ 'failed to parse CPython sys.version: %s' %
+ repr(sys_version))
+ version, buildno, builddate, buildtime, compiler = \
+ match.groups()
+ if hasattr(sys, 'subversion'):
+ # sys.subversion was added in Python 2.5
+ name, branch, revision = sys.subversion
+ else:
+ name = 'CPython'
+ branch = ''
+ revision = ''
+ builddate = builddate + ' ' + buildtime
- if _sys_version_cache is not None:
- return _sys_version_cache
- version, buildno, builddate, buildtime, compiler = \
- _sys_version_parser.match(sys.version).groups()
- builddate = builddate + ' ' + buildtime
+ # Add the patchlevel version if missing
l = string.split(version, '.')
if len(l) == 2:
l.append('0')
version = string.join(l, '.')
- _sys_version_cache = (version, buildno, builddate, compiler)
- return _sys_version_cache
+
+ # Build and cache the result
+ result = (name, version, branch, revision, buildno, builddate, compiler)
+ _sys_version_cache[sys_version] = result
+ return result
+
+def _test_sys_version():
+
+ _sys_version_cache.clear()
+ for input, output in (
+ ('2.4.3 (#1, Jun 21 2006, 13:54:21) \n[GCC 3.3.4 (pre 3.3.5 20040809)]',
+ ('CPython', '2.4.3', '', '', '1', 'Jun 21 2006 13:54:21', 'GCC 3.3.4 (pre 3.3.5 20040809)')),
+ ('IronPython 1.0.60816 on .NET 2.0.50727.42',
+ ('IronPython', '1.0.60816', '', '', '', '', '.NET 2.0.50727.42')),
+ ('IronPython 1.0 (1.0.61005.1977) on .NET 2.0.50727.42',
+ ('IronPython', '1.0.0', '', '', '', '', '.NET 2.0.50727.42')),
+ ):
+ parsed = _sys_version(input)
+ if parsed != output:
+ print((input, parsed))
+
+def python_implementation():
+
+ """ Returns a string identifying the Python implementation.
+
+ Currently, the following implementations are identified:
+ 'CPython' (C implementation of Python),
+ 'IronPython' (.NET implementation of Python),
+ 'Jython' (Java implementation of Python).
+
+ """
+ return _sys_version()[0]
def python_version():
@@ -1131,7 +1330,9 @@
will always include the patchlevel (it defaults to 0).
"""
- return _sys_version()[0]
+ if hasattr(sys, 'version_info'):
+ return '%i.%i.%i' % sys.version_info[:3]
+ return _sys_version()[1]
def python_version_tuple():
@@ -1142,7 +1343,36 @@
will always include the patchlevel (it defaults to 0).
"""
- return string.split(_sys_version()[0], '.')
+ if hasattr(sys, 'version_info'):
+ return sys.version_info[:3]
+ return tuple(string.split(_sys_version()[1], '.'))
+
+def python_branch():
+
+ """ Returns a string identifying the Python implementation
+ branch.
+
+ For CPython this is the Subversion branch from which the
+ Python binary was built.
+
+ If not available, an empty string is returned.
+
+ """
+
+ return _sys_version()[2]
+
+def python_revision():
+
+ """ Returns a string identifying the Python implementation
+ revision.
+
+ For CPython this is the Subversion revision from which the
+ Python binary was built.
+
+ If not available, an empty string is returned.
+
+ """
+ return _sys_version()[3]
def python_build():
@@ -1150,7 +1380,7 @@
build number and date as strings.
"""
- return _sys_version()[1:3]
+ return _sys_version()[4:6]
def python_compiler():
@@ -1158,7 +1388,7 @@
Python.
"""
- return _sys_version()[3]
+ return _sys_version()[6]
### The Opus Magnum of platform strings :-)
@@ -1219,7 +1449,7 @@
elif system == 'Java':
# Java platforms
r,v,vminfo,(os_name,os_version,os_arch) = java_ver()
- if terse:
+ if terse or not os_name:
platform = _platform(system,release,version)
else:
platform = _platform(system,release,version,
@@ -1250,5 +1480,5 @@
# Default is to print the aliased verbose platform string
terse = ('terse' in sys.argv or '--terse' in sys.argv)
aliased = (not 'nonaliased' in sys.argv and not '--nonaliased' in sys.argv)
- print platform(aliased,terse)
+ print(platform(aliased,terse))
sys.exit(0)
Modified: python/branches/p3yk-noslice/Lib/popen2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/popen2.py (original)
+++ python/branches/p3yk-noslice/Lib/popen2.py Fri Feb 23 18:29:35 2007
@@ -213,14 +213,14 @@
# sometimes adding an extra newline at the start or the
# end. So we strip whitespace off both ends for comparison.
expected = teststr.strip()
- print "testing popen2..."
+ print("testing popen2...")
r, w = popen2(cmd)
w.write(teststr)
w.close()
got = r.read()
if got.strip() != expected:
raise ValueError("wrote %r read %r" % (teststr, got))
- print "testing popen3..."
+ print("testing popen3...")
try:
r, w, e = popen3([cmd])
except:
@@ -238,7 +238,7 @@
_cleanup()
if _active:
raise ValueError("_active not empty")
- print "All OK"
+ print("All OK")
if __name__ == '__main__':
_test()
Modified: python/branches/p3yk-noslice/Lib/poplib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/poplib.py (original)
+++ python/branches/p3yk-noslice/Lib/poplib.py Fri Feb 23 18:29:35 2007
@@ -100,14 +100,14 @@
def _putline(self, line):
- if self._debugging > 1: print '*put*', repr(line)
+ if self._debugging > 1: print('*put*', repr(line))
self.sock.sendall('%s%s' % (line, CRLF))
# Internal: send one command to the server (through _putline())
def _putcmd(self, line):
- if self._debugging: print '*cmd*', repr(line)
+ if self._debugging: print('*cmd*', repr(line))
self._putline(line)
@@ -117,7 +117,7 @@
def _getline(self):
line = self.file.readline()
- if self._debugging > 1: print '*get*', repr(line)
+ if self._debugging > 1: print('*get*', repr(line))
if not line: raise error_proto('-ERR EOF')
octets = len(line)
# server can send any combination of CR & LF
@@ -135,7 +135,7 @@
def _getresp(self):
resp, o = self._getline()
- if self._debugging > 1: print '*resp*', repr(resp)
+ if self._debugging > 1: print('*resp*', repr(resp))
c = resp[:1]
if c != '+':
raise error_proto(resp)
@@ -209,7 +209,7 @@
"""
retval = self._shortcmd('STAT')
rets = retval.split()
- if self._debugging: print '*stat*', repr(rets)
+ if self._debugging: print('*stat*', repr(rets))
numMessages = int(rets[1])
sizeMessages = int(rets[2])
return (numMessages, sizeMessages)
@@ -375,7 +375,7 @@
match = renewline.match(self.buffer)
line = match.group(0)
self.buffer = renewline.sub('' ,self.buffer, 1)
- if self._debugging > 1: print '*get*', repr(line)
+ if self._debugging > 1: print('*get*', repr(line))
octets = len(line)
if line[-2:] == CRLF:
@@ -385,7 +385,7 @@
return line[:-1], octets
def _putline(self, line):
- if self._debugging > 1: print '*put*', repr(line)
+ if self._debugging > 1: print('*put*', repr(line))
line += CRLF
bytes = len(line)
while bytes > 0:
@@ -409,15 +409,15 @@
if __name__ == "__main__":
import sys
a = POP3(sys.argv[1])
- print a.getwelcome()
+ print(a.getwelcome())
a.user(sys.argv[2])
a.pass_(sys.argv[3])
a.list()
(numMsgs, totalSize) = a.stat()
for i in range(1, numMsgs + 1):
(header, msg, octets) = a.retr(i)
- print "Message %d:" % i
+ print("Message %d:" % i)
for line in msg:
- print ' ' + line
- print '-----------------------'
+ print(' ' + line)
+ print('-----------------------')
a.quit()
Modified: python/branches/p3yk-noslice/Lib/pprint.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pprint.py (original)
+++ python/branches/p3yk-noslice/Lib/pprint.py Fri Feb 23 18:29:35 2007
@@ -141,8 +141,7 @@
if length:
context[objid] = 1
indent = indent + self._indent_per_level
- items = object.items()
- items.sort()
+ items = sorted(object.items())
key, ent = items[0]
rep = self._repr(key, context, level)
write(rep)
@@ -313,8 +312,8 @@
t2 = time.time()
p.pformat(object)
t3 = time.time()
- print "_safe_repr:", t2 - t1
- print "pformat:", t3 - t2
+ print("_safe_repr:", t2 - t1)
+ print("pformat:", t3 - t2)
if __name__ == "__main__":
_perfcheck()
Modified: python/branches/p3yk-noslice/Lib/profile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/profile.py (original)
+++ python/branches/p3yk-noslice/Lib/profile.py Fri Feb 23 18:29:35 2007
@@ -94,8 +94,8 @@
# Backwards compatibility.
def help():
- print "Documentation for the profile module can be found "
- print "in the Python Library Reference, section 'The Python Profiler'."
+ print("Documentation for the profile module can be found ")
+ print("in the Python Library Reference, section 'The Python Profiler'.")
if os.name == "mac":
import MacOS
@@ -439,10 +439,10 @@
def snapshot_stats(self):
self.stats = {}
- for func, (cc, ns, tt, ct, callers) in self.timings.iteritems():
+ for func, (cc, ns, tt, ct, callers) in self.timings.items():
callers = callers.copy()
nc = 0
- for callcnt in callers.itervalues():
+ for callcnt in callers.values():
nc += callcnt
self.stats[func] = cc, nc, tt, ct, callers
@@ -550,7 +550,7 @@
t1 = get_time()
elapsed_noprofile = t1 - t0
if verbose:
- print "elapsed time without profiling =", elapsed_noprofile
+ print("elapsed time without profiling =", elapsed_noprofile)
# elapsed_profile <- time f(m) takes with profiling. The difference
# is profiling overhead, only some of which the profiler subtracts
@@ -561,7 +561,7 @@
t1 = get_time()
elapsed_profile = t1 - t0
if verbose:
- print "elapsed time with profiling =", elapsed_profile
+ print("elapsed time with profiling =", elapsed_profile)
# reported_time <- "CPU seconds" the profiler charged to f and f1.
total_calls = 0.0
@@ -573,8 +573,8 @@
reported_time += tt
if verbose:
- print "'CPU seconds' profiler reported =", reported_time
- print "total # calls =", total_calls
+ print("'CPU seconds' profiler reported =", reported_time)
+ print("total # calls =", total_calls)
if total_calls != m + 1:
raise ValueError("internal error: total calls = %d" % total_calls)
@@ -584,12 +584,12 @@
# overhead per event.
mean = (reported_time - elapsed_noprofile) / 2.0 / total_calls
if verbose:
- print "mean stopwatch overhead per profile event =", mean
+ print("mean stopwatch overhead per profile event =", mean)
return mean
#****************************************************************************
def Stats(*args):
- print 'Report generating functions are in the "pstats" module\a'
+ print('Report generating functions are in the "pstats" module\a')
def main():
usage = "profile.py [-o output_file_path] [-s sort] scriptfile [arg] ..."
Modified: python/branches/p3yk-noslice/Lib/pstats.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pstats.py (original)
+++ python/branches/p3yk-noslice/Lib/pstats.py Fri Feb 23 18:29:35 2007
@@ -110,9 +110,9 @@
trouble = 0
finally:
if trouble:
- print >> self.stream, "Invalid timing data",
- if self.files: print >> self.stream, self.files[-1],
- print >> self.stream
+ print("Invalid timing data", end=' ', file=self.stream)
+ if self.files: print(self.files[-1], end=' ', file=self.stream)
+ print(file=self.stream)
def load_stats(self, arg):
if not arg: self.stats = {}
@@ -163,7 +163,7 @@
self.fcn_list = None
- for func, stat in other.stats.iteritems():
+ for func, stat in other.stats.items():
if func in self.stats:
old_func_stat = self.stats[func]
else:
@@ -199,7 +199,7 @@
if not self.sort_arg_dict:
self.sort_arg_dict = dict = {}
bad_list = {}
- for word, tup in self.sort_arg_dict_default.iteritems():
+ for word, tup in self.sort_arg_dict_default.items():
fragment = word
while fragment:
if not fragment:
@@ -234,7 +234,7 @@
connector = ", "
stats_list = []
- for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
+ for func, (cc, nc, tt, ct, callers) in self.stats.items():
stats_list.append((cc, nc, tt, ct) + func +
(func_std_string(func), func))
@@ -254,12 +254,12 @@
oldstats = self.stats
self.stats = newstats = {}
max_name_len = 0
- for func, (cc, nc, tt, ct, callers) in oldstats.iteritems():
+ for func, (cc, nc, tt, ct, callers) in oldstats.items():
newfunc = func_strip_path(func)
if len(func_std_string(newfunc)) > max_name_len:
max_name_len = len(func_std_string(newfunc))
newcallers = {}
- for func2, caller in callers.iteritems():
+ for func2, caller in callers.items():
newcallers[func_strip_path(func2)] = caller
if newfunc in newstats:
@@ -282,10 +282,10 @@
def calc_callees(self):
if self.all_callees: return
self.all_callees = all_callees = {}
- for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
+ for func, (cc, nc, tt, ct, callers) in self.stats.items():
if not func in all_callees:
all_callees[func] = {}
- for func2, caller in callers.iteritems():
+ for func2, caller in callers.items():
if not func2 in all_callees:
all_callees[func2] = {}
all_callees[func2][func] = caller
@@ -334,7 +334,7 @@
if not list:
return 0, list
- print >> self.stream, msg
+ print(msg, file=self.stream)
if count < len(self.stats):
width = 0
for func in list:
@@ -344,24 +344,24 @@
def print_stats(self, *amount):
for filename in self.files:
- print >> self.stream, filename
- if self.files: print >> self.stream
+ print(filename, file=self.stream)
+ if self.files: print(file=self.stream)
indent = ' ' * 8
for func in self.top_level:
- print >> self.stream, indent, func_get_function_name(func)
+ print(indent, func_get_function_name(func), file=self.stream)
- print >> self.stream, indent, self.total_calls, "function calls",
+ print(indent, self.total_calls, "function calls", end=' ', file=self.stream)
if self.total_calls != self.prim_calls:
- print >> self.stream, "(%d primitive calls)" % self.prim_calls,
- print >> self.stream, "in %.3f CPU seconds" % self.total_tt
- print >> self.stream
+ print("(%d primitive calls)" % self.prim_calls, end=' ', file=self.stream)
+ print("in %.3f CPU seconds" % self.total_tt, file=self.stream)
+ print(file=self.stream)
width, list = self.get_print_list(amount)
if list:
self.print_title()
for func in list:
self.print_line(func)
- print >> self.stream
- print >> self.stream
+ print(file=self.stream)
+ print(file=self.stream)
return self
def print_callees(self, *amount):
@@ -375,8 +375,8 @@
self.print_call_line(width, func, self.all_callees[func])
else:
self.print_call_line(width, func, {})
- print >> self.stream
- print >> self.stream
+ print(file=self.stream)
+ print(file=self.stream)
return self
def print_callers(self, *amount):
@@ -386,29 +386,28 @@
for func in list:
cc, nc, tt, ct, callers = self.stats[func]
self.print_call_line(width, func, callers, "<-")
- print >> self.stream
- print >> self.stream
+ print(file=self.stream)
+ print(file=self.stream)
return self
def print_call_heading(self, name_size, column_title):
- print >> self.stream, "Function ".ljust(name_size) + column_title
+ print("Function ".ljust(name_size) + column_title, file=self.stream)
# print sub-header only if we have new-style callers
subheader = False
- for cc, nc, tt, ct, callers in self.stats.itervalues():
+ for cc, nc, tt, ct, callers in self.stats.values():
if callers:
- value = callers.itervalues().next()
+ value = iter(callers.values()).next()
subheader = isinstance(value, tuple)
break
if subheader:
- print >> self.stream, " "*name_size + " ncalls tottime cumtime"
+ print(" "*name_size + " ncalls tottime cumtime", file=self.stream)
def print_call_line(self, name_size, source, call_dict, arrow="->"):
- print >> self.stream, func_std_string(source).ljust(name_size) + arrow,
+ print(func_std_string(source).ljust(name_size) + arrow, end=' ', file=self.stream)
if not call_dict:
- print >> self.stream
+ print(file=self.stream)
return
- clist = call_dict.keys()
- clist.sort()
+ clist = sorted(call_dict.keys())
indent = ""
for func in clist:
name = func_std_string(func)
@@ -425,30 +424,30 @@
else:
substats = '%s(%r) %s' % (name, value, f8(self.stats[func][3]))
left_width = name_size + 3
- print >> self.stream, indent*left_width + substats
+ print(indent*left_width + substats, file=self.stream)
indent = " "
def print_title(self):
- print >> self.stream, ' ncalls tottime percall cumtime percall',
- print >> self.stream, 'filename:lineno(function)'
+ print(' ncalls tottime percall cumtime percall', end=' ', file=self.stream)
+ print('filename:lineno(function)', file=self.stream)
def print_line(self, func): # hack : should print percentages
cc, nc, tt, ct, callers = self.stats[func]
c = str(nc)
if nc != cc:
c = c + '/' + str(cc)
- print >> self.stream, c.rjust(9),
- print >> self.stream, f8(tt),
+ print(c.rjust(9), end=' ', file=self.stream)
+ print(f8(tt), end=' ', file=self.stream)
if nc == 0:
- print >> self.stream, ' '*8,
+ print(' '*8, end=' ', file=self.stream)
else:
- print >> self.stream, f8(tt/nc),
- print >> self.stream, f8(ct),
+ print(f8(tt/nc), end=' ', file=self.stream)
+ print(f8(ct), end=' ', file=self.stream)
if cc == 0:
- print >> self.stream, ' '*8,
+ print(' '*8, end=' ', file=self.stream)
else:
- print >> self.stream, f8(ct/cc),
- print >> self.stream, func_std_string(func)
+ print(f8(ct/cc), end=' ', file=self.stream)
+ print(func_std_string(func), file=self.stream)
class TupleComp:
"""This class provides a generic function for comparing any two tuples.
@@ -508,9 +507,9 @@
def add_callers(target, source):
"""Combine two caller lists in a single list."""
new_callers = {}
- for func, caller in target.iteritems():
+ for func, caller in target.items():
new_callers[func] = caller
- for func, caller in source.iteritems():
+ for func, caller in source.items():
if func in new_callers:
new_callers[func] = caller + new_callers[func]
else:
@@ -520,7 +519,7 @@
def count_calls(callers):
"""Sum the caller statistics to get total number of calls received."""
nc = 0
- for calls in callers.itervalues():
+ for calls in callers.values():
nc += calls
return nc
@@ -565,7 +564,7 @@
try:
frac = float(term)
if frac > 1 or frac < 0:
- print >> self.stream, "Fraction argument must be in [0, 1]"
+ print("Fraction argument must be in [0, 1]", file=self.stream)
continue
processed.append(frac)
continue
@@ -575,93 +574,93 @@
if self.stats:
getattr(self.stats, fn)(*processed)
else:
- print >> self.stream, "No statistics object is loaded."
+ print("No statistics object is loaded.", file=self.stream)
return 0
def generic_help(self):
- print >> self.stream, "Arguments may be:"
- print >> self.stream, "* An integer maximum number of entries to print."
- print >> self.stream, "* A decimal fractional number between 0 and 1, controlling"
- print >> self.stream, " what fraction of selected entries to print."
- print >> self.stream, "* A regular expression; only entries with function names"
- print >> self.stream, " that match it are printed."
+ print("Arguments may be:", file=self.stream)
+ print("* An integer maximum number of entries to print.", file=self.stream)
+ print("* A decimal fractional number between 0 and 1, controlling", file=self.stream)
+ print(" what fraction of selected entries to print.", file=self.stream)
+ print("* A regular expression; only entries with function names", file=self.stream)
+ print(" that match it are printed.", file=self.stream)
def do_add(self, line):
self.stats.add(line)
return 0
def help_add(self):
- print >> self.stream, "Add profile info from given file to current statistics object."
+ print("Add profile info from given file to current statistics object.", file=self.stream)
def do_callees(self, line):
return self.generic('print_callees', line)
def help_callees(self):
- print >> self.stream, "Print callees statistics from the current stat object."
+ print("Print callees statistics from the current stat object.", file=self.stream)
self.generic_help()
def do_callers(self, line):
return self.generic('print_callers', line)
def help_callers(self):
- print >> self.stream, "Print callers statistics from the current stat object."
+ print("Print callers statistics from the current stat object.", file=self.stream)
self.generic_help()
def do_EOF(self, line):
- print >> self.stream, ""
+ print("", file=self.stream)
return 1
def help_EOF(self):
- print >> self.stream, "Leave the profile brower."
+ print("Leave the profile brower.", file=self.stream)
def do_quit(self, line):
return 1
def help_quit(self):
- print >> self.stream, "Leave the profile brower."
+ print("Leave the profile brower.", file=self.stream)
def do_read(self, line):
if line:
try:
self.stats = Stats(line)
except IOError as args:
- print >> self.stream, args[1]
+ print(args[1], file=self.stream)
return
self.prompt = line + "% "
elif len(self.prompt) > 2:
line = self.prompt[-2:]
else:
- print >> self.stream, "No statistics object is current -- cannot reload."
+ print("No statistics object is current -- cannot reload.", file=self.stream)
return 0
def help_read(self):
- print >> self.stream, "Read in profile data from a specified file."
+ print("Read in profile data from a specified file.", file=self.stream)
def do_reverse(self, line):
self.stats.reverse_order()
return 0
def help_reverse(self):
- print >> self.stream, "Reverse the sort order of the profiling report."
+ print("Reverse the sort order of the profiling report.", file=self.stream)
def do_sort(self, line):
abbrevs = self.stats.get_sort_arg_defs()
if line and not filter(lambda x,a=abbrevs: x not in a,line.split()):
self.stats.sort_stats(*line.split())
else:
- print >> self.stream, "Valid sort keys (unique prefixes are accepted):"
- for (key, value) in Stats.sort_arg_dict_default.iteritems():
- print >> self.stream, "%s -- %s" % (key, value[1])
+ print("Valid sort keys (unique prefixes are accepted):", file=self.stream)
+ for (key, value) in Stats.sort_arg_dict_default.items():
+ print("%s -- %s" % (key, value[1]), file=self.stream)
return 0
def help_sort(self):
- print >> self.stream, "Sort profile data according to specified keys."
- print >> self.stream, "(Typing `sort' without arguments lists valid keys.)"
+ print("Sort profile data according to specified keys.", file=self.stream)
+ print("(Typing `sort' without arguments lists valid keys.)", file=self.stream)
def complete_sort(self, text, *args):
return [a for a in Stats.sort_arg_dict_default if a.startswith(text)]
def do_stats(self, line):
return self.generic('print_stats', line)
def help_stats(self):
- print >> self.stream, "Print statistics from the current stat object."
+ print("Print statistics from the current stat object.", file=self.stream)
self.generic_help()
def do_strip(self, line):
self.stats.strip_dirs()
return 0
def help_strip(self):
- print >> self.stream, "Strip leading path information from filenames in the report."
+ print("Strip leading path information from filenames in the report.", file=self.stream)
def postcmd(self, stop, line):
if stop:
@@ -675,9 +674,9 @@
initprofile = None
try:
browser = ProfileBrowser(initprofile)
- print >> browser.stream, "Welcome to the profile statistics browser."
+ print("Welcome to the profile statistics browser.", file=browser.stream)
browser.cmdloop()
- print >> browser.stream, "Goodbye."
+ print("Goodbye.", file=browser.stream)
except KeyboardInterrupt:
pass
Modified: python/branches/p3yk-noslice/Lib/pty.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pty.py (original)
+++ python/branches/p3yk-noslice/Lib/pty.py Fri Feb 23 18:29:35 2007
@@ -123,7 +123,7 @@
os.close(tmp_fd)
else:
os.close(slave_fd)
-
+
# Parent and child process.
return pid, master_fd
Modified: python/branches/p3yk-noslice/Lib/py_compile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/py_compile.py (original)
+++ python/branches/p3yk-noslice/Lib/py_compile.py Fri Feb 23 18:29:35 2007
@@ -114,9 +114,9 @@
"""
f = open(file, 'U')
try:
- timestamp = long(os.fstat(f.fileno()).st_mtime)
+ timestamp = int(os.fstat(f.fileno()).st_mtime)
except AttributeError:
- timestamp = long(os.stat(file).st_mtime)
+ timestamp = int(os.stat(file).st_mtime)
codestring = f.read()
f.close()
if codestring and codestring[-1] != '\n':
Modified: python/branches/p3yk-noslice/Lib/pyclbr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pyclbr.py (original)
+++ python/branches/p3yk-noslice/Lib/pyclbr.py Fri Feb 23 18:29:35 2007
@@ -328,13 +328,13 @@
getattr(b, 'lineno', 0)))
for obj in objs:
if isinstance(obj, Class):
- print "class", obj.name, obj.super, obj.lineno
- methods = sorted(obj.methods.iteritems(), key=itemgetter(1))
+ print("class", obj.name, obj.super, obj.lineno)
+ methods = sorted(obj.methods.items(), key=itemgetter(1))
for name, lineno in methods:
if name != "__path__":
- print " def", name, lineno
+ print(" def", name, lineno)
elif isinstance(obj, Function):
- print "def", obj.name, obj.lineno
+ print("def", obj.name, obj.lineno)
if __name__ == "__main__":
_main()
Modified: python/branches/p3yk-noslice/Lib/pydoc.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/pydoc.py (original)
+++ python/branches/p3yk-noslice/Lib/pydoc.py Fri Feb 23 18:29:35 2007
@@ -1468,19 +1468,19 @@
desc += ' in ' + name[:name.rfind('.')]
elif module and module is not object:
desc += ' in module ' + module.__name__
- if not (inspect.ismodule(object) or
- inspect.isclass(object) or
- inspect.isroutine(object) or
- inspect.isgetsetdescriptor(object) or
- inspect.ismemberdescriptor(object) or
- isinstance(object, property)):
+ elif not (inspect.ismodule(object) or
+ inspect.isclass(object) or
+ inspect.isroutine(object) or
+ inspect.isgetsetdescriptor(object) or
+ inspect.ismemberdescriptor(object) or
+ isinstance(object, property)):
# If the passed object is a piece of data or an instance,
# document its available methods instead of its value.
object = type(object)
desc += ' object'
pager(title % desc + '\n\n' + text.document(object, name))
except (ImportError, ErrorDuringImport) as value:
- print value
+ print(value)
def writedoc(thing, forceload=0):
"""Write HTML documentation to a file in the current directory."""
@@ -1490,9 +1490,9 @@
file = open(name + '.html', 'w')
file.write(page)
file.close()
- print 'wrote', name + '.html'
+ print('wrote', name + '.html')
except (ImportError, ErrorDuringImport) as value:
- print value
+ print(value)
def writedocs(dir, pkgpath='', done=None):
"""Write out HTML documentation for all modules in a directory tree."""
@@ -1883,7 +1883,7 @@
def callback(path, modname, desc):
if modname[-9:] == '.__init__':
modname = modname[:-9] + ' (package)'
- print modname, desc and '- ' + desc
+ print(modname, desc and '- ' + desc)
try: import warnings
except ImportError: pass
else: warnings.filterwarnings('ignore') # ignore problems during import
@@ -2200,9 +2200,9 @@
except ValueError:
raise BadUsage
def ready(server):
- print 'pydoc server ready at %s' % server.url
+ print('pydoc server ready at %s' % server.url)
def stopped():
- print 'pydoc server stopped'
+ print('pydoc server stopped')
serve(port, ready, stopped)
return
if opt == '-w':
@@ -2211,7 +2211,7 @@
if not args: raise BadUsage
for arg in args:
if ispath(arg) and not os.path.exists(arg):
- print 'file %r does not exist' % arg
+ print('file %r does not exist' % arg)
break
try:
if ispath(arg) and os.path.isfile(arg):
@@ -2224,11 +2224,11 @@
else:
help.help(arg)
except ErrorDuringImport as value:
- print value
+ print(value)
except (getopt.error, BadUsage):
cmd = os.path.basename(sys.argv[0])
- print """pydoc - the Python documentation tool
+ print("""pydoc - the Python documentation tool
%s <name> ...
Show text documentation on something. <name> may be the name of a
@@ -2251,6 +2251,6 @@
Write out the HTML documentation for a module to a file in the current
directory. If <name> contains a '%s', it is treated as a filename; if
it names a directory, documentation is written for all the contents.
-""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
+""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep))
if __name__ == '__main__': cli()
Modified: python/branches/p3yk-noslice/Lib/quopri.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/quopri.py (original)
+++ python/branches/p3yk-noslice/Lib/quopri.py Fri Feb 23 18:29:35 2007
@@ -196,10 +196,10 @@
opts, args = getopt.getopt(sys.argv[1:], 'td')
except getopt.error as msg:
sys.stdout = sys.stderr
- print msg
- print "usage: quopri [-t | -d] [file] ..."
- print "-t: quote tabs"
- print "-d: decode; default encode"
+ print(msg)
+ print("usage: quopri [-t | -d] [file] ...")
+ print("-t: quote tabs")
+ print("-d: decode; default encode")
sys.exit(2)
deco = 0
tabs = 0
@@ -208,7 +208,7 @@
if o == '-d': deco = 1
if tabs and deco:
sys.stdout = sys.stderr
- print "-t and -d are mutually exclusive"
+ print("-t and -d are mutually exclusive")
sys.exit(2)
if not args: args = ['-']
sts = 0
Modified: python/branches/p3yk-noslice/Lib/random.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/random.py (original)
+++ python/branches/p3yk-noslice/Lib/random.py Fri Feb 23 18:29:35 2007
@@ -105,10 +105,10 @@
if a is None:
try:
- a = long(_hexlify(_urandom(16)), 16)
+ a = int(_hexlify(_urandom(16)), 16)
except NotImplementedError:
import time
- a = long(time.time() * 256) # use fractional seconds
+ a = int(time.time() * 256) # use fractional seconds
super(Random, self).seed(a)
self.gauss_next = None
@@ -145,7 +145,7 @@
## -------------------- integer methods -------------------
def randrange(self, start, stop=None, step=1, int=int, default=None,
- maxwidth=1L<<BPF):
+ maxwidth=1<<BPF):
"""Choose a random item from range(start, stop[, step]).
This fixes the problem with randint() which includes the
@@ -214,7 +214,7 @@
return self.randrange(a, b+1)
- def _randbelow(self, n, _log=_log, int=int, _maxwidth=1L<<BPF,
+ def _randbelow(self, n, _log=_log, int=int, _maxwidth=1<<BPF,
_Method=_MethodType, _BuiltinMethod=_BuiltinMethodType):
"""Return a random int in the range [0,n)
@@ -569,7 +569,7 @@
def betavariate(self, alpha, beta):
"""Beta distribution.
- Conditions on the parameters are alpha > -1 and beta} > -1.
+ Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1.
"""
@@ -626,12 +626,12 @@
if a is None:
try:
- a = long(_hexlify(_urandom(16)), 16)
+ a = int(_hexlify(_urandom(16)), 16)
except NotImplementedError:
import time
- a = long(time.time() * 256) # use fractional seconds
+ a = int(time.time() * 256) # use fractional seconds
- if not isinstance(a, (int, long)):
+ if not isinstance(a, (int, int)):
a = hash(a)
a, x = divmod(a, 30268)
@@ -721,7 +721,7 @@
if 0 == x == y == z:
# Initialize from current time
import time
- t = long(time.time() * 256)
+ t = int(time.time() * 256)
t = int((t&0xffffff) ^ (t>>24))
t, x = divmod(t, 256)
t, y = divmod(t, 256)
@@ -766,7 +766,7 @@
def random(self):
"""Get the next random number in the range [0.0, 1.0)."""
- return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
+ return (int(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
def getrandbits(self, k):
"""getrandbits(k) -> x. Generates a long int with k random bits."""
@@ -775,7 +775,7 @@
if k != int(k):
raise TypeError('number of bits should be an integer')
bytes = (k + 7) // 8 # bits / 8 and rounded up
- x = long(_hexlify(_urandom(bytes)), 16)
+ x = int(_hexlify(_urandom(bytes)), 16)
return x >> (bytes * 8 - k) # trim excess bits
def _stub(self, *args, **kwds):
@@ -792,7 +792,7 @@
def _test_generator(n, func, args):
import time
- print n, 'times', func.__name__
+ print(n, 'times', func.__name__)
total = 0.0
sqsum = 0.0
smallest = 1e10
@@ -805,11 +805,11 @@
smallest = min(x, smallest)
largest = max(x, largest)
t1 = time.time()
- print round(t1-t0, 3), 'sec,',
+ print(round(t1-t0, 3), 'sec,', end=' ')
avg = total/n
stddev = _sqrt(sqsum/n - avg*avg)
- print 'avg %g, stddev %g, min %g, max %g' % \
- (avg, stddev, smallest, largest)
+ print('avg %g, stddev %g, min %g, max %g' % \
+ (avg, stddev, smallest, largest))
def _test(N=2000):
Modified: python/branches/p3yk-noslice/Lib/repr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/repr.py (original)
+++ python/branches/p3yk-noslice/Lib/repr.py Fri Feb 23 18:29:35 2007
@@ -92,7 +92,7 @@
s = s[:i] + '...' + s[len(s)-j:]
return s
- def repr_long(self, x, level):
+ def repr_int(self, x, level):
s = __builtin__.repr(x) # XXX Hope this isn't too slow...
if len(s) > self.maxlong:
i = max(0, (self.maxlong-3)//2)
Modified: python/branches/p3yk-noslice/Lib/rexec.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/rexec.py (original)
+++ python/branches/p3yk-noslice/Lib/rexec.py Fri Feb 23 18:29:35 2007
@@ -552,7 +552,7 @@
try:
fp = open(args[0])
except IOError as msg:
- print "%s: can't open file %r" % (sys.argv[0], args[0])
+ print("%s: can't open file %r" % (sys.argv[0], args[0]))
return 1
if fp.isatty():
try:
Modified: python/branches/p3yk-noslice/Lib/rfc822.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/rfc822.py (original)
+++ python/branches/p3yk-noslice/Lib/rfc822.py Fri Feb 23 18:29:35 2007
@@ -437,18 +437,18 @@
def keys(self):
"""Get all of a message's header field names."""
- return self.dict.keys()
+ return list(self.dict.keys())
def values(self):
"""Get all of a message's header field values."""
- return self.dict.values()
+ return list(self.dict.values())
def items(self):
"""Get all of a message's headers.
Returns a list of name, value tuples.
"""
- return self.dict.items()
+ return list(self.dict.items())
def __str__(self):
return ''.join(self.headers)
@@ -850,6 +850,11 @@
if data[0][-1] in (',', '.') or data[0].lower() in _daynames:
# There's a dayname here. Skip it
del data[0]
+ else:
+ # no space after the "weekday,"?
+ i = data[0].rfind(',')
+ if i >= 0:
+ data[0] = data[0][i+1:]
if len(data) == 3: # RFC 850 date, deprecated
stuff = data[0].split('-')
if len(stuff) == 3:
@@ -967,32 +972,32 @@
if sys.argv[1:]: file = sys.argv[1]
f = open(file, 'r')
m = Message(f)
- print 'From:', m.getaddr('from')
- print 'To:', m.getaddrlist('to')
- print 'Subject:', m.getheader('subject')
- print 'Date:', m.getheader('date')
+ print('From:', m.getaddr('from'))
+ print('To:', m.getaddrlist('to'))
+ print('Subject:', m.getheader('subject'))
+ print('Date:', m.getheader('date'))
date = m.getdate_tz('date')
tz = date[-1]
date = time.localtime(mktime_tz(date))
if date:
- print 'ParsedDate:', time.asctime(date),
+ print('ParsedDate:', time.asctime(date), end=' ')
hhmmss = tz
hhmm, ss = divmod(hhmmss, 60)
hh, mm = divmod(hhmm, 60)
- print "%+03d%02d" % (hh, mm),
- if ss: print ".%02d" % ss,
- print
+ print("%+03d%02d" % (hh, mm), end=' ')
+ if ss: print(".%02d" % ss, end=' ')
+ print()
else:
- print 'ParsedDate:', None
+ print('ParsedDate:', None)
m.rewindbody()
n = 0
while f.readline():
n += 1
- print 'Lines:', n
- print '-'*70
- print 'len =', len(m)
- if 'Date' in m: print 'Date =', m['Date']
+ print('Lines:', n)
+ print('-'*70)
+ print('len =', len(m))
+ if 'Date' in m: print('Date =', m['Date'])
if 'X-Nonsense' in m: pass
- print 'keys =', m.keys()
- print 'values =', m.values()
- print 'items =', m.items()
+ print('keys =', m.keys())
+ print('values =', m.values())
+ print('items =', m.items())
Modified: python/branches/p3yk-noslice/Lib/robotparser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/robotparser.py (original)
+++ python/branches/p3yk-noslice/Lib/robotparser.py Fri Feb 23 18:29:35 2007
@@ -16,7 +16,7 @@
debug = 0
def _debug(msg):
- if debug: print msg
+ if debug: print(msg)
class RobotFileParser:
@@ -244,10 +244,10 @@
else:
ac = "access allowed"
if a!=b:
- print "failed"
+ print("failed")
else:
- print "ok (%s)" % ac
- print
+ print("ok (%s)" % ac)
+ print()
def _test():
global debug
Modified: python/branches/p3yk-noslice/Lib/runpy.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/runpy.py (original)
+++ python/branches/p3yk-noslice/Lib/runpy.py Fri Feb 23 18:29:35 2007
@@ -98,7 +98,7 @@
if __name__ == "__main__":
# Run the module specified as the next command line argument
if len(sys.argv) < 2:
- print >> sys.stderr, "No module specified for execution"
+ print("No module specified for execution", file=sys.stderr)
else:
del sys.argv[0] # Make the requested module sys.argv[0]
run_module(sys.argv[0], run_name="__main__", alter_sys=True)
Modified: python/branches/p3yk-noslice/Lib/sgmllib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sgmllib.py (original)
+++ python/branches/p3yk-noslice/Lib/sgmllib.py Fri Feb 23 18:29:35 2007
@@ -382,8 +382,8 @@
# Example -- report an unbalanced </...> tag.
def report_unbalanced(self, tag):
if self.verbose:
- print '*** Unbalanced </' + tag + '>'
- print '*** Stack:', self.stack
+ print('*** Unbalanced </' + tag + '>')
+ print('*** Stack:', self.stack)
def convert_charref(self, name):
"""Convert character reference, may be overridden."""
@@ -468,40 +468,40 @@
data = self.testdata
if data:
self.testdata = ""
- print 'data:', repr(data)
+ print('data:', repr(data))
def handle_comment(self, data):
self.flush()
r = repr(data)
if len(r) > 68:
r = r[:32] + '...' + r[-32:]
- print 'comment:', r
+ print('comment:', r)
def unknown_starttag(self, tag, attrs):
self.flush()
if not attrs:
- print 'start tag: <' + tag + '>'
+ print('start tag: <' + tag + '>')
else:
- print 'start tag: <' + tag,
+ print('start tag: <' + tag, end=' ')
for name, value in attrs:
- print name + '=' + '"' + value + '"',
- print '>'
+ print(name + '=' + '"' + value + '"', end=' ')
+ print('>')
def unknown_endtag(self, tag):
self.flush()
- print 'end tag: </' + tag + '>'
+ print('end tag: </' + tag + '>')
def unknown_entityref(self, ref):
self.flush()
- print '*** unknown entity ref: &' + ref + ';'
+ print('*** unknown entity ref: &' + ref + ';')
def unknown_charref(self, ref):
self.flush()
- print '*** unknown char ref: &#' + ref + ';'
+ print('*** unknown char ref: &#' + ref + ';')
def unknown_decl(self, data):
self.flush()
- print '*** unknown decl: [' + data + ']'
+ print('*** unknown decl: [' + data + ']')
def close(self):
SGMLParser.close(self)
@@ -531,7 +531,7 @@
try:
f = open(file, 'r')
except IOError as msg:
- print file, ":", msg
+ print(file, ":", msg)
sys.exit(1)
data = f.read()
Modified: python/branches/p3yk-noslice/Lib/shelve.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/shelve.py (original)
+++ python/branches/p3yk-noslice/Lib/shelve.py Fri Feb 23 18:29:35 2007
@@ -144,7 +144,7 @@
def sync(self):
if self.writeback and self.cache:
self.writeback = False
- for key, entry in self.cache.iteritems():
+ for key, entry in self.cache.items():
self[key] = entry
self.writeback = True
self.cache = {}
Modified: python/branches/p3yk-noslice/Lib/shlex.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/shlex.py (original)
+++ python/branches/p3yk-noslice/Lib/shlex.py Fri Feb 23 18:29:35 2007
@@ -53,13 +53,13 @@
self.filestack = deque()
self.source = None
if self.debug:
- print 'shlex: reading from %s, line %d' \
- % (self.instream, self.lineno)
+ print('shlex: reading from %s, line %d' \
+ % (self.instream, self.lineno))
def push_token(self, tok):
"Push a token onto the stack popped by the get_token method"
if self.debug >= 1:
- print "shlex: pushing token " + repr(tok)
+ print("shlex: pushing token " + repr(tok))
self.pushback.appendleft(tok)
def push_source(self, newstream, newfile=None):
@@ -72,17 +72,17 @@
self.lineno = 1
if self.debug:
if newfile is not None:
- print 'shlex: pushing to file %s' % (self.infile,)
+ print('shlex: pushing to file %s' % (self.infile,))
else:
- print 'shlex: pushing to stream %s' % (self.instream,)
+ print('shlex: pushing to stream %s' % (self.instream,))
def pop_source(self):
"Pop the input source stack."
self.instream.close()
(self.infile, self.instream, self.lineno) = self.filestack.popleft()
if self.debug:
- print 'shlex: popping to %s, line %d' \
- % (self.instream, self.lineno)
+ print('shlex: popping to %s, line %d' \
+ % (self.instream, self.lineno))
self.state = ' '
def get_token(self):
@@ -90,7 +90,7 @@
if self.pushback:
tok = self.pushback.popleft()
if self.debug >= 1:
- print "shlex: popping token " + repr(tok)
+ print("shlex: popping token " + repr(tok))
return tok
# No pushback. Get a token.
raw = self.read_token()
@@ -112,9 +112,9 @@
# Neither inclusion nor EOF
if self.debug >= 1:
if raw != self.eof:
- print "shlex: token=" + repr(raw)
+ print("shlex: token=" + repr(raw))
else:
- print "shlex: token=EOF"
+ print("shlex: token=EOF")
return raw
def read_token(self):
@@ -125,8 +125,8 @@
if nextchar == '\n':
self.lineno = self.lineno + 1
if self.debug >= 3:
- print "shlex: in state", repr(self.state), \
- "I see character:", repr(nextchar)
+ print("shlex: in state", repr(self.state), \
+ "I see character:", repr(nextchar))
if self.state is None:
self.token = '' # past end of file
break
@@ -136,7 +136,7 @@
break
elif nextchar in self.whitespace:
if self.debug >= 2:
- print "shlex: I see whitespace in whitespace state"
+ print("shlex: I see whitespace in whitespace state")
if self.token or (self.posix and quoted):
break # emit current token
else:
@@ -167,7 +167,7 @@
quoted = True
if not nextchar: # end of file
if self.debug >= 2:
- print "shlex: I see EOF in quotes state"
+ print("shlex: I see EOF in quotes state")
# XXX what error should be raised here?
raise ValueError, "No closing quotation"
if nextchar == self.state:
@@ -186,7 +186,7 @@
elif self.state in self.escape:
if not nextchar: # end of file
if self.debug >= 2:
- print "shlex: I see EOF in escape state"
+ print("shlex: I see EOF in escape state")
# XXX what error should be raised here?
raise ValueError, "No escaped character"
# In posix shells, only the quote itself or the escape
@@ -202,7 +202,7 @@
break
elif nextchar in self.whitespace:
if self.debug >= 2:
- print "shlex: I see whitespace in word state"
+ print("shlex: I see whitespace in word state")
self.state = ' '
if self.token or (self.posix and quoted):
break # emit current token
@@ -228,7 +228,7 @@
else:
self.pushback.appendleft(nextchar)
if self.debug >= 2:
- print "shlex: I see punctuation in word state"
+ print("shlex: I see punctuation in word state")
self.state = ' '
if self.token:
break # emit current token
@@ -240,9 +240,9 @@
result = None
if self.debug > 1:
if result:
- print "shlex: raw token=" + repr(result)
+ print("shlex: raw token=" + repr(result))
else:
- print "shlex: raw token=EOF"
+ print("shlex: raw token=EOF")
return result
def sourcehook(self, newfile):
@@ -287,6 +287,6 @@
while 1:
tt = lexer.get_token()
if tt:
- print "Token: " + repr(tt)
+ print("Token: " + repr(tt))
else:
break
Modified: python/branches/p3yk-noslice/Lib/shutil.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/shutil.py (original)
+++ python/branches/p3yk-noslice/Lib/shutil.py Fri Feb 23 18:29:35 2007
@@ -60,13 +60,15 @@
os.chmod(dst, mode)
def copystat(src, dst):
- """Copy all stat info (mode bits, atime and mtime) from src to dst"""
+ """Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
if hasattr(os, 'utime'):
os.utime(dst, (st.st_atime, st.st_mtime))
if hasattr(os, 'chmod'):
os.chmod(dst, mode)
+ if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
+ os.chflags(dst, st.st_flags)
def copy(src, dst):
Modified: python/branches/p3yk-noslice/Lib/site.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/site.py (original)
+++ python/branches/p3yk-noslice/Lib/site.py Fri Feb 23 18:29:35 2007
@@ -301,7 +301,7 @@
while 1:
try:
for i in range(lineno, lineno + self.MAXLINES):
- print self.__lines[i]
+ print(self.__lines[i])
except IndexError:
break
else:
@@ -424,10 +424,10 @@
main()
def _test():
- print "sys.path = ["
+ print("sys.path = [")
for dir in sys.path:
- print " %r," % (dir,)
- print "]"
+ print(" %r," % (dir,))
+ print("]")
if __name__ == '__main__':
_test()
Modified: python/branches/p3yk-noslice/Lib/smtpd.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/smtpd.py (original)
+++ python/branches/p3yk-noslice/Lib/smtpd.py Fri Feb 23 18:29:35 2007
@@ -98,9 +98,9 @@
def usage(code, msg=''):
- print >> sys.stderr, __doc__ % globals()
+ print(__doc__ % globals(), file=sys.stderr)
if msg:
- print >> sys.stderr, msg
+ print(msg, file=sys.stderr)
sys.exit(code)
@@ -122,7 +122,7 @@
self.__data = ''
self.__fqdn = socket.getfqdn()
self.__peer = conn.getpeername()
- print >> DEBUGSTREAM, 'Peer:', repr(self.__peer)
+ print('Peer:', repr(self.__peer), file=DEBUGSTREAM)
self.push('220 %s %s' % (self.__fqdn, __version__))
self.set_terminator('\r\n')
@@ -137,7 +137,7 @@
# Implementation of base class abstract method
def found_terminator(self):
line = EMPTYSTRING.join(self.__line)
- print >> DEBUGSTREAM, 'Data:', repr(line)
+ print('Data:', repr(line), file=DEBUGSTREAM)
self.__line = []
if self.__state == self.COMMAND:
if not line:
@@ -220,7 +220,7 @@
return address
def smtp_MAIL(self, arg):
- print >> DEBUGSTREAM, '===> MAIL', arg
+ print('===> MAIL', arg, file=DEBUGSTREAM)
address = self.__getaddr('FROM:', arg)
if not address:
self.push('501 Syntax: MAIL FROM:<address>')
@@ -229,11 +229,11 @@
self.push('503 Error: nested MAIL command')
return
self.__mailfrom = address
- print >> DEBUGSTREAM, 'sender:', self.__mailfrom
+ print('sender:', self.__mailfrom, file=DEBUGSTREAM)
self.push('250 Ok')
def smtp_RCPT(self, arg):
- print >> DEBUGSTREAM, '===> RCPT', arg
+ print('===> RCPT', arg, file=DEBUGSTREAM)
if not self.__mailfrom:
self.push('503 Error: need MAIL command')
return
@@ -242,7 +242,7 @@
self.push('501 Syntax: RCPT TO: <address>')
return
self.__rcpttos.append(address)
- print >> DEBUGSTREAM, 'recips:', self.__rcpttos
+ print('recips:', self.__rcpttos, file=DEBUGSTREAM)
self.push('250 Ok')
def smtp_RSET(self, arg):
@@ -279,14 +279,13 @@
self.set_reuse_addr()
self.bind(localaddr)
self.listen(5)
- print >> DEBUGSTREAM, \
- '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
+ print('%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % (
self.__class__.__name__, time.ctime(time.time()),
- localaddr, remoteaddr)
+ localaddr, remoteaddr), file=DEBUGSTREAM)
def handle_accept(self):
conn, addr = self.accept()
- print >> DEBUGSTREAM, 'Incoming connection from %s' % repr(addr)
+ print('Incoming connection from %s' % repr(addr), file=DEBUGSTREAM)
channel = SMTPChannel(self, conn, addr)
# API for "doing something useful with the message"
@@ -321,14 +320,14 @@
def process_message(self, peer, mailfrom, rcpttos, data):
inheaders = 1
lines = data.split('\n')
- print '---------- MESSAGE FOLLOWS ----------'
+ print('---------- MESSAGE FOLLOWS ----------')
for line in lines:
# headers first
if inheaders and not line:
- print 'X-Peer:', peer[0]
+ print('X-Peer:', peer[0])
inheaders = 0
- print line
- print '------------ END MESSAGE ------------'
+ print(line)
+ print('------------ END MESSAGE ------------')
@@ -345,7 +344,7 @@
data = NEWLINE.join(lines)
refused = self._deliver(mailfrom, rcpttos, data)
# TBD: what to do with refused addresses?
- print >> DEBUGSTREAM, 'we got some refusals:', refused
+ print('we got some refusals:', refused, file=DEBUGSTREAM)
def _deliver(self, mailfrom, rcpttos, data):
import smtplib
@@ -358,10 +357,10 @@
finally:
s.quit()
except smtplib.SMTPRecipientsRefused as e:
- print >> DEBUGSTREAM, 'got SMTPRecipientsRefused'
+ print('got SMTPRecipientsRefused', file=DEBUGSTREAM)
refused = e.recipients
except (socket.error, smtplib.SMTPException) as e:
- print >> DEBUGSTREAM, 'got', e.__class__
+ print('got', e.__class__, file=DEBUGSTREAM)
# All recipients were refused. If the exception had an associated
# error code, use it. Otherwise,fake it with a non-triggering
# exception code.
@@ -410,11 +409,11 @@
for rcpt, listname, command in listnames:
rcpttos.remove(rcpt)
# If there's any non-list destined recipients left,
- print >> DEBUGSTREAM, 'forwarding recips:', ' '.join(rcpttos)
+ print('forwarding recips:', ' '.join(rcpttos), file=DEBUGSTREAM)
if rcpttos:
refused = self._deliver(mailfrom, rcpttos, data)
# TBD: what to do with refused addresses?
- print >> DEBUGSTREAM, 'we got refusals:', refused
+ print('we got refusals:', refused, file=DEBUGSTREAM)
# Now deliver directly to the list commands
mlists = {}
s = StringIO(data)
@@ -427,7 +426,7 @@
if not msg.getheader('date'):
msg['Date'] = time.ctime(time.time())
for rcpt, listname, command in listnames:
- print >> DEBUGSTREAM, 'sending message to', rcpt
+ print('sending message to', rcpt, file=DEBUGSTREAM)
mlist = mlists.get(listname)
if not mlist:
mlist = MailList.MailList(listname, lock=0)
@@ -472,7 +471,7 @@
if opt in ('-h', '--help'):
usage(0)
elif opt in ('-V', '--version'):
- print >> sys.stderr, __version__
+ print(__version__, file=sys.stderr)
sys.exit(0)
elif opt in ('-n', '--nosetuid'):
options.setuid = 0
@@ -522,16 +521,14 @@
try:
import pwd
except ImportError:
- print >> sys.stderr, \
- 'Cannot import module "pwd"; try running with -n option.'
+ print('Cannot import module "pwd"; try running with -n option.', file=sys.stderr)
sys.exit(1)
nobody = pwd.getpwnam('nobody')[2]
try:
os.setuid(nobody)
except OSError as e:
if e.errno != errno.EPERM: raise
- print >> sys.stderr, \
- 'Cannot setuid "nobody"; try running with -n option.'
+ print('Cannot setuid "nobody"; try running with -n option.', file=sys.stderr)
sys.exit(1)
classname = options.classname
if "." in classname:
Modified: python/branches/p3yk-noslice/Lib/smtplib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/smtplib.py (original)
+++ python/branches/p3yk-noslice/Lib/smtplib.py Fri Feb 23 18:29:35 2007
@@ -15,7 +15,7 @@
>>> import smtplib
>>> s=smtplib.SMTP("localhost")
- >>> print s.help()
+ >>> print(s.help())
This is Sendmail version 8.8.4
Topics:
HELO EHLO MAIL RCPT DATA
@@ -43,10 +43,10 @@
import socket
import re
-import email.Utils
+import email.utils
import base64
import hmac
-from email.base64MIME import encode as encode_base64
+from email.base64mime import encode as encode_base64
from sys import stderr
__all__ = ["SMTPException","SMTPServerDisconnected","SMTPResponseException",
@@ -172,7 +172,7 @@
"""
m = (None, None)
try:
- m = email.Utils.parseaddr(addr)[1]
+ m = email.utils.parseaddr(addr)[1]
except AttributeError:
pass
if m == (None, None): # Indicates parse failure or AttributeError
@@ -277,7 +277,7 @@
# This makes it simpler for SMTP_SSL to use the SMTP connect code
# and just alter the socket connection bit.
self.sock = socket.socket(af, socktype, proto)
- if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
+ if self.debuglevel > 0: print('connect:', (host, port), file=stderr)
self.sock.connect(sa)
def connect(self, host='localhost', port = 0):
@@ -299,7 +299,7 @@
except ValueError:
raise socket.error, "nonnumeric port"
if not port: port = self.default_port
- if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
+ if self.debuglevel > 0: print('connect:', (host, port), file=stderr)
msg = "getaddrinfo returns an empty list"
self.sock = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
@@ -307,7 +307,7 @@
try:
self._get_socket(af,socktype,proto,sa)
except socket.error as msg:
- if self.debuglevel > 0: print>>stderr, 'connect fail:', msg
+ if self.debuglevel > 0: print('connect fail:', msg, file=stderr)
if self.sock:
self.sock.close()
self.sock = None
@@ -316,12 +316,12 @@
if not self.sock:
raise socket.error, msg
(code, msg) = self.getreply()
- if self.debuglevel > 0: print>>stderr, "connect:", msg
+ if self.debuglevel > 0: print("connect:", msg, file=stderr)
return (code, msg)
def send(self, str):
"""Send `str' to the server."""
- if self.debuglevel > 0: print>>stderr, 'send:', repr(str)
+ if self.debuglevel > 0: print('send:', repr(str), file=stderr)
if self.sock:
try:
self.sock.sendall(str)
@@ -360,7 +360,7 @@
if line == '':
self.close()
raise SMTPServerDisconnected("Connection unexpectedly closed")
- if self.debuglevel > 0: print>>stderr, 'reply:', repr(line)
+ if self.debuglevel > 0: print('reply:', repr(line), file=stderr)
resp.append(line[4:].strip())
code=line[:3]
# Check that the error code is syntactically correct.
@@ -376,7 +376,7 @@
errmsg = "\n".join(resp)
if self.debuglevel > 0:
- print>>stderr, 'reply: retcode (%s); Msg: %s' % (errcode,errmsg)
+ print('reply: retcode (%s); Msg: %s' % (errcode,errmsg), file=stderr)
return errcode, errmsg
def docmd(self, cmd, args=""):
@@ -489,7 +489,7 @@
"""
self.putcmd("data")
(code,repl)=self.getreply()
- if self.debuglevel >0 : print>>stderr, "data:", (code,repl)
+ if self.debuglevel >0 : print("data:", (code,repl), file=stderr)
if code != 354:
raise SMTPDataError(code,repl)
else:
@@ -499,7 +499,7 @@
q = q + "." + CRLF
self.send(q)
(code,msg)=self.getreply()
- if self.debuglevel >0 : print>>stderr, "data:", (code,msg)
+ if self.debuglevel >0 : print("data:", (code,msg), file=stderr)
return (code,msg)
def verify(self, address):
@@ -740,7 +740,7 @@
def _get_socket(self,af, socktype, proto,sa):
self.sock = socket.socket(af, socktype, proto)
- if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)
+ if self.debuglevel > 0: print('connect:', (host, port), file=stderr)
self.sock.connect(sa)
sslobj = socket.ssl(self.sock, self.keyfile, self.certfile)
self.sock = SSLFakeSocket(self.sock, sslobj)
@@ -757,14 +757,14 @@
fromaddr = prompt("From")
toaddrs = prompt("To").split(',')
- print "Enter message, end with ^D:"
+ print("Enter message, end with ^D:")
msg = ''
while 1:
line = sys.stdin.readline()
if not line:
break
msg = msg + line
- print "Message length is %d" % len(msg)
+ print("Message length is %d" % len(msg))
server = SMTP('localhost')
server.set_debuglevel(1)
Modified: python/branches/p3yk-noslice/Lib/sndhdr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sndhdr.py (original)
+++ python/branches/p3yk-noslice/Lib/sndhdr.py Fri Feb 23 18:29:35 2007
@@ -208,21 +208,21 @@
import os
for filename in list:
if os.path.isdir(filename):
- print filename + '/:',
+ print(filename + '/:', end=' ')
if recursive or toplevel:
- print 'recursing down:'
+ print('recursing down:')
import glob
names = glob.glob(os.path.join(filename, '*'))
testall(names, recursive, 0)
else:
- print '*** directory (use -r) ***'
+ print('*** directory (use -r) ***')
else:
- print filename + ':',
+ print(filename + ':', end=' ')
sys.stdout.flush()
try:
- print what(filename)
+ print(what(filename))
except IOError:
- print '*** not found ***'
+ print('*** not found ***')
if __name__ == '__main__':
test()
Modified: python/branches/p3yk-noslice/Lib/socket.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/socket.py (original)
+++ python/branches/p3yk-noslice/Lib/socket.py Fri Feb 23 18:29:35 2007
@@ -202,17 +202,17 @@
default_bufsize = 8192
name = "<socket>"
- __slots__ = ["mode", "bufsize", "softspace",
+ __slots__ = ["mode", "bufsize",
# "closed" is a property, see below
- "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf"]
+ "_sock", "_rbufsize", "_wbufsize", "_rbuf", "_wbuf",
+ "_close"]
- def __init__(self, sock, mode='rb', bufsize=-1):
+ def __init__(self, sock, mode='rb', bufsize=-1, close=False):
self._sock = sock
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:
@@ -222,6 +222,7 @@
self._wbufsize = bufsize
self._rbuf = "" # A string
self._wbuf = [] # A list of strings
+ self._close = close
def _getclosed(self):
return self._sock is None
@@ -232,6 +233,8 @@
if self._sock:
self.flush()
finally:
+ if self._close:
+ self._sock.close()
self._sock = None
def __del__(self):
Modified: python/branches/p3yk-noslice/Lib/sqlite3/dbapi2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sqlite3/dbapi2.py (original)
+++ python/branches/p3yk-noslice/Lib/sqlite3/dbapi2.py Fri Feb 23 18:29:35 2007
@@ -68,7 +68,7 @@
timepart_full = timepart.split(".")
hours, minutes, seconds = map(int, timepart_full[0].split(":"))
if len(timepart_full) == 2:
- microseconds = int(float("0." + timepart_full[1]) * 1000000)
+ microseconds = int(timepart_full[1])
else:
microseconds = 0
Modified: python/branches/p3yk-noslice/Lib/sqlite3/test/dbapi.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sqlite3/test/dbapi.py (original)
+++ python/branches/p3yk-noslice/Lib/sqlite3/test/dbapi.py Fri Feb 23 18:29:35 2007
@@ -327,7 +327,7 @@
except TypeError:
return
except Exception as e:
- print "raised", e.__class__
+ print("raised", e.__class__)
self.fail("raised wrong exception.")
def CheckFetchIter(self):
Modified: python/branches/p3yk-noslice/Lib/sqlite3/test/factory.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sqlite3/test/factory.py (original)
+++ python/branches/p3yk-noslice/Lib/sqlite3/test/factory.py Fri Feb 23 18:29:35 2007
@@ -91,7 +91,7 @@
list),
"row is not instance of list")
- def CheckSqliteRow(self):
+ def CheckSqliteRowIndex(self):
self.con.row_factory = sqlite.Row
row = self.con.execute("select 1 as a, 2 as b").fetchone()
self.failUnless(isinstance(row,
@@ -110,6 +110,27 @@
self.failUnless(col1 == 1, "by index: wrong result for column 0")
self.failUnless(col2 == 2, "by index: wrong result for column 1")
+ def CheckSqliteRowIter(self):
+ """Checks if the row object is iterable"""
+ self.con.row_factory = sqlite.Row
+ row = self.con.execute("select 1 as a, 2 as b").fetchone()
+ for col in row:
+ pass
+
+ def CheckSqliteRowAsTuple(self):
+ """Checks if the row object can be converted to a tuple"""
+ self.con.row_factory = sqlite.Row
+ row = self.con.execute("select 1 as a, 2 as b").fetchone()
+ t = tuple(row)
+
+ def CheckSqliteRowAsDict(self):
+ """Checks if the row object can be correctly converted to a dictionary"""
+ self.con.row_factory = sqlite.Row
+ row = self.con.execute("select 1 as a, 2 as b").fetchone()
+ d = dict(row)
+ self.failUnlessEqual(d["a"], row["a"])
+ self.failUnlessEqual(d["b"], row["b"])
+
def tearDown(self):
self.con.close()
Modified: python/branches/p3yk-noslice/Lib/sqlite3/test/regression.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sqlite3/test/regression.py (original)
+++ python/branches/p3yk-noslice/Lib/sqlite3/test/regression.py Fri Feb 23 18:29:35 2007
@@ -69,6 +69,16 @@
cur.execute('select 1 as "foo baz"')
self.failUnlessEqual(cur.description[0][0], "foo baz")
+ def CheckStatementAvailable(self):
+ # pysqlite up to 2.3.2 crashed on this, because the active statement handle was not checked
+ # before trying to fetch data from it. close() destroys the active statement ...
+ con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES)
+ cur = con.cursor()
+ cur.execute("select 4 union select 5")
+ cur.close()
+ cur.fetchone()
+ cur.fetchone()
+
def suite():
regression_suite = unittest.makeSuite(RegressionTests, "Check")
return unittest.TestSuite((regression_suite,))
Modified: python/branches/p3yk-noslice/Lib/sqlite3/test/types.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sqlite3/test/types.py (original)
+++ python/branches/p3yk-noslice/Lib/sqlite3/test/types.py Fri Feb 23 18:29:35 2007
@@ -112,6 +112,7 @@
# and implement two custom ones
sqlite.converters["BOOL"] = lambda x: bool(int(x))
sqlite.converters["FOO"] = DeclTypesTests.Foo
+ sqlite.converters["WRONG"] = lambda x: "WRONG"
def tearDown(self):
del sqlite.converters["FLOAT"]
@@ -123,7 +124,7 @@
def CheckString(self):
# default
self.cur.execute("insert into test(s) values (?)", ("foo",))
- self.cur.execute("select s from test")
+ self.cur.execute('select s as "s [WRONG]" from test')
row = self.cur.fetchone()
self.failUnlessEqual(row[0], "foo")
@@ -210,26 +211,32 @@
class ColNamesTests(unittest.TestCase):
def setUp(self):
- self.con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES|sqlite.PARSE_DECLTYPES)
+ self.con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_COLNAMES)
self.cur = self.con.cursor()
self.cur.execute("create table test(x foo)")
sqlite.converters["FOO"] = lambda x: "[%s]" % x
sqlite.converters["BAR"] = lambda x: "<%s>" % x
sqlite.converters["EXC"] = lambda x: 5/0
+ sqlite.converters["B1B1"] = lambda x: "MARKER"
def tearDown(self):
del sqlite.converters["FOO"]
del sqlite.converters["BAR"]
del sqlite.converters["EXC"]
+ del sqlite.converters["B1B1"]
self.cur.close()
self.con.close()
- def CheckDeclType(self):
+ def CheckDeclTypeNotUsed(self):
+ """
+ Assures that the declared type is not used when PARSE_DECLTYPES
+ is not set.
+ """
self.cur.execute("insert into test(x) values (?)", ("xxx",))
self.cur.execute("select x from test")
val = self.cur.fetchone()[0]
- self.failUnlessEqual(val, "[xxx]")
+ self.failUnlessEqual(val, "xxx")
def CheckNone(self):
self.cur.execute("insert into test(x) values (?)", (None,))
@@ -247,6 +254,11 @@
# whitespace should be stripped.
self.failUnlessEqual(self.cur.description[0][0], "x")
+ def CheckCaseInConverterName(self):
+ self.cur.execute("""select 'other' as "x [b1b1]\"""")
+ val = self.cur.fetchone()[0]
+ self.failUnlessEqual(val, "MARKER")
+
def CheckCursorDescriptionNoRow(self):
"""
cursor.description should at least provide the column name(s), even if
@@ -340,6 +352,13 @@
ts2 = self.cur.fetchone()[0]
self.failUnlessEqual(ts, ts2)
+ def CheckDateTimeSubSecondsFloatingPoint(self):
+ ts = sqlite.Timestamp(2004, 2, 14, 7, 15, 0, 510241)
+ self.cur.execute("insert into test(ts) values (?)", (ts,))
+ self.cur.execute("select ts from test")
+ ts2 = self.cur.fetchone()[0]
+ self.failUnlessEqual(ts, ts2)
+
def suite():
sqlite_type_suite = unittest.makeSuite(SqliteTypeTests, "Check")
decltypes_type_suite = unittest.makeSuite(DeclTypesTests, "Check")
Modified: python/branches/p3yk-noslice/Lib/sre_compile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sre_compile.py (original)
+++ python/branches/p3yk-noslice/Lib/sre_compile.py Fri Feb 23 18:29:35 2007
@@ -19,7 +19,7 @@
if _sre.CODESIZE == 2:
MAXCODE = 65535
else:
- MAXCODE = 0xFFFFFFFFL
+ MAXCODE = 0xFFFFFFFF
def _identityfunction(x):
return x
@@ -267,7 +267,7 @@
if _sre.CODESIZE == 2:
start = (1, 0)
else:
- start = (1L, 0L)
+ start = (1, 0)
m, v = start
for c in bits:
if c:
Modified: python/branches/p3yk-noslice/Lib/sre_constants.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sre_constants.py (original)
+++ python/branches/p3yk-noslice/Lib/sre_constants.py Fri Feb 23 18:29:35 2007
@@ -258,4 +258,4 @@
f.write("#define SRE_INFO_CHARSET %d\n" % SRE_INFO_CHARSET)
f.close()
- print "done"
+ print("done")
Modified: python/branches/p3yk-noslice/Lib/sre_parse.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sre_parse.py (original)
+++ python/branches/p3yk-noslice/Lib/sre_parse.py Fri Feb 23 18:29:35 2007
@@ -103,30 +103,30 @@
nl = 1
seqtypes = type(()), type([])
for op, av in self.data:
- print level*" " + op,; nl = 0
+ print(level*" " + op, end=' '); nl = 0
if op == "in":
# member sublanguage
- print; nl = 1
+ print(); nl = 1
for op, a in av:
- print (level+1)*" " + op, a
+ print((level+1)*" " + op, a)
elif op == "branch":
- print; nl = 1
+ print(); nl = 1
i = 0
for a in av[1]:
if i > 0:
- print level*" " + "or"
+ print(level*" " + "or")
a.dump(level+1); nl = 1
i = i + 1
elif type(av) in seqtypes:
for a in av:
if isinstance(a, SubPattern):
- if not nl: print
+ if not nl: print()
a.dump(level+1); nl = 1
else:
- print a, ; nl = 0
+ print(a, end=' ') ; nl = 0
else:
- print av, ; nl = 0
- if not nl: print
+ print(av, end=' ') ; nl = 0
+ if not nl: print()
def __repr__(self):
return repr(self.data)
def __len__(self):
@@ -147,7 +147,7 @@
# determine the width (min, max) for this subpattern
if self.width:
return self.width
- lo = hi = 0L
+ lo = hi = 0
UNITCODES = (ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY)
REPEATCODES = (MIN_REPEAT, MAX_REPEAT)
for op, av in self.data:
@@ -170,8 +170,8 @@
hi = hi + j
elif op in REPEATCODES:
i, j = av[2].getwidth()
- lo = lo + long(i) * av[0]
- hi = hi + long(j) * av[1]
+ lo = lo + int(i) * av[0]
+ hi = hi + int(j) * av[1]
elif op in UNITCODES:
lo = lo + 1
hi = hi + 1
Modified: python/branches/p3yk-noslice/Lib/stat.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/stat.py (original)
+++ python/branches/p3yk-noslice/Lib/stat.py Fri Feb 23 18:29:35 2007
@@ -84,3 +84,16 @@
S_IROTH = 00004
S_IWOTH = 00002
S_IXOTH = 00001
+
+# Names for file flags
+
+UF_NODUMP = 0x00000001
+UF_IMMUTABLE = 0x00000002
+UF_APPEND = 0x00000004
+UF_OPAQUE = 0x00000008
+UF_NOUNLINK = 0x00000010
+SF_ARCHIVED = 0x00010000
+SF_IMMUTABLE = 0x00020000
+SF_APPEND = 0x00040000
+SF_NOUNLINK = 0x00100000
+SF_SNAPSHOT = 0x00200000
Modified: python/branches/p3yk-noslice/Lib/string.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/string.py (original)
+++ python/branches/p3yk-noslice/Lib/string.py Fri Feb 23 18:29:35 2007
@@ -374,7 +374,7 @@
# for a bit of speed
_float = float
_int = int
-_long = long
+_long = int
# Convert string to float
def atof(s):
Modified: python/branches/p3yk-noslice/Lib/stringold.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/stringold.py (original)
+++ python/branches/p3yk-noslice/Lib/stringold.py Fri Feb 23 18:29:35 2007
@@ -184,7 +184,7 @@
# for a bit of speed
_float = float
_int = int
-_long = long
+_long = int
_StringType = type('')
# Convert string to float
Modified: python/branches/p3yk-noslice/Lib/subprocess.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/subprocess.py (original)
+++ python/branches/p3yk-noslice/Lib/subprocess.py Fri Feb 23 18:29:35 2007
@@ -500,7 +500,7 @@
if result:
result.append(' ')
- needquote = (" " in arg) or ("\t" in arg)
+ needquote = (" " in arg) or ("\t" in arg) or arg == ""
if needquote:
result.append('"')
@@ -541,7 +541,7 @@
_cleanup()
self._child_created = False
- if not isinstance(bufsize, (int, long)):
+ if not isinstance(bufsize, (int, int)):
raise TypeError("bufsize must be an integer")
if mswindows:
@@ -593,14 +593,30 @@
c2pread, c2pwrite,
errread, errwrite)
- if p2cwrite:
+ # On Windows, you cannot just redirect one or two handles: You
+ # either have to redirect all three or none. If the subprocess
+ # user has only redirected one or two handles, we are
+ # automatically creating PIPEs for the rest. We should close
+ # these after the process is started. See bug #1124861.
+ if mswindows:
+ if stdin is None and p2cwrite is not None:
+ os.close(p2cwrite)
+ p2cwrite = None
+ if stdout is None and c2pread is not None:
+ os.close(c2pread)
+ c2pread = None
+ if stderr is None and errread is not None:
+ os.close(errread)
+ errread = None
+
+ if p2cwrite is not None:
self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
- if c2pread:
+ if c2pread is not None:
if universal_newlines:
self.stdout = os.fdopen(c2pread, 'rU', bufsize)
else:
self.stdout = os.fdopen(c2pread, 'rb', bufsize)
- if errread:
+ if errread is not None:
if universal_newlines:
self.stderr = os.fdopen(errread, 'rU', bufsize)
else:
@@ -669,7 +685,9 @@
if stdin is None:
p2cread = GetStdHandle(STD_INPUT_HANDLE)
- elif stdin == PIPE:
+ if p2cread is not None:
+ pass
+ elif stdin is None or stdin == PIPE:
p2cread, p2cwrite = CreatePipe(None, 0)
# Detach and turn into fd
p2cwrite = p2cwrite.Detach()
@@ -683,7 +701,9 @@
if stdout is None:
c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
- elif stdout == PIPE:
+ if c2pwrite is not None:
+ pass
+ elif stdout is None or stdout == PIPE:
c2pread, c2pwrite = CreatePipe(None, 0)
# Detach and turn into fd
c2pread = c2pread.Detach()
@@ -697,7 +717,9 @@
if stderr is None:
errwrite = GetStdHandle(STD_ERROR_HANDLE)
- elif stderr == PIPE:
+ if errwrite is not None:
+ pass
+ elif stderr is None or stderr == PIPE:
errread, errwrite = CreatePipe(None, 0)
# Detach and turn into fd
errread = errread.Detach()
@@ -764,7 +786,7 @@
startupinfo.wShowWindow = SW_HIDE
comspec = os.environ.get("COMSPEC", "cmd.exe")
args = comspec + " /c " + args
- if (GetVersion() >= 0x80000000L or
+ if (GetVersion() >= 0x80000000 or
os.path.basename(comspec).lower() == "command.com"):
# Win9x, or using command.com on NT. We need to
# use the w9xpopen intermediate program. For more
@@ -987,29 +1009,29 @@
# Child
try:
# Close parent's pipe ends
- if p2cwrite:
+ if p2cwrite is not None:
os.close(p2cwrite)
- if c2pread:
+ if c2pread is not None:
os.close(c2pread)
- if errread:
+ if errread is not None:
os.close(errread)
os.close(errpipe_read)
# Dup fds for child
- if p2cread:
+ if p2cread is not None:
os.dup2(p2cread, 0)
- if c2pwrite:
+ if c2pwrite is not None:
os.dup2(c2pwrite, 1)
- if errwrite:
+ if errwrite is not None:
os.dup2(errwrite, 2)
# Close pipe fds. Make sure we don't close the same
# fd more than once, or standard fds.
- if p2cread and p2cread not in (0,):
+ if p2cread is not None and p2cread not in (0,):
os.close(p2cread)
- if c2pwrite and c2pwrite not in (p2cread, 1):
+ if c2pwrite is not None and c2pwrite not in (p2cread, 1):
os.close(c2pwrite)
- if errwrite and errwrite not in (p2cread, c2pwrite, 2):
+ if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2):
os.close(errwrite)
# Close all other fds, if asked for
@@ -1042,11 +1064,11 @@
# Parent
os.close(errpipe_write)
- if p2cread and p2cwrite:
+ if p2cread is not None and p2cwrite is not None:
os.close(p2cread)
- if c2pwrite and c2pread:
+ if c2pwrite is not None and c2pread is not None:
os.close(c2pwrite)
- if errwrite and errread:
+ if errwrite is not None and errread is not None:
os.close(errwrite)
# Wait for exec to fail or succeed; possibly raising exception
@@ -1121,7 +1143,7 @@
# we can write up to PIPE_BUF bytes without risk
# blocking. POSIX defines PIPE_BUF >= 512
bytes_written = os.write(self.stdin.fileno(), buffer(input, input_offset, 512))
- input_offset += bytes_written
+ input_offset += bytes_written
if input_offset >= len(input):
self.stdin.close()
write_set.remove(self.stdin)
@@ -1165,8 +1187,8 @@
# Example 1: Simple redirection: Get process list
#
plist = Popen(["ps"], stdout=PIPE).communicate()[0]
- print "Process list:"
- print plist
+ print("Process list:")
+ print(plist)
#
# Example 2: Change uid before executing child
@@ -1178,42 +1200,42 @@
#
# Example 3: Connecting several subprocesses
#
- print "Looking for 'hda'..."
+ print("Looking for 'hda'...")
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
- print repr(p2.communicate()[0])
+ print(repr(p2.communicate()[0]))
#
# Example 4: Catch execution error
#
- print
- print "Trying a weird file..."
+ print()
+ print("Trying a weird file...")
try:
- print Popen(["/this/path/does/not/exist"]).communicate()
+ print(Popen(["/this/path/does/not/exist"]).communicate())
except OSError as e:
if e.errno == errno.ENOENT:
- print "The file didn't exist. I thought so..."
- print "Child traceback:"
- print e.child_traceback
+ print("The file didn't exist. I thought so...")
+ print("Child traceback:")
+ print(e.child_traceback)
else:
- print "Error", e.errno
+ print("Error", e.errno)
else:
- print >>sys.stderr, "Gosh. No error."
+ print("Gosh. No error.", file=sys.stderr)
def _demo_windows():
#
# Example 1: Connecting several subprocesses
#
- print "Looking for 'PROMPT' in set output..."
+ print("Looking for 'PROMPT' in set output...")
p1 = Popen("set", stdout=PIPE, shell=True)
p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
- print repr(p2.communicate()[0])
+ print(repr(p2.communicate()[0]))
#
# Example 2: Simple execution of program
#
- print "Executing calc..."
+ print("Executing calc...")
p = Popen("calc")
p.wait()
Modified: python/branches/p3yk-noslice/Lib/sunau.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sunau.py (original)
+++ python/branches/p3yk-noslice/Lib/sunau.py Fri Feb 23 18:29:35 2007
@@ -119,7 +119,7 @@
AUDIO_FILE_ENCODING_ALAW_8 = 27
# from <multimedia/audio_hdr.h>
-AUDIO_UNKNOWN_SIZE = 0xFFFFFFFFL # ((unsigned)(~0))
+AUDIO_UNKNOWN_SIZE = 0xFFFFFFFF # ((unsigned)(~0))
_simple_encodings = [AUDIO_FILE_ENCODING_MULAW_8,
AUDIO_FILE_ENCODING_LINEAR_8,
@@ -132,7 +132,7 @@
pass
def _read_u32(file):
- x = 0L
+ x = 0
for i in range(4):
byte = file.read(1)
if byte == '':
Modified: python/branches/p3yk-noslice/Lib/sunaudio.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/sunaudio.py (original)
+++ python/branches/p3yk-noslice/Lib/sunaudio.py Fri Feb 23 18:29:35 2007
@@ -36,9 +36,9 @@
data_size, encoding, sample_rate, channels, info = hdr
while info[-1:] == '\0':
info = info[:-1]
- print 'File name: ', file
- print 'Data size: ', data_size
- print 'Encoding: ', encoding
- print 'Sample rate:', sample_rate
- print 'Channels: ', channels
- print 'Info: ', repr(info)
+ print('File name: ', file)
+ print('Data size: ', data_size)
+ print('Encoding: ', encoding)
+ print('Sample rate:', sample_rate)
+ print('Channels: ', channels)
+ print('Info: ', repr(info))
Modified: python/branches/p3yk-noslice/Lib/symbol.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/symbol.py (original)
+++ python/branches/p3yk-noslice/Lib/symbol.py Fri Feb 23 18:29:35 2007
@@ -30,78 +30,77 @@
small_stmt = 273
expr_stmt = 274
augassign = 275
-print_stmt = 276
-del_stmt = 277
-pass_stmt = 278
-flow_stmt = 279
-break_stmt = 280
-continue_stmt = 281
-return_stmt = 282
-yield_stmt = 283
-raise_stmt = 284
-import_stmt = 285
-import_name = 286
-import_from = 287
-import_as_name = 288
-dotted_as_name = 289
-import_as_names = 290
-dotted_as_names = 291
-dotted_name = 292
-global_stmt = 293
-assert_stmt = 294
-compound_stmt = 295
-if_stmt = 296
-while_stmt = 297
-for_stmt = 298
-try_stmt = 299
-with_stmt = 300
-with_var = 301
-except_clause = 302
-suite = 303
-testlist_safe = 304
-old_test = 305
-old_lambdef = 306
-test = 307
-or_test = 308
-and_test = 309
-not_test = 310
-comparison = 311
-comp_op = 312
-expr = 313
-xor_expr = 314
-and_expr = 315
-shift_expr = 316
-arith_expr = 317
-term = 318
-factor = 319
-power = 320
-atom = 321
-listmaker = 322
-testlist_gexp = 323
-lambdef = 324
-trailer = 325
-subscriptlist = 326
-subscript = 327
-sliceop = 328
-exprlist = 329
-testlist = 330
-dictsetmaker = 331
-classdef = 332
-arglist = 333
-argument = 334
-list_iter = 335
-list_for = 336
-list_if = 337
-gen_iter = 338
-gen_for = 339
-gen_if = 340
-testlist1 = 341
-encoding_decl = 342
-yield_expr = 343
+del_stmt = 276
+pass_stmt = 277
+flow_stmt = 278
+break_stmt = 279
+continue_stmt = 280
+return_stmt = 281
+yield_stmt = 282
+raise_stmt = 283
+import_stmt = 284
+import_name = 285
+import_from = 286
+import_as_name = 287
+dotted_as_name = 288
+import_as_names = 289
+dotted_as_names = 290
+dotted_name = 291
+global_stmt = 292
+assert_stmt = 293
+compound_stmt = 294
+if_stmt = 295
+while_stmt = 296
+for_stmt = 297
+try_stmt = 298
+with_stmt = 299
+with_var = 300
+except_clause = 301
+suite = 302
+testlist_safe = 303
+old_test = 304
+old_lambdef = 305
+test = 306
+or_test = 307
+and_test = 308
+not_test = 309
+comparison = 310
+comp_op = 311
+expr = 312
+xor_expr = 313
+and_expr = 314
+shift_expr = 315
+arith_expr = 316
+term = 317
+factor = 318
+power = 319
+atom = 320
+listmaker = 321
+testlist_gexp = 322
+lambdef = 323
+trailer = 324
+subscriptlist = 325
+subscript = 326
+sliceop = 327
+exprlist = 328
+testlist = 329
+dictsetmaker = 330
+classdef = 331
+arglist = 332
+argument = 333
+list_iter = 334
+list_for = 335
+list_if = 336
+gen_iter = 337
+gen_for = 338
+gen_if = 339
+testlist1 = 340
+encoding_decl = 341
+yield_expr = 342
#--end constants--
sym_name = {}
-for _name, _value in globals().items():
+for _name, _value in list(globals().items()):
if type(_value) is type(0):
sym_name[_value] = _name
Modified: python/branches/p3yk-noslice/Lib/symtable.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/symtable.py (original)
+++ python/branches/p3yk-noslice/Lib/symtable.py Fri Feb 23 18:29:35 2007
@@ -13,7 +13,7 @@
def symtable(code, filename, compile_type):
raw = _symtable.symtable(code, filename, compile_type)
- for top in raw.itervalues():
+ for top in raw.values():
if top.name == 'top':
break
return newSymbolTable(top, filename)
@@ -249,4 +249,4 @@
mod = symtable(src, os.path.split(sys.argv[0])[1], "exec")
for ident in mod.get_identifiers():
info = mod.lookup(ident)
- print info, info.is_local(), info.is_namespace()
+ print(info, info.is_local(), info.is_namespace())
Modified: python/branches/p3yk-noslice/Lib/tabnanny.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/tabnanny.py (original)
+++ python/branches/p3yk-noslice/Lib/tabnanny.py Fri Feb 23 18:29:35 2007
@@ -83,7 +83,7 @@
if os.path.isdir(file) and not os.path.islink(file):
if verbose:
- print "%r: listing directory" % (file,)
+ print("%r: listing directory" % (file,))
names = os.listdir(file)
for name in names:
fullname = os.path.join(file, name)
@@ -100,7 +100,7 @@
return
if verbose > 1:
- print "checking %r ..." % file
+ print("checking %r ..." % file)
try:
process_tokens(tokenize.generate_tokens(f.readline))
@@ -117,17 +117,17 @@
badline = nag.get_lineno()
line = nag.get_line()
if verbose:
- print "%r: *** Line %d: trouble in tab city! ***" % (file, badline)
- print "offending line: %r" % (line,)
- print nag.get_msg()
+ print("%r: *** Line %d: trouble in tab city! ***" % (file, badline))
+ print("offending line: %r" % (line,))
+ print(nag.get_msg())
else:
if ' ' in file: file = '"' + file + '"'
- if filename_only: print file
- else: print file, badline, repr(line)
+ if filename_only: print(file)
+ else: print(file, badline, repr(line))
return
if verbose:
- print "%r: Clean bill of health." % (file,)
+ print("%r: Clean bill of health." % (file,))
class Whitespace:
# the characters used for space and tab
Modified: python/branches/p3yk-noslice/Lib/tarfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/tarfile.py (original)
+++ python/branches/p3yk-noslice/Lib/tarfile.py Fri Feb 23 18:29:35 2007
@@ -80,7 +80,7 @@
LENGTH_NAME = 100 # maximum length of a filename
LENGTH_LINK = 100 # maximum length of a linkname
LENGTH_PREFIX = 155 # maximum length of the prefix field
-MAXSIZE_MEMBER = 077777777777L # maximum size of a file (11 octal digits)
+MAXSIZE_MEMBER = 077777777777 # maximum size of a file (11 octal digits)
REGTYPE = "0" # regular file
AREGTYPE = "\0" # regular file
@@ -152,7 +152,7 @@
except ValueError:
raise HeaderError("invalid header")
else:
- n = 0L
+ n = 0
for i in xrange(len(s) - 1):
n <<= 8
n += ord(s[i + 1])
@@ -347,7 +347,7 @@
self.fileobj = fileobj
self.bufsize = bufsize
self.buf = ""
- self.pos = 0L
+ self.pos = 0
self.closed = False
if comptype == "gz":
@@ -384,7 +384,7 @@
-self.zlib.MAX_WBITS,
self.zlib.DEF_MEM_LEVEL,
0)
- timestamp = struct.pack("<L", long(time.time()))
+ timestamp = struct.pack("<L", int(time.time()))
self.__write("\037\213\010\010%s\002\377" % timestamp)
if self.name.endswith(".gz"):
self.name = self.name[:-3]
@@ -429,8 +429,8 @@
# while the same crc on a 64-bit box may "look positive".
# To avoid irksome warnings from the `struct` module, force
# it to look positive on all boxes.
- self.fileobj.write(struct.pack("<L", self.crc & 0xffffffffL))
- self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFFL))
+ self.fileobj.write(struct.pack("<L", self.crc & 0xffffffff))
+ self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFF))
if not self._extfileobj:
self.fileobj.close()
@@ -1062,6 +1062,10 @@
self.mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode]
if not fileobj:
+ if self._mode == "a" and not os.path.exists(self.name):
+ # Create nonexistent files in append mode.
+ self._mode = "w"
+ self.mode = "wb"
fileobj = _open(self.name, self.mode)
self._extfileobj = False
else:
@@ -1076,7 +1080,7 @@
self.closed = False
self.members = [] # list of members as TarInfo objects
self._loaded = False # flag if all members have been read
- self.offset = 0L # current position in the archive file
+ self.offset = 0 # current position in the archive file
self.inodes = {} # dictionary caching the inodes of
# archive members already added
@@ -1095,7 +1099,8 @@
self.fileobj.seek(0)
break
if tarinfo is None:
- self.fileobj.seek(- BLOCKSIZE, 1)
+ if self.offset > 0:
+ self.fileobj.seek(- BLOCKSIZE, 1)
break
if self._mode in "aw":
@@ -1122,7 +1127,7 @@
'r:' open for reading exclusively uncompressed
'r:gz' open for reading with gzip compression
'r:bz2' open for reading with bzip2 compression
- 'a' or 'a:' open for appending
+ 'a' or 'a:' open for appending, creating the file if necessary
'w' or 'w:' open for writing without compression
'w:gz' open for writing with gzip compression
'w:bz2' open for writing with bzip2 compression
@@ -1378,7 +1383,7 @@
if stat.S_ISREG(stmd):
tarinfo.size = statres.st_size
else:
- tarinfo.size = 0L
+ tarinfo.size = 0
tarinfo.mtime = statres.st_mtime
tarinfo.type = type
tarinfo.linkname = linkname
@@ -1408,25 +1413,25 @@
for tarinfo in self:
if verbose:
- print filemode(tarinfo.mode),
- print "%s/%s" % (tarinfo.uname or tarinfo.uid,
- tarinfo.gname or tarinfo.gid),
+ print(filemode(tarinfo.mode), end=' ')
+ print("%s/%s" % (tarinfo.uname or tarinfo.uid,
+ tarinfo.gname or tarinfo.gid), end=' ')
if tarinfo.ischr() or tarinfo.isblk():
- print "%10s" % ("%d,%d" \
- % (tarinfo.devmajor, tarinfo.devminor)),
+ print("%10s" % ("%d,%d" \
+ % (tarinfo.devmajor, tarinfo.devminor)), end=' ')
else:
- print "%10d" % tarinfo.size,
- print "%d-%02d-%02d %02d:%02d:%02d" \
- % time.localtime(tarinfo.mtime)[:6],
+ print("%10d" % tarinfo.size, end=' ')
+ print("%d-%02d-%02d %02d:%02d:%02d" \
+ % time.localtime(tarinfo.mtime)[:6], end=' ')
- print tarinfo.name,
+ print(tarinfo.name, end=' ')
if verbose:
if tarinfo.issym():
- print "->", tarinfo.linkname,
+ print("->", tarinfo.linkname, end=' ')
if tarinfo.islnk():
- print "link to", tarinfo.linkname,
- print
+ print("link to", tarinfo.linkname, end=' ')
+ print()
def add(self, name, arcname=None, recursive=True):
"""Add the file `name' to the archive. `name' may be any type of file
@@ -1632,19 +1637,7 @@
# Create all upper directories.
upperdirs = os.path.dirname(targetpath)
if upperdirs and not os.path.exists(upperdirs):
- ti = TarInfo()
- ti.name = upperdirs
- ti.type = DIRTYPE
- ti.mode = 0777
- ti.mtime = tarinfo.mtime
- ti.uid = tarinfo.uid
- ti.gid = tarinfo.gid
- ti.uname = tarinfo.uname
- ti.gname = tarinfo.gname
- try:
- self._extract_member(ti, ti.name)
- except:
- pass
+ os.makedirs(upperdirs)
if tarinfo.islnk() or tarinfo.issym():
self._dbg(1, "%s -> %s" % (tarinfo.name, tarinfo.linkname))
@@ -1924,8 +1917,8 @@
buf = tarinfo.buf
sp = _ringbuffer()
pos = 386
- lastpos = 0L
- realpos = 0L
+ lastpos = 0
+ realpos = 0
# There are 4 possible sparse structs in the
# first header.
for i in xrange(4):
@@ -2034,7 +2027,7 @@
"""Write debugging output to sys.stderr.
"""
if level <= self.debug:
- print >> sys.stderr, msg
+ print(msg, file=sys.stderr)
# class TarFile
class TarIter:
Modified: python/branches/p3yk-noslice/Lib/telnetlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/telnetlib.py (original)
+++ python/branches/p3yk-noslice/Lib/telnetlib.py Fri Feb 23 18:29:35 2007
@@ -8,7 +8,7 @@
>>> from telnetlib import Telnet
>>> tn = Telnet('www.python.org', 79) # connect to finger port
>>> tn.write('guido\r\n')
->>> print tn.read_all()
+>>> print(tn.read_all())
Login Name TTY Idle When Where
guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
@@ -248,11 +248,11 @@
"""
if self.debuglevel > 0:
- print 'Telnet(%s,%d):' % (self.host, self.port),
+ print('Telnet(%s,%d):' % (self.host, self.port), end=' ')
if args:
- print msg % args
+ print(msg % args)
else:
- print msg
+ print(msg)
def set_debuglevel(self, debuglevel):
"""Set the debug level.
@@ -545,7 +545,7 @@
try:
text = self.read_eager()
except EOFError:
- print '*** Connection closed by remote host ***'
+ print('*** Connection closed by remote host ***')
break
if text:
sys.stdout.write(text)
@@ -572,7 +572,7 @@
try:
data = self.read_eager()
except EOFError:
- print '*** Connection closed by remote host ***'
+ print('*** Connection closed by remote host ***')
return
if data:
sys.stdout.write(data)
Modified: python/branches/p3yk-noslice/Lib/test/badsyntax_future8.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/badsyntax_future8.py (original)
+++ python/branches/p3yk-noslice/Lib/test/badsyntax_future8.py Fri Feb 23 18:29:35 2007
@@ -7,4 +7,4 @@
return x + y
return g
-print f(2)(4)
+print(f(2)(4))
Modified: python/branches/p3yk-noslice/Lib/test/badsyntax_future9.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/badsyntax_future9.py (original)
+++ python/branches/p3yk-noslice/Lib/test/badsyntax_future9.py Fri Feb 23 18:29:35 2007
@@ -7,4 +7,4 @@
return x + y
return g
-print f(2)(4)
+print(f(2)(4))
Modified: python/branches/p3yk-noslice/Lib/test/crashers/bogus_sre_bytecode.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/crashers/bogus_sre_bytecode.py (original)
+++ python/branches/p3yk-noslice/Lib/test/crashers/bogus_sre_bytecode.py Fri Feb 23 18:29:35 2007
@@ -38,7 +38,7 @@
while 1:
code = [pick() for i in range(random.randrange(5, 25))]
- print code
+ print(code)
pat = _sre.compile(None, 0, code)
for s in ss:
try:
Modified: python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_1.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_1.py (original)
+++ python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_1.py Fri Feb 23 18:29:35 2007
@@ -8,7 +8,7 @@
class B(object):
def __del__(self):
- print 'hi'
+ print('hi')
del D.__missing__
class D(dict):
Modified: python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_2.py (original)
+++ python/branches/p3yk-noslice/Lib/test/crashers/borrowed_ref_2.py Fri Feb 23 18:29:35 2007
@@ -10,7 +10,7 @@
class B(object):
def __del__(self):
- print "hi"
+ print("hi")
del C.d
class D(object):
Modified: python/branches/p3yk-noslice/Lib/test/crashers/gc_inspection.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/crashers/gc_inspection.py (original)
+++ python/branches/p3yk-noslice/Lib/test/crashers/gc_inspection.py Fri Feb 23 18:29:35 2007
@@ -25,8 +25,8 @@
yield marker
# now the marker is in the tuple being constructed
[tup] = [x for x in gc.get_referrers(marker) if type(x) is tuple]
- print tup
- print tup[1]
+ print(tup)
+ print(tup[1])
tuple(g())
Modified: python/branches/p3yk-noslice/Lib/test/crashers/loosing_mro_ref.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/crashers/loosing_mro_ref.py (original)
+++ python/branches/p3yk-noslice/Lib/test/crashers/loosing_mro_ref.py Fri Feb 23 18:29:35 2007
@@ -32,5 +32,5 @@
# there from the beginning :-)
locals()[MyKey()] = 5
-print X.mykey
+print(X.mykey)
# I get a segfault, or a slightly wrong assertion error in a debug build.
Modified: python/branches/p3yk-noslice/Lib/test/crashers/modify_dict_attr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/crashers/modify_dict_attr.py (original)
+++ python/branches/p3yk-noslice/Lib/test/crashers/modify_dict_attr.py Fri Feb 23 18:29:35 2007
@@ -16,4 +16,4 @@
if __name__ == '__main__':
del MyClass.__dict__ # if we set tp_dict to NULL,
- print MyClass # doing anything with MyClass segfaults
+ print(MyClass) # doing anything with MyClass segfaults
Modified: python/branches/p3yk-noslice/Lib/test/crashers/nasty_eq_vs_dict.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/crashers/nasty_eq_vs_dict.py (original)
+++ python/branches/p3yk-noslice/Lib/test/crashers/nasty_eq_vs_dict.py Fri Feb 23 18:29:35 2007
@@ -44,4 +44,4 @@
z = Yuck()
y.make_dangerous()
-print dict[z]
+print(dict[z])
Modified: python/branches/p3yk-noslice/Lib/test/crashers/weakref_in_del.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/crashers/weakref_in_del.py (original)
+++ python/branches/p3yk-noslice/Lib/test/crashers/weakref_in_del.py Fri Feb 23 18:29:35 2007
@@ -1,11 +1,12 @@
import weakref
# http://python.org/sf/1377858
+# Fixed for new-style classes in 2.5c1.
ref = None
def test_weakref_in_del():
- class Target(object):
+ class Target():
def __del__(self):
global ref
ref = weakref.ref(self)
Modified: python/branches/p3yk-noslice/Lib/test/doctest_aliases.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/doctest_aliases.py (original)
+++ python/branches/p3yk-noslice/Lib/test/doctest_aliases.py Fri Feb 23 18:29:35 2007
@@ -5,7 +5,7 @@
def f(self):
'''
- >>> print TwoNames().f()
+ >>> print(TwoNames().f())
f
'''
return 'f'
Modified: python/branches/p3yk-noslice/Lib/test/fork_wait.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/fork_wait.py (original)
+++ python/branches/p3yk-noslice/Lib/test/fork_wait.py Fri Feb 23 18:29:35 2007
@@ -51,8 +51,7 @@
time.sleep(LONGSLEEP)
- a = self.alive.keys()
- a.sort()
+ a = sorted(self.alive.keys())
self.assertEquals(a, range(NUM_THREADS))
prefork_lives = self.alive.copy()
Modified: python/branches/p3yk-noslice/Lib/test/inspect_fodder2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/inspect_fodder2.py (original)
+++ python/branches/p3yk-noslice/Lib/test/inspect_fodder2.py Fri Feb 23 18:29:35 2007
@@ -7,7 +7,7 @@
# line 7
def replace(func):
def insteadfunc():
- print 'hello'
+ print('hello')
return insteadfunc
# line 13
Modified: python/branches/p3yk-noslice/Lib/test/list_tests.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/list_tests.py (original)
+++ python/branches/p3yk-noslice/Lib/test/list_tests.py Fri Feb 23 18:29:35 2007
@@ -54,7 +54,7 @@
d.append(400)
try:
fo = open(test_support.TESTFN, "wb")
- print >> fo, d,
+ fo.write(str(d))
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), repr(d))
@@ -99,16 +99,16 @@
self.assertRaises(TypeError, a.__setitem__)
a = self.type2test([0,1,2,3,4])
- a[0L] = 1
- a[1L] = 2
- a[2L] = 3
+ a[0] = 1
+ a[1] = 2
+ a[2] = 3
self.assertEqual(a, self.type2test([1,2,3,3,4]))
a[0] = 5
a[1] = 6
a[2] = 7
self.assertEqual(a, self.type2test([5,6,7,3,4]))
- a[-2L] = 88
- a[-1L] = 99
+ a[-2] = 88
+ a[-1] = 99
self.assertEqual(a, self.type2test([5,6,7,88,99]))
a[-2] = 8
a[-1] = 9
@@ -189,8 +189,8 @@
self.assertEqual(a, self.type2test([]))
a = self.type2test([0, 1])
- del a[1L:2L]
- del a[0L:1L]
+ del a[1:2]
+ del a[0:1]
self.assertEqual(a, self.type2test([]))
a = self.type2test([0, 1])
@@ -198,7 +198,7 @@
self.assertEqual(a, self.type2test([1]))
a = self.type2test([0, 1])
- del a[-2L:-1L]
+ del a[-2:-1]
self.assertEqual(a, self.type2test([1]))
a = self.type2test([0, 1])
@@ -207,8 +207,8 @@
self.assertEqual(a, self.type2test([]))
a = self.type2test([0, 1])
- del a[1L:]
- del a[:1L]
+ del a[1:]
+ del a[:1]
self.assertEqual(a, self.type2test([]))
a = self.type2test([0, 1])
@@ -216,7 +216,7 @@
self.assertEqual(a, self.type2test([0]))
a = self.type2test([0, 1])
- del a[-1L:]
+ del a[-1:]
self.assertEqual(a, self.type2test([0]))
a = self.type2test([0, 1])
Modified: python/branches/p3yk-noslice/Lib/test/mapping_tests.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/mapping_tests.py (original)
+++ python/branches/p3yk-noslice/Lib/test/mapping_tests.py Fri Feb 23 18:29:35 2007
@@ -49,7 +49,7 @@
#Indexing
for key, value in self.reference.items():
self.assertEqual(d[key], value)
- knownkey = self.other.keys()[0]
+ knownkey = list(self.other.keys())[0]
self.failUnlessRaises(KeyError, lambda:d[knownkey])
#len
self.assertEqual(len(p), 0)
@@ -73,13 +73,16 @@
self.assert_(hasattr(iter, '__iter__'))
x = list(iter)
self.assert_(set(x)==set(lst)==set(ref))
- check_iterandlist(d.iterkeys(), d.keys(), self.reference.keys())
- check_iterandlist(iter(d), d.keys(), self.reference.keys())
- check_iterandlist(d.itervalues(), d.values(), self.reference.values())
- check_iterandlist(d.iteritems(), d.items(), self.reference.items())
+ check_iterandlist(iter(d.keys()), list(d.keys()),
+ self.reference.keys())
+ check_iterandlist(iter(d), list(d.keys()), self.reference.keys())
+ check_iterandlist(iter(d.values()), list(d.values()),
+ self.reference.values())
+ check_iterandlist(iter(d.items()), list(d.items()),
+ self.reference.items())
#get
- key, value = d.iteritems().next()
- knownkey, knownvalue = self.other.iteritems().next()
+ key, value = iter(d.items()).next()
+ knownkey, knownvalue = iter(self.other.items()).next()
self.assertEqual(d.get(key, knownvalue), value)
self.assertEqual(d.get(knownkey, knownvalue), knownvalue)
self.failIf(knownkey in d)
@@ -98,14 +101,14 @@
#update
p.update(self.reference)
self.assertEqual(dict(p), self.reference)
- items = p.items()
+ items = list(p.items())
p = self._empty_mapping()
p.update(items)
self.assertEqual(dict(p), self.reference)
d = self._full_mapping(self.reference)
#setdefault
- key, value = d.iteritems().next()
- knownkey, knownvalue = self.other.iteritems().next()
+ key, value = iter(d.items()).next()
+ knownkey, knownvalue = iter(self.other.items()).next()
self.assertEqual(d.setdefault(key, knownvalue), value)
self.assertEqual(d[key], value)
self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue)
@@ -137,21 +140,21 @@
def test_keys(self):
d = self._empty_mapping()
- self.assertEqual(d.keys(), [])
+ self.assertEqual(list(d.keys()), [])
d = self.reference
- self.assert_(self.inmapping.keys()[0] in d.keys())
- self.assert_(self.other.keys()[0] not in d.keys())
+ self.assert_(list(self.inmapping.keys())[0] in d.keys())
+ self.assert_(list(self.other.keys())[0] not in d.keys())
self.assertRaises(TypeError, d.keys, None)
def test_values(self):
d = self._empty_mapping()
- self.assertEqual(d.values(), [])
+ self.assertEqual(list(d.values()), [])
self.assertRaises(TypeError, d.values, None)
def test_items(self):
d = self._empty_mapping()
- self.assertEqual(d.items(), [])
+ self.assertEqual(list(d.items()), [])
self.assertRaises(TypeError, d.items, None)
@@ -161,7 +164,8 @@
def test_getitem(self):
d = self.reference
- self.assertEqual(d[self.inmapping.keys()[0]], self.inmapping.values()[0])
+ self.assertEqual(d[list(self.inmapping.keys())[0]],
+ list(self.inmapping.values())[0])
self.assertRaises(TypeError, d.__getitem__)
@@ -169,7 +173,7 @@
# mapping argument
d = self._empty_mapping()
d.update(self.other)
- self.assertEqual(d.items(), self.other.items())
+ self.assertEqual(list(d.items()), list(self.other.items()))
# No argument
d = self._empty_mapping()
@@ -179,12 +183,12 @@
# item sequence
d = self._empty_mapping()
d.update(self.other.items())
- self.assertEqual(d.items(), self.other.items())
+ self.assertEqual(list(d.items()), list(self.other.items()))
# Iterator
d = self._empty_mapping()
- d.update(self.other.iteritems())
- self.assertEqual(d.items(), self.other.items())
+ d.update(self.other.items())
+ self.assertEqual(list(d.items()), list(self.other.items()))
# FIXME: Doesn't work with UserDict
# self.assertRaises((TypeError, AttributeError), d.update, None)
@@ -200,10 +204,8 @@
return self.d[i]
d.clear()
d.update(SimpleUserDict())
- i1 = d.items()
- i2 = self.reference.items()
- i1.sort()
- i2.sort()
+ i1 = sorted(d.items())
+ i2 = sorted(self.reference.items())
self.assertEqual(i1, i2)
class Exc(Exception): pass
@@ -266,13 +268,15 @@
def test_get(self):
d = self._empty_mapping()
- self.assert_(d.get(self.other.keys()[0]) is None)
- self.assertEqual(d.get(self.other.keys()[0], 3), 3)
+ self.assert_(d.get(list(self.other.keys())[0]) is None)
+ self.assertEqual(d.get(list(self.other.keys())[0], 3), 3)
d = self.reference
- self.assert_(d.get(self.other.keys()[0]) is None)
- self.assertEqual(d.get(self.other.keys()[0], 3), 3)
- self.assertEqual(d.get(self.inmapping.keys()[0]), self.inmapping.values()[0])
- self.assertEqual(d.get(self.inmapping.keys()[0], 3), self.inmapping.values()[0])
+ self.assert_(d.get(list(self.other.keys())[0]) is None)
+ self.assertEqual(d.get(list(self.other.keys())[0], 3), 3)
+ self.assertEqual(d.get(list(self.inmapping.keys())[0]),
+ list(self.inmapping.values())[0])
+ self.assertEqual(d.get(list(self.inmapping.keys())[0], 3),
+ list(self.inmapping.values())[0])
self.assertRaises(TypeError, d.get)
self.assertRaises(TypeError, d.get, None, None, None)
@@ -287,9 +291,9 @@
def test_pop(self):
d = self._empty_mapping()
- k, v = self.inmapping.items()[0]
+ k, v = list(self.inmapping.items())[0]
d[k] = v
- self.assertRaises(KeyError, d.pop, self.other.keys()[0])
+ self.assertRaises(KeyError, d.pop, list(self.other.keys())[0])
self.assertEqual(d.pop(k), v)
self.assertEqual(len(d), 0)
@@ -313,7 +317,7 @@
def test_keys(self):
BasicTestMappingProtocol.test_keys(self)
d = self._empty_mapping()
- self.assertEqual(d.keys(), [])
+ self.assertEqual(list(d.keys()), [])
d = self._full_mapping({'a': 1, 'b': 2})
k = d.keys()
self.assert_('a' in k)
@@ -323,13 +327,13 @@
def test_values(self):
BasicTestMappingProtocol.test_values(self)
d = self._full_mapping({1:2})
- self.assertEqual(d.values(), [2])
+ self.assertEqual(list(d.values()), [2])
def test_items(self):
BasicTestMappingProtocol.test_items(self)
d = self._full_mapping({1:2})
- self.assertEqual(d.items(), [(1, 2)])
+ self.assertEqual(list(d.items()), [(1, 2)])
def test_contains(self):
d = self._empty_mapping()
@@ -400,7 +404,7 @@
# iterator
d = self._full_mapping({1:3, 2:4})
- d.update(self._full_mapping({1:2, 3:4, 5:6}).iteritems())
+ d.update(self._full_mapping({1:2, 3:4, 5:6}).items())
self.assertEqual(d, {1:2, 2:4, 3:4, 5:6})
class SimpleUserDict:
@@ -526,7 +530,7 @@
# verify longs/ints get same value when key > 32 bits (for 64-bit archs)
# see SF bug #689659
- x = 4503599627370496L
+ x = 4503599627370496
y = 4503599627370496
h = self._full_mapping({x: 'anything', y: 'something else'})
self.assertEqual(h[x], h[y])
@@ -626,7 +630,7 @@
def test_eq(self):
self.assertEqual(self._empty_mapping(), self._empty_mapping())
self.assertEqual(self._full_mapping({1: 2}),
- self._full_mapping({1L: 2L}))
+ self._full_mapping({1: 2}))
class Exc(Exception): pass
Modified: python/branches/p3yk-noslice/Lib/test/output/test_cProfile
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/output/test_cProfile (original)
+++ python/branches/p3yk-noslice/Lib/test/output/test_cProfile Fri Feb 23 18:29:35 2007
@@ -29,12 +29,12 @@
<string>:1(<module>) -> 1 0.270 1.000 test_cProfile.py:30(testfunc)
test_cProfile.py:103(subhelper) -> 16 0.016 0.016 test_cProfile.py:115(__getattr__)
8 0.000 0.000 {range}
-test_cProfile.py:115(__getattr__) ->
+test_cProfile.py:115(__getattr__) ->
test_cProfile.py:30(testfunc) -> 1 0.014 0.130 test_cProfile.py:40(factorial)
2 0.040 0.600 test_cProfile.py:60(helper)
test_cProfile.py:40(factorial) -> 20/3 0.130 0.147 test_cProfile.py:40(factorial)
20 0.020 0.020 test_cProfile.py:53(mul)
-test_cProfile.py:53(mul) ->
+test_cProfile.py:53(mul) ->
test_cProfile.py:60(helper) -> 4 0.116 0.120 test_cProfile.py:78(helper1)
2 0.000 0.140 test_cProfile.py:89(helper2_indirect)
6 0.234 0.300 test_cProfile.py:93(helper2)
@@ -47,10 +47,10 @@
8 0.000 0.008 {hasattr}
{exec} -> 1 0.000 1.000 <string>:1(<module>)
{hasattr} -> 12 0.012 0.012 test_cProfile.py:115(__getattr__)
-{method 'append' of 'list' objects} ->
-{method 'disable' of '_lsprof.Profiler' objects} ->
-{range} ->
-{sys.exc_info} ->
+{method 'append' of 'list' objects} ->
+{method 'disable' of '_lsprof.Profiler' objects} ->
+{range} ->
+{sys.exc_info} ->
Ordered by: standard name
@@ -71,11 +71,11 @@
test_cProfile.py:89(helper2_indirect) <- 2 0.000 0.140 test_cProfile.py:60(helper)
test_cProfile.py:93(helper2) <- 6 0.234 0.300 test_cProfile.py:60(helper)
2 0.078 0.100 test_cProfile.py:89(helper2_indirect)
-{exec} <-
+{exec} <-
{hasattr} <- 4 0.000 0.004 test_cProfile.py:78(helper1)
8 0.000 0.008 test_cProfile.py:93(helper2)
{method 'append' of 'list' objects} <- 4 0.000 0.000 test_cProfile.py:78(helper1)
-{method 'disable' of '_lsprof.Profiler' objects} <-
+{method 'disable' of '_lsprof.Profiler' objects} <-
{range} <- 8 0.000 0.000 test_cProfile.py:103(subhelper)
{sys.exc_info} <- 4 0.000 0.000 test_cProfile.py:78(helper1)
Modified: python/branches/p3yk-noslice/Lib/test/output/test_class
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/output/test_class (original)
+++ python/branches/p3yk-noslice/Lib/test/output/test_class Fri Feb 23 18:29:35 2007
@@ -44,7 +44,7 @@
__pos__: ()
__abs__: ()
__int__: ()
-__long__: ()
+__int__: ()
__float__: ()
__oct__: ()
__hex__: ()
Deleted: /python/branches/p3yk-noslice/Lib/test/output/test_new
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/output/test_new Fri Feb 23 18:29:35 2007
+++ (empty file)
@@ -1,6 +0,0 @@
-test_new
-new.module()
-new.classobj()
-new.instancemethod()
-new.function()
-new.code()
Deleted: /python/branches/p3yk-noslice/Lib/test/output/test_popen
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/output/test_popen Fri Feb 23 18:29:35 2007
+++ (empty file)
@@ -1,3 +0,0 @@
-test_popen
-Test popen:
-popen seemed to process the command-line correctly
Modified: python/branches/p3yk-noslice/Lib/test/output/test_profile
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/output/test_profile (original)
+++ python/branches/p3yk-noslice/Lib/test/output/test_profile Fri Feb 23 18:29:35 2007
@@ -27,24 +27,24 @@
Ordered by: standard name
Function called...
-:0(append) ->
-:0(exc_info) ->
+:0(append) ->
+:0(exc_info) ->
:0(exec) -> <string>:1(<module>)(1) 1.000
:0(hasattr) -> test_profile.py:115(__getattr__)(12) 0.028
-:0(range) ->
-:0(setprofile) ->
+:0(range) ->
+:0(setprofile) ->
<string>:1(<module>) -> test_profile.py:30(testfunc)(1) 1.000
profile:0(profiler) -> profile:0(testfunc())(1) 1.000
profile:0(testfunc()) -> :0(exec)(1) 1.000
:0(setprofile)(1) 0.000
test_profile.py:103(subhelper) -> :0(range)(8) 0.000
test_profile.py:115(__getattr__)(16) 0.028
-test_profile.py:115(__getattr__) ->
+test_profile.py:115(__getattr__) ->
test_profile.py:30(testfunc) -> test_profile.py:40(factorial)(1) 0.170
test_profile.py:60(helper)(2) 0.600
test_profile.py:40(factorial) -> test_profile.py:40(factorial)(20) 0.170
test_profile.py:53(mul)(20) 0.020
-test_profile.py:53(mul) ->
+test_profile.py:53(mul) ->
test_profile.py:60(helper) -> test_profile.py:78(helper1)(4) 0.120
test_profile.py:89(helper2_indirect)(2) 0.140
test_profile.py:93(helper2)(6) 0.400
@@ -68,7 +68,7 @@
:0(range) <- test_profile.py:103(subhelper)(8) 0.080
:0(setprofile) <- profile:0(testfunc())(1) 1.000
<string>:1(<module>) <- :0(exec)(1) 1.000
-profile:0(profiler) <-
+profile:0(profiler) <-
profile:0(testfunc()) <- profile:0(profiler)(1) 0.000
test_profile.py:103(subhelper) <- test_profile.py:93(helper2)(8) 0.400
test_profile.py:115(__getattr__) <- :0(hasattr)(12) 0.012
Deleted: /python/branches/p3yk-noslice/Lib/test/output/test_resource
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/output/test_resource Fri Feb 23 18:29:35 2007
+++ (empty file)
@@ -1,2 +0,0 @@
-test_resource
-True
Modified: python/branches/p3yk-noslice/Lib/test/pickletester.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/pickletester.py (original)
+++ python/branches/p3yk-noslice/Lib/test/pickletester.py Fri Feb 23 18:29:35 2007
@@ -349,7 +349,7 @@
c = C()
c.foo = 1
c.bar = 2
- x = [0, 1L, 2.0, 3.0+0j]
+ x = [0, 1, 2.0, 3.0+0j]
# Append some integer test cases at cPickle.c's internal size
# cutoffs.
uint1max = 0xff
@@ -438,7 +438,7 @@
for proto in protocols:
s = self.dumps(d, proto)
x = self.loads(s)
- self.assertEqual(x.keys(), [1])
+ self.assertEqual(list(x.keys()), [1])
self.assert_(x[1] is x)
def test_recursive_inst(self):
@@ -461,7 +461,7 @@
x = self.loads(s)
self.assertEqual(len(x), 1)
self.assertEqual(dir(x[0]), dir(i))
- self.assertEqual(x[0].attr.keys(), [1])
+ self.assertEqual(list(x[0].attr.keys()), [1])
self.assert_(x[0].attr[1] is x)
def test_garyp(self):
@@ -504,7 +504,7 @@
n = n >> 1
def test_maxint64(self):
- maxint64 = (1L << 63) - 1
+ maxint64 = (1 << 63) - 1
data = 'I' + str(maxint64) + '\n.'
got = self.loads(data)
self.assertEqual(got, maxint64)
@@ -517,7 +517,7 @@
for proto in protocols:
# 256 bytes is where LONG4 begins.
for nbits in 1, 8, 8*254, 8*255, 8*256, 8*257:
- nbase = 1L << nbits
+ nbase = 1 << nbits
for npos in nbase-1, nbase, nbase+1:
for n in npos, -npos:
pickle = self.dumps(n, proto)
@@ -525,7 +525,7 @@
self.assertEqual(n, got)
# Try a monster. This is quadratic-time in protos 0 & 1, so don't
# bother with those.
- nbase = long("deadbeeffeedface", 16)
+ nbase = int("deadbeeffeedface", 16)
nbase += nbase << 1000000
for n in nbase, -nbase:
p = self.dumps(n, 2)
@@ -592,7 +592,7 @@
self.fail("expected bad protocol number to raise ValueError")
def test_long1(self):
- x = 12345678910111213141516178920L
+ x = 12345678910111213141516178920
for proto in protocols:
s = self.dumps(x, proto)
y = self.loads(s)
@@ -600,7 +600,7 @@
self.assertEqual(opcode_in_pickle(pickle.LONG1, s), proto >= 2)
def test_long4(self):
- x = 12345678910111213141516178920L << (256*8)
+ x = 12345678910111213141516178920 << (256*8)
for proto in protocols:
s = self.dumps(x, proto)
y = self.loads(s)
@@ -864,8 +864,8 @@
class MyInt(int):
sample = 1
-class MyLong(long):
- sample = 1L
+class MyLong(int):
+ sample = 1
class MyFloat(float):
sample = 1.0
Modified: python/branches/p3yk-noslice/Lib/test/pydocfodder.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/pydocfodder.py (original)
+++ python/branches/p3yk-noslice/Lib/test/pydocfodder.py Fri Feb 23 18:29:35 2007
@@ -192,19 +192,19 @@
def __init__(self, attr):
self.attr = attr
def __call__(self, inst):
- print 'Get called', self, inst
+ print('Get called', self, inst)
return inst.desc[self.attr]
class set_desc:
def __init__(self, attr):
self.attr = attr
def __call__(self, inst, val):
- print 'Set called', self, inst, val
+ print('Set called', self, inst, val)
inst.desc[self.attr] = val
class del_desc:
def __init__(self, attr):
self.attr = attr
def __call__(self, inst):
- print 'Del called', self, inst
+ print('Del called', self, inst)
del inst.desc[self.attr]
x = property(get_desc('x'), set_desc('x'), del_desc('x'), 'prop x')
Modified: python/branches/p3yk-noslice/Lib/test/pystone.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/pystone.py (original)
+++ python/branches/p3yk-noslice/Lib/test/pystone.py Fri Feb 23 18:29:35 2007
@@ -59,9 +59,9 @@
def main(loops=LOOPS):
benchtime, stones = pystones(loops)
- print "Pystone(%s) time for %d passes = %g" % \
- (__version__, loops, benchtime)
- print "This machine benchmarks at %g pystones/second" % stones
+ print("Pystone(%s) time for %d passes = %g" % \
+ (__version__, loops, benchtime))
+ print("This machine benchmarks at %g pystones/second" % stones)
def pystones(loops=LOOPS):
@@ -251,8 +251,8 @@
if __name__ == '__main__':
import sys
def error(msg):
- print >>sys.stderr, msg,
- print >>sys.stderr, "usage: %s [number_of_loops]" % sys.argv[0]
+ print(msg, end=' ', file=sys.stderr)
+ print("usage: %s [number_of_loops]" % sys.argv[0], file=sys.stderr)
sys.exit(100)
nargs = len(sys.argv) - 1
if nargs > 1:
Modified: python/branches/p3yk-noslice/Lib/test/regrtest.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/regrtest.py (original)
+++ python/branches/p3yk-noslice/Lib/test/regrtest.py Fri Feb 23 18:29:35 2007
@@ -171,8 +171,8 @@
def usage(code, msg=''):
- print __doc__
- if msg: print msg
+ print(__doc__)
+ if msg: print(msg)
sys.exit(code)
@@ -253,7 +253,7 @@
elif o in ('-R', '--huntrleaks'):
huntrleaks = a.split(':')
if len(huntrleaks) != 3:
- print a, huntrleaks
+ print(a, huntrleaks)
usage(2, '-R takes three colon-separated arguments')
if len(huntrleaks[0]) == 0:
huntrleaks[0] = 5
@@ -298,7 +298,7 @@
try:
import gc
except ImportError:
- print 'No GC available, disabling findleaks.'
+ print('No GC available, disabling findleaks.')
findleaks = False
else:
# Uncomment the line below to report garbage that is not
@@ -355,7 +355,7 @@
save_modules = sys.modules.keys()
for test in tests:
if not quiet:
- print test
+ print(test)
sys.stdout.flush()
if trace:
# If we're tracing code coverage, then we don't exit with status
@@ -368,7 +368,7 @@
huntrleaks)
except KeyboardInterrupt:
# print a newline separate from the ^C
- print
+ print()
break
except:
raise
@@ -383,8 +383,8 @@
if findleaks:
gc.collect()
if gc.garbage:
- print "Warning: test created", len(gc.garbage),
- print "uncollectable object(s)."
+ print("Warning: test created", len(gc.garbage), end=' ')
+ print("uncollectable object(s).")
# move the uncollectable objects somewhere so we don't see
# them again
found_garbage.extend(gc.garbage)
@@ -401,16 +401,16 @@
if good and not quiet:
if not bad and not skipped and len(good) > 1:
- print "All",
- print count(len(good), "test"), "OK."
+ print("All", end=' ')
+ print(count(len(good), "test"), "OK.")
if verbose:
- print "CAUTION: stdout isn't compared in verbose mode:"
- print "a test that passes in verbose mode may fail without it."
+ print("CAUTION: stdout isn't compared in verbose mode:")
+ print("a test that passes in verbose mode may fail without it.")
if bad:
- print count(len(bad), "test"), "failed:"
+ print(count(len(bad), "test"), "failed:")
printlist(bad)
if skipped and not quiet:
- print count(len(skipped), "test"), "skipped:"
+ print(count(len(skipped), "test"), "skipped:")
printlist(skipped)
e = _ExpectedSkips()
@@ -418,19 +418,19 @@
if e.isvalid():
surprise = set(skipped) - e.getexpected() - set(resource_denieds)
if surprise:
- print count(len(surprise), "skip"), \
- "unexpected on", plat + ":"
+ print(count(len(surprise), "skip"), \
+ "unexpected on", plat + ":")
printlist(surprise)
else:
- print "Those skips are all expected on", plat + "."
+ print("Those skips are all expected on", plat + ".")
else:
- print "Ask someone to teach regrtest.py about which tests are"
- print "expected to get skipped on", plat + "."
+ print("Ask someone to teach regrtest.py about which tests are")
+ print("expected to get skipped on", plat + ".")
if verbose2 and bad:
- print "Re-running failed tests in verbose mode"
+ print("Re-running failed tests in verbose mode")
for test in bad:
- print "Re-running test %r in verbose mode" % test
+ print("Re-running test %r in verbose mode" % test)
sys.stdout.flush()
try:
test_support.verbose = 1
@@ -438,7 +438,7 @@
huntrleaks)
except KeyboardInterrupt:
# print a newline separate from the ^C
- print
+ print()
break
except:
raise
@@ -537,7 +537,7 @@
try:
if cfp:
sys.stdout = cfp
- print test # Output file starts with test name
+ print(test) # Output file starts with test name
if test.startswith('test.'):
abstest = test
else:
@@ -558,23 +558,23 @@
sys.stdout = save_stdout
except test_support.ResourceDenied as msg:
if not quiet:
- print test, "skipped --", msg
+ print(test, "skipped --", msg)
sys.stdout.flush()
return -2
except (ImportError, test_support.TestSkipped) as msg:
if not quiet:
- print test, "skipped --", msg
+ print(test, "skipped --", msg)
sys.stdout.flush()
return -1
except KeyboardInterrupt:
raise
except test_support.TestFailed as msg:
- print "test", test, "failed --", msg
+ print("test", test, "failed --", msg)
sys.stdout.flush()
return 0
except:
type, value = sys.exc_info()[:2]
- print "test", test, "crashed --", str(type) + ":", value
+ print("test", test, "crashed --", str(type) + ":", value)
sys.stdout.flush()
if verbose:
traceback.print_exc(file=sys.stdout)
@@ -590,8 +590,8 @@
# Write it since it already exists (and the contents
# may have changed), but let the user know it isn't
# needed:
- print "output file", outputfile, \
- "is no longer needed; consider removing it"
+ print("output file", outputfile, \
+ "is no longer needed; consider removing it")
else:
# We don't need it, so don't create it.
return 1
@@ -607,7 +607,7 @@
expected = test + "\n"
if output == expected or huntrleaks:
return 1
- print "test", test, "produced unexpected output:"
+ print("test", test, "produced unexpected output:")
sys.stdout.flush()
reportdiff(expected, output)
sys.stdout.flush()
@@ -637,12 +637,12 @@
"directory nor file" % name)
if verbose:
- print "%r left behind %s %r" % (testname, kind, name)
+ print("%r left behind %s %r" % (testname, kind, name))
try:
nuker(name)
except Exception as msg:
- print >> sys.stderr, ("%r left behind %s %r and it couldn't be "
- "removed: %s" % (testname, kind, name, msg))
+ print(("%r left behind %s %r and it couldn't be "
+ "removed: %s" % (testname, kind, name, msg)), file=sys.stderr)
def dash_R(the_module, test, indirect_test, huntrleaks):
# This code is hackish and inelegant, but it seems to do the job.
@@ -667,8 +667,8 @@
deltas = []
nwarmup, ntracked, fname = huntrleaks
repcount = nwarmup + ntracked
- print >> sys.stderr, "beginning", repcount, "repetitions"
- print >> sys.stderr, ("1234567890"*(repcount//10 + 1))[:repcount]
+ print("beginning", repcount, "repetitions", file=sys.stderr)
+ print(("1234567890"*(repcount//10 + 1))[:repcount], file=sys.stderr)
dash_R_cleanup(fs, ps, pic)
for i in range(repcount):
rc = sys.gettotalrefcount()
@@ -677,11 +677,11 @@
dash_R_cleanup(fs, ps, pic)
if i >= nwarmup:
deltas.append(sys.gettotalrefcount() - rc - 2)
- print >> sys.stderr
+ print(file=sys.stderr)
if any(deltas):
- print >> sys.stderr, test, 'leaked', deltas, 'references'
+ print(test, 'leaked', deltas, 'references', file=sys.stderr)
refrep = open(fname, "a")
- print >> refrep, test, 'leaked', deltas, 'references'
+ print(test, 'leaked', deltas, 'references', file=refrep)
refrep.close()
def dash_R_cleanup(fs, ps, pic):
@@ -717,7 +717,7 @@
def reportdiff(expected, output):
import difflib
- print "*" * 70
+ print("*" * 70)
a = expected.splitlines(1)
b = output.splitlines(1)
sm = difflib.SequenceMatcher(a=a, b=b)
@@ -736,26 +736,26 @@
pass
elif op == 'delete':
- print "***", pair(a0, a1), "of expected output missing:"
+ print("***", pair(a0, a1), "of expected output missing:")
for line in a[a0:a1]:
- print "-", line,
+ print("-", line, end='')
elif op == 'replace':
- print "*** mismatch between", pair(a0, a1), "of expected", \
- "output and", pair(b0, b1), "of actual output:"
+ print("*** mismatch between", pair(a0, a1), "of expected", \
+ "output and", pair(b0, b1), "of actual output:")
for line in difflib.ndiff(a[a0:a1], b[b0:b1]):
- print line,
+ print(line, end='')
elif op == 'insert':
- print "***", pair(b0, b1), "of actual output doesn't appear", \
- "in expected output after line", str(a1)+":"
+ print("***", pair(b0, b1), "of actual output doesn't appear", \
+ "in expected output after line", str(a1)+":")
for line in b[b0:b1]:
- print "+", line,
+ print("+", line, end='')
else:
- print "get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1)
+ print("get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1))
- print "*" * 70
+ print("*" * 70)
def findtestdir():
if __name__ == '__main__':
@@ -786,8 +786,8 @@
from textwrap import fill
blanks = ' ' * indent
- print fill(' '.join(map(str, x)), width,
- initial_indent=blanks, subsequent_indent=blanks)
+ print(fill(' '.join(map(str, x)), width,
+ initial_indent=blanks, subsequent_indent=blanks))
# Map sys.platform to a string containing the basenames of tests
# expected to be skipped on that platform.
@@ -1324,7 +1324,7 @@
if test_timeout.skip_expected:
self.expected.add('test_timeout')
- if sys.maxint == 9223372036854775807L:
+ if sys.maxint == 9223372036854775807:
self.expected.add('test_rgbimg')
self.expected.add('test_imageop')
@@ -1369,5 +1369,5 @@
if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
del sys.path[i]
if len(sys.path) == pathlen:
- print 'Could not find %r in sys.path to remove it' % mydir
+ print('Could not find %r in sys.path to remove it' % mydir)
main()
Modified: python/branches/p3yk-noslice/Lib/test/reperf.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/reperf.py (original)
+++ python/branches/p3yk-noslice/Lib/test/reperf.py Fri Feb 23 18:29:35 2007
@@ -17,7 +17,7 @@
finally:
t1 = time.clock()
if n > 1:
- print n, "times",
- print func.__name__, "%.3f" % (t1-t0), "CPU seconds"
+ print(n, "times", end=' ')
+ print(func.__name__, "%.3f" % (t1-t0), "CPU seconds")
main()
Modified: python/branches/p3yk-noslice/Lib/test/sample_doctest.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/sample_doctest.py (original)
+++ python/branches/p3yk-noslice/Lib/test/sample_doctest.py Fri Feb 23 18:29:35 2007
@@ -40,9 +40,9 @@
def w_blank():
"""
>>> if 1:
- ... print 'a'
- ... print
- ... print 'b'
+ ... print('a')
+ ... print()
+ ... print('b')
a
<BLANKLINE>
b
Modified: python/branches/p3yk-noslice/Lib/test/seq_tests.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/seq_tests.py (original)
+++ python/branches/p3yk-noslice/Lib/test/seq_tests.py Fri Feb 23 18:29:35 2007
@@ -138,10 +138,10 @@
u = self.type2test([0, 1, 2, 3, 4])
for i in xrange(len(u)):
self.assertEqual(u[i], i)
- self.assertEqual(u[long(i)], i)
+ self.assertEqual(u[int(i)], i)
for i in xrange(-len(u), -1):
self.assertEqual(u[i], len(u)+i)
- self.assertEqual(u[long(i)], len(u)+i)
+ self.assertEqual(u[int(i)], len(u)+i)
self.assertRaises(IndexError, u.__getitem__, -len(u)-1)
self.assertRaises(IndexError, u.__getitem__, len(u))
self.assertRaises(ValueError, u.__getitem__, slice(0,10,0))
@@ -189,12 +189,12 @@
self.assertEqual(u[-100:100:], u)
self.assertEqual(u[100:-100:-1], u[::-1])
self.assertEqual(u[-100:100:-1], self.type2test([]))
- self.assertEqual(u[-100L:100L:2L], self.type2test([0, 2, 4]))
+ self.assertEqual(u[-100:100:2], self.type2test([0, 2, 4]))
# Test extreme cases with long ints
a = self.type2test([0,1,2,3,4])
- self.assertEqual(a[ -pow(2,128L): 3 ], self.type2test([0,1,2]))
- self.assertEqual(a[ 3: pow(2,145L) ], self.type2test([3,4]))
+ self.assertEqual(a[ -pow(2,128): 3 ], self.type2test([0,1,2]))
+ self.assertEqual(a[ 3: pow(2,145) ], self.type2test([3,4]))
def test_contains(self):
u = self.type2test([0, 1, 2])
@@ -252,16 +252,16 @@
self.assertEqual(self.type2test([-1]) + u1, self.type2test([-1, 0]))
self.assertEqual(self.type2test(), u2*0)
self.assertEqual(self.type2test(), 0*u2)
- self.assertEqual(self.type2test(), u2*0L)
- self.assertEqual(self.type2test(), 0L*u2)
+ self.assertEqual(self.type2test(), u2*0)
+ self.assertEqual(self.type2test(), 0*u2)
+ self.assertEqual(u2, u2*1)
+ self.assertEqual(u2, 1*u2)
self.assertEqual(u2, u2*1)
self.assertEqual(u2, 1*u2)
- self.assertEqual(u2, u2*1L)
- self.assertEqual(u2, 1L*u2)
self.assertEqual(u2+u2, u2*2)
self.assertEqual(u2+u2, 2*u2)
- self.assertEqual(u2+u2, u2*2L)
- self.assertEqual(u2+u2, 2L*u2)
+ self.assertEqual(u2+u2, u2*2)
+ self.assertEqual(u2+u2, 2*u2)
self.assertEqual(u2+u2+u2, u2*3)
self.assertEqual(u2+u2+u2, 3*u2)
@@ -306,10 +306,10 @@
def test_subscript(self):
a = self.type2test([10, 11])
- self.assertEqual(a.__getitem__(0L), 10)
- self.assertEqual(a.__getitem__(1L), 11)
- self.assertEqual(a.__getitem__(-2L), 10)
- self.assertEqual(a.__getitem__(-1L), 11)
+ self.assertEqual(a.__getitem__(0), 10)
+ self.assertEqual(a.__getitem__(1), 11)
+ self.assertEqual(a.__getitem__(-2), 10)
+ self.assertEqual(a.__getitem__(-1), 11)
self.assertRaises(IndexError, a.__getitem__, -3)
self.assertRaises(IndexError, a.__getitem__, 3)
self.assertEqual(a.__getitem__(slice(0,1)), self.type2test([10]))
Modified: python/branches/p3yk-noslice/Lib/test/sortperf.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/sortperf.py (original)
+++ python/branches/p3yk-noslice/Lib/test/sortperf.py Fri Feb 23 18:29:35 2007
@@ -38,7 +38,7 @@
except os.error:
pass
except IOError as msg:
- print "can't write", fn, ":", msg
+ print("can't write", fn, ":", msg)
else:
result = marshal.load(fp)
fp.close()
@@ -60,7 +60,7 @@
t0 = time.clock()
L.sort()
t1 = time.clock()
- print "%6.2f" % (t1-t0),
+ print("%6.2f" % (t1-t0), end=' ')
flush()
def tabulate(r):
@@ -84,11 +84,11 @@
"""
cases = tuple([ch + "sort" for ch in r"*\/3+%~=!"])
fmt = ("%2s %7s" + " %6s"*len(cases))
- print fmt % (("i", "2**i") + cases)
+ print(fmt % (("i", "2**i") + cases))
for i in r:
n = 1 << i
L = randfloats(n)
- print "%2d %7d" % (i, n),
+ print("%2d %7d" % (i, n), end=' ')
flush()
doit(L) # *sort
L.reverse()
@@ -137,7 +137,7 @@
# significantly faster if we leave tham as ints.
L = map(float, L)
doit(L) # !sort
- print
+ print()
def main():
"""Main program when invoked as a script.
Modified: python/branches/p3yk-noslice/Lib/test/string_tests.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/string_tests.py (original)
+++ python/branches/p3yk-noslice/Lib/test/string_tests.py Fri Feb 23 18:29:35 2007
@@ -12,7 +12,7 @@
def __getitem__(self, i): return self.seq[i]
class BadSeq1(Sequence):
- def __init__(self): self.seq = [7, 'hello', 123L]
+ def __init__(self): self.seq = [7, 'hello', 123]
class BadSeq2(Sequence):
def __init__(self): self.seq = ['a', 'b', 'c']
@@ -40,7 +40,7 @@
elif isinstance(obj, dict):
return dict([
(self.fixtype(key), self.fixtype(value))
- for (key, value) in obj.iteritems()
+ for (key, value) in obj.items()
])
else:
return obj
@@ -902,7 +902,7 @@
def test_subscript(self):
self.checkequal(u'a', 'abc', '__getitem__', 0)
self.checkequal(u'c', 'abc', '__getitem__', -1)
- self.checkequal(u'a', 'abc', '__getitem__', 0L)
+ self.checkequal(u'a', 'abc', '__getitem__', 0)
self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 3))
self.checkequal(u'abc', 'abc', '__getitem__', slice(0, 1000))
self.checkequal(u'a', 'abc', '__getitem__', slice(0, 1))
@@ -962,7 +962,7 @@
self.checkraises(TypeError, ' ', 'join')
self.checkraises(TypeError, ' ', 'join', 7)
- self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123L]))
+ self.checkraises(TypeError, ' ', 'join', Sequence([7, 'hello', 123]))
try:
def f():
yield 4 + ""
Modified: python/branches/p3yk-noslice/Lib/test/test___all__.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test___all__.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test___all__.py Fri Feb 23 18:29:35 2007
@@ -132,7 +132,6 @@
self.check_all("rlcompleter")
self.check_all("robotparser")
self.check_all("sched")
- self.check_all("sets")
self.check_all("sgmllib")
self.check_all("shelve")
self.check_all("shlex")
Modified: python/branches/p3yk-noslice/Lib/test/test_al.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_al.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_al.py Fri Feb 23 18:29:35 2007
@@ -14,10 +14,10 @@
def main():
# touch all the attributes of al without doing anything
if verbose:
- print 'Touching al module attributes...'
+ print('Touching al module attributes...')
for attr in alattrs:
if verbose:
- print 'touching: ', attr
+ print('touching: ', attr)
getattr(al, attr)
main()
Modified: python/branches/p3yk-noslice/Lib/test/test_anydbm.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_anydbm.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_anydbm.py Fri Feb 23 18:29:35 2007
@@ -72,10 +72,8 @@
f.close()
def keys_helper(self, f):
- keys = f.keys()
- keys.sort()
- dkeys = self._dict.keys()
- dkeys.sort()
+ keys = sorted(f.keys())
+ dkeys = sorted(self._dict.keys())
self.assertEqual(keys, dkeys)
return keys
Modified: python/branches/p3yk-noslice/Lib/test/test_array.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_array.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_array.py Fri Feb 23 18:29:35 2007
@@ -12,6 +12,10 @@
class ArraySubclass(array.array):
pass
+class ArraySubclassWithKwargs(array.array):
+ def __init__(self, typecode, newarg=None):
+ array.array.__init__(typecode)
+
tests = [] # list to accumulate all tests
typecodes = "cubBhHiIlLfd"
@@ -61,7 +65,7 @@
bi = a.buffer_info()
self.assert_(isinstance(bi, tuple))
self.assertEqual(len(bi), 2)
- self.assert_(isinstance(bi[0], (int, long)))
+ self.assert_(isinstance(bi[0], (int, int)))
self.assert_(isinstance(bi[1], int))
self.assertEqual(bi[1], len(a))
@@ -323,9 +327,9 @@
def test_getitem(self):
a = array.array(self.typecode, self.example)
self.assertEntryEqual(a[0], self.example[0])
- self.assertEntryEqual(a[0L], self.example[0])
+ self.assertEntryEqual(a[0], self.example[0])
+ self.assertEntryEqual(a[-1], self.example[-1])
self.assertEntryEqual(a[-1], self.example[-1])
- self.assertEntryEqual(a[-1L], self.example[-1])
self.assertEntryEqual(a[len(self.example)-1], self.example[-1])
self.assertEntryEqual(a[-len(self.example)], self.example[0])
self.assertRaises(TypeError, a.__getitem__)
@@ -338,7 +342,7 @@
self.assertEntryEqual(a[0], a[-1])
a = array.array(self.typecode, self.example)
- a[0L] = a[-1]
+ a[0] = a[-1]
self.assertEntryEqual(a[0], a[-1])
a = array.array(self.typecode, self.example)
@@ -346,7 +350,7 @@
self.assertEntryEqual(a[0], a[-1])
a = array.array(self.typecode, self.example)
- a[-1L] = a[0]
+ a[-1] = a[0]
self.assertEntryEqual(a[0], a[-1])
a = array.array(self.typecode, self.example)
@@ -715,6 +719,9 @@
b = array.array('B', range(64))
self.assertEqual(rc, sys.getrefcount(10))
+ def test_subclass_with_kwargs(self):
+ # SF bug #1486663 -- this used to erroneously raise a TypeError
+ ArraySubclassWithKwargs('b', newarg=1)
class StringTest(BaseTest):
@@ -754,7 +761,7 @@
self.assertEqual(s.color, "blue")
s.color = "red"
self.assertEqual(s.color, "red")
- self.assertEqual(s.__dict__.keys(), ["color"])
+ self.assertEqual(list(s.__dict__.keys()), ["color"])
def test_nounicode(self):
a = array.array(self.typecode, self.example)
@@ -809,7 +816,7 @@
self.assertEqual(a[3::-2], array.array(self.typecode, [3,1]))
self.assertEqual(a[-100:100:], a)
self.assertEqual(a[100:-100:-1], a[::-1])
- self.assertEqual(a[-100L:100L:2L], array.array(self.typecode, [0,2,4]))
+ self.assertEqual(a[-100:100:2], array.array(self.typecode, [0,2,4]))
self.assertEqual(a[1000:2000:2], array.array(self.typecode, []))
self.assertEqual(a[-1000:-2000:-2], array.array(self.typecode, []))
@@ -895,8 +902,8 @@
def test_overflow(self):
a = array.array(self.typecode)
- lower = -1 * long(pow(2, a.itemsize * 8 - 1))
- upper = long(pow(2, a.itemsize * 8 - 1)) - 1L
+ lower = -1 * int(pow(2, a.itemsize * 8 - 1))
+ upper = int(pow(2, a.itemsize * 8 - 1)) - 1
self.check_overflow(lower, upper)
class UnsignedNumberTest(NumberTest):
@@ -908,7 +915,7 @@
def test_overflow(self):
a = array.array(self.typecode)
lower = 0
- upper = long(pow(2, a.itemsize * 8)) - 1L
+ upper = int(pow(2, a.itemsize * 8)) - 1
self.check_overflow(lower, upper)
@@ -1000,7 +1007,7 @@
test_support.run_unittest(*tests)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
Modified: python/branches/p3yk-noslice/Lib/test/test_ast.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_ast.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_ast.py Fri Feb 23 18:29:35 2007
@@ -2,7 +2,7 @@
import _ast
def to_tuple(t):
- if t is None or isinstance(t, (basestring, int, long, complex)):
+ if t is None or isinstance(t, (basestring, int, int, complex)):
return t
elif isinstance(t, list):
return [to_tuple(e) for e in t]
@@ -30,8 +30,6 @@
"v = 1",
# AugAssign
"v += 1",
- # Print
- "print >>f, 1, ",
# For
"for v in v:pass",
# While
@@ -93,7 +91,7 @@
# Call
"f(1,2,c=3,*d,**e)",
# Num
- "10L",
+ "10",
# Str
"'string'",
# Attribute
@@ -117,11 +115,11 @@
if __name__=='__main__' and sys.argv[1:] == ['-g']:
for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
(eval_tests, "eval")):
- print kind+"_results = ["
+ print(kind+"_results = [")
for s in statements:
- print repr(to_tuple(compile(s, "?", kind, 0x400)))+","
- print "]"
- print "run_tests()"
+ print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",")
+ print("]")
+ print("run_tests()")
raise SystemExit
def test_order(ast_node, parent_pos):
@@ -157,7 +155,6 @@
('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]),
('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Num', (1, 5), 1))]),
-('Module', [('Print', (1, 0), ('Name', (1, 8), 'f', ('Load',)), [('Num', (1, 11), 1)], False)]),
('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]),
('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]),
('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]),
Modified: python/branches/p3yk-noslice/Lib/test/test_asynchat.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_asynchat.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_asynchat.py Fri Feb 23 18:29:35 2007
@@ -77,7 +77,7 @@
s = echo_server()
s.start()
time.sleep(1) # Give server time to initialize
- c = echo_client(6L)
+ c = echo_client(6)
c.push("hello ")
c.push("world\n")
asyncore.loop()
Modified: python/branches/p3yk-noslice/Lib/test/test_atexit.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_atexit.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_atexit.py Fri Feb 23 18:29:35 2007
@@ -75,16 +75,16 @@
### helpers
def h1(self):
- print "h1"
+ print("h1")
def h2(self):
- print "h2"
+ print("h2")
def h3(self):
- print "h3"
+ print("h3")
def h4(self, *args, **kwargs):
- print "h4", args, kwargs
+ print("h4", args, kwargs)
def raise1(self):
raise TypeError
Modified: python/branches/p3yk-noslice/Lib/test/test_audioop.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_audioop.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_audioop.py Fri Feb 23 18:29:35 2007
@@ -7,7 +7,7 @@
def gendata2():
if verbose:
- print 'getsample'
+ print('getsample')
if audioop.getsample('\0\1', 2, 0) == 1:
return '\0\0\0\1\0\2'
else:
@@ -15,7 +15,7 @@
def gendata4():
if verbose:
- print 'getsample'
+ print('getsample')
if audioop.getsample('\0\0\0\1', 4, 0) == 1:
return '\0\0\0\0\0\0\0\1\0\0\0\2'
else:
@@ -23,7 +23,7 @@
def testmax(data):
if verbose:
- print 'max'
+ print('max')
if audioop.max(data[0], 1) != 2 or \
audioop.max(data[1], 2) != 2 or \
audioop.max(data[2], 4) != 2:
@@ -32,7 +32,7 @@
def testminmax(data):
if verbose:
- print 'minmax'
+ print('minmax')
if audioop.minmax(data[0], 1) != (0, 2) or \
audioop.minmax(data[1], 2) != (0, 2) or \
audioop.minmax(data[2], 4) != (0, 2):
@@ -41,7 +41,7 @@
def testmaxpp(data):
if verbose:
- print 'maxpp'
+ print('maxpp')
if audioop.maxpp(data[0], 1) != 0 or \
audioop.maxpp(data[1], 2) != 0 or \
audioop.maxpp(data[2], 4) != 0:
@@ -50,7 +50,7 @@
def testavg(data):
if verbose:
- print 'avg'
+ print('avg')
if audioop.avg(data[0], 1) != 1 or \
audioop.avg(data[1], 2) != 1 or \
audioop.avg(data[2], 4) != 1:
@@ -59,7 +59,7 @@
def testavgpp(data):
if verbose:
- print 'avgpp'
+ print('avgpp')
if audioop.avgpp(data[0], 1) != 0 or \
audioop.avgpp(data[1], 2) != 0 or \
audioop.avgpp(data[2], 4) != 0:
@@ -75,7 +75,7 @@
def testcross(data):
if verbose:
- print 'cross'
+ print('cross')
if audioop.cross(data[0], 1) != 0 or \
audioop.cross(data[1], 2) != 0 or \
audioop.cross(data[2], 4) != 0:
@@ -84,7 +84,7 @@
def testadd(data):
if verbose:
- print 'add'
+ print('add')
data2 = []
for d in data:
str = ''
@@ -99,7 +99,7 @@
def testbias(data):
if verbose:
- print 'bias'
+ print('bias')
# Note: this test assumes that avg() works
d1 = audioop.bias(data[0], 1, 100)
d2 = audioop.bias(data[1], 2, 100)
@@ -112,7 +112,7 @@
def testlin2lin(data):
if verbose:
- print 'lin2lin'
+ print('lin2lin')
# too simple: we test only the size
for d1 in data:
for d2 in data:
@@ -130,7 +130,7 @@
def testlin2adpcm(data):
if verbose:
- print 'lin2adpcm'
+ print('lin2adpcm')
# Very cursory test
if audioop.lin2adpcm('\0\0\0\0', 1, None) != ('\0\0', (0,0)):
return 0
@@ -138,7 +138,7 @@
def testlin2alaw(data):
if verbose:
- print 'lin2alaw'
+ print('lin2alaw')
if audioop.lin2alaw(data[0], 1) != '\xd5\xc5\xf5' or \
audioop.lin2alaw(data[1], 2) != '\xd5\xd5\xd5' or \
audioop.lin2alaw(data[2], 4) != '\xd5\xd5\xd5':
@@ -147,7 +147,7 @@
def testalaw2lin(data):
if verbose:
- print 'alaw2lin'
+ print('alaw2lin')
# Cursory
d = audioop.lin2alaw(data[0], 1)
if audioop.alaw2lin(d, 1) != data[0]:
@@ -156,7 +156,7 @@
def testlin2ulaw(data):
if verbose:
- print 'lin2ulaw'
+ print('lin2ulaw')
if audioop.lin2ulaw(data[0], 1) != '\xff\xe7\xdb' or \
audioop.lin2ulaw(data[1], 2) != '\xff\xff\xff' or \
audioop.lin2ulaw(data[2], 4) != '\xff\xff\xff':
@@ -165,7 +165,7 @@
def testulaw2lin(data):
if verbose:
- print 'ulaw2lin'
+ print('ulaw2lin')
# Cursory
d = audioop.lin2ulaw(data[0], 1)
if audioop.ulaw2lin(d, 1) != data[0]:
@@ -174,7 +174,7 @@
def testmul(data):
if verbose:
- print 'mul'
+ print('mul')
data2 = []
for d in data:
str = ''
@@ -189,7 +189,7 @@
def testratecv(data):
if verbose:
- print 'ratecv'
+ print('ratecv')
state = None
d1, state = audioop.ratecv(data[0], 1, 1, 8000, 16000, state)
d2, state = audioop.ratecv(data[0], 1, 1, 8000, 16000, state)
@@ -199,14 +199,14 @@
def testreverse(data):
if verbose:
- print 'reverse'
+ print('reverse')
if audioop.reverse(data[0], 1) != '\2\1\0':
return 0
return 1
def testtomono(data):
if verbose:
- print 'tomono'
+ print('tomono')
data2 = ''
for d in data[0]:
data2 = data2 + d + d
@@ -216,7 +216,7 @@
def testtostereo(data):
if verbose:
- print 'tostereo'
+ print('tostereo')
data2 = ''
for d in data[0]:
data2 = data2 + d + d
@@ -226,28 +226,28 @@
def testfindfactor(data):
if verbose:
- print 'findfactor'
+ print('findfactor')
if audioop.findfactor(data[1], data[1]) != 1.0:
return 0
return 1
def testfindfit(data):
if verbose:
- print 'findfit'
+ print('findfit')
if audioop.findfit(data[1], data[1]) != (0, 1.0):
return 0
return 1
def testfindmax(data):
if verbose:
- print 'findmax'
+ print('findmax')
if audioop.findmax(data[1], 1) != 2:
return 0
return 1
def testgetsample(data):
if verbose:
- print 'getsample'
+ print('getsample')
for i in range(3):
if audioop.getsample(data[0], 1, i) != i or \
audioop.getsample(data[1], 2, i) != i or \
@@ -259,15 +259,15 @@
try:
func = eval('test'+name)
except NameError:
- print 'No test found for audioop.'+name+'()'
+ print('No test found for audioop.'+name+'()')
return
try:
rv = func(data)
except 'xx':
- print 'Test FAILED for audioop.'+name+'() (with an exception)'
+ print('Test FAILED for audioop.'+name+'() (with an exception)')
return
if not rv:
- print 'Test FAILED for audioop.'+name+'()'
+ print('Test FAILED for audioop.'+name+'()')
def testall():
data = [gendata1(), gendata2(), gendata4()]
Modified: python/branches/p3yk-noslice/Lib/test/test_bigmem.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bigmem.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_bigmem.py Fri Feb 23 18:29:35 2007
@@ -866,13 +866,13 @@
@bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5)
def test_index(self, size):
- l = [1L, 2L, 3L, 4L, 5L] * size
+ l = [1, 2, 3, 4, 5] * size
size *= 5
self.assertEquals(l.index(1), 0)
self.assertEquals(l.index(5, size - 5), size - 1)
self.assertEquals(l.index(5, size - 5, size), size - 1)
self.assertRaises(ValueError, l.index, 1, size - 4, size)
- self.assertRaises(ValueError, l.index, 6L)
+ self.assertRaises(ValueError, l.index, 6)
# This tests suffers from overallocation, just like test_append.
@bigmemtest(minsize=_2G + 10, memuse=9)
Modified: python/branches/p3yk-noslice/Lib/test/test_binop.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_binop.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_binop.py Fri Feb 23 18:29:35 2007
@@ -11,11 +11,11 @@
def isint(x):
"""Test whether an object is an instance of int or long."""
- return isinstance(x, int) or isinstance(x, long)
+ return isinstance(x, int) or isinstance(x, int)
def isnum(x):
"""Test whether an object is an instance of a built-in numeric type."""
- for T in int, long, float, complex:
+ for T in int, int, float, complex:
if isinstance(x, T):
return 1
return 0
@@ -30,7 +30,7 @@
__slots__ = ['_Rat__num', '_Rat__den']
- def __init__(self, num=0L, den=1L):
+ def __init__(self, num=0, den=1):
"""Constructor: Rat([num[, den]]).
The arguments must be ints or longs, and default to (0, 1)."""
@@ -42,8 +42,8 @@
if den == 0:
raise ZeroDivisionError, "zero denominator"
g = gcd(den, num)
- self.__num = long(num//g)
- self.__den = long(den//g)
+ self.__num = int(num//g)
+ self.__den = int(den//g)
def _get_num(self):
"""Accessor function for read-only 'num' attribute of Rat."""
@@ -80,7 +80,7 @@
def __long__(self):
"""Convert a Rat to an long; self.den must be 1."""
if self.__den == 1:
- return long(self.__num)
+ return int(self.__num)
raise ValueError, "can't convert %s to long" % repr(self)
def __add__(self, other):
@@ -225,7 +225,7 @@
a = Rat(10, 15)
self.assertEqual(a.num, 2)
self.assertEqual(a.den, 3)
- a = Rat(10L, 15L)
+ a = Rat(10, 15)
self.assertEqual(a.num, 2)
self.assertEqual(a.den, 3)
a = Rat(10, -15)
Modified: python/branches/p3yk-noslice/Lib/test/test_bisect.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bisect.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_bisect.py Fri Feb 23 18:29:35 2007
@@ -252,7 +252,7 @@
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
Modified: python/branches/p3yk-noslice/Lib/test/test_bool.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bool.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_bool.py Fri Feb 23 18:29:35 2007
@@ -27,7 +27,7 @@
def test_print(self):
try:
fo = open(test_support.TESTFN, "wb")
- print >> fo, False, True
+ print(False, True, file=fo)
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), 'False True\n')
Modified: python/branches/p3yk-noslice/Lib/test/test_bsddb.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bsddb.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_bsddb.py Fri Feb 23 18:29:35 2007
@@ -15,7 +15,7 @@
def setUp(self):
self.f = self.openmethod[0](self.fname, self.openflag, cachesize=32768)
self.d = dict(q='Guido', w='van', e='Rossum', r='invented', t='Python', y='')
- for k, v in self.d.iteritems():
+ for k, v in self.d.items():
self.f[k] = v
def tearDown(self):
@@ -29,7 +29,7 @@
pass
def test_getitem(self):
- for k, v in self.d.iteritems():
+ for k, v in self.d.items():
self.assertEqual(self.f[k], v)
def test_len(self):
@@ -48,7 +48,7 @@
return
self.f.close()
self.f = self.openmethod[0](self.fname, 'w')
- for k, v in self.d.iteritems():
+ for k, v in self.d.items():
self.assertEqual(self.f[k], v)
def assertSetEquals(self, seqn1, seqn2):
@@ -61,9 +61,9 @@
self.assertSetEquals(d.keys(), f.keys())
self.assertSetEquals(d.values(), f.values())
self.assertSetEquals(d.items(), f.items())
- self.assertSetEquals(d.iterkeys(), f.iterkeys())
- self.assertSetEquals(d.itervalues(), f.itervalues())
- self.assertSetEquals(d.iteritems(), f.iteritems())
+ self.assertSetEquals(d.keys(), f.keys())
+ self.assertSetEquals(d.values(), f.values())
+ self.assertSetEquals(d.items(), f.items())
def test_iter_while_modifying_values(self):
if not hasattr(self.f, '__iter__'):
@@ -94,7 +94,7 @@
if not hasattr(self.f, 'iteritems'):
return
- di = self.d.iteritems()
+ di = iter(self.d.items())
while 1:
try:
k, v = di.next()
@@ -105,7 +105,7 @@
# it should behave the same as a dict. modifying values
# of existing keys should not break iteration. (adding
# or removing keys should)
- fi = self.f.iteritems()
+ fi = iter(self.f.items())
while 1:
try:
k, v = fi.next()
@@ -147,42 +147,42 @@
# in pybsddb's _DBWithCursor this causes an internal DBCursor
# object is created. Other test_ methods in this class could
# inadvertently cause the deadlock but an explicit test is needed.
- if debug: print "A"
+ if debug: print("A")
k,v = self.f.first()
- if debug: print "B", k
+ if debug: print("B", k)
self.f[k] = "deadlock. do not pass go. do not collect $200."
- if debug: print "C"
+ if debug: print("C")
# if the bsddb implementation leaves the DBCursor open during
# the database write and locking+threading support is enabled
# the cursor's read lock will deadlock the write lock request..
# test the iterator interface (if present)
if hasattr(self.f, 'iteritems'):
- if debug: print "D"
- i = self.f.iteritems()
+ if debug: print("D")
+ i = iter(self.f.items())
k,v = i.next()
- if debug: print "E"
+ if debug: print("E")
self.f[k] = "please don't deadlock"
- if debug: print "F"
+ if debug: print("F")
while 1:
try:
k,v = i.next()
except StopIteration:
break
- if debug: print "F2"
+ if debug: print("F2")
i = iter(self.f)
- if debug: print "G"
+ if debug: print("G")
while i:
try:
- if debug: print "H"
+ if debug: print("H")
k = i.next()
- if debug: print "I"
+ if debug: print("I")
self.f[k] = "deadlocks-r-us"
- if debug: print "J"
+ if debug: print("J")
except StopIteration:
i = None
- if debug: print "K"
+ if debug: print("K")
# test the legacy cursor interface mixed with writes
self.assert_(self.f.first()[0] in self.d)
@@ -198,9 +198,9 @@
# do the bsddb._DBWithCursor _iter_mixin internals leak cursors?
nc1 = len(self.f._cursor_refs)
# create iterator
- i = self.f.iteritems()
+ i = iter(self.f.iteritems())
nc2 = len(self.f._cursor_refs)
- # use the iterator (should run to the first yeild, creating the cursor)
+ # use the iterator (should run to the first yield, creating the cursor)
k, v = i.next()
nc3 = len(self.f._cursor_refs)
# destroy the iterator; this should cause the weakref callback
@@ -210,7 +210,7 @@
self.assertEqual(nc1, nc2)
self.assertEqual(nc1, nc4)
- self.assert_(nc3 == nc1+1)
+ self.assertEqual(nc3, nc1+1)
def test_popitem(self):
k, v = self.f.popitem()
@@ -240,14 +240,13 @@
new = dict(y='life', u='of', i='brian')
self.f.update(new)
self.d.update(new)
- for k, v in self.d.iteritems():
+ for k, v in self.d.items():
self.assertEqual(self.f[k], v)
def test_keyordering(self):
if self.openmethod[0] is not bsddb.btopen:
return
- keys = self.d.keys()
- keys.sort()
+ keys = sorted(self.d.keys())
self.assertEqual(self.f.first()[0], keys[0])
self.assertEqual(self.f.next()[0], keys[1])
self.assertEqual(self.f.last()[0], keys[-1])
Modified: python/branches/p3yk-noslice/Lib/test/test_bsddb3.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bsddb3.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_bsddb3.py Fri Feb 23 18:29:35 2007
@@ -65,12 +65,12 @@
# For invocation as a script
if __name__ == '__main__':
from bsddb import db
- print '-=' * 38
- print db.DB_VERSION_STRING
- print 'bsddb.db.version(): %s' % (db.version(),)
- print 'bsddb.db.__version__: %s' % db.__version__
- print 'bsddb.db.cvsid: %s' % db.cvsid
- print 'python version: %s' % sys.version
- print '-=' * 38
+ print('-=' * 38)
+ print(db.DB_VERSION_STRING)
+ print('bsddb.db.version(): %s' % (db.version(),))
+ print('bsddb.db.__version__: %s' % db.__version__)
+ print('bsddb.db.cvsid: %s' % db.cvsid)
+ print('python version: %s' % sys.version)
+ print('-=' * 38)
unittest.main(defaultTest='suite')
Modified: python/branches/p3yk-noslice/Lib/test/test_builtin.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_builtin.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_builtin.py Fri Feb 23 18:29:35 2007
@@ -122,9 +122,9 @@
self.assertEqual(abs(3.14), 3.14)
self.assertEqual(abs(-3.14), 3.14)
# long
- self.assertEqual(abs(0L), 0L)
- self.assertEqual(abs(1234L), 1234L)
- self.assertEqual(abs(-1234L), 1234L)
+ self.assertEqual(abs(0), 0)
+ self.assertEqual(abs(1234), 1234)
+ self.assertEqual(abs(-1234), 1234)
# str
self.assertRaises(TypeError, abs, 'a')
@@ -204,15 +204,15 @@
self.assertRaises(TypeError, cmp)
def test_compile(self):
- compile('print 1\n', '', 'exec')
+ compile('print(1)\n', '', 'exec')
bom = '\xef\xbb\xbf'
- compile(bom + 'print 1\n', '', 'exec')
+ compile(bom + 'print(1)\n', '', 'exec')
self.assertRaises(TypeError, compile)
- self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'badmode')
- self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'single', 0xff)
+ self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
+ self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff)
self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
if have_unicode:
- compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec')
+ compile(unicode('print(u"\xc3\xa5")\n', 'utf8'), '', 'exec')
self.assertRaises(TypeError, compile, unichr(0), 'f', 'exec')
self.assertRaises(ValueError, compile, unicode('a = 1'), 'f', 'bad')
@@ -235,15 +235,15 @@
self.assertEqual(divmod(12, -7), (-2, -2))
self.assertEqual(divmod(-12, -7), (1, -5))
- self.assertEqual(divmod(12L, 7L), (1L, 5L))
- self.assertEqual(divmod(-12L, 7L), (-2L, 2L))
- self.assertEqual(divmod(12L, -7L), (-2L, -2L))
- self.assertEqual(divmod(-12L, -7L), (1L, -5L))
-
- self.assertEqual(divmod(12, 7L), (1, 5L))
- self.assertEqual(divmod(-12, 7L), (-2, 2L))
- self.assertEqual(divmod(12L, -7), (-2L, -2))
- self.assertEqual(divmod(-12L, -7), (1L, -5))
+ self.assertEqual(divmod(12, 7), (1, 5))
+ self.assertEqual(divmod(-12, 7), (-2, 2))
+ self.assertEqual(divmod(12, -7), (-2, -2))
+ self.assertEqual(divmod(-12, -7), (1, -5))
+
+ self.assertEqual(divmod(12, 7), (1, 5))
+ self.assertEqual(divmod(-12, 7), (-2, 2))
+ self.assertEqual(divmod(12, -7), (-2, -2))
+ self.assertEqual(divmod(-12, -7), (1, -5))
self.assertEqual(divmod(-sys.maxint-1, -1),
(sys.maxint+1, 0))
@@ -347,7 +347,7 @@
def __getitem__(self, item):
raise KeyError(item)
def keys(self):
- return 'a'
+ return 1 # used to be 'a' but that's no longer an error
self.assertRaises(TypeError, eval, 'dir()', globals(), C())
# Done outside of the method test_z to get the correct scope
@@ -525,8 +525,8 @@
unicode("123"): unicode("112233")
}
- for (cls, inps) in inputs.iteritems():
- for (inp, exp) in inps.iteritems():
+ for (cls, inps) in inputs.items():
+ for (inp, exp) in inps.items():
# make sure the output goes through __getitem__
# even if func is None
self.assertEqual(
@@ -541,7 +541,7 @@
def test_float(self):
self.assertEqual(float(3.14), 3.14)
self.assertEqual(float(314), 314.0)
- self.assertEqual(float(314L), 314.0)
+ self.assertEqual(float(314), 314.0)
self.assertEqual(float(" 3.14 "), 3.14)
self.assertRaises(ValueError, float, " 0x3.1 ")
self.assertRaises(ValueError, float, " -0x3.p-1 ")
@@ -627,7 +627,7 @@
def test_hash(self):
hash(None)
- self.assertEqual(hash(1), hash(1L))
+ self.assertEqual(hash(1), hash(1))
self.assertEqual(hash(1), hash(1.0))
hash('spam')
if have_unicode:
@@ -645,22 +645,22 @@
def __hash__(self):
return 2**100
self.assertEquals(type(hash(Y())), int)
- class Z(long):
+ class Z(int):
def __hash__(self):
return self
- self.assertEquals(hash(Z(42)), hash(42L))
+ self.assertEquals(hash(Z(42)), hash(42))
def test_hex(self):
self.assertEqual(hex(16), '0x10')
- self.assertEqual(hex(16L), '0x10')
+ self.assertEqual(hex(16), '0x10')
+ self.assertEqual(hex(-16), '-0x10')
self.assertEqual(hex(-16), '-0x10')
- self.assertEqual(hex(-16L), '-0x10')
self.assertRaises(TypeError, hex, {})
def test_id(self):
id(None)
id(1)
- id(1L)
+ id(1)
id(1.0)
id('spam')
id((0,1,2,3))
@@ -670,7 +670,7 @@
def test_int(self):
self.assertEqual(int(314), 314)
self.assertEqual(int(3.14), 3)
- self.assertEqual(int(314L), 314)
+ self.assertEqual(int(314), 314)
# Check that conversion from float truncates towards zero
self.assertEqual(int(-3.14), -3)
self.assertEqual(int(3.9), 3)
@@ -678,9 +678,9 @@
self.assertEqual(int(3.5), 3)
self.assertEqual(int(-3.5), -3)
# Different base:
- self.assertEqual(int("10",16), 16L)
+ self.assertEqual(int("10",16), 16)
if have_unicode:
- self.assertEqual(int(unicode("10"),16), 16L)
+ self.assertEqual(int(unicode("10"),16), 16)
# Test conversion from strings and various anomalies
for s, v in L:
for sign in "", "+", "-":
@@ -703,9 +703,9 @@
# should return long
x = int(1e100)
- self.assert_(isinstance(x, long))
+ self.assert_(isinstance(x, int))
x = int(-1e100)
- self.assert_(isinstance(x, long))
+ self.assert_(isinstance(x, int))
# SF bug 434186: 0x80000000/2 != 0x80000000>>1.
@@ -723,11 +723,11 @@
self.assertRaises(ValueError, int, '123\x00 245', 20)
x = int('1' * 600)
- self.assert_(isinstance(x, long))
+ self.assert_(isinstance(x, int))
if have_unicode:
x = int(unichr(0x661) * 600)
- self.assert_(isinstance(x, long))
+ self.assert_(isinstance(x, int))
self.assertRaises(TypeError, int, 1, 12)
@@ -738,79 +738,79 @@
# Various representations of 2**32 evaluated to 0
# rather than 2**32 in previous versions
- self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296L)
- self.assertEqual(int('102002022201221111211', 3), 4294967296L)
- self.assertEqual(int('10000000000000000', 4), 4294967296L)
- self.assertEqual(int('32244002423141', 5), 4294967296L)
- self.assertEqual(int('1550104015504', 6), 4294967296L)
- self.assertEqual(int('211301422354', 7), 4294967296L)
- self.assertEqual(int('40000000000', 8), 4294967296L)
- self.assertEqual(int('12068657454', 9), 4294967296L)
- self.assertEqual(int('4294967296', 10), 4294967296L)
- self.assertEqual(int('1904440554', 11), 4294967296L)
- self.assertEqual(int('9ba461594', 12), 4294967296L)
- self.assertEqual(int('535a79889', 13), 4294967296L)
- self.assertEqual(int('2ca5b7464', 14), 4294967296L)
- self.assertEqual(int('1a20dcd81', 15), 4294967296L)
- self.assertEqual(int('100000000', 16), 4294967296L)
- self.assertEqual(int('a7ffda91', 17), 4294967296L)
- self.assertEqual(int('704he7g4', 18), 4294967296L)
- self.assertEqual(int('4f5aff66', 19), 4294967296L)
- self.assertEqual(int('3723ai4g', 20), 4294967296L)
- self.assertEqual(int('281d55i4', 21), 4294967296L)
- self.assertEqual(int('1fj8b184', 22), 4294967296L)
- self.assertEqual(int('1606k7ic', 23), 4294967296L)
- self.assertEqual(int('mb994ag', 24), 4294967296L)
- self.assertEqual(int('hek2mgl', 25), 4294967296L)
- self.assertEqual(int('dnchbnm', 26), 4294967296L)
- self.assertEqual(int('b28jpdm', 27), 4294967296L)
- self.assertEqual(int('8pfgih4', 28), 4294967296L)
- self.assertEqual(int('76beigg', 29), 4294967296L)
- self.assertEqual(int('5qmcpqg', 30), 4294967296L)
- self.assertEqual(int('4q0jto4', 31), 4294967296L)
- self.assertEqual(int('4000000', 32), 4294967296L)
- self.assertEqual(int('3aokq94', 33), 4294967296L)
- self.assertEqual(int('2qhxjli', 34), 4294967296L)
- self.assertEqual(int('2br45qb', 35), 4294967296L)
- self.assertEqual(int('1z141z4', 36), 4294967296L)
+ self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296)
+ self.assertEqual(int('102002022201221111211', 3), 4294967296)
+ self.assertEqual(int('10000000000000000', 4), 4294967296)
+ self.assertEqual(int('32244002423141', 5), 4294967296)
+ self.assertEqual(int('1550104015504', 6), 4294967296)
+ self.assertEqual(int('211301422354', 7), 4294967296)
+ self.assertEqual(int('40000000000', 8), 4294967296)
+ self.assertEqual(int('12068657454', 9), 4294967296)
+ self.assertEqual(int('4294967296', 10), 4294967296)
+ self.assertEqual(int('1904440554', 11), 4294967296)
+ self.assertEqual(int('9ba461594', 12), 4294967296)
+ self.assertEqual(int('535a79889', 13), 4294967296)
+ self.assertEqual(int('2ca5b7464', 14), 4294967296)
+ self.assertEqual(int('1a20dcd81', 15), 4294967296)
+ self.assertEqual(int('100000000', 16), 4294967296)
+ self.assertEqual(int('a7ffda91', 17), 4294967296)
+ self.assertEqual(int('704he7g4', 18), 4294967296)
+ self.assertEqual(int('4f5aff66', 19), 4294967296)
+ self.assertEqual(int('3723ai4g', 20), 4294967296)
+ self.assertEqual(int('281d55i4', 21), 4294967296)
+ self.assertEqual(int('1fj8b184', 22), 4294967296)
+ self.assertEqual(int('1606k7ic', 23), 4294967296)
+ self.assertEqual(int('mb994ag', 24), 4294967296)
+ self.assertEqual(int('hek2mgl', 25), 4294967296)
+ self.assertEqual(int('dnchbnm', 26), 4294967296)
+ self.assertEqual(int('b28jpdm', 27), 4294967296)
+ self.assertEqual(int('8pfgih4', 28), 4294967296)
+ self.assertEqual(int('76beigg', 29), 4294967296)
+ self.assertEqual(int('5qmcpqg', 30), 4294967296)
+ self.assertEqual(int('4q0jto4', 31), 4294967296)
+ self.assertEqual(int('4000000', 32), 4294967296)
+ self.assertEqual(int('3aokq94', 33), 4294967296)
+ self.assertEqual(int('2qhxjli', 34), 4294967296)
+ self.assertEqual(int('2br45qb', 35), 4294967296)
+ self.assertEqual(int('1z141z4', 36), 4294967296)
# SF bug 1334662: int(string, base) wrong answers
# Checks for proper evaluation of 2**32 + 1
- self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297L)
- self.assertEqual(int('102002022201221111212', 3), 4294967297L)
- self.assertEqual(int('10000000000000001', 4), 4294967297L)
- self.assertEqual(int('32244002423142', 5), 4294967297L)
- self.assertEqual(int('1550104015505', 6), 4294967297L)
- self.assertEqual(int('211301422355', 7), 4294967297L)
- self.assertEqual(int('40000000001', 8), 4294967297L)
- self.assertEqual(int('12068657455', 9), 4294967297L)
- self.assertEqual(int('4294967297', 10), 4294967297L)
- self.assertEqual(int('1904440555', 11), 4294967297L)
- self.assertEqual(int('9ba461595', 12), 4294967297L)
- self.assertEqual(int('535a7988a', 13), 4294967297L)
- self.assertEqual(int('2ca5b7465', 14), 4294967297L)
- self.assertEqual(int('1a20dcd82', 15), 4294967297L)
- self.assertEqual(int('100000001', 16), 4294967297L)
- self.assertEqual(int('a7ffda92', 17), 4294967297L)
- self.assertEqual(int('704he7g5', 18), 4294967297L)
- self.assertEqual(int('4f5aff67', 19), 4294967297L)
- self.assertEqual(int('3723ai4h', 20), 4294967297L)
- self.assertEqual(int('281d55i5', 21), 4294967297L)
- self.assertEqual(int('1fj8b185', 22), 4294967297L)
- self.assertEqual(int('1606k7id', 23), 4294967297L)
- self.assertEqual(int('mb994ah', 24), 4294967297L)
- self.assertEqual(int('hek2mgm', 25), 4294967297L)
- self.assertEqual(int('dnchbnn', 26), 4294967297L)
- self.assertEqual(int('b28jpdn', 27), 4294967297L)
- self.assertEqual(int('8pfgih5', 28), 4294967297L)
- self.assertEqual(int('76beigh', 29), 4294967297L)
- self.assertEqual(int('5qmcpqh', 30), 4294967297L)
- self.assertEqual(int('4q0jto5', 31), 4294967297L)
- self.assertEqual(int('4000001', 32), 4294967297L)
- self.assertEqual(int('3aokq95', 33), 4294967297L)
- self.assertEqual(int('2qhxjlj', 34), 4294967297L)
- self.assertEqual(int('2br45qc', 35), 4294967297L)
- self.assertEqual(int('1z141z5', 36), 4294967297L)
+ self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297)
+ self.assertEqual(int('102002022201221111212', 3), 4294967297)
+ self.assertEqual(int('10000000000000001', 4), 4294967297)
+ self.assertEqual(int('32244002423142', 5), 4294967297)
+ self.assertEqual(int('1550104015505', 6), 4294967297)
+ self.assertEqual(int('211301422355', 7), 4294967297)
+ self.assertEqual(int('40000000001', 8), 4294967297)
+ self.assertEqual(int('12068657455', 9), 4294967297)
+ self.assertEqual(int('4294967297', 10), 4294967297)
+ self.assertEqual(int('1904440555', 11), 4294967297)
+ self.assertEqual(int('9ba461595', 12), 4294967297)
+ self.assertEqual(int('535a7988a', 13), 4294967297)
+ self.assertEqual(int('2ca5b7465', 14), 4294967297)
+ self.assertEqual(int('1a20dcd82', 15), 4294967297)
+ self.assertEqual(int('100000001', 16), 4294967297)
+ self.assertEqual(int('a7ffda92', 17), 4294967297)
+ self.assertEqual(int('704he7g5', 18), 4294967297)
+ self.assertEqual(int('4f5aff67', 19), 4294967297)
+ self.assertEqual(int('3723ai4h', 20), 4294967297)
+ self.assertEqual(int('281d55i5', 21), 4294967297)
+ self.assertEqual(int('1fj8b185', 22), 4294967297)
+ self.assertEqual(int('1606k7id', 23), 4294967297)
+ self.assertEqual(int('mb994ah', 24), 4294967297)
+ self.assertEqual(int('hek2mgm', 25), 4294967297)
+ self.assertEqual(int('dnchbnn', 26), 4294967297)
+ self.assertEqual(int('b28jpdn', 27), 4294967297)
+ self.assertEqual(int('8pfgih5', 28), 4294967297)
+ self.assertEqual(int('76beigh', 29), 4294967297)
+ self.assertEqual(int('5qmcpqh', 30), 4294967297)
+ self.assertEqual(int('4q0jto5', 31), 4294967297)
+ self.assertEqual(int('4000001', 32), 4294967297)
+ self.assertEqual(int('3aokq95', 33), 4294967297)
+ self.assertEqual(int('2qhxjlj', 34), 4294967297)
+ self.assertEqual(int('2br45qc', 35), 4294967297)
+ self.assertEqual(int('1z141z5', 36), 4294967297)
def test_intconversion(self):
# Test __int__()
@@ -832,7 +832,7 @@
class Foo4(int):
def __int__(self):
- return 42L
+ return 42
class Foo5(int):
def __int__(self):
@@ -842,7 +842,7 @@
self.assertEqual(int(Foo1()), 42)
self.assertEqual(int(Foo2()), 42)
self.assertEqual(int(Foo3()), 0)
- self.assertEqual(int(Foo4()), 42L)
+ self.assertEqual(int(Foo4()), 42)
self.assertRaises(TypeError, int, Foo5())
def test_iter(self):
@@ -938,32 +938,32 @@
self.assertEqual(x, [])
def test_long(self):
- self.assertEqual(long(314), 314L)
- self.assertEqual(long(3.14), 3L)
- self.assertEqual(long(314L), 314L)
+ self.assertEqual(int(314), 314)
+ self.assertEqual(int(3.14), 3)
+ self.assertEqual(int(314), 314)
# Check that conversion from float truncates towards zero
- self.assertEqual(long(-3.14), -3L)
- self.assertEqual(long(3.9), 3L)
- self.assertEqual(long(-3.9), -3L)
- self.assertEqual(long(3.5), 3L)
- self.assertEqual(long(-3.5), -3L)
- self.assertEqual(long("-3"), -3L)
+ self.assertEqual(int(-3.14), -3)
+ self.assertEqual(int(3.9), 3)
+ self.assertEqual(int(-3.9), -3)
+ self.assertEqual(int(3.5), 3)
+ self.assertEqual(int(-3.5), -3)
+ self.assertEqual(int("-3"), -3)
if have_unicode:
- self.assertEqual(long(unicode("-3")), -3L)
+ self.assertEqual(int(unicode("-3")), -3)
# Different base:
- self.assertEqual(long("10",16), 16L)
+ self.assertEqual(int("10",16), 16)
if have_unicode:
- self.assertEqual(long(unicode("10"),16), 16L)
+ self.assertEqual(int(unicode("10"),16), 16)
# Check conversions from string (same test set as for int(), and then some)
LL = [
- ('1' + '0'*20, 10L**20),
- ('1' + '0'*100, 10L**100)
+ ('1' + '0'*20, 10**20),
+ ('1' + '0'*100, 10**100)
]
L2 = L[:]
if have_unicode:
L2 += [
- (unicode('1') + unicode('0')*20, 10L**20),
- (unicode('1') + unicode('0')*100, 10L**100),
+ (unicode('1') + unicode('0')*20, 10**20),
+ (unicode('1') + unicode('0')*100, 10**100),
]
for s, v in L2 + LL:
for sign in "", "+", "-":
@@ -973,121 +973,123 @@
if sign == "-" and v is not ValueError:
vv = -v
try:
- self.assertEqual(long(ss), long(vv))
+ self.assertEqual(int(ss), int(vv))
except v:
pass
- self.assertRaises(ValueError, long, '123\0')
- self.assertRaises(ValueError, long, '53', 40)
- self.assertRaises(TypeError, long, 1, 12)
+ self.assertRaises(ValueError, int, '123\0')
+ self.assertRaises(ValueError, int, '53', 40)
+ self.assertRaises(TypeError, int, 1, 12)
- self.assertEqual(long('100000000000000000000000000000000', 2),
+ self.assertEqual(int('100000000000000000000000000000000', 2),
4294967296)
- self.assertEqual(long('102002022201221111211', 3), 4294967296)
- self.assertEqual(long('10000000000000000', 4), 4294967296)
- self.assertEqual(long('32244002423141', 5), 4294967296)
- self.assertEqual(long('1550104015504', 6), 4294967296)
- self.assertEqual(long('211301422354', 7), 4294967296)
- self.assertEqual(long('40000000000', 8), 4294967296)
- self.assertEqual(long('12068657454', 9), 4294967296)
- self.assertEqual(long('4294967296', 10), 4294967296)
- self.assertEqual(long('1904440554', 11), 4294967296)
- self.assertEqual(long('9ba461594', 12), 4294967296)
- self.assertEqual(long('535a79889', 13), 4294967296)
- self.assertEqual(long('2ca5b7464', 14), 4294967296)
- self.assertEqual(long('1a20dcd81', 15), 4294967296)
- self.assertEqual(long('100000000', 16), 4294967296)
- self.assertEqual(long('a7ffda91', 17), 4294967296)
- self.assertEqual(long('704he7g4', 18), 4294967296)
- self.assertEqual(long('4f5aff66', 19), 4294967296)
- self.assertEqual(long('3723ai4g', 20), 4294967296)
- self.assertEqual(long('281d55i4', 21), 4294967296)
- self.assertEqual(long('1fj8b184', 22), 4294967296)
- self.assertEqual(long('1606k7ic', 23), 4294967296)
- self.assertEqual(long('mb994ag', 24), 4294967296)
- self.assertEqual(long('hek2mgl', 25), 4294967296)
- self.assertEqual(long('dnchbnm', 26), 4294967296)
- self.assertEqual(long('b28jpdm', 27), 4294967296)
- self.assertEqual(long('8pfgih4', 28), 4294967296)
- self.assertEqual(long('76beigg', 29), 4294967296)
- self.assertEqual(long('5qmcpqg', 30), 4294967296)
- self.assertEqual(long('4q0jto4', 31), 4294967296)
- self.assertEqual(long('4000000', 32), 4294967296)
- self.assertEqual(long('3aokq94', 33), 4294967296)
- self.assertEqual(long('2qhxjli', 34), 4294967296)
- self.assertEqual(long('2br45qb', 35), 4294967296)
- self.assertEqual(long('1z141z4', 36), 4294967296)
+ self.assertEqual(int('102002022201221111211', 3), 4294967296)
+ self.assertEqual(int('10000000000000000', 4), 4294967296)
+ self.assertEqual(int('32244002423141', 5), 4294967296)
+ self.assertEqual(int('1550104015504', 6), 4294967296)
+ self.assertEqual(int('211301422354', 7), 4294967296)
+ self.assertEqual(int('40000000000', 8), 4294967296)
+ self.assertEqual(int('12068657454', 9), 4294967296)
+ self.assertEqual(int('4294967296', 10), 4294967296)
+ self.assertEqual(int('1904440554', 11), 4294967296)
+ self.assertEqual(int('9ba461594', 12), 4294967296)
+ self.assertEqual(int('535a79889', 13), 4294967296)
+ self.assertEqual(int('2ca5b7464', 14), 4294967296)
+ self.assertEqual(int('1a20dcd81', 15), 4294967296)
+ self.assertEqual(int('100000000', 16), 4294967296)
+ self.assertEqual(int('a7ffda91', 17), 4294967296)
+ self.assertEqual(int('704he7g4', 18), 4294967296)
+ self.assertEqual(int('4f5aff66', 19), 4294967296)
+ self.assertEqual(int('3723ai4g', 20), 4294967296)
+ self.assertEqual(int('281d55i4', 21), 4294967296)
+ self.assertEqual(int('1fj8b184', 22), 4294967296)
+ self.assertEqual(int('1606k7ic', 23), 4294967296)
+ self.assertEqual(int('mb994ag', 24), 4294967296)
+ self.assertEqual(int('hek2mgl', 25), 4294967296)
+ self.assertEqual(int('dnchbnm', 26), 4294967296)
+ self.assertEqual(int('b28jpdm', 27), 4294967296)
+ self.assertEqual(int('8pfgih4', 28), 4294967296)
+ self.assertEqual(int('76beigg', 29), 4294967296)
+ self.assertEqual(int('5qmcpqg', 30), 4294967296)
+ self.assertEqual(int('4q0jto4', 31), 4294967296)
+ self.assertEqual(int('4000000', 32), 4294967296)
+ self.assertEqual(int('3aokq94', 33), 4294967296)
+ self.assertEqual(int('2qhxjli', 34), 4294967296)
+ self.assertEqual(int('2br45qb', 35), 4294967296)
+ self.assertEqual(int('1z141z4', 36), 4294967296)
- self.assertEqual(long('100000000000000000000000000000001', 2),
+ self.assertEqual(int('100000000000000000000000000000001', 2),
4294967297)
- self.assertEqual(long('102002022201221111212', 3), 4294967297)
- self.assertEqual(long('10000000000000001', 4), 4294967297)
- self.assertEqual(long('32244002423142', 5), 4294967297)
- self.assertEqual(long('1550104015505', 6), 4294967297)
- self.assertEqual(long('211301422355', 7), 4294967297)
- self.assertEqual(long('40000000001', 8), 4294967297)
- self.assertEqual(long('12068657455', 9), 4294967297)
- self.assertEqual(long('4294967297', 10), 4294967297)
- self.assertEqual(long('1904440555', 11), 4294967297)
- self.assertEqual(long('9ba461595', 12), 4294967297)
- self.assertEqual(long('535a7988a', 13), 4294967297)
- self.assertEqual(long('2ca5b7465', 14), 4294967297)
- self.assertEqual(long('1a20dcd82', 15), 4294967297)
- self.assertEqual(long('100000001', 16), 4294967297)
- self.assertEqual(long('a7ffda92', 17), 4294967297)
- self.assertEqual(long('704he7g5', 18), 4294967297)
- self.assertEqual(long('4f5aff67', 19), 4294967297)
- self.assertEqual(long('3723ai4h', 20), 4294967297)
- self.assertEqual(long('281d55i5', 21), 4294967297)
- self.assertEqual(long('1fj8b185', 22), 4294967297)
- self.assertEqual(long('1606k7id', 23), 4294967297)
- self.assertEqual(long('mb994ah', 24), 4294967297)
- self.assertEqual(long('hek2mgm', 25), 4294967297)
- self.assertEqual(long('dnchbnn', 26), 4294967297)
- self.assertEqual(long('b28jpdn', 27), 4294967297)
- self.assertEqual(long('8pfgih5', 28), 4294967297)
- self.assertEqual(long('76beigh', 29), 4294967297)
- self.assertEqual(long('5qmcpqh', 30), 4294967297)
- self.assertEqual(long('4q0jto5', 31), 4294967297)
- self.assertEqual(long('4000001', 32), 4294967297)
- self.assertEqual(long('3aokq95', 33), 4294967297)
- self.assertEqual(long('2qhxjlj', 34), 4294967297)
- self.assertEqual(long('2br45qc', 35), 4294967297)
- self.assertEqual(long('1z141z5', 36), 4294967297)
+ self.assertEqual(int('102002022201221111212', 3), 4294967297)
+ self.assertEqual(int('10000000000000001', 4), 4294967297)
+ self.assertEqual(int('32244002423142', 5), 4294967297)
+ self.assertEqual(int('1550104015505', 6), 4294967297)
+ self.assertEqual(int('211301422355', 7), 4294967297)
+ self.assertEqual(int('40000000001', 8), 4294967297)
+ self.assertEqual(int('12068657455', 9), 4294967297)
+ self.assertEqual(int('4294967297', 10), 4294967297)
+ self.assertEqual(int('1904440555', 11), 4294967297)
+ self.assertEqual(int('9ba461595', 12), 4294967297)
+ self.assertEqual(int('535a7988a', 13), 4294967297)
+ self.assertEqual(int('2ca5b7465', 14), 4294967297)
+ self.assertEqual(int('1a20dcd82', 15), 4294967297)
+ self.assertEqual(int('100000001', 16), 4294967297)
+ self.assertEqual(int('a7ffda92', 17), 4294967297)
+ self.assertEqual(int('704he7g5', 18), 4294967297)
+ self.assertEqual(int('4f5aff67', 19), 4294967297)
+ self.assertEqual(int('3723ai4h', 20), 4294967297)
+ self.assertEqual(int('281d55i5', 21), 4294967297)
+ self.assertEqual(int('1fj8b185', 22), 4294967297)
+ self.assertEqual(int('1606k7id', 23), 4294967297)
+ self.assertEqual(int('mb994ah', 24), 4294967297)
+ self.assertEqual(int('hek2mgm', 25), 4294967297)
+ self.assertEqual(int('dnchbnn', 26), 4294967297)
+ self.assertEqual(int('b28jpdn', 27), 4294967297)
+ self.assertEqual(int('8pfgih5', 28), 4294967297)
+ self.assertEqual(int('76beigh', 29), 4294967297)
+ self.assertEqual(int('5qmcpqh', 30), 4294967297)
+ self.assertEqual(int('4q0jto5', 31), 4294967297)
+ self.assertEqual(int('4000001', 32), 4294967297)
+ self.assertEqual(int('3aokq95', 33), 4294967297)
+ self.assertEqual(int('2qhxjlj', 34), 4294967297)
+ self.assertEqual(int('2br45qc', 35), 4294967297)
+ self.assertEqual(int('1z141z5', 36), 4294967297)
def test_longconversion(self):
# Test __long__()
class Foo0:
def __long__(self):
- return 42L
+ return 42
class Foo1(object):
def __long__(self):
- return 42L
+ return 42
- class Foo2(long):
+ class Foo2(int):
def __long__(self):
- return 42L
+ return 42
- class Foo3(long):
+ class Foo3(int):
def __long__(self):
return self
- class Foo4(long):
+ class Foo4(int):
def __long__(self):
return 42
- class Foo5(long):
+ class Foo5(int):
def __long__(self):
return 42.
- self.assertEqual(long(Foo0()), 42L)
- self.assertEqual(long(Foo1()), 42L)
- self.assertEqual(long(Foo2()), 42L)
- self.assertEqual(long(Foo3()), 0)
- self.assertEqual(long(Foo4()), 42)
- self.assertRaises(TypeError, long, Foo5())
+ self.assertEqual(int(Foo0()), 42)
+ self.assertEqual(int(Foo1()), 42)
+ # XXX invokes __int__ now
+ # self.assertEqual(long(Foo2()), 42L)
+ self.assertEqual(int(Foo3()), 0)
+ # XXX likewise
+ # self.assertEqual(long(Foo4()), 42)
+ # self.assertRaises(TypeError, long, Foo5())
def test_map(self):
self.assertEqual(
@@ -1175,9 +1177,9 @@
self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
- self.assertEqual(max(1, 2L, 3.0), 3.0)
- self.assertEqual(max(1L, 2.0, 3), 3)
- self.assertEqual(max(1.0, 2, 3L), 3L)
+ self.assertEqual(max(1, 2, 3.0), 3.0)
+ self.assertEqual(max(1, 2.0, 3), 3)
+ self.assertEqual(max(1.0, 2, 3), 3)
for stmt in (
"max(key=int)", # no args
@@ -1209,9 +1211,9 @@
self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
- self.assertEqual(min(1, 2L, 3.0), 1)
- self.assertEqual(min(1L, 2.0, 3), 1L)
- self.assertEqual(min(1.0, 2, 3L), 1.0)
+ self.assertEqual(min(1, 2, 3.0), 1)
+ self.assertEqual(min(1, 2.0, 3), 1)
+ self.assertEqual(min(1.0, 2, 3), 1.0)
self.assertRaises(TypeError, min)
self.assertRaises(TypeError, min, 42)
@@ -1251,9 +1253,9 @@
def test_oct(self):
self.assertEqual(oct(100), '0144')
- self.assertEqual(oct(100L), '0144')
+ self.assertEqual(oct(100), '0144')
+ self.assertEqual(oct(-100), '-0144')
self.assertEqual(oct(-100), '-0144')
- self.assertEqual(oct(-100L), '-0144')
self.assertRaises(TypeError, oct, ())
def write_testfile(self):
@@ -1310,20 +1312,20 @@
self.assertEqual(pow(-2,2), 4)
self.assertEqual(pow(-2,3), -8)
- self.assertEqual(pow(0L,0), 1)
- self.assertEqual(pow(0L,1), 0)
- self.assertEqual(pow(1L,0), 1)
- self.assertEqual(pow(1L,1), 1)
-
- self.assertEqual(pow(2L,0), 1)
- self.assertEqual(pow(2L,10), 1024)
- self.assertEqual(pow(2L,20), 1024*1024)
- self.assertEqual(pow(2L,30), 1024*1024*1024)
-
- self.assertEqual(pow(-2L,0), 1)
- self.assertEqual(pow(-2L,1), -2)
- self.assertEqual(pow(-2L,2), 4)
- self.assertEqual(pow(-2L,3), -8)
+ self.assertEqual(pow(0,0), 1)
+ self.assertEqual(pow(0,1), 0)
+ self.assertEqual(pow(1,0), 1)
+ self.assertEqual(pow(1,1), 1)
+
+ self.assertEqual(pow(2,0), 1)
+ self.assertEqual(pow(2,10), 1024)
+ self.assertEqual(pow(2,20), 1024*1024)
+ self.assertEqual(pow(2,30), 1024*1024*1024)
+
+ self.assertEqual(pow(-2,0), 1)
+ self.assertEqual(pow(-2,1), -2)
+ self.assertEqual(pow(-2,2), 4)
+ self.assertEqual(pow(-2,3), -8)
self.assertAlmostEqual(pow(0.,0), 1.)
self.assertAlmostEqual(pow(0.,1), 0.)
@@ -1340,9 +1342,9 @@
self.assertAlmostEqual(pow(-2.,2), 4.)
self.assertAlmostEqual(pow(-2.,3), -8.)
- for x in 2, 2L, 2.0:
- for y in 10, 10L, 10.0:
- for z in 1000, 1000L, 1000.0:
+ for x in 2, 2, 2.0:
+ for y in 10, 10, 10.0:
+ for z in 1000, 1000, 1000.0:
if isinstance(x, float) or \
isinstance(y, float) or \
isinstance(z, float):
@@ -1352,8 +1354,8 @@
self.assertRaises(TypeError, pow, -1, -2, 3)
self.assertRaises(ValueError, pow, 1, 2, 0)
- self.assertRaises(TypeError, pow, -1L, -2L, 3L)
- self.assertRaises(ValueError, pow, 1L, 2L, 0L)
+ 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)
@@ -1372,12 +1374,12 @@
self.assertEqual(range(0, 2**100, -1), [])
self.assertEqual(range(0, 2**100, -1), [])
- a = long(10 * sys.maxint)
- b = long(100 * sys.maxint)
- c = long(50 * sys.maxint)
+ a = int(10 * sys.maxint)
+ b = int(100 * sys.maxint)
+ c = int(50 * sys.maxint)
self.assertEqual(range(a, a+2), [a, a+1])
- self.assertEqual(range(a+2, a, -1L), [a+2, a+1])
+ self.assertEqual(range(a+2, a, -1), [a+2, a+1])
self.assertEqual(range(a+4, a, -2), [a+4, a+2])
seq = range(a, b, c)
@@ -1398,7 +1400,7 @@
self.assertRaises(TypeError, range)
self.assertRaises(TypeError, range, 1, 2, 3, 4)
self.assertRaises(ValueError, range, 1, 2, 0)
- self.assertRaises(ValueError, range, a, a + 1, long(0))
+ self.assertRaises(ValueError, range, a, a + 1, int(0))
class badzero(int):
def __eq__(self, other):
@@ -1429,7 +1431,7 @@
def test_repr(self):
self.assertEqual(repr(''), '\'\'')
self.assertEqual(repr(0), '0')
- self.assertEqual(repr(0L), '0')
+ self.assertEqual(repr(0), '0')
self.assertEqual(repr(()), '()')
self.assertEqual(repr([]), '[]')
self.assertEqual(repr({}), '{}')
@@ -1485,7 +1487,7 @@
def test_str(self):
self.assertEqual(str(''), '')
self.assertEqual(str(0), '0')
- self.assertEqual(str(0L), '0')
+ self.assertEqual(str(0), '0')
self.assertEqual(str(()), '()')
self.assertEqual(str([]), '[]')
self.assertEqual(str({}), '{}')
@@ -1660,7 +1662,7 @@
run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
Modified: python/branches/p3yk-noslice/Lib/test/test_bytes.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_bytes.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_bytes.py Fri Feb 23 18:29:35 2007
@@ -361,9 +361,9 @@
def test_contains(self):
b = bytes("abc")
self.failUnless(ord('a') in b)
- self.failUnless(long(ord('a')) in b)
+ self.failUnless(int(ord('a')) in b)
+ self.failIf(200 in b)
self.failIf(200 in b)
- self.failIf(200L in b)
self.assertRaises(ValueError, lambda: 300 in b)
self.assertRaises(ValueError, lambda: -1 in b)
self.assertRaises(TypeError, lambda: None in b)
Modified: python/branches/p3yk-noslice/Lib/test/test_capi.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_capi.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_capi.py Fri Feb 23 18:29:35 2007
@@ -11,7 +11,7 @@
if name.startswith('test_'):
test = getattr(_testcapi, name)
if test_support.verbose:
- print "internal", name
+ print("internal", name)
try:
test()
except _testcapi.error:
@@ -23,7 +23,7 @@
import time
if test_support.verbose:
- print "auto-thread-state"
+ print("auto-thread-state")
idents = []
Modified: python/branches/p3yk-noslice/Lib/test/test_cd.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_cd.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_cd.py Fri Feb 23 18:29:35 2007
@@ -17,10 +17,10 @@
def main():
# touch all the attributes of cd without doing anything
if verbose:
- print 'Touching cd module attributes...'
+ print('Touching cd module attributes...')
for attr in cdattrs:
if verbose:
- print 'touching: ', attr
+ print('touching: ', attr)
getattr(cd, attr)
main()
Modified: python/branches/p3yk-noslice/Lib/test/test_cfgparser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_cfgparser.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_cfgparser.py Fri Feb 23 18:29:35 2007
@@ -7,18 +7,13 @@
class SortedDict(UserDict.UserDict):
def items(self):
- result = self.data.items()
- result.sort()
- return result
+ return sorted(self.data.items())
def keys(self):
- result = self.data.keys()
- result.sort()
- return result
-
+ return sorted(self.data.keys())
+
def values(self):
- result = self.items()
- return [i[1] for i in values]
+ return [i[1] for i in self.items()]
def iteritems(self): return iter(self.items())
def iterkeys(self): return iter(self.keys())
@@ -446,12 +441,12 @@
"o2=3\n"
"o1=4\n"
"[a]\n"
- "k=v\n")
+ "k=v\n")
output = StringIO.StringIO()
self.cf.write(output)
self.assertEquals(output.getvalue(),
"[a]\n"
- "k = v\n\n"
+ "k = v\n\n"
"[b]\n"
"o1 = 4\n"
"o2 = 3\n"
Modified: python/branches/p3yk-noslice/Lib/test/test_cgi.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_cgi.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_cgi.py Fri Feb 23 18:29:35 2007
@@ -118,9 +118,7 @@
]
def norm(seq):
- if isinstance(seq, list):
- seq.sort(key=repr)
- return seq
+ return sorted(seq, key=repr)
def first_elts(list):
return map(lambda x:x[0], list)
Modified: python/branches/p3yk-noslice/Lib/test/test_cl.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_cl.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_cl.py Fri Feb 23 18:29:35 2007
@@ -69,10 +69,10 @@
def main():
# touch all the attributes of al without doing anything
if verbose:
- print 'Touching cl module attributes...'
+ print('Touching cl module attributes...')
for attr in clattrs:
if verbose:
- print 'touching: ', attr
+ print('touching: ', attr)
getattr(cl, attr)
main()
Modified: python/branches/p3yk-noslice/Lib/test/test_class.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_class.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_class.py Fri Feb 23 18:29:35 2007
@@ -65,73 +65,69 @@
class AllTests:
def __hash__(self, *args):
- print "__hash__:", args
+ print("__hash__:", args)
return hash(id(self))
def __str__(self, *args):
- print "__str__:", args
+ print("__str__:", args)
return "AllTests"
def __repr__(self, *args):
- print "__repr__:", args
+ print("__repr__:", args)
return "AllTests"
def __int__(self, *args):
- print "__int__:", args
+ print("__int__:", args)
return 1
def __float__(self, *args):
- print "__float__:", args
+ print("__float__:", args)
return 1.0
- def __long__(self, *args):
- print "__long__:", args
- return 1L
-
def __oct__(self, *args):
- print "__oct__:", args
+ print("__oct__:", args)
return '01'
def __hex__(self, *args):
- print "__hex__:", args
+ print("__hex__:", args)
return '0x1'
def __cmp__(self, *args):
- print "__cmp__:", args
+ print("__cmp__:", args)
return 0
def __eq__(self, *args):
- print "__eq__:", args
+ print("__eq__:", args)
return True
def __ne__(self, *args):
- print "__ne__:", args
+ print("__ne__:", args)
return False
def __lt__(self, *args):
- print "__lt__:", args
+ print("__lt__:", args)
return False
def __le__(self, *args):
- print "__le__:", args
+ print("__le__:", args)
return True
def __gt__(self, *args):
- print "__gt__:", args
+ print("__gt__:", args)
return False
def __ge__(self, *args):
- print "__ge__:", args
+ print("__ge__:", args)
return True
def __del__(self, *args):
- print "__del__:", args
+ print("__del__:", args)
# Synthesize AllTests methods from the names in testmeths.
method_template = """\
def __%(method)s__(self, *args):
- print "__%(method)s__:", args
+ print("__%(method)s__:", args)
"""
d = {}
@@ -190,7 +186,7 @@
try:
1 in Empty()
- print 'failed, should have raised TypeError'
+ print('failed, should have raised TypeError')
except TypeError:
pass
@@ -228,9 +224,9 @@
else:
# This works under Jython, but the actual slice values are
# different.
- print "__getitem__: (slice(0, 42, None),)"
- print "__setitem__: (slice(0, 42, None), 'The Answer')"
- print "__delitem__: (slice(0, 42, None),)"
+ print("__getitem__: (slice(0, 42, None),)")
+ print("__setitem__: (slice(0, 42, None), 'The Answer')")
+ print("__delitem__: (slice(0, 42, None),)")
# Unary operations
@@ -238,7 +234,7 @@
+testme
abs(testme)
int(testme)
-long(testme)
+int(testme)
float(testme)
oct(testme)
hex(testme)
@@ -269,14 +265,14 @@
class ExtraTests:
def __getattr__(self, *args):
- print "__getattr__:", args
+ print("__getattr__:", args)
return "SomeVal"
def __setattr__(self, *args):
- print "__setattr__:", args
+ print("__setattr__:", args)
def __delattr__(self, *args):
- print "__delattr__:", args
+ print("__delattr__:", args)
testme = ExtraTests()
testme.spam
@@ -289,7 +285,6 @@
def __int__(self):
return None
__float__ = __int__
- __long__ = __int__
__str__ = __int__
__repr__ = __int__
__oct__ = __int__
@@ -307,31 +302,11 @@
check_exc("int(BadTypeClass())", TypeError)
check_exc("float(BadTypeClass())", TypeError)
-check_exc("long(BadTypeClass())", TypeError)
check_exc("str(BadTypeClass())", TypeError)
check_exc("repr(BadTypeClass())", TypeError)
check_exc("oct(BadTypeClass())", TypeError)
check_exc("hex(BadTypeClass())", TypeError)
-# mixing up ints and longs is okay
-class IntLongMixClass:
- def __int__(self):
- return 0L
-
- def __long__(self):
- return 0
-
-try:
- int(IntLongMixClass())
-except TypeError:
- raise TestFailed, "TypeError should not be raised"
-
-try:
- long(IntLongMixClass())
-except TypeError:
- raise TestFailed, "TypeError should not be raised"
-
-
# Test correct errors from hash() on objects with comparisons but no __hash__
class C0:
@@ -374,7 +349,7 @@
A().a # Raised AttributeError: A instance has no attribute 'a'
except AttributeError as x:
if str(x) != "booh":
- print "attribute error for A().a got masked:", str(x)
+ print("attribute error for A().a got masked:", str(x))
class E:
__eq__ = property(booh)
@@ -387,7 +362,7 @@
except AttributeError as x:
pass
else:
- print "attribute error for I.__init__ got masked"
+ print("attribute error for I.__init__ got masked")
# Test comparison and hash of methods
Modified: python/branches/p3yk-noslice/Lib/test/test_cmath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_cmath.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_cmath.py Fri Feb 23 18:29:35 2007
@@ -43,10 +43,10 @@
f = getattr(cmath, func)
r = f(testdict[func])
if verbose:
- print 'Calling %s(%f) = %f' % (func, testdict[func], abs(r))
+ print('Calling %s(%f) = %f' % (func, testdict[func], abs(r)))
p = cmath.pi
e = cmath.e
if verbose:
- print 'PI = ', abs(p)
- print 'E = ', abs(e)
+ print('PI = ', abs(p))
+ print('E = ', abs(e))
Modified: python/branches/p3yk-noslice/Lib/test/test_code.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_code.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_code.py Fri Feb 23 18:29:35 2007
@@ -50,15 +50,15 @@
consts: ('None',)
>>> def attrs(obj):
-... print obj.attr1
-... print obj.attr2
-... print obj.attr3
+... print(obj.attr1)
+... print(obj.attr2)
+... print(obj.attr3)
>>> dump(attrs.func_code)
name: attrs
argcount: 1
kwonlyargcount: 0
-names: ('attr1', 'attr2', 'attr3')
+names: ('print', 'attr1', 'attr2', 'attr3')
varnames: ('obj',)
cellvars: ()
freevars: ()
@@ -70,7 +70,7 @@
... 'doc string'
... 'not a docstring'
... 53
-... 53L
+... 0x53
>>> dump(optimize_away.func_code)
name: optimize_away
@@ -115,8 +115,8 @@
"""Print out a text representation of a code object."""
for attr in ["name", "argcount", "kwonlyargcount", "names", "varnames",
"cellvars", "freevars", "nlocals", "flags"]:
- print "%s: %s" % (attr, getattr(co, "co_" + attr))
- print "consts:", tuple(consts(co.co_consts))
+ print("%s: %s" % (attr, getattr(co, "co_" + attr)))
+ print("consts:", tuple(consts(co.co_consts)))
def test_main(verbose=None):
from test.test_support import run_doctest
Modified: python/branches/p3yk-noslice/Lib/test/test_codecs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_codecs.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_codecs.py Fri Feb 23 18:29:35 2007
@@ -548,7 +548,7 @@
for i in punycode_testcases:
if len(i)!=2:
- print repr(i)
+ print(repr(i))
class PunycodeTest(unittest.TestCase):
def test_encode(self):
Modified: python/branches/p3yk-noslice/Lib/test/test_compare.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_compare.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_compare.py Fri Feb 23 18:29:35 2007
@@ -17,7 +17,7 @@
return self.arg == other
class ComparisonTest(unittest.TestCase):
- set1 = [2, 2.0, 2L, 2+0j, Cmp(2.0)]
+ set1 = [2, 2.0, 2, 2+0j, Cmp(2.0)]
set2 = [[1], (3,), None, Empty()]
candidates = set1 + set2
Modified: python/branches/p3yk-noslice/Lib/test/test_compile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_compile.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_compile.py Fri Feb 23 18:29:35 2007
@@ -182,10 +182,8 @@
self.assertRaises(SyntaxError, eval, arg)
self.assertEqual(eval("0777"), 511)
- self.assertEqual(eval("0777L"), 511)
self.assertEqual(eval("000777"), 511)
self.assertEqual(eval("0xff"), 255)
- self.assertEqual(eval("0xffL"), 255)
self.assertEqual(eval("0XfF"), 255)
self.assertEqual(eval("0777."), 777)
self.assertEqual(eval("0777.0"), 777)
@@ -212,19 +210,19 @@
if sys.maxint == 2147483647:
# 32-bit machine
all_one_bits = '0xffffffff'
- self.assertEqual(eval(all_one_bits), 4294967295L)
- self.assertEqual(eval("-" + all_one_bits), -4294967295L)
+ self.assertEqual(eval(all_one_bits), 4294967295)
+ self.assertEqual(eval("-" + all_one_bits), -4294967295)
elif sys.maxint == 9223372036854775807:
# 64-bit machine
all_one_bits = '0xffffffffffffffff'
- self.assertEqual(eval(all_one_bits), 18446744073709551615L)
- self.assertEqual(eval("-" + all_one_bits), -18446744073709551615L)
+ self.assertEqual(eval(all_one_bits), 18446744073709551615)
+ self.assertEqual(eval("-" + all_one_bits), -18446744073709551615)
else:
self.fail("How many bits *does* this machine have???")
# Verify treatment of contant folding on -(sys.maxint+1)
# i.e. -2147483648 on 32 bit platforms. Should return int, not long.
self.assertTrue(isinstance(eval("%s" % (-sys.maxint - 1)), int))
- self.assertTrue(isinstance(eval("%s" % (-sys.maxint - 2)), long))
+ self.assertTrue(isinstance(eval("%s" % (-sys.maxint - 2)), int))
if sys.maxint == 9223372036854775807:
def test_32_63_bit_values(self):
Modified: python/branches/p3yk-noslice/Lib/test/test_compiler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_compiler.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_compiler.py Fri Feb 23 18:29:35 2007
@@ -7,6 +7,12 @@
# How much time in seconds can pass before we print a 'Still working' message.
_PRINT_WORKING_MSG_INTERVAL = 5 * 60
+class TrivialContext(object):
+ def __enter__(self):
+ return self
+ def __exit__(self, *exc_info):
+ pass
+
class CompilerTest(unittest.TestCase):
def testCompileLibrary(self):
@@ -24,8 +30,7 @@
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
- print >>sys.__stdout__, \
- ' testCompileLibrary still working, be patient...'
+ print(' testCompileLibrary still working, be patient...', file=sys.__stdout__)
sys.__stdout__.flush()
if not basename.endswith(".py"):
@@ -34,7 +39,7 @@
continue
path = os.path.join(dir, basename)
if test.test_support.verbose:
- print "compiling", path
+ print("compiling", path)
f = open(path, "U")
buf = f.read()
f.close()
@@ -88,7 +93,7 @@
try:
self._check_lineno(node)
except AssertionError:
- print node.__class__, node.lineno
+ print(node.__class__, node.lineno)
raise
def _check_lineno(self, node):
@@ -157,6 +162,31 @@
exec(c, dct)
self.assertEquals(dct['f'].func_annotations, expected)
+ def testWith(self):
+ # SF bug 1638243
+ c = compiler.compile('from __future__ import with_statement\n'
+ 'def f():\n'
+ ' with TrivialContext():\n'
+ ' return 1\n'
+ 'result = f()',
+ '<string>',
+ 'exec' )
+ dct = {'TrivialContext': TrivialContext}
+ exec(c, dct)
+ self.assertEquals(dct.get('result'), 1)
+
+ def testWithAss(self):
+ c = compiler.compile('from __future__ import with_statement\n'
+ 'def f():\n'
+ ' with TrivialContext() as tc:\n'
+ ' return 1\n'
+ 'result = f()',
+ '<string>',
+ 'exec' )
+ dct = {'TrivialContext': TrivialContext}
+ exec(c, dct)
+ self.assertEquals(dct.get('result'), 1)
+
NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard,
compiler.ast.Const)
@@ -187,7 +217,7 @@
a, b = b, a
try:
- print yo
+ print(yo)
except:
yo = 3
else:
Modified: python/branches/p3yk-noslice/Lib/test/test_complex.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_complex.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_complex.py Fri Feb 23 18:29:35 2007
@@ -93,7 +93,7 @@
self.assertRaises(ZeroDivisionError, complex.__floordiv__, 3+0j, 0+0j)
def test_richcompare(self):
- self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1L<<10000)
+ self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1<<10000)
self.assertEqual(complex.__lt__(1+1j, None), NotImplemented)
self.assertIs(complex.__eq__(1+1j, 1+1j), True)
self.assertIs(complex.__eq__(1+1j, 2+2j), False)
@@ -180,25 +180,25 @@
self.assertAlmostEqual(complex("1+10j"), 1+10j)
self.assertAlmostEqual(complex(10), 10+0j)
self.assertAlmostEqual(complex(10.0), 10+0j)
- self.assertAlmostEqual(complex(10L), 10+0j)
+ self.assertAlmostEqual(complex(10), 10+0j)
self.assertAlmostEqual(complex(10+0j), 10+0j)
self.assertAlmostEqual(complex(1,10), 1+10j)
- self.assertAlmostEqual(complex(1,10L), 1+10j)
+ self.assertAlmostEqual(complex(1,10), 1+10j)
+ self.assertAlmostEqual(complex(1,10.0), 1+10j)
+ self.assertAlmostEqual(complex(1,10), 1+10j)
+ self.assertAlmostEqual(complex(1,10), 1+10j)
self.assertAlmostEqual(complex(1,10.0), 1+10j)
- self.assertAlmostEqual(complex(1L,10), 1+10j)
- self.assertAlmostEqual(complex(1L,10L), 1+10j)
- self.assertAlmostEqual(complex(1L,10.0), 1+10j)
self.assertAlmostEqual(complex(1.0,10), 1+10j)
- self.assertAlmostEqual(complex(1.0,10L), 1+10j)
+ self.assertAlmostEqual(complex(1.0,10), 1+10j)
self.assertAlmostEqual(complex(1.0,10.0), 1+10j)
self.assertAlmostEqual(complex(3.14+0j), 3.14+0j)
self.assertAlmostEqual(complex(3.14), 3.14+0j)
self.assertAlmostEqual(complex(314), 314.0+0j)
- self.assertAlmostEqual(complex(314L), 314.0+0j)
+ self.assertAlmostEqual(complex(314), 314.0+0j)
self.assertAlmostEqual(complex(3.14+0j, 0j), 3.14+0j)
self.assertAlmostEqual(complex(3.14, 0.0), 3.14+0j)
self.assertAlmostEqual(complex(314, 0), 314.0+0j)
- self.assertAlmostEqual(complex(314L, 0L), 314.0+0j)
+ self.assertAlmostEqual(complex(314, 0), 314.0+0j)
self.assertAlmostEqual(complex(0j, 3.14j), -3.14+0j)
self.assertAlmostEqual(complex(0.0, 3.14j), -3.14+0j)
self.assertAlmostEqual(complex(0j, 3.14), 3.14j)
@@ -232,7 +232,7 @@
self.assertRaises(ValueError, complex, '1+1j\0j')
self.assertRaises(TypeError, int, 5+3j)
- self.assertRaises(TypeError, long, 5+3j)
+ self.assertRaises(TypeError, int, 5+3j)
self.assertRaises(TypeError, float, 5+3j)
self.assertRaises(ValueError, complex, "")
self.assertRaises(TypeError, complex, None)
@@ -315,7 +315,7 @@
fo = None
try:
fo = open(test_support.TESTFN, "wb")
- print >>fo, a, b
+ print(a, b, file=fo)
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), "%s %s\n" % (a, b))
Modified: python/branches/p3yk-noslice/Lib/test/test_cookie.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_cookie.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_cookie.py Fri Feb 23 18:29:35 2007
@@ -38,7 +38,7 @@
C.load(case['data'])
self.assertEqual(repr(C), case['repr'])
self.assertEqual(C.output(sep='\n'), case['output'])
- for k, v in sorted(case['dict'].iteritems()):
+ for k, v in sorted(case['dict'].items()):
self.assertEqual(C[k].value, v)
def test_load(self):
Modified: python/branches/p3yk-noslice/Lib/test/test_cookielib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_cookielib.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_cookielib.py Fri Feb 23 18:29:35 2007
@@ -103,7 +103,7 @@
from cookielib import parse_ns_headers
# quotes should be stripped
- expected = [[('foo', 'bar'), ('expires', 2209069412L), ('version', '0')]]
+ expected = [[('foo', 'bar'), ('expires', 2209069412), ('version', '0')]]
for hdr in [
'foo=bar; expires=01 Jan 2040 22:23:32 GMT',
'foo=bar; expires="01 Jan 2040 22:23:32 GMT"',
Modified: python/branches/p3yk-noslice/Lib/test/test_copy.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_copy.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_copy.py Fri Feb 23 18:29:35 2007
@@ -82,7 +82,7 @@
pass
def f():
pass
- tests = [None, 42, 2L**100, 3.14, True, False, 1j,
+ tests = [None, 42, 2**100, 3.14, True, False, 1j,
"hello", u"hello\u1234", f.func_code,
NewStyle, xrange(10), Classic, max]
for x in tests:
@@ -255,7 +255,7 @@
pass
def f():
pass
- tests = [None, 42, 2L**100, 3.14, True, False, 1j,
+ tests = [None, 42, 2**100, 3.14, True, False, 1j,
"hello", u"hello\u1234", f.func_code,
NewStyle, xrange(10), Classic, max]
for x in tests:
@@ -491,7 +491,7 @@
def test_reduce_5tuple(self):
class C(dict):
def __reduce__(self):
- return (C, (), self.__dict__, None, self.iteritems())
+ return (C, (), self.__dict__, None, self.items())
def __eq__(self, other):
return (dict(self) == dict(other) and
self.__dict__ == other.__dict__)
Modified: python/branches/p3yk-noslice/Lib/test/test_copy_reg.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_copy_reg.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_copy_reg.py Fri Feb 23 18:29:35 2007
@@ -96,7 +96,7 @@
e.restore()
# Ensure invalid codes blow up.
- for code in -1, 0, 0x80000000L:
+ for code in -1, 0, 0x80000000:
self.assertRaises(ValueError, copy_reg.add_extension,
mod, func, code)
Modified: python/branches/p3yk-noslice/Lib/test/test_crypt.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_crypt.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_crypt.py Fri Feb 23 18:29:35 2007
@@ -8,4 +8,4 @@
c = crypt.crypt('mypassword', 'ab')
if verbose:
- print 'Test encryption: ', c
+ print('Test encryption: ', c)
Modified: python/branches/p3yk-noslice/Lib/test/test_csv.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_csv.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_csv.py Fri Feb 23 18:29:35 2007
@@ -894,7 +894,7 @@
self.assertEqual(dialect.quotechar, "'")
if not hasattr(sys, "gettotalrefcount"):
- if test_support.verbose: print "*** skipping leakage tests ***"
+ if test_support.verbose: print("*** skipping leakage tests ***")
else:
class NUL:
def write(s, *args):
Modified: python/branches/p3yk-noslice/Lib/test/test_curses.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_curses.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_curses.py Fri Feb 23 18:29:35 2007
@@ -228,7 +228,7 @@
('\x8a', '!^J'), ('\xc1', '!A'),
]:
if ascii.unctrl(ch) != expected:
- print 'curses.unctrl fails on character', repr(ch)
+ print('curses.unctrl fails on character', repr(ch))
def test_userptr_without_set(stdscr):
Modified: python/branches/p3yk-noslice/Lib/test/test_datetime.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_datetime.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_datetime.py Fri Feb 23 18:29:35 2007
@@ -32,7 +32,7 @@
# An arbitrary collection of objects of non-datetime types, for testing
# mixed-type comparisons.
-OTHERSTUFF = (10, 10L, 34.5, "abc", {}, [], ())
+OTHERSTUFF = (10, 10, 34.5, "abc", {}, [], ())
#############################################################################
@@ -149,11 +149,11 @@
self.failIf(() == me)
self.failUnless(() != me)
- self.failUnless(me in [1, 20L, [], me])
- self.failIf(me not in [1, 20L, [], me])
+ self.failUnless(me in [1, 20, [], me])
+ self.failIf(me not in [1, 20, [], me])
- self.failUnless([] in [me, 1, 20L, []])
- self.failIf([] not in [me, 1, 20L, []])
+ self.failUnless([] in [me, 1, 20, []])
+ self.failIf([] not in [me, 1, 20, []])
def test_harmful_mixed_comparison(self):
me = self.theclass(1, 1, 1)
@@ -222,13 +222,13 @@
eq(td(0, 0, 60*1000000), b)
eq(a*10, td(70))
eq(a*10, 10*a)
- eq(a*10L, 10*a)
+ eq(a*10, 10*a)
eq(b*10, td(0, 600))
eq(10*b, td(0, 600))
- eq(b*10L, td(0, 600))
+ eq(b*10, td(0, 600))
eq(c*10, td(0, 0, 10000))
eq(10*c, td(0, 0, 10000))
- eq(c*10L, td(0, 0, 10000))
+ eq(c*10, td(0, 0, 10000))
eq(a*-1, -a)
eq(b*-2, -b-b)
eq(c*-2, -c+-c)
@@ -246,7 +246,7 @@
a = timedelta(42)
# Add/sub ints, longs, floats should be illegal
- for i in 1, 1L, 1.0:
+ for i in 1, 1, 1.0:
self.assertRaises(TypeError, lambda: a+i)
self.assertRaises(TypeError, lambda: a-i)
self.assertRaises(TypeError, lambda: i+a)
@@ -263,7 +263,7 @@
# Divison of int by timedelta doesn't make sense.
# Division by zero doesn't make sense.
- for zero in 0, 0L:
+ for zero in 0, 0:
self.assertRaises(TypeError, lambda: zero // a)
self.assertRaises(ZeroDivisionError, lambda: a // zero)
@@ -696,7 +696,7 @@
self.assertEqual(a - (a - day), day)
# Add/sub ints, longs, floats should be illegal
- for i in 1, 1L, 1.0:
+ for i in 1, 1, 1.0:
self.assertRaises(TypeError, lambda: a+i)
self.assertRaises(TypeError, lambda: a-i)
self.assertRaises(TypeError, lambda: i+a)
@@ -1325,7 +1325,7 @@
self.assertEqual(a - (week + day + hour + millisec),
(((a - week) - day) - hour) - millisec)
# Add/sub ints, longs, floats should be illegal
- for i in 1, 1L, 1.0:
+ for i in 1, 1, 1.0:
self.assertRaises(TypeError, lambda: a+i)
self.assertRaises(TypeError, lambda: a-i)
self.assertRaises(TypeError, lambda: i+a)
@@ -1767,6 +1767,11 @@
self.assertEqual(t.isoformat(), "00:00:00.100000")
self.assertEqual(t.isoformat(), str(t))
+ def test_1653736(self):
+ # verify it doesn't accept extra keyword arguments
+ t = self.theclass(second=1)
+ self.assertRaises(TypeError, t.isoformat, foo=3)
+
def test_strftime(self):
t = self.theclass(1, 2, 3, 4)
self.assertEqual(t.strftime('%H %M %S'), "01 02 03")
@@ -3287,11 +3292,11 @@
gc.garbage)
if hasattr(sys, 'gettotalrefcount'):
thisrc = sys.gettotalrefcount()
- print >> sys.stderr, '*' * 10, 'total refs:', thisrc,
+ print('*' * 10, 'total refs:', thisrc, end=' ', file=sys.stderr)
if lastrc:
- print >> sys.stderr, 'delta:', thisrc - lastrc
+ print('delta:', thisrc - lastrc, file=sys.stderr)
else:
- print >> sys.stderr
+ print(file=sys.stderr)
lastrc = thisrc
if __name__ == "__main__":
Modified: python/branches/p3yk-noslice/Lib/test/test_dbm.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_dbm.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_dbm.py Fri Feb 23 18:29:35 2007
@@ -31,7 +31,7 @@
d.keys()
if 'a' in d:
if verbose:
- print 'Test dbm keys: ', d.keys()
+ print('Test dbm keys: ', d.keys())
d.close()
Modified: python/branches/p3yk-noslice/Lib/test/test_decimal.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_decimal.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_decimal.py Fri Feb 23 18:29:35 2007
@@ -143,8 +143,8 @@
try:
t = self.eval_line(line)
except InvalidOperation:
- print 'Error in test cases:'
- print line
+ print('Error in test cases:')
+ print(line)
continue
except DecimalException as exception:
#Exception raised where there shoudn't have been one.
@@ -271,7 +271,7 @@
except Signals as error:
self.fail("Raised %s in %s" % (error, s))
except: #Catch any error long enough to state the test case.
- print "ERROR:", s
+ print("ERROR:", s)
raise
myexceptions = self.getexceptions()
@@ -907,8 +907,8 @@
self.assertEqual(int(d2), 15)
#long
- self.assertEqual(long(d1), 66)
- self.assertEqual(long(d2), 15)
+ self.assertEqual(int(d1), 66)
+ self.assertEqual(int(d2), 15)
#float
self.assertEqual(float(d1), 66)
Modified: python/branches/p3yk-noslice/Lib/test/test_defaultdict.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_defaultdict.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_defaultdict.py Fri Feb 23 18:29:35 2007
@@ -47,6 +47,7 @@
self.assertEqual(err.args, (15,))
else:
self.fail("d2[15] didn't raise KeyError")
+ self.assertRaises(TypeError, defaultdict, 1)
def test_missing(self):
d1 = defaultdict()
@@ -60,10 +61,10 @@
self.assertEqual(repr(d1), "defaultdict(None, {})")
d1[11] = 41
self.assertEqual(repr(d1), "defaultdict(None, {11: 41})")
- d2 = defaultdict(0)
- self.assertEqual(d2.default_factory, 0)
+ d2 = defaultdict(int)
+ self.assertEqual(d2.default_factory, int)
d2[12] = 42
- self.assertEqual(repr(d2), "defaultdict(0, {12: 42})")
+ self.assertEqual(repr(d2), "defaultdict(<type 'int'>, {12: 42})")
def foo(): return 43
d3 = defaultdict(foo)
self.assert_(d3.default_factory is foo)
@@ -81,8 +82,8 @@
try:
f = open(tfn, "w+")
try:
- print >>f, d1
- print >>f, d2
+ print(d1, file=f)
+ print(d2, file=f)
f.seek(0)
self.assertEqual(f.readline(), repr(d1) + "\n")
self.assertEqual(f.readline(), repr(d2) + "\n")
Modified: python/branches/p3yk-noslice/Lib/test/test_deque.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_deque.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_deque.py Fri Feb 23 18:29:35 2007
@@ -245,7 +245,7 @@
d.append(d)
try:
fo = open(test_support.TESTFN, "wb")
- print >> fo, d,
+ fo.write(str(d))
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), repr(d))
@@ -486,6 +486,16 @@
d1 == d2 # not clear if this is supposed to be True or False,
# but it used to give a SystemError
+
+class SubclassWithKwargs(deque):
+ def __init__(self, newarg=1):
+ deque.__init__(self)
+
+class TestSubclassWithKwargs(unittest.TestCase):
+ def test_subclass_with_kwargs(self):
+ # SF bug #1486663 -- this used to erroneously raise a TypeError
+ SubclassWithKwargs(newarg=1)
+
#==============================================================================
libreftest = """
@@ -494,7 +504,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
@@ -564,8 +574,8 @@
...
>>> for value in roundrobin('abc', 'd', 'efgh'):
-... print value
-...
+... print(value)
+...
a
d
e
@@ -583,7 +593,7 @@
... d.append(pair)
... return list(d)
...
->>> print maketree('abcdefgh')
+>>> print(maketree('abcdefgh'))
[[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
"""
@@ -599,6 +609,7 @@
TestBasic,
TestVariousIteratorArgs,
TestSubclass,
+ TestSubclassWithKwargs,
)
test_support.run_unittest(*test_classes)
@@ -611,7 +622,7 @@
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
# doctests
from test import test_deque
Modified: python/branches/p3yk-noslice/Lib/test/test_descr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_descr.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_descr.py Fri Feb 23 18:29:35 2007
@@ -13,7 +13,7 @@
raise TestFailed, "%r is %r" % (a, b)
def testunop(a, res, expr="len(a)", meth="__len__"):
- if verbose: print "checking", expr
+ if verbose: print("checking", expr)
dict = {'a': a}
vereq(eval(expr, dict), res)
t = type(a)
@@ -26,7 +26,7 @@
vereq(bm(), res)
def testbinop(a, b, res, expr="a+b", meth="__add__"):
- if verbose: print "checking", expr
+ if verbose: print("checking", expr)
dict = {'a': a, 'b': b}
vereq(eval(expr, dict), res)
@@ -40,7 +40,7 @@
vereq(bm(b), res)
def testternop(a, b, c, res, expr="a[b:c]", meth="__getitem__"):
- if verbose: print "checking", expr
+ if verbose: print("checking", expr)
dict = {'a': a, 'b': b, 'c': c}
vereq(eval(expr, dict), res)
t = type(a)
@@ -53,7 +53,7 @@
vereq(bm(slice(b, c, None)), res)
def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
- if verbose: print "checking", stmt
+ if verbose: print("checking", stmt)
dict = {'a': deepcopy(a), 'b': b}
exec(stmt, dict)
vereq(dict['a'], res)
@@ -71,7 +71,7 @@
vereq(dict['a'], res)
def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
- if verbose: print "checking", stmt
+ if verbose: print("checking", stmt)
dict = {'a': deepcopy(a), 'b': b, 'c': c}
exec(stmt, dict)
vereq(dict['a'], res)
@@ -89,7 +89,7 @@
vereq(dict['a'], res)
def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
- if verbose: print "checking", stmt
+ if verbose: print("checking", stmt)
dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
exec(stmt, dict)
vereq(dict['a'], res)
@@ -135,7 +135,7 @@
verify(NewDynamic2.__doc__ is None)
def lists():
- if verbose: print "Testing list operations..."
+ if verbose: print("Testing list operations...")
testbinop([1], [2], [1,2], "a+b", "__add__")
testbinop([1,2,3], 2, 1, "b in a", "__contains__")
testbinop([1,2,3], 4, 0, "b in a", "__contains__")
@@ -150,7 +150,7 @@
testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setitem__")
def dicts():
- if verbose: print "Testing dict operations..."
+ if verbose: print("Testing dict operations...")
##testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
@@ -175,7 +175,7 @@
def dict_constructor():
if verbose:
- print "Testing dict constructor ..."
+ print("Testing dict constructor ...")
d = dict()
vereq(d, {})
d = dict({})
@@ -183,7 +183,7 @@
d = dict({1: 2, 'a': 'b'})
vereq(d, {1: 2, 'a': 'b'})
vereq(d, dict(d.items()))
- vereq(d, dict(d.iteritems()))
+ vereq(d, dict(d.items()))
d = dict({'one':1, 'two':2})
vereq(d, dict(one=1, two=2))
vereq(d, dict(**d))
@@ -191,7 +191,7 @@
vereq(d, dict([("two", 2)], one=1))
vereq(d, dict([("one", 100), ("two", 200)], **d))
verify(d is not dict(**d))
- for badarg in 0, 0L, 0j, "0", [0], (0,):
+ for badarg in 0, 0, 0j, "0", [0], (0,):
try:
dict(badarg)
except TypeError:
@@ -258,13 +258,13 @@
def test_dir():
if verbose:
- print "Testing dir() ..."
+ print("Testing dir() ...")
junk = 12
vereq(dir(), ['junk'])
del junk
# Just make sure these don't blow up!
- for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
+ for arg in 2, 2, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
dir(arg)
# Test dir on custom classes. Since these have object as a
@@ -385,7 +385,6 @@
'abs': 'abs',
'invert': '~',
'int': 'int',
- 'long': 'long',
'float': 'float',
'oct': 'oct',
'hex': 'hex',
@@ -414,7 +413,7 @@
testunop(a, res, expr, name)
def ints():
- if verbose: print "Testing int operations..."
+ if verbose: print("Testing int operations...")
numops(100, 3)
# The following crashes in Python 2.2
vereq((1).__bool__(), True)
@@ -423,31 +422,24 @@
class C(int):
def __add__(self, other):
return NotImplemented
- vereq(C(5L), 5)
+ vereq(C(5), 5)
try:
C() + ""
except TypeError:
pass
else:
raise TestFailed, "NotImplemented should have caused TypeError"
- import sys
- try:
- C(sys.maxint+1)
- except OverflowError:
- pass
- else:
- raise TestFailed, "should have raised OverflowError"
def longs():
- if verbose: print "Testing long operations..."
- numops(100L, 3L)
+ if verbose: print("Testing long operations...")
+ numops(100, 3)
def floats():
- if verbose: print "Testing float operations..."
+ if verbose: print("Testing float operations...")
numops(100.0, 3.0)
def complexes():
- if verbose: print "Testing complex operations..."
+ if verbose: print("Testing complex operations...")
numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
class Number(complex):
__slots__ = ['prec']
@@ -477,7 +469,7 @@
vereq(a.prec, 12)
def spamlists():
- if verbose: print "Testing spamlist operations..."
+ if verbose: print("Testing spamlist operations...")
import copy, xxsubtype as spam
def spamlist(l, memo=None):
import xxsubtype as spam
@@ -513,7 +505,7 @@
vereq(a.getstate(), 42)
def spamdicts():
- if verbose: print "Testing spamdict operations..."
+ if verbose: print("Testing spamdict operations...")
import copy, xxsubtype as spam
def spamdict(d, memo=None):
import xxsubtype as spam
@@ -549,16 +541,16 @@
class C(spam.spamdict):
def foo(self): return 1
a = C()
- vereq(a.items(), [])
+ vereq(list(a.items()), [])
vereq(a.foo(), 1)
a['foo'] = 'bar'
- vereq(a.items(), [('foo', 'bar')])
+ vereq(list(a.items()), [('foo', 'bar')])
vereq(a.getstate(), 0)
a.setstate(100)
vereq(a.getstate(), 100)
def pydicts():
- if verbose: print "Testing Python subclass of dict..."
+ if verbose: print("Testing Python subclass of dict...")
verify(issubclass(dict, dict))
verify(isinstance({}, dict))
d = dict()
@@ -599,7 +591,7 @@
vereq(a[42], 0)
a[42] = 24
vereq(a[42], 24)
- if verbose: print "pydict stress test ..."
+ if verbose: print("pydict stress test ...")
N = 50
for i in range(N):
a[i] = C()
@@ -610,7 +602,7 @@
vereq(a[i][j], i*j)
def pylists():
- if verbose: print "Testing Python subclass of list..."
+ if verbose: print("Testing Python subclass of list...")
class C(list):
def __getitem__(self, i):
if isinstance(i, slice):
@@ -624,7 +616,7 @@
vereq(a[100:200], (100,200))
def metaclass():
- if verbose: print "Testing __metaclass__..."
+ if verbose: print("Testing __metaclass__...")
class C:
__metaclass__ = type
def __init__(self):
@@ -722,7 +714,7 @@
# named _get_x and/or _set_x are found
def __new__(metaclass, name, bases, dict):
hits = {}
- for key, val in dict.iteritems():
+ for key, val in dict.items():
if key.startswith("_get_"):
key = key[5:]
get, set = hits.get(key, (None, None))
@@ -733,7 +725,7 @@
get, set = hits.get(key, (None, None))
set = val
hits[key] = get, set
- for key, (get, set) in hits.iteritems():
+ for key, (get, set) in hits.items():
dict[key] = property(get, set)
return super(autoproperty, metaclass).__new__(metaclass,
name, bases, dict)
@@ -786,7 +778,7 @@
else: raise TestFailed, "calling object w/o call method should raise TypeError"
def pymods():
- if verbose: print "Testing Python subclass of module..."
+ if verbose: print("Testing Python subclass of module...")
log = []
import sys
MT = type(sys)
@@ -811,7 +803,7 @@
("delattr", "foo")])
def multi():
- if verbose: print "Testing multiple inheritance..."
+ if verbose: print("Testing multiple inheritance...")
class C(object):
def __init__(self):
self.__state = 0
@@ -828,9 +820,9 @@
type({}).__init__(self)
C.__init__(self)
d = D()
- vereq(d.keys(), [])
+ vereq(list(d.keys()), [])
d["hello"] = "world"
- vereq(d.items(), [("hello", "world")])
+ vereq(list(d.items()), [("hello", "world")])
vereq(d["hello"], "world")
vereq(d.getstate(), 0)
d.setstate(10)
@@ -852,7 +844,7 @@
vereq(int(Frag()), 42)
def diamond():
- if verbose: print "Testing multiple inheritance special cases..."
+ if verbose: print("Testing multiple inheritance special cases...")
class A(object):
def spam(self): return "A"
vereq(A().spam(), "A")
@@ -890,7 +882,7 @@
# see thread python-dev/2002-October/029035.html
def ex5():
- if verbose: print "Testing ex5 from C3 switch discussion..."
+ if verbose: print("Testing ex5 from C3 switch discussion...")
class A(object): pass
class B(object): pass
class C(object): pass
@@ -902,7 +894,7 @@
# see "A Monotonic Superclass Linearization for Dylan",
# by Kim Barrett et al. (OOPSLA 1996)
def monotonicity():
- if verbose: print "Testing MRO monotonicity..."
+ if verbose: print("Testing MRO monotonicity...")
class Boat(object): pass
class DayBoat(Boat): pass
class WheelBoat(Boat): pass
@@ -925,7 +917,7 @@
# see "A Monotonic Superclass Linearization for Dylan",
# by Kim Barrett et al. (OOPSLA 1996)
def consistency_with_epg():
- if verbose: print "Testing consistentcy with EPG..."
+ if verbose: print("Testing consistentcy with EPG...")
class Pane(object): pass
class ScrollingMixin(object): pass
class EditingMixin(object): pass
@@ -941,7 +933,7 @@
order (MRO) for bases """
def mro_disagreement():
- if verbose: print "Testing error messages for MRO disagreement..."
+ if verbose: print("Testing error messages for MRO disagreement...")
def raises(exc, expected, callable, *args):
try:
callable(*args)
@@ -971,7 +963,7 @@
type, "ConfusedGrid", (HVGrid, VHGrid), {})
def objects():
- if verbose: print "Testing object class..."
+ if verbose: print("Testing object class...")
a = object()
vereq(a.__class__, object)
vereq(type(a), object)
@@ -995,7 +987,7 @@
vereq(x.__dict__, {'foo': 1})
def slots():
- if verbose: print "Testing __slots__..."
+ if verbose: print("Testing __slots__...")
class C0(object):
__slots__ = []
x = C0()
@@ -1160,7 +1152,7 @@
sys.stderr = save_stderr
def slotspecials():
- if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
+ if verbose: print("Testing __dict__ and __weakref__ in __slots__...")
class D(object):
__slots__ = ["__dict__"]
@@ -1207,7 +1199,7 @@
# __slots__ = []
def dynamics():
- if verbose: print "Testing class attribute propagation..."
+ if verbose: print("Testing class attribute propagation...")
class D(object):
pass
class E(D):
@@ -1270,10 +1262,10 @@
vereq(I(3)*I(2), 6)
# Test handling of long*seq and seq*long
- class L(long):
+ class L(int):
pass
- vereq("a"*L(2L), "aa")
- vereq(L(2L)*"a", "aa")
+ vereq("a"*L(2), "aa")
+ vereq(L(2)*"a", "aa")
vereq(2*L(3), 6)
vereq(L(3)*2, 6)
vereq(L(3)*L(2), 6)
@@ -1286,7 +1278,7 @@
verify(someclass != object)
def errors():
- if verbose: print "Testing errors..."
+ if verbose: print("Testing errors...")
try:
class C(list, dict):
@@ -1331,7 +1323,7 @@
verify(0, "__slots__ = [1] should be illegal")
def classmethods():
- if verbose: print "Testing class methods..."
+ if verbose: print("Testing class methods...")
class C(object):
def foo(*a): return a
goo = classmethod(foo)
@@ -1377,7 +1369,7 @@
raise TestFailed, "classmethod shouldn't accept keyword args"
def classmethods_in_c():
- if verbose: print "Testing C-based class methods..."
+ if verbose: print("Testing C-based class methods...")
import xxsubtype as spam
a = (1, 2, 3)
d = {'abc': 123}
@@ -1391,7 +1383,7 @@
vereq(d, d1)
def staticmethods():
- if verbose: print "Testing static methods..."
+ if verbose: print("Testing static methods...")
class C(object):
def foo(*a): return a
goo = staticmethod(foo)
@@ -1408,7 +1400,7 @@
vereq(D.foo(d, 1), (d, 1))
def staticmethods_in_c():
- if verbose: print "Testing C-based static methods..."
+ if verbose: print("Testing C-based static methods...")
import xxsubtype as spam
a = (1, 2, 3)
d = {"abc": 123}
@@ -1422,7 +1414,7 @@
vereq(d, d1)
def classic():
- if verbose: print "Testing classic classes..."
+ if verbose: print("Testing classic classes...")
class C:
def foo(*a): return a
goo = classmethod(foo)
@@ -1443,7 +1435,7 @@
verify(repr(C.foo.__get__(C())).startswith("<bound method "))
def compattr():
- if verbose: print "Testing computed attributes..."
+ if verbose: print("Testing computed attributes...")
class C(object):
class computed_attribute(object):
def __init__(self, get, set=None, delete=None):
@@ -1477,7 +1469,7 @@
vereq(hasattr(a, 'x'), 0)
def newslot():
- if verbose: print "Testing __new__ slot override..."
+ if verbose: print("Testing __new__ slot override...")
class C(list):
def __new__(cls):
self = list.__new__(cls)
@@ -1495,7 +1487,7 @@
verify(b.__class__ is D)
def altmro():
- if verbose: print "Testing mro() and overriding it..."
+ if verbose: print("Testing mro() and overriding it...")
class A(object):
def f(self): return "A"
class B(A):
@@ -1550,7 +1542,7 @@
def overloading():
- if verbose: print "Testing operator overloading..."
+ if verbose: print("Testing operator overloading...")
class B(object):
"Intermediate class because object doesn't have a __setattr__"
@@ -1600,7 +1592,7 @@
vereq(a.delitem, slice(0, 10, None))
def methods():
- if verbose: print "Testing methods..."
+ if verbose: print("Testing methods...")
class C(object):
def __init__(self, x):
self.x = x
@@ -1622,7 +1614,7 @@
def specials():
# Test operators like __hash__ for which a built-in default exists
- if verbose: print "Testing special operators..."
+ if verbose: print("Testing special operators...")
# Test the default behavior for static classes
class C(object):
def __getitem__(self, i):
@@ -1783,7 +1775,7 @@
sys.stdout = get_original_stdout()
try:
# nothing should actually be printed, this should raise an exception
- print Letter('w')
+ print(Letter('w'))
except RuntimeError:
pass
else:
@@ -1791,7 +1783,7 @@
sys.stdout = test_stdout
def weakrefs():
- if verbose: print "Testing weak references..."
+ if verbose: print("Testing weak references...")
import weakref
class C(object):
pass
@@ -1820,7 +1812,7 @@
del r
def properties():
- if verbose: print "Testing property..."
+ if verbose: print("Testing property...")
class C(object):
def getx(self):
return self.__x
@@ -1903,7 +1895,7 @@
def supers():
- if verbose: print "Testing super..."
+ if verbose: print("Testing super...")
class A(object):
def meth(self, a):
@@ -2019,7 +2011,7 @@
raise TestFailed, "super shouldn't accept keyword args"
def inherits():
- if verbose: print "Testing inheritance from basic types..."
+ if verbose: print("Testing inheritance from basic types...")
class hexint(int):
def __repr__(self):
@@ -2041,7 +2033,7 @@
verify((hexint(0) << 12).__class__ is int)
verify((hexint(0) >> 12).__class__ is int)
- class octlong(long):
+ class octlong(int):
__slots__ = []
def __str__(self):
s = oct(self)
@@ -2056,45 +2048,45 @@
# because the example uses a short int left argument.)
vereq(str(5 + octlong(3000)), "05675")
a = octlong(12345)
- vereq(a, 12345L)
- vereq(long(a), 12345L)
- vereq(hash(a), hash(12345L))
- verify(long(a).__class__ is long)
- verify((+a).__class__ is long)
- verify((-a).__class__ is long)
- verify((-octlong(0)).__class__ is long)
- verify((a >> 0).__class__ is long)
- verify((a << 0).__class__ is long)
- verify((a - 0).__class__ is long)
- verify((a * 1).__class__ is long)
- verify((a ** 1).__class__ is long)
- verify((a // 1).__class__ is long)
- verify((1 * a).__class__ is long)
- verify((a | 0).__class__ is long)
- verify((a ^ 0).__class__ is long)
- verify((a & -1L).__class__ is long)
- verify((octlong(0) << 12).__class__ is long)
- verify((octlong(0) >> 12).__class__ is long)
- verify(abs(octlong(0)).__class__ is long)
+ vereq(a, 12345)
+ vereq(int(a), 12345)
+ vereq(hash(a), hash(12345))
+ verify(int(a).__class__ is int)
+ verify((+a).__class__ is int)
+ verify((-a).__class__ is int)
+ verify((-octlong(0)).__class__ is int)
+ verify((a >> 0).__class__ is int)
+ verify((a << 0).__class__ is int)
+ verify((a - 0).__class__ is int)
+ verify((a * 1).__class__ is int)
+ verify((a ** 1).__class__ is int)
+ verify((a // 1).__class__ is int)
+ verify((1 * a).__class__ is int)
+ verify((a | 0).__class__ is int)
+ verify((a ^ 0).__class__ is int)
+ verify((a & -1).__class__ is int)
+ verify((octlong(0) << 12).__class__ is int)
+ verify((octlong(0) >> 12).__class__ is int)
+ verify(abs(octlong(0)).__class__ is int)
# Because octlong overrides __add__, we can't check the absence of +0
# optimizations using octlong.
- class longclone(long):
+ class longclone(int):
pass
a = longclone(1)
- verify((a + 0).__class__ is long)
- verify((0 + a).__class__ is long)
+ verify((a + 0).__class__ is int)
+ verify((0 + a).__class__ is int)
# Check that negative clones don't segfault
a = longclone(-1)
vereq(a.__dict__, {})
- vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
+ vereq(int(a), -1) # verify PyNumber_Long() copies the sign bit
class precfloat(float):
__slots__ = ['prec']
def __init__(self, value=0.0, prec=12):
self.prec = int(prec)
- float.__init__(value)
+ float.__init__(self, value)
def __repr__(self):
return "%.*g" % (self.prec, self)
vereq(repr(precfloat(1.1)), "1.1")
@@ -2363,10 +2355,10 @@
def keywords():
if verbose:
- print "Testing keyword args to basic type constructors ..."
+ print("Testing keyword args to basic type constructors ...")
vereq(int(x=1), 1)
vereq(float(x=2), 2.0)
- vereq(long(x=3), 3L)
+ vereq(int(x=3), 3)
vereq(complex(imag=42, real=666), complex(666, 42))
vereq(str(object=500), '500')
vereq(unicode(string='abc', errors='strict'), u'abc')
@@ -2374,7 +2366,7 @@
vereq(list(sequence=(0, 1, 2)), range(3))
# note: as of Python 2.3, dict() no longer has an "items" keyword arg
- for constructor in (int, float, long, complex, str, unicode,
+ for constructor in (int, float, int, complex, str, unicode,
tuple, list, file):
try:
constructor(bogus_keyword_arg=1)
@@ -2389,7 +2381,7 @@
return
import rexec
if verbose:
- print "Testing interaction with restricted execution ..."
+ print("Testing interaction with restricted execution ...")
sandbox = rexec.RExec()
@@ -2429,7 +2421,7 @@
def str_subclass_as_dict_key():
if verbose:
- print "Testing a str subclass used as dict key .."
+ print("Testing a str subclass used as dict key ..")
class cistr(str):
"""Sublcass of str that computes __eq__ case-insensitively.
@@ -2461,48 +2453,48 @@
vereq(d.get(cistr('thrEE')), 3)
def classic_comparisons():
- if verbose: print "Testing classic comparisons..."
+ if verbose: print("Testing classic comparisons...")
class classic:
pass
for base in (classic, int, object):
- if verbose: print " (base = %s)" % base
+ if verbose: print(" (base = %s)" % base)
class C(base):
def __init__(self, value):
self.value = int(value)
def __eq__(self, other):
if isinstance(other, C):
return self.value == other.value
- if isinstance(other, int) or isinstance(other, long):
+ if isinstance(other, int) or isinstance(other, int):
return self.value == other
return NotImplemented
def __ne__(self, other):
if isinstance(other, C):
return self.value != other.value
- if isinstance(other, int) or isinstance(other, long):
+ if isinstance(other, int) or isinstance(other, int):
return self.value != other
return NotImplemented
def __lt__(self, other):
if isinstance(other, C):
return self.value < other.value
- if isinstance(other, int) or isinstance(other, long):
+ if isinstance(other, int) or isinstance(other, int):
return self.value < other
return NotImplemented
def __le__(self, other):
if isinstance(other, C):
return self.value <= other.value
- if isinstance(other, int) or isinstance(other, long):
+ if isinstance(other, int) or isinstance(other, int):
return self.value <= other
return NotImplemented
def __gt__(self, other):
if isinstance(other, C):
return self.value > other.value
- if isinstance(other, int) or isinstance(other, long):
+ if isinstance(other, int) or isinstance(other, int):
return self.value > other
return NotImplemented
def __ge__(self, other):
if isinstance(other, C):
return self.value >= other.value
- if isinstance(other, int) or isinstance(other, long):
+ if isinstance(other, int) or isinstance(other, int):
return self.value >= other
return NotImplemented
@@ -2522,7 +2514,7 @@
def rich_comparisons():
if verbose:
- print "Testing rich comparisons..."
+ print("Testing rich comparisons...")
class Z(complex):
pass
z = Z(1)
@@ -2541,7 +2533,7 @@
class classic:
pass
for base in (classic, int, object, list):
- if verbose: print " (base = %s)" % base
+ if verbose: print(" (base = %s)" % base)
class C(base):
def __init__(self, value):
self.value = int(value)
@@ -2550,37 +2542,37 @@
def __eq__(self, other):
if isinstance(other, C):
return self.value == other.value
- if isinstance(other, int) or isinstance(other, long):
+ if isinstance(other, int) or isinstance(other, int):
return self.value == other
return NotImplemented
def __ne__(self, other):
if isinstance(other, C):
return self.value != other.value
- if isinstance(other, int) or isinstance(other, long):
+ if isinstance(other, int) or isinstance(other, int):
return self.value != other
return NotImplemented
def __lt__(self, other):
if isinstance(other, C):
return self.value < other.value
- if isinstance(other, int) or isinstance(other, long):
+ if isinstance(other, int) or isinstance(other, int):
return self.value < other
return NotImplemented
def __le__(self, other):
if isinstance(other, C):
return self.value <= other.value
- if isinstance(other, int) or isinstance(other, long):
+ if isinstance(other, int) or isinstance(other, int):
return self.value <= other
return NotImplemented
def __gt__(self, other):
if isinstance(other, C):
return self.value > other.value
- if isinstance(other, int) or isinstance(other, long):
+ if isinstance(other, int) or isinstance(other, int):
return self.value > other
return NotImplemented
def __ge__(self, other):
if isinstance(other, C):
return self.value >= other.value
- if isinstance(other, int) or isinstance(other, long):
+ if isinstance(other, int) or isinstance(other, int):
return self.value >= other
return NotImplemented
c1 = C(1)
@@ -2599,14 +2591,14 @@
"x=%d, y=%d" % (x, y))
def descrdoc():
- if verbose: print "Testing descriptor doc strings..."
+ if verbose: print("Testing descriptor doc strings...")
def check(descr, what):
vereq(descr.__doc__, what)
check(file.closed, "True if the file is closed") # getset descriptor
check(file.name, "file name") # member descriptor
def setclass():
- if verbose: print "Testing __class__ assignment..."
+ if verbose: print("Testing __class__ assignment...")
class C(object): pass
class D(object): pass
class E(object): pass
@@ -2648,7 +2640,7 @@
del o
def setdict():
- if verbose: print "Testing __dict__ assignment..."
+ if verbose: print("Testing __dict__ assignment...")
class C(object): pass
a = C()
a.__dict__ = {'b': 1}
@@ -2669,7 +2661,7 @@
def pickles():
if verbose:
- print "Testing pickling and copying new-style classes and objects..."
+ print("Testing pickling and copying new-style classes and objects...")
import pickle
try:
import cPickle
@@ -2677,9 +2669,7 @@
cPickle = None
def sorteditems(d):
- L = d.items()
- L.sort()
- return L
+ return sorted(d.items())
global C
class C(object):
@@ -2734,7 +2724,7 @@
continue # cPickle not found -- skip it
for bin in 0, 1:
if verbose:
- print p.__name__, ["text", "binary"][bin]
+ print(p.__name__, ["text", "binary"][bin])
for cls in C, C1, C2:
s = p.dumps(cls, bin)
@@ -2752,8 +2742,8 @@
vereq(repr(x), repr(a))
vereq(repr(y), repr(b))
if verbose:
- print "a = x =", a
- print "b = y =", b
+ print("a = x =", a)
+ print("b = y =", b)
# Test for __getstate__ and __setstate__ on new style class
u = C3(42)
s = p.dumps(u, bin)
@@ -2770,7 +2760,7 @@
# Testing copy.deepcopy()
if verbose:
- print "deepcopy"
+ print("deepcopy")
import copy
for cls in C, C1, C2:
cls2 = copy.deepcopy(cls)
@@ -2786,11 +2776,11 @@
vereq(repr(x), repr(a))
vereq(repr(y), repr(b))
if verbose:
- print "a = x =", a
- print "b = y =", b
+ print("a = x =", a)
+ print("b = y =", b)
def pickleslots():
- if verbose: print "Testing pickling of classes with __slots__ ..."
+ if verbose: print("Testing pickling of classes with __slots__ ...")
import pickle, pickle as cPickle
# Pickling of classes with __slots__ but without __getstate__ should fail
global B, C, D, E
@@ -2877,7 +2867,7 @@
vereq(y.b, x.b)
def copies():
- if verbose: print "Testing copy.copy() and copy.deepcopy()..."
+ if verbose: print("Testing copy.copy() and copy.deepcopy()...")
import copy
class C(object):
pass
@@ -2898,7 +2888,7 @@
vereq(d.bar, [1,2,3])
def binopoverride():
- if verbose: print "Testing overrides of binary operations..."
+ if verbose: print("Testing overrides of binary operations...")
class I(int):
def __repr__(self):
return "I(%r)" % int(self)
@@ -2928,7 +2918,7 @@
return self.lower() == other.lower()
def subclasspropagation():
- if verbose: print "Testing propagation of slot functions to subclasses..."
+ if verbose: print("Testing propagation of slot functions to subclasses...")
class A(object):
pass
class B(A):
@@ -3001,7 +2991,7 @@
import binascii
# SF bug [#470040] ParseTuple t# vs subclasses.
if verbose:
- print "Testing that buffer interface is inherited ..."
+ print("Testing that buffer interface is inherited ...")
class MyStr(str):
pass
@@ -3033,7 +3023,7 @@
import cStringIO
if verbose:
- print "Testing __str__ defined in subclass of str ..."
+ print("Testing __str__ defined in subclass of str ...")
class octetstring(str):
def __str__(self):
@@ -3053,13 +3043,13 @@
capture = cStringIO.StringIO()
# Calling str() or not exercises different internal paths.
- print >> capture, o
- print >> capture, str(o)
+ print(o, file=capture)
+ print(str(o), file=capture)
vereq(capture.getvalue(), '41\n41\n')
capture.close()
def kwdargs():
- if verbose: print "Testing keyword arguments to __init__, __call__..."
+ if verbose: print("Testing keyword arguments to __init__, __call__...")
def f(a): return a
vereq(f.__call__(a=42), 42)
a = []
@@ -3067,8 +3057,8 @@
vereq(a, [0, 1, 2])
def recursive__call__():
- if verbose: print ("Testing recursive __call__() by setting to instance of "
- "class ...")
+ if verbose: print(("Testing recursive __call__() by setting to instance of "
+ "class ..."))
class A(object):
pass
@@ -3082,7 +3072,7 @@
"__call__()")
def delhook():
- if verbose: print "Testing __del__ hook..."
+ if verbose: print("Testing __del__ hook...")
log = []
class C(object):
def __del__(self):
@@ -3099,7 +3089,7 @@
else: raise TestFailed, "invalid del() didn't raise TypeError"
def hashinherit():
- if verbose: print "Testing hash of mutable subclasses..."
+ if verbose: print("Testing hash of mutable subclasses...")
class mydict(dict):
pass
@@ -3168,7 +3158,7 @@
vereq('%c' % '5', '5')
def deepcopyrecursive():
- if verbose: print "Testing deepcopy of recursive objects..."
+ if verbose: print("Testing deepcopy of recursive objects...")
class Node:
pass
a = Node()
@@ -3178,7 +3168,7 @@
z = deepcopy(a) # This blew up before
def modules():
- if verbose: print "Testing uninitialized module objects..."
+ if verbose: print("Testing uninitialized module objects...")
from types import ModuleType as M
m = M.__new__(M)
str(m)
@@ -3193,8 +3183,8 @@
class C(object):
def meth(self):
pass
- if verbose: print "Testing dict-proxy iterkeys..."
- keys = [ key for key in C.__dict__.iterkeys() ]
+ if verbose: print("Testing dict-proxy iterkeys...")
+ keys = [ key for key in C.__dict__.keys() ]
keys.sort()
vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
@@ -3202,21 +3192,21 @@
class C(object):
def meth(self):
pass
- if verbose: print "Testing dict-proxy itervalues..."
- values = [ values for values in C.__dict__.itervalues() ]
+ if verbose: print("Testing dict-proxy itervalues...")
+ values = [ values for values in C.__dict__.values() ]
vereq(len(values), 5)
def dictproxyiteritems():
class C(object):
def meth(self):
pass
- if verbose: print "Testing dict-proxy iteritems..."
- keys = [ key for (key, value) in C.__dict__.iteritems() ]
+ if verbose: print("Testing dict-proxy iteritems...")
+ keys = [ key for (key, value) in C.__dict__.items() ]
keys.sort()
vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
def funnynew():
- if verbose: print "Testing __new__ returning something unexpected..."
+ if verbose: print("Testing __new__ returning something unexpected...")
class C(object):
def __new__(cls, arg):
if isinstance(arg, str): return [1, 2, 3]
@@ -3238,7 +3228,7 @@
def imulbug():
# SF bug 544647
- if verbose: print "Testing for __imul__ problems..."
+ if verbose: print("Testing for __imul__ problems...")
class C(object):
def __imul__(self, other):
return (self, other)
@@ -3250,11 +3240,11 @@
y *= 2
vereq(y, (x, 2))
y = x
- y *= 3L
- vereq(y, (x, 3L))
+ y *= 3
+ vereq(y, (x, 3))
y = x
- y *= 1L<<100
- vereq(y, (x, 1L<<100))
+ y *= 1<<100
+ vereq(y, (x, 1<<100))
y = x
y *= None
vereq(y, (x, None))
@@ -3264,7 +3254,7 @@
def docdescriptor():
# SF bug 542984
- if verbose: print "Testing __doc__ descriptor..."
+ if verbose: print("Testing __doc__ descriptor...")
class DocDescr(object):
def __get__(self, object, otype):
if object:
@@ -3283,7 +3273,7 @@
def copy_setstate():
if verbose:
- print "Testing that copy.*copy() correctly uses __setstate__..."
+ print("Testing that copy.*copy() correctly uses __setstate__...")
import copy
class C(object):
def __init__(self, foo=None):
@@ -3311,7 +3301,7 @@
def slices():
if verbose:
- print "Testing cases with slices and overridden __getitem__ ..."
+ print("Testing cases with slices and overridden __getitem__ ...")
# Strings
vereq("hello"[:4], "hell")
vereq("hello"[slice(4)], "hell")
@@ -3355,7 +3345,7 @@
def subtype_resurrection():
if verbose:
- print "Testing resurrection of new-style instance..."
+ print("Testing resurrection of new-style instance...")
class C(object):
container = []
@@ -3385,7 +3375,7 @@
def slottrash():
# Deallocating deeply nested slotted trash caused stack overflows
if verbose:
- print "Testing slot trash..."
+ print("Testing slot trash...")
class trash(object):
__slots__ = ['x']
def __init__(self, x):
@@ -3411,7 +3401,7 @@
def testrmul():
# SF patch 592646
if verbose:
- print "Testing correct invocation of __rmul__..."
+ print("Testing correct invocation of __rmul__...")
class C(object):
def __mul__(self, other):
return "mul"
@@ -3426,7 +3416,7 @@
def testipow():
# [SF bug 620179]
if verbose:
- print "Testing correct invocation of __ipow__..."
+ print("Testing correct invocation of __ipow__...")
class C(object):
def __ipow__(self, other):
pass
@@ -3435,7 +3425,7 @@
def do_this_first():
if verbose:
- print "Testing SF bug 551412 ..."
+ print("Testing SF bug 551412 ...")
# This dumps core when SF bug 551412 isn't fixed --
# but only when test_descr.py is run separately.
# (That can't be helped -- as soon as PyType_Ready()
@@ -3444,19 +3434,19 @@
def __pow__(self, *args):
pass
try:
- pow(0L, UserLong(), 0L)
+ pow(0, UserLong(), 0)
except:
pass
if verbose:
- print "Testing SF bug 570483..."
+ print("Testing SF bug 570483...")
# Another segfault only when run early
# (before PyType_Ready(tuple) is called)
type.mro(tuple)
def test_mutable_bases():
if verbose:
- print "Testing mutable bases..."
+ print("Testing mutable bases...")
# stuff that should work:
class C(object):
pass
@@ -3546,7 +3536,7 @@
def test_mutable_bases_with_failing_mro():
if verbose:
- print "Testing mutable bases with failing mro..."
+ print("Testing mutable bases with failing mro...")
class WorkOnce(type):
def __new__(self, name, bases, ns):
self.flag = 0
@@ -3601,7 +3591,7 @@
def test_mutable_bases_catch_mro_conflict():
if verbose:
- print "Testing mutable bases catch mro conflict..."
+ print("Testing mutable bases catch mro conflict...")
class A(object):
pass
@@ -3626,7 +3616,7 @@
def mutable_names():
if verbose:
- print "Testing mutable names..."
+ print("Testing mutable names...")
class C(object):
pass
@@ -3641,7 +3631,7 @@
def subclass_right_op():
if verbose:
- print "Testing correct dispatch of subclass overloading __r<op>__..."
+ print("Testing correct dispatch of subclass overloading __r<op>__...")
# This code tests various cases where right-dispatch of a subclass
# should be preferred over left-dispatch of a base class.
@@ -3693,7 +3683,7 @@
def dict_type_with_metaclass():
if verbose:
- print "Testing type of __dict__ when __metaclass__ set..."
+ print("Testing type of __dict__ when __metaclass__ set...")
class B(object):
pass
@@ -3707,7 +3697,7 @@
def meth_class_get():
# Full coverage of descrobject.c::classmethod_get()
if verbose:
- print "Testing __get__ method of METH_CLASS C methods..."
+ print("Testing __get__ method of METH_CLASS C methods...")
# Baseline
arg = [1, 2, 3]
res = {1: None, 2: None, 3: None}
@@ -3746,7 +3736,7 @@
def isinst_isclass():
if verbose:
- print "Testing proxy isinstance() and isclass()..."
+ print("Testing proxy isinstance() and isclass()...")
class Proxy(object):
def __init__(self, obj):
self.__obj = obj
@@ -3786,7 +3776,7 @@
def proxysuper():
if verbose:
- print "Testing super() for a proxy object..."
+ print("Testing super() for a proxy object...")
class Proxy(object):
def __init__(self, obj):
self.__obj = obj
@@ -3810,7 +3800,7 @@
def carloverre():
if verbose:
- print "Testing prohibition of Carlo Verre's hack..."
+ print("Testing prohibition of Carlo Verre's hack...")
try:
object.__setattr__(str, "foo", 42)
except TypeError:
@@ -3827,7 +3817,7 @@
def weakref_segfault():
# SF 742911
if verbose:
- print "Testing weakref segfault..."
+ print("Testing weakref segfault...")
import weakref
@@ -3855,7 +3845,7 @@
# Fix SF #762455, segfault when sys.stdout is changed in getattr
def filefault():
if verbose:
- print "Testing sys.stdout is changed in getattr..."
+ print("Testing sys.stdout is changed in getattr...")
import sys
class StdoutGuard:
def __getattr__(self, attr):
@@ -3863,7 +3853,7 @@
raise RuntimeError("Premature access to sys.stdout.%s" % attr)
sys.stdout = StdoutGuard()
try:
- print "Oops!"
+ print("Oops!")
except RuntimeError:
pass
@@ -3872,7 +3862,7 @@
# python-dev 2003-04-17, turned into an example & fixed by Michael
# Hudson just less than four months later...
if verbose:
- print "Testing vicious_descriptor_nonsense..."
+ print("Testing vicious_descriptor_nonsense...")
class Evil(object):
def __hash__(self):
@@ -3911,7 +3901,7 @@
def methodwrapper():
# <type 'method-wrapper'> did not support any reflection before 2.5
if verbose:
- print "Testing method-wrapper objects..."
+ print("Testing method-wrapper objects...")
return # XXX should methods really support __eq__?
@@ -3939,7 +3929,7 @@
def notimplemented():
# all binary methods should be able to return a NotImplemented
if verbose:
- print "Testing NotImplemented..."
+ print("Testing NotImplemented...")
import sys
import types
@@ -3956,7 +3946,7 @@
else:
raise TestFailed("no TypeError from %r" % (expr,))
- N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
+ N1 = sys.maxint + 1 # might trigger OverflowErrors instead of TypeErrors
N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
# ValueErrors instead of TypeErrors
for metaclass in [type, types.ClassType]:
@@ -4099,7 +4089,7 @@
methodwrapper()
notimplemented()
- if verbose: print "All OK"
+ if verbose: print("All OK")
if __name__ == "__main__":
test_main()
Modified: python/branches/p3yk-noslice/Lib/test/test_descrtut.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_descrtut.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_descrtut.py Fri Feb 23 18:29:35 2007
@@ -36,28 +36,28 @@
Here's the new type at work:
- >>> print defaultdict # show our type
+ >>> print(defaultdict) # show our type
<class 'test.test_descrtut.defaultdict'>
- >>> print type(defaultdict) # its metatype
+ >>> print(type(defaultdict)) # its metatype
<type 'type'>
>>> a = defaultdict(default=0.0) # create an instance
- >>> print a # show the instance
+ >>> print(a) # show the instance
{}
- >>> print type(a) # show its type
+ >>> print(type(a)) # show its type
<class 'test.test_descrtut.defaultdict'>
- >>> print a.__class__ # show its class
+ >>> print(a.__class__) # show its class
<class 'test.test_descrtut.defaultdict'>
- >>> print type(a) is a.__class__ # its type is its class
+ >>> print(type(a) is a.__class__) # its type is its class
True
>>> a[1] = 3.25 # modify the instance
- >>> print a # show the new value
+ >>> print(a) # show the new value
{1: 3.25}
- >>> print a[1] # show the new item
+ >>> print(a[1]) # show the new item
3.25
- >>> print a[0] # a non-existant item
+ >>> print(a[0]) # a non-existant item
0.0
>>> a.merge({1:100, 2:200}) # use a dict method
- >>> print sortdict(a) # show the result
+ >>> print(sortdict(a)) # show the result
{1: 3.25, 2: 200}
>>>
@@ -65,13 +65,14 @@
dictionaries, such as the locals/globals dictionaries for the exec
statement or the built-in function eval():
- >>> print sorted(a.keys())
+ >>> print(sorted(a.keys()))
[1, 2]
- >>> exec("x = 3; print x", a)
+ >>> a['print'] = print # need the print function here
+ >>> exec("x = 3; print(x)", a)
3
- >>> print sorted(a.keys(), key=lambda x: (str(type(x)), x))
- [1, 2, '__builtins__', 'x']
- >>> print a['x']
+ >>> print(sorted(a.keys(), key=lambda x: (str(type(x)), x)))
+ [1, 2, '__builtins__', 'print', 'x']
+ >>> print(a['x'])
3
>>>
@@ -79,21 +80,21 @@
just like classic classes:
>>> a.default = -1
- >>> print a["noway"]
+ >>> print(a["noway"])
-1
>>> a.default = -1000
- >>> print a["noway"]
+ >>> print(a["noway"])
-1000
>>> 'default' in dir(a)
True
>>> a.x1 = 100
>>> a.x2 = 200
- >>> print a.x1
+ >>> print(a.x1)
100
>>> d = dir(a)
>>> 'default' in d and 'x1' in d and 'x2' in d
True
- >>> print sortdict(a.__dict__)
+ >>> print(sortdict(a.__dict__))
{'default': -1000, 'x1': 100, 'x2': 200}
>>>
"""
@@ -239,10 +240,10 @@
static methods in C++ or Java. Here's an example:
>>> class C:
- ...
+ ...
... @staticmethod
... def foo(x, y):
- ... print "staticmethod", x, y
+ ... print("staticmethod", x, y)
>>> C.foo(1, 2)
staticmethod 1 2
@@ -256,7 +257,7 @@
>>> class C:
... @classmethod
... def foo(cls, y):
- ... print "classmethod", cls, y
+ ... print("classmethod", cls, y)
>>> C.foo(1)
classmethod <class 'test.test_descrtut.C'> 1
@@ -282,7 +283,7 @@
>>> class E(C):
... @classmethod
... def foo(cls, y): # override C.foo
- ... print "E.foo() called"
+ ... print("E.foo() called")
... C.foo(y)
>>> E.foo(1)
@@ -340,10 +341,10 @@
>>> a = C()
>>> a.x = 10
- >>> print a.x
+ >>> print(a.x)
10
>>> a.x = -10
- >>> print a.x
+ >>> print(a.x)
0
>>>
@@ -366,10 +367,10 @@
>>> a = C()
>>> a.x = 10
- >>> print a.x
+ >>> print(a.x)
10
>>> a.x = -10
- >>> print a.x
+ >>> print(a.x)
0
>>>
"""
@@ -382,12 +383,12 @@
>>> class A: # implicit new-style class
... def save(self):
-... print "called A.save()"
+... print("called A.save()")
>>> class B(A):
... pass
>>> class C(A):
... def save(self):
-... print "called C.save()"
+... print("called C.save()")
>>> class D(B, C):
... pass
@@ -396,12 +397,12 @@
>>> class A(object): # explicit new-style class
... def save(self):
-... print "called A.save()"
+... print("called A.save()")
>>> class B(A):
... pass
>>> class C(A):
... def save(self):
-... print "called C.save()"
+... print("called C.save()")
>>> class D(B, C):
... pass
@@ -430,7 +431,7 @@
Cooperative methods and "super"
->>> print D().m() # "DCBA"
+>>> print(D().m()) # "DCBA"
DCBA
"""
@@ -440,7 +441,7 @@
>>> class A:
... def foo(self):
-... print "called A.foo()"
+... print("called A.foo()")
>>> class B(A):
... pass
Modified: python/branches/p3yk-noslice/Lib/test/test_dict.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_dict.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_dict.py Fri Feb 23 18:29:35 2007
@@ -19,7 +19,7 @@
def test_keys(self):
d = {}
- self.assertEqual(d.keys(), [])
+ self.assertEqual(set(d.keys()), set())
d = {'a': 1, 'b': 2}
k = d.keys()
self.assert_('a' in d)
@@ -29,18 +29,18 @@
def test_values(self):
d = {}
- self.assertEqual(d.values(), [])
+ self.assertEqual(set(d.values()), set())
d = {1:2}
- self.assertEqual(d.values(), [2])
+ self.assertEqual(set(d.values()), {2})
self.assertRaises(TypeError, d.values, None)
def test_items(self):
d = {}
- self.assertEqual(d.items(), [])
+ self.assertEqual(set(d.items()), set())
d = {1:2}
- self.assertEqual(d.items(), [(1, 2)])
+ self.assertEqual(set(d.items()), {(1, 2)})
self.assertRaises(TypeError, d.items, None)
@@ -182,6 +182,14 @@
self.assertRaises(ValueError, {}.update, [(1, 2, 3)])
+ # SF #1615701: make d.update(m) honor __getitem__() and keys() in dict subclasses
+ class KeyUpperDict(dict):
+ def __getitem__(self, key):
+ return key.upper()
+ d.clear()
+ d.update(KeyUpperDict.fromkeys('abc'))
+ self.assertEqual(d, {'a':'A', 'b':'B', 'c':'C'})
+
def test_fromkeys(self):
self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
d = {}
@@ -314,7 +322,7 @@
# verify longs/ints get same value when key > 32 bits (for 64-bit archs)
# see SF bug #689659
- x = 4503599627370496L
+ x = 4503599627370496
y = 4503599627370496
h = {x: 'anything', y: 'something else'}
self.assertEqual(h[x], h[y])
@@ -371,7 +379,7 @@
def test_eq(self):
self.assertEqual({}, {})
- self.assertEqual({1: 2}, {1L: 2L})
+ self.assertEqual({1: 2}, {1: 2})
class Exc(Exception): pass
Modified: python/branches/p3yk-noslice/Lib/test/test_dis.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_dis.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_dis.py Fri Feb 23 18:29:35 2007
@@ -8,16 +8,17 @@
import unittest
def _f(a):
- print a
+ print(a)
return 1
dis_f = """\
- %-4d 0 LOAD_FAST 0 (a)
- 3 PRINT_ITEM
- 4 PRINT_NEWLINE
+ %-4d 0 LOAD_GLOBAL 0 (print)
+ 3 LOAD_FAST 0 (a)
+ 6 CALL_FUNCTION 1
+ 9 POP_TOP
- %-4d 5 LOAD_CONST 1 (1)
- 8 RETURN_VALUE
+ %-4d 10 LOAD_CONST 1 (1)
+ 13 RETURN_VALUE
"""%(_f.func_code.co_firstlineno + 1,
_f.func_code.co_firstlineno + 2)
Modified: python/branches/p3yk-noslice/Lib/test/test_dl.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_dl.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_dl.py Fri Feb 23 18:29:35 2007
@@ -16,19 +16,19 @@
for s, func in sharedlibs:
try:
if verbose:
- print 'trying to open:', s,
+ print('trying to open:', s, end=' ')
l = dl.open(s)
except dl.error as err:
if verbose:
- print 'failed', repr(str(err))
+ print('failed', repr(str(err)))
pass
else:
if verbose:
- print 'succeeded...',
+ print('succeeded...', end=' ')
l.call(func)
l.close()
if verbose:
- print 'worked!'
+ print('worked!')
break
else:
raise TestSkipped, 'Could not open any shared libraries'
Modified: python/branches/p3yk-noslice/Lib/test/test_doctest.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_doctest.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_doctest.py Fri Feb 23 18:29:35 2007
@@ -14,7 +14,7 @@
"""
Blah blah
- >>> print sample_func(22)
+ >>> print(sample_func(22))
44
Yee ha!
@@ -23,7 +23,7 @@
class SampleClass:
"""
- >>> print 1
+ >>> print(1)
1
>>> # comments get ignored. so are empty PS1 and PS2 prompts:
@@ -34,33 +34,33 @@
>>> sc = SampleClass(3)
>>> for i in range(10):
... sc = sc.double()
- ... print sc.get(),
- 6 12 24 48 96 192 384 768 1536 3072
+ ... print(sc.get(), end=' ')
+ 6 12 24 48 96 192 384 768 1536 3072
"""
def __init__(self, val):
"""
- >>> print SampleClass(12).get()
+ >>> print(SampleClass(12).get())
12
"""
self.val = val
def double(self):
"""
- >>> print SampleClass(12).double().get()
+ >>> print(SampleClass(12).double().get())
24
"""
return SampleClass(self.val + self.val)
def get(self):
"""
- >>> print SampleClass(-5).get()
+ >>> print(SampleClass(-5).get())
-5
"""
return self.val
def a_staticmethod(v):
"""
- >>> print SampleClass.a_staticmethod(10)
+ >>> print(SampleClass.a_staticmethod(10))
11
"""
return v+1
@@ -68,16 +68,16 @@
def a_classmethod(cls, v):
"""
- >>> print SampleClass.a_classmethod(10)
+ >>> print(SampleClass.a_classmethod(10))
12
- >>> print SampleClass(0).a_classmethod(10)
+ >>> print(SampleClass(0).a_classmethod(10))
12
"""
return v+2
a_classmethod = classmethod(a_classmethod)
a_property = property(get, doc="""
- >>> print SampleClass(22).a_property
+ >>> print(SampleClass(22).a_property)
22
""")
@@ -85,12 +85,12 @@
"""
>>> x = SampleClass.NestedClass(5)
>>> y = x.square()
- >>> print y.get()
+ >>> print(y.get())
25
"""
def __init__(self, val=0):
"""
- >>> print SampleClass.NestedClass().get()
+ >>> print(SampleClass.NestedClass().get())
0
"""
self.val = val
@@ -101,28 +101,28 @@
class SampleNewStyleClass(object):
r"""
- >>> print '1\n2\n3'
+ >>> print('1\n2\n3')
1
2
3
"""
def __init__(self, val):
"""
- >>> print SampleNewStyleClass(12).get()
+ >>> print(SampleNewStyleClass(12).get())
12
"""
self.val = val
def double(self):
"""
- >>> print SampleNewStyleClass(12).double().get()
+ >>> print(SampleNewStyleClass(12).double().get())
24
"""
return SampleNewStyleClass(self.val + self.val)
def get(self):
"""
- >>> print SampleNewStyleClass(-5).get()
+ >>> print(SampleNewStyleClass(-5).get())
-5
"""
return self.val
@@ -143,7 +143,7 @@
def readline(self):
line = self.lines.pop(0)
- print line
+ print(line)
return line+'\n'
######################################################################
@@ -166,10 +166,10 @@
These attributes are set by the constructor. `source` and `want` are
required; the other attributes all have default values:
- >>> example = doctest.Example('print 1', '1\n')
+ >>> example = doctest.Example('print(1)', '1\n')
>>> (example.source, example.want, example.exc_msg,
... example.lineno, example.indent, example.options)
- ('print 1\n', '1\n', None, 0, 0, {})
+ ('print(1)\n', '1\n', None, 0, 0, {})
The first three attributes (`source`, `want`, and `exc_msg`) may be
specified positionally; the remaining arguments should be specified as
@@ -186,22 +186,22 @@
The constructor normalizes the `source` string to end in a newline:
Source spans a single line: no terminating newline.
- >>> e = doctest.Example('print 1', '1\n')
+ >>> e = doctest.Example('print(1)', '1\n')
>>> e.source, e.want
- ('print 1\n', '1\n')
+ ('print(1)\n', '1\n')
- >>> e = doctest.Example('print 1\n', '1\n')
+ >>> e = doctest.Example('print(1)\n', '1\n')
>>> e.source, e.want
- ('print 1\n', '1\n')
+ ('print(1)\n', '1\n')
Source spans multiple lines: require terminating newline.
- >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
+ >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
>>> e.source, e.want
- ('print 1;\nprint 2\n', '1\n2\n')
+ ('print(1);\nprint(2)\n', '1\n2\n')
- >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
+ >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
>>> e.source, e.want
- ('print 1;\nprint 2\n', '1\n2\n')
+ ('print(1);\nprint(2)\n', '1\n2\n')
Empty source string (which should never appear in real examples)
>>> e = doctest.Example('', '')
@@ -211,13 +211,13 @@
The constructor normalizes the `want` string to end in a newline,
unless it's the empty string:
- >>> e = doctest.Example('print 1', '1\n')
+ >>> e = doctest.Example('print(1)', '1\n')
>>> e.source, e.want
- ('print 1\n', '1\n')
+ ('print(1)\n', '1\n')
- >>> e = doctest.Example('print 1', '1')
+ >>> e = doctest.Example('print(1)', '1')
>>> e.source, e.want
- ('print 1\n', '1\n')
+ ('print(1)\n', '1\n')
>>> e = doctest.Example('print', '')
>>> e.source, e.want
@@ -265,12 +265,12 @@
constructor:
>>> docstring = '''
- ... >>> print 12
+ ... >>> print(12)
... 12
...
... Non-example text.
...
- ... >>> print 'another\example'
+ ... >>> print('another\example')
... another
... example
... '''
@@ -278,15 +278,15 @@
>>> parser = doctest.DocTestParser()
>>> test = parser.get_doctest(docstring, globs, 'some_test',
... 'some_file', 20)
- >>> print test
+ >>> print(test)
<DocTest some_test from some_file:20 (2 examples)>
>>> len(test.examples)
2
>>> e1, e2 = test.examples
>>> (e1.source, e1.want, e1.lineno)
- ('print 12\n', '12\n', 1)
+ ('print(12)\n', '12\n', 1)
>>> (e2.source, e2.want, e2.lineno)
- ("print 'another\\example'\n", 'another\nexample\n', 6)
+ ("print('another\\example')\n", 'another\nexample\n', 6)
Source information (name, filename, and line number) is available as
attributes on the doctest object:
@@ -307,7 +307,7 @@
expected output of an example, then `DocTest` will raise a ValueError:
>>> docstring = r'''
- ... >>> print 'bad\nindentation'
+ ... >>> print('bad\nindentation')
... bad
... indentation
... '''
@@ -319,29 +319,29 @@
continuation lines, then `DocTest` will raise a ValueError:
>>> docstring = r'''
- ... >>> print ('bad indentation',
- ... ... 2)
+ ... >>> print(('bad indentation',
+ ... ... 2))
... ('bad', 'indentation')
... '''
>>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Traceback (most recent call last):
- ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2)'
+ ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '... 2))'
If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
will raise a ValueError:
- >>> docstring = '>>>print 1\n1'
+ >>> docstring = '>>>print(1)\n1'
>>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Traceback (most recent call last):
- ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
+ ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
If there's no blank space after a PS2 prompt ('...'), then `DocTest`
will raise a ValueError:
- >>> docstring = '>>> if 1:\n...print 1\n1'
+ >>> docstring = '>>> if 1:\n...print(1)\n1'
>>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
Traceback (most recent call last):
- ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
+ ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
"""
@@ -368,7 +368,7 @@
>>> tests = finder.find(sample_func)
- >>> print tests # doctest: +ELLIPSIS
+ >>> print(tests) # doctest: +ELLIPSIS
[<DocTest sample_func from ...:13 (1 example)>]
The exact name depends on how test_doctest was invoked, so allow for
@@ -382,7 +382,7 @@
>>> e = tests[0].examples[0]
>>> (e.source, e.want, e.lineno)
- ('print sample_func(22)\n', '44\n', 3)
+ ('print(sample_func(22))\n', '44\n', 3)
By default, tests are created for objects with no docstring:
@@ -420,7 +420,7 @@
>>> finder = doctest.DocTestFinder()
>>> tests = finder.find(SampleClass)
>>> for t in tests:
- ... print '%2s %s' % (len(t.examples), t.name)
+ ... print('%2s %s' % (len(t.examples), t.name))
3 SampleClass
3 SampleClass.NestedClass
1 SampleClass.NestedClass.__init__
@@ -435,7 +435,7 @@
>>> tests = finder.find(SampleNewStyleClass)
>>> for t in tests:
- ... print '%2s %s' % (len(t.examples), t.name)
+ ... print('%2s %s' % (len(t.examples), t.name))
1 SampleNewStyleClass
1 SampleNewStyleClass.__init__
1 SampleNewStyleClass.double
@@ -452,7 +452,7 @@
>>> m = new.module('some_module')
>>> def triple(val):
... '''
- ... >>> print triple(11)
+ ... >>> print(triple(11))
... 33
... '''
... return val*3
@@ -461,11 +461,11 @@
... 'SampleClass': SampleClass,
... '__doc__': '''
... Module docstring.
- ... >>> print 'module'
+ ... >>> print('module')
... module
... ''',
... '__test__': {
- ... 'd': '>>> print 6\n6\n>>> print 7\n7\n',
+ ... 'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
... 'c': triple}})
>>> finder = doctest.DocTestFinder()
@@ -474,7 +474,7 @@
>>> import test.test_doctest
>>> tests = finder.find(m, module=test.test_doctest)
>>> for t in tests:
- ... print '%2s %s' % (len(t.examples), t.name)
+ ... print('%2s %s' % (len(t.examples), t.name))
1 some_module
3 some_module.SampleClass
3 some_module.SampleClass.NestedClass
@@ -496,9 +496,9 @@
>>> from test import doctest_aliases
>>> tests = excl_empty_finder.find(doctest_aliases)
- >>> print len(tests)
+ >>> print(len(tests))
2
- >>> print tests[0].name
+ >>> print(tests[0].name)
test.doctest_aliases.TwoNames
TwoNames.f and TwoNames.g are bound to the same object.
@@ -514,7 +514,7 @@
>>> tests = doctest.DocTestFinder().find(SampleClass)
>>> for t in tests:
- ... print '%2s %s' % (len(t.examples), t.name)
+ ... print('%2s %s' % (len(t.examples), t.name))
3 SampleClass
3 SampleClass.NestedClass
1 SampleClass.NestedClass.__init__
@@ -532,7 +532,7 @@
>>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
>>> for t in tests:
- ... print '%2s %s' % (len(t.examples), t.name)
+ ... print('%2s %s' % (len(t.examples), t.name))
3 SampleClass
3 SampleClass.NestedClass
1 SampleClass.NestedClass.__init__
@@ -552,7 +552,7 @@
>>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
>>> for t in tests:
- ... print '%2s %s' % (len(t.examples), t.name)
+ ... print('%2s %s' % (len(t.examples), t.name))
3 SampleClass
Line numbers
@@ -570,8 +570,8 @@
... ...
...
... >>> for x in range(10):
- ... ... print x,
- ... 0 1 2 3 4 5 6 7 8 9
+ ... ... print(x, end=' ')
+ ... 0 1 2 3 4 5 6 7 8 9
... >>> x//2
... 6
... '''
@@ -591,8 +591,8 @@
>>> s = '''
... >>> x, y = 2, 3 # no output expected
... >>> if 1:
- ... ... print x
- ... ... print y
+ ... ... print(x)
+ ... ... print(y)
... 2
... 3
...
@@ -603,13 +603,13 @@
>>> parser = doctest.DocTestParser()
>>> for piece in parser.parse(s):
... if isinstance(piece, doctest.Example):
- ... print 'Example:', (piece.source, piece.want, piece.lineno)
+ ... print('Example:', (piece.source, piece.want, piece.lineno))
... else:
- ... print ' Text:', repr(piece)
+ ... print(' Text:', repr(piece))
Text: '\n'
Example: ('x, y = 2, 3 # no output expected\n', '', 1)
Text: ''
- Example: ('if 1:\n print x\n print y\n', '2\n3\n', 2)
+ Example: ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
Text: '\nSome text.\n'
Example: ('x+y\n', '5\n', 9)
Text: ''
@@ -617,9 +617,9 @@
The `get_examples` method returns just the examples:
>>> for piece in parser.get_examples(s):
- ... print (piece.source, piece.want, piece.lineno)
+ ... print((piece.source, piece.want, piece.lineno))
('x, y = 2, 3 # no output expected\n', '', 1)
- ('if 1:\n print x\n print y\n', '2\n3\n', 2)
+ ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
('x+y\n', '5\n', 9)
The `get_doctest` method creates a Test from the examples, along with the
@@ -629,9 +629,9 @@
>>> (test.name, test.filename, test.lineno)
('name', 'filename', 5)
>>> for piece in test.examples:
- ... print (piece.source, piece.want, piece.lineno)
+ ... print((piece.source, piece.want, piece.lineno))
('x, y = 2, 3 # no output expected\n', '', 1)
- ('if 1:\n print x\n print y\n', '2\n3\n', 2)
+ ('if 1:\n print(x)\n print(y)\n', '2\n3\n', 2)
('x+y\n', '5\n', 9)
"""
@@ -645,7 +645,7 @@
>>> def f(x):
... '''
... >>> x = 12
- ... >>> print x
+ ... >>> print(x)
... 12
... >>> x//2
... 6
@@ -666,7 +666,7 @@
>>> def f(x):
... '''
... >>> x = 12
- ... >>> print x
+ ... >>> print(x)
... 14
... >>> x//2
... 6
@@ -679,13 +679,13 @@
Expecting nothing
ok
Trying:
- print x
+ print(x)
Expecting:
14
**********************************************************************
File ..., line 4, in f
Failed example:
- print x
+ print(x)
Expected:
14
Got:
@@ -704,7 +704,7 @@
>>> def f(x):
... '''
... >>> x = 12
- ... >>> print x
+ ... >>> print(x)
... 12
... >>> x//2
... 6
@@ -717,7 +717,7 @@
Expecting nothing
ok
Trying:
- print x
+ print(x)
Expecting:
12
ok
@@ -747,7 +747,7 @@
Expecting nothing
ok
Trying:
- print x
+ print(x)
Expecting:
12
ok
@@ -774,7 +774,7 @@
>>> def f(x):
... '''
... >>> x = 12
- ... >>> print x//0
+ ... >>> print(x//0)
... Traceback (most recent call last):
... ZeroDivisionError: integer division or modulo by zero
... '''
@@ -790,7 +790,7 @@
>>> def f(x):
... '''
... >>> x = 12
- ... >>> print 'pre-exception output', x//0
+ ... >>> print('pre-exception output', x//0)
... pre-exception output
... Traceback (most recent call last):
... ZeroDivisionError: integer division or modulo by zero
@@ -801,7 +801,7 @@
**********************************************************************
File ..., line 4, in f
Failed example:
- print 'pre-exception output', x//0
+ print('pre-exception output', x//0)
Exception raised:
...
ZeroDivisionError: integer division or modulo by zero
@@ -942,7 +942,7 @@
and the '<BLANKLINE>' marker:
>>> def f(x):
- ... '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
+ ... '>>> print("a\\n\\nb")\na\n<BLANKLINE>\nb\n'
>>> # Without the flag:
>>> test = doctest.DocTestFinder().find(f)[0]
@@ -957,7 +957,7 @@
**********************************************************************
File ..., line 2, in f
Failed example:
- print "a\n\nb"
+ print("a\n\nb")
Expected:
a
<BLANKLINE>
@@ -972,7 +972,7 @@
treated as equal:
>>> def f(x):
- ... '>>> print 1, 2, 3\n 1 2\n 3'
+ ... '>>> print(1, 2, 3)\n 1 2\n 3'
>>> # Without the flag:
>>> test = doctest.DocTestFinder().find(f)[0]
@@ -981,7 +981,7 @@
**********************************************************************
File ..., line 2, in f
Failed example:
- print 1, 2, 3
+ print(1, 2, 3)
Expected:
1 2
3
@@ -996,7 +996,7 @@
(0, 1)
An example from the docs:
- >>> 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]
@@ -1004,7 +1004,7 @@
output to match any substring in the actual output:
>>> def f(x):
- ... '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
+ ... '>>> print(range(15))\n[0, 1, 2, ..., 14]\n'
>>> # Without the flag:
>>> test = doctest.DocTestFinder().find(f)[0]
@@ -1013,7 +1013,7 @@
**********************************************************************
File ..., line 2, in f
Failed example:
- print range(15)
+ print(range(15))
Expected:
[0, 1, 2, ..., 14]
Got:
@@ -1028,22 +1028,26 @@
... also matches nothing:
- >>> for i in range(100):
- ... print i**2, #doctest: +ELLIPSIS
- 0 1...4...9 16 ... 36 49 64 ... 9801
+ >>> if 1:
+ ... for i in range(100):
+ ... print(i**2, end=' ') #doctest: +ELLIPSIS
+ ... print('!')
+ 0 1...4...9 16 ... 36 49 64 ... 9801 !
... can be surprising; e.g., this test passes:
- >>> for i in range(21): #doctest: +ELLIPSIS
- ... print i,
+ >>> if 1: #doctest: +ELLIPSIS
+ ... for i in range(20):
+ ... print(i, end=' ')
+ ... print(20)
0 1 2 ...1...2...0
Examples from the docs:
- >>> print range(20) # doctest:+ELLIPSIS
+ >>> print(range(20)) # doctest:+ELLIPSIS
[0, 1, ..., 18, 19]
- >>> print range(20) # doctest: +ELLIPSIS
+ >>> print(range(20)) # doctest: +ELLIPSIS
... # doctest: +NORMALIZE_WHITESPACE
[0, 1, ..., 18, 19]
@@ -1063,7 +1067,7 @@
UncheckedBlowUpError: Nobody checks me.
>>> import random
- >>> print random.random() # doctest: +SKIP
+ >>> print(random.random()) # doctest: +SKIP
0.721216923889
The REPORT_UDIFF flag causes failures that involve multi-line expected
@@ -1071,7 +1075,7 @@
>>> def f(x):
... r'''
- ... >>> print '\n'.join('abcdefg')
+ ... >>> print('\n'.join('abcdefg'))
... a
... B
... c
@@ -1088,7 +1092,7 @@
**********************************************************************
File ..., line 3, in f
Failed example:
- print '\n'.join('abcdefg')
+ print('\n'.join('abcdefg'))
Expected:
a
B
@@ -1115,7 +1119,7 @@
**********************************************************************
File ..., line 3, in f
Failed example:
- print '\n'.join('abcdefg')
+ print('\n'.join('abcdefg'))
Differences (unified diff with -expected +actual):
@@ -1,7 +1,7 @@
a
@@ -1140,7 +1144,7 @@
**********************************************************************
File ..., line 3, in f
Failed example:
- print '\n'.join('abcdefg')
+ print('\n'.join('abcdefg'))
Differences (context diff with expected followed by actual):
***************
*** 1,7 ****
@@ -1168,7 +1172,7 @@
>>> def f(x):
... r'''
- ... >>> print "a b c d e f g h i j k l m"
+ ... >>> print("a b c d e f g h i j k l m")
... a b c d e f g h i j k 1 m
... '''
>>> test = doctest.DocTestFinder().find(f)[0]
@@ -1178,7 +1182,7 @@
**********************************************************************
File ..., line 3, in f
Failed example:
- print "a b c d e f g h i j k l m"
+ print("a b c d e f g h i j k l m")
Differences (ndiff with -expected +actual):
- a b c d e f g h i j k 1 m
? ^
@@ -1191,15 +1195,15 @@
>>> def f(x):
... r'''
- ... >>> print 1 # first success
+ ... >>> print(1) # first success
... 1
- ... >>> print 2 # first failure
+ ... >>> print(2) # first failure
... 200
- ... >>> print 3 # second failure
+ ... >>> print(3) # second failure
... 300
- ... >>> print 4 # second success
+ ... >>> print(4) # second success
... 4
- ... >>> print 5 # third failure
+ ... >>> print(5) # third failure
... 500
... '''
>>> test = doctest.DocTestFinder().find(f)[0]
@@ -1209,7 +1213,7 @@
**********************************************************************
File ..., line 5, in f
Failed example:
- print 2 # first failure
+ print(2) # first failure
Expected:
200
Got:
@@ -1221,18 +1225,18 @@
>>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
... # doctest: +ELLIPSIS
Trying:
- print 1 # first success
+ print(1) # first success
Expecting:
1
ok
Trying:
- print 2 # first failure
+ print(2) # first failure
Expecting:
200
**********************************************************************
File ..., line 5, in f
Failed example:
- print 2 # first failure
+ print(2) # first failure
Expected:
200
Got:
@@ -1244,15 +1248,15 @@
>>> def f(x):
... r'''
- ... >>> print 1 # first success
+ ... >>> print(1) # first success
... 1
... >>> raise ValueError(2) # first failure
... 200
- ... >>> print 3 # second failure
+ ... >>> print(3) # second failure
... 300
- ... >>> print 4 # second success
+ ... >>> print(4) # second success
... 4
- ... >>> print 5 # third failure
+ ... >>> print(5) # third failure
... 500
... '''
>>> test = doctest.DocTestFinder().find(f)[0]
@@ -1298,10 +1302,10 @@
example with a comment of the form ``# doctest: +OPTION``:
>>> def f(x): r'''
- ... >>> print range(10) # should fail: no ellipsis
+ ... >>> print(range(10)) # should fail: no ellipsis
... [0, 1, ..., 9]
...
- ... >>> print range(10) # doctest: +ELLIPSIS
+ ... >>> print(range(10)) # doctest: +ELLIPSIS
... [0, 1, ..., 9]
... '''
>>> test = doctest.DocTestFinder().find(f)[0]
@@ -1310,7 +1314,7 @@
**********************************************************************
File ..., line 2, in f
Failed example:
- print range(10) # should fail: no ellipsis
+ print(range(10)) # should fail: no ellipsis
Expected:
[0, 1, ..., 9]
Got:
@@ -1321,11 +1325,11 @@
comment of the form ``# doctest: -OPTION``:
>>> def f(x): r'''
- ... >>> print range(10)
+ ... >>> print(range(10))
... [0, 1, ..., 9]
...
... >>> # should fail: no ellipsis
- ... >>> print range(10) # doctest: -ELLIPSIS
+ ... >>> print(range(10)) # doctest: -ELLIPSIS
... [0, 1, ..., 9]
... '''
>>> test = doctest.DocTestFinder().find(f)[0]
@@ -1335,7 +1339,7 @@
**********************************************************************
File ..., line 6, in f
Failed example:
- print range(10) # doctest: -ELLIPSIS
+ print(range(10)) # doctest: -ELLIPSIS
Expected:
[0, 1, ..., 9]
Got:
@@ -1346,13 +1350,13 @@
do not change the options for surrounding examples:
>>> def f(x): r'''
- ... >>> print range(10) # Should fail: no ellipsis
+ ... >>> print(range(10)) # Should fail: no ellipsis
... [0, 1, ..., 9]
...
- ... >>> print range(10) # doctest: +ELLIPSIS
+ ... >>> print(range(10)) # doctest: +ELLIPSIS
... [0, 1, ..., 9]
...
- ... >>> print range(10) # Should fail: no ellipsis
+ ... >>> print(range(10)) # Should fail: no ellipsis
... [0, 1, ..., 9]
... '''
>>> test = doctest.DocTestFinder().find(f)[0]
@@ -1361,7 +1365,7 @@
**********************************************************************
File ..., line 2, in f
Failed example:
- print range(10) # Should fail: no ellipsis
+ print(range(10)) # Should fail: no ellipsis
Expected:
[0, 1, ..., 9]
Got:
@@ -1369,7 +1373,7 @@
**********************************************************************
File ..., line 8, in f
Failed example:
- print range(10) # Should fail: no ellipsis
+ print(range(10)) # Should fail: no ellipsis
Expected:
[0, 1, ..., 9]
Got:
@@ -1380,9 +1384,9 @@
may be separated by whitespace, commas, or both:
>>> def f(x): r'''
- ... >>> print range(10) # Should fail
+ ... >>> print(range(10)) # Should fail
... [0, 1, ..., 9]
- ... >>> print range(10) # Should succeed
+ ... >>> print(range(10)) # Should succeed
... ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
... [0, 1, ..., 9]
... '''
@@ -1392,7 +1396,7 @@
**********************************************************************
File ..., line 2, in f
Failed example:
- print range(10) # Should fail
+ print(range(10)) # Should fail
Expected:
[0, 1, ..., 9]
Got:
@@ -1400,9 +1404,9 @@
(1, 2)
>>> def f(x): r'''
- ... >>> print range(10) # Should fail
+ ... >>> print(range(10)) # Should fail
... [0, 1, ..., 9]
- ... >>> print range(10) # Should succeed
+ ... >>> print(range(10)) # Should succeed
... ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
... [0, 1, ..., 9]
... '''
@@ -1412,7 +1416,7 @@
**********************************************************************
File ..., line 2, in f
Failed example:
- print range(10) # Should fail
+ print(range(10)) # Should fail
Expected:
[0, 1, ..., 9]
Got:
@@ -1420,9 +1424,9 @@
(1, 2)
>>> def f(x): r'''
- ... >>> print range(10) # Should fail
+ ... >>> print(range(10)) # Should fail
... [0, 1, ..., 9]
- ... >>> print range(10) # Should succeed
+ ... >>> print(range(10)) # Should succeed
... ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
... [0, 1, ..., 9]
... '''
@@ -1432,7 +1436,7 @@
**********************************************************************
File ..., line 2, in f
Failed example:
- print range(10) # Should fail
+ print(range(10)) # Should fail
Expected:
[0, 1, ..., 9]
Got:
@@ -1443,7 +1447,7 @@
long as a continuation prompt is used:
>>> def f(x): r'''
- ... >>> print range(10)
+ ... >>> print(range(10))
... ... # doctest: +ELLIPSIS
... [0, 1, ..., 9]
... '''
@@ -1456,12 +1460,12 @@
>>> def f(x): r'''
... >>> for x in range(10): # doctest: +ELLIPSIS
- ... ... print x,
- ... 0 1 2 ... 9
+ ... ... print(x, end=' ')
+ ... 0 1 2 ... 9
...
... >>> for x in range(10):
- ... ... print x, # doctest: +ELLIPSIS
- ... 0 1 2 ... 9
+ ... ... print(x, end=' ') # doctest: +ELLIPSIS
+ ... 0 1 2 ... 9
... '''
>>> test = doctest.DocTestFinder().find(f)[0]
>>> doctest.DocTestRunner(verbose=False).run(test)
@@ -1473,8 +1477,8 @@
>>> def f(x): r'''
... Should fail (option directive not on the last line):
... >>> for x in range(10): # doctest: +ELLIPSIS
- ... ... print x, # doctest: +NORMALIZE_WHITESPACE
- ... 0 1 2...9
+ ... ... print(x, end=' ') # doctest: +NORMALIZE_WHITESPACE
+ ... 0 1 2...9
... '''
>>> test = doctest.DocTestFinder().find(f)[0]
>>> doctest.DocTestRunner(verbose=False).run(test)
@@ -1486,13 +1490,13 @@
`register_option`:
>>> # Error: Option not registered
- >>> s = '>>> print 12 #doctest: +BADOPTION'
+ >>> s = '>>> print(12) #doctest: +BADOPTION'
>>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
Traceback (most recent call last):
ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
>>> # Error: No + or - prefix
- >>> s = '>>> print 12 #doctest: ELLIPSIS'
+ >>> s = '>>> print(12) #doctest: ELLIPSIS'
>>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
Traceback (most recent call last):
ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
@@ -1516,10 +1520,10 @@
>>> import test.test_doctest
>>> name = 'test.test_doctest.sample_func'
- >>> print doctest.testsource(test.test_doctest, name)
+ >>> print(doctest.testsource(test.test_doctest, name))
# Blah blah
#
- print sample_func(22)
+ print(sample_func(22))
# Expected:
## 44
#
@@ -1527,8 +1531,8 @@
<BLANKLINE>
>>> name = 'test.test_doctest.SampleNewStyleClass'
- >>> print doctest.testsource(test.test_doctest, name)
- print '1\n2\n3'
+ >>> print(doctest.testsource(test.test_doctest, name))
+ print('1\n2\n3')
# Expected:
## 1
## 2
@@ -1536,11 +1540,11 @@
<BLANKLINE>
>>> name = 'test.test_doctest.SampleClass.a_classmethod'
- >>> print doctest.testsource(test.test_doctest, name)
- print SampleClass.a_classmethod(10)
+ >>> print(doctest.testsource(test.test_doctest, name))
+ print(SampleClass.a_classmethod(10))
# Expected:
## 12
- print SampleClass(0).a_classmethod(10)
+ print(SampleClass(0).a_classmethod(10))
# Expected:
## 12
<BLANKLINE>
@@ -1552,7 +1556,7 @@
>>> s = '''
... >>> x = 12
- ... >>> print x
+ ... >>> print(x)
... 12
... '''
@@ -1560,7 +1564,7 @@
>>> import tempfile
>>> real_stdin = sys.stdin
- >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
+ >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
Run the debugger on the docstring, and then restore sys.stdin.
@@ -1571,7 +1575,7 @@
12
--Return--
> <string>(1)<module>()->None
- (Pdb) print x
+ (Pdb) print(x)
12
(Pdb) continue
@@ -1601,7 +1605,7 @@
>>> import tempfile
>>> real_stdin = sys.stdin
>>> sys.stdin = _FakeInput([
- ... 'print x', # print data defined by the example
+ ... 'print(x)', # print data defined by the example
... 'continue', # stop debugging
... ''])
@@ -1610,7 +1614,7 @@
--Return--
> <doctest foo[1]>(1)<module>()->None
-> import pdb; pdb.set_trace()
- (Pdb) print x
+ (Pdb) print(x)
42
(Pdb) continue
(0, 2)
@@ -1628,9 +1632,9 @@
>>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
>>> real_stdin = sys.stdin
>>> sys.stdin = _FakeInput([
- ... 'print y', # print data defined in the function
+ ... 'print(y)', # print data defined in the function
... 'up', # out of function
- ... 'print x', # print data defined by the example
+ ... 'print(x)', # print data defined by the example
... 'continue', # stop debugging
... ''])
@@ -1641,12 +1645,12 @@
--Return--
> <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
-> import pdb; pdb.set_trace()
- (Pdb) print y
+ (Pdb) print(y)
2
(Pdb) up
> <doctest foo[1]>(1)<module>()
-> calls_set_trace()
- (Pdb) print x
+ (Pdb) print(x)
1
(Pdb) continue
(0, 2)
@@ -1658,7 +1662,7 @@
... >>> def f(x):
... ... g(x*2)
... >>> def g(x):
- ... ... print x+3
+ ... ... print(x+3)
... ... import pdb; pdb.set_trace()
... >>> f(3)
... '''
@@ -1680,7 +1684,7 @@
-> 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) next
@@ -1737,11 +1741,11 @@
>>> test = parser.get_doctest(doc, globals(), "foo", "foo.py", 0)
>>> real_stdin = sys.stdin
>>> sys.stdin = _FakeInput([
- ... 'print y', # print data defined in the function
- ... 'step', 'step', 'step', 'step', 'step', 'step', 'print z',
- ... 'up', 'print x',
- ... 'up', 'print y',
- ... 'up', 'print foo',
+ ... 'print(y)', # print data defined in the function
+ ... 'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
+ ... 'up', 'print(x)',
+ ... 'up', 'print(y)',
+ ... 'up', 'print(foo)',
... 'continue', # stop debugging
... ''])
@@ -1751,7 +1755,7 @@
... sys.stdin = real_stdin
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
-> self.f1()
- (Pdb) print y
+ (Pdb) print(y)
1
(Pdb) step
--Call--
@@ -1773,22 +1777,22 @@
(Pdb) step
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
-> z = 2
- (Pdb) print z
+ (Pdb) print(z)
1
(Pdb) up
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
-> self.f2()
- (Pdb) print x
+ (Pdb) print(x)
1
(Pdb) up
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
-> self.f1()
- (Pdb) print y
+ (Pdb) print(y)
1
(Pdb) up
> <doctest foo[1]>(1)<module>()
-> calls_set_trace()
- (Pdb) print foo
+ (Pdb) print(foo)
*** NameError: name 'foo' is not defined
(Pdb) continue
(0, 2)
@@ -2037,7 +2041,7 @@
Trailing spaces in expected output are significant:
>>> x, y = 'foo', ''
- >>> print x, y
+ >>> print(x, y)
foo \n
"""
@@ -2054,7 +2058,7 @@
... optionflags=doctest.DONT_ACCEPT_BLANKLINE)
>>> import unittest
>>> result = suite.run(unittest.TestResult())
- >>> print result.failures[0][1] # doctest: +ELLIPSIS
+ >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Traceback ...
Failed example:
favorite_color
@@ -2071,7 +2075,7 @@
Now, when we run the test:
>>> result = suite.run(unittest.TestResult())
- >>> print result.failures[0][1] # doctest: +ELLIPSIS
+ >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Traceback ...
Failed example:
favorite_color
@@ -2092,16 +2096,16 @@
Then the default eporting options are ignored:
>>> result = suite.run(unittest.TestResult())
- >>> print result.failures[0][1] # doctest: +ELLIPSIS
+ >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
Traceback ...
Failed example:
favorite_color
...
Failed example:
if 1:
- print 'a'
- print
- print 'b'
+ print('a')
+ print()
+ print('b')
Differences (ndiff with -expected +actual):
a
- <BLANKLINE>
@@ -2185,9 +2189,9 @@
ok
Trying:
if 1:
- print 'a'
- print
- print 'b'
+ print('a')
+ print()
+ print('b')
Expecting:
a
<BLANKLINE>
@@ -2279,19 +2283,19 @@
>>> t = Tester(globs={'x': 42}, verbose=0)
>>> t.runstring(r'''
... >>> x = x * 2
-... >>> print x
+... >>> print(x)
... 42
... ''', 'XYZ')
**********************************************************************
Line 3, in XYZ
Failed example:
- print x
+ print(x)
Expected:
42
Got:
84
(1, 2)
->>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
+>>> t.runstring(">>> x = x * 2\n>>> print(x)\n84\n", 'example2')
(0, 2)
>>> t.summarize()
**********************************************************************
@@ -2407,7 +2411,7 @@
trace=0, count=1)
tracer.run('reload(doctest); test_main()')
r = tracer.results()
- print 'Writing coverage results...'
+ print('Writing coverage results...')
r.write_results(show_missing=True, summary=True,
coverdir=coverdir)
Modified: python/branches/p3yk-noslice/Lib/test/test_doctest.txt
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_doctest.txt (original)
+++ python/branches/p3yk-noslice/Lib/test/test_doctest.txt Fri Feb 23 18:29:35 2007
@@ -9,9 +9,9 @@
We can make this fail by disabling the blank-line feature.
>>> if 1:
- ... print 'a'
- ... print
- ... print 'b'
+ ... print('a')
+ ... print()
+ ... print('b')
a
<BLANKLINE>
b
Modified: python/branches/p3yk-noslice/Lib/test/test_doctest2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_doctest2.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_doctest2.py Fri Feb 23 18:29:35 2007
@@ -2,7 +2,7 @@
u"""A module to test whether doctest recognizes some 2.2 features,
like static and class methods.
->>> print 'yup' # 1
+>>> print('yup') # 1
yup
We include some (random) encoded (utf-8) text in the text surrounding
@@ -17,7 +17,7 @@
class C(object):
u"""Class C.
- >>> print C() # 2
+ >>> print(C()) # 2
42
@@ -31,13 +31,13 @@
def __init__(self):
"""C.__init__.
- >>> print C() # 3
+ >>> print(C()) # 3
42
"""
def __str__(self):
"""
- >>> print C() # 4
+ >>> print(C()) # 4
42
"""
return "42"
@@ -45,13 +45,13 @@
class D(object):
"""A nested D class.
- >>> print "In D!" # 5
+ >>> print("In D!") # 5
In D!
"""
def nested(self):
"""
- >>> print 3 # 6
+ >>> print(3) # 6
3
"""
@@ -59,7 +59,7 @@
"""
>>> c = C() # 7
>>> c.x = 12 # 8
- >>> print c.x # 9
+ >>> print(c.x) # 9
-12
"""
return -self._x
@@ -68,7 +68,7 @@
"""
>>> c = C() # 10
>>> c.x = 12 # 11
- >>> print c.x # 12
+ >>> print(c.x) # 12
-12
"""
self._x = value
@@ -76,7 +76,7 @@
x = property(getx, setx, doc="""\
>>> c = C() # 13
>>> c.x = 12 # 14
- >>> print c.x # 15
+ >>> print(c.x) # 15
-12
""")
@@ -85,9 +85,9 @@
"""
A static method.
- >>> print C.statm() # 16
+ >>> print(C.statm()) # 16
666
- >>> print C().statm() # 17
+ >>> print(C().statm()) # 17
666
"""
return 666
@@ -97,9 +97,9 @@
"""
A class method.
- >>> print C.clsm(22) # 18
+ >>> print(C.clsm(22)) # 18
22
- >>> print C().clsm(23) # 19
+ >>> print(C().clsm(23)) # 19
23
"""
return val
Modified: python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_dumbdbm.py Fri Feb 23 18:29:35 2007
@@ -32,7 +32,7 @@
def test_dumbdbm_creation(self):
f = dumbdbm.open(_fname, 'c')
- self.assertEqual(f.keys(), [])
+ self.assertEqual(list(f.keys()), [])
for key in self._dict:
f[key] = self._dict[key]
self.read_helper(f)
@@ -49,13 +49,19 @@
f.close()
finally:
os.umask(old_umask)
-
+
+ expected_mode = 0635
+ if os.name != 'posix':
+ # Windows only supports setting the read-only attribute.
+ # This shouldn't fail, but doesn't work like Unix either.
+ expected_mode = 0666
+
import stat
st = os.stat(_fname + '.dat')
- self.assertEqual(stat.S_IMODE(st.st_mode), 0635)
+ self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode)
st = os.stat(_fname + '.dir')
- self.assertEqual(stat.S_IMODE(st.st_mode), 0635)
-
+ self.assertEqual(stat.S_IMODE(st.st_mode), expected_mode)
+
def test_close_twice(self):
f = dumbdbm.open(_fname)
f['a'] = 'b'
@@ -122,10 +128,8 @@
f.close()
def keys_helper(self, f):
- keys = f.keys()
- keys.sort()
- dkeys = self._dict.keys()
- dkeys.sort()
+ keys = sorted(f.keys())
+ dkeys = sorted(self._dict.keys())
self.assertEqual(keys, dkeys)
return keys
@@ -150,10 +154,8 @@
f.close()
f = dumbdbm.open(_fname)
- expected = d.items()
- expected.sort()
- got = f.items()
- got.sort()
+ expected = sorted(d.items())
+ got = sorted(f.items())
self.assertEqual(expected, got)
f.close()
Modified: python/branches/p3yk-noslice/Lib/test/test_dummy_thread.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_dummy_thread.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_dummy_thread.py Fri Feb 23 18:29:35 2007
@@ -72,13 +72,13 @@
start_time = int(time.time())
_thread.start_new_thread(delay_unlock,(self.lock, DELAY))
if test_support.verbose:
- print
- print "*** Waiting for thread to release the lock "\
- "(approx. %s sec.) ***" % DELAY
+ print()
+ print("*** Waiting for thread to release the lock "\
+ "(approx. %s sec.) ***" % DELAY)
self.lock.acquire()
end_time = int(time.time())
if test_support.verbose:
- print "done"
+ print("done")
self.failUnless((end_time - start_time) >= DELAY,
"Blocking by unconditional acquiring failed.")
@@ -150,9 +150,9 @@
thread_count = 5
testing_queue = Queue.Queue(thread_count)
if test_support.verbose:
- print
- print "*** Testing multiple thread creation "\
- "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count)
+ print()
+ print("*** Testing multiple thread creation "\
+ "(will take approx. %s to %s sec.) ***" % (DELAY, thread_count))
for count in xrange(thread_count):
if DELAY:
local_delay = round(random.random(), 1)
@@ -162,7 +162,7 @@
(testing_queue, local_delay))
time.sleep(DELAY)
if test_support.verbose:
- print 'done'
+ print('done')
self.failUnless(testing_queue.qsize() == thread_count,
"Not all %s threads executed properly after %s sec." %
(thread_count, DELAY))
@@ -173,8 +173,8 @@
_thread = imported_module
DELAY = 2
if test_support.verbose:
- print
- print "*** Using %s as _thread module ***" % _thread
+ print()
+ print("*** Using %s as _thread module ***" % _thread)
test_support.run_unittest(LockTests, MiscTests, ThreadTests)
if __name__ == '__main__':
Modified: python/branches/p3yk-noslice/Lib/test/test_dummy_threading.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_dummy_threading.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_dummy_threading.py Fri Feb 23 18:29:35 2007
@@ -17,20 +17,20 @@
#delay = random.random() * 2
delay = 0
if verbose:
- print 'task', self.getName(), 'will run for', delay, 'sec'
+ print('task', self.getName(), 'will run for', delay, 'sec')
sema.acquire()
mutex.acquire()
running = running + 1
if verbose:
- print running, 'tasks are running'
+ print(running, 'tasks are running')
mutex.release()
time.sleep(delay)
if verbose:
- print 'task', self.getName(), 'done'
+ print('task', self.getName(), 'done')
mutex.acquire()
running = running - 1
if verbose:
- print self.getName(), 'is finished.', running, 'tasks are running'
+ print(self.getName(), 'is finished.', running, 'tasks are running')
mutex.release()
sema.release()
@@ -61,11 +61,11 @@
starttasks()
if verbose:
- print 'waiting for all tasks to complete'
+ print('waiting for all tasks to complete')
for t in threads:
t.join()
if verbose:
- print 'all tasks done'
+ print('all tasks done')
Modified: python/branches/p3yk-noslice/Lib/test/test_enumerate.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_enumerate.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_enumerate.py Fri Feb 23 18:29:35 2007
@@ -208,7 +208,7 @@
for i in xrange(len(counts)):
test_support.run_unittest(*testclasses)
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
Modified: python/branches/p3yk-noslice/Lib/test/test_errno.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_errno.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_errno.py Fri Feb 23 18:29:35 2007
@@ -43,7 +43,7 @@
a = getattr(errno, error)
except AttributeError:
if verbose:
- print '%s: not found' % error
+ print('%s: not found' % error)
else:
if verbose:
- print '%s: %d' % (error, a)
+ print('%s: %d' % (error, a))
Modified: python/branches/p3yk-noslice/Lib/test/test_exceptions.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_exceptions.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_exceptions.py Fri Feb 23 18:29:35 2007
@@ -311,6 +311,13 @@
'pickled "%r", attribute "%s' %
(e, checkArgName))
+ def testSlicing(self):
+ # Test that you can slice an exception directly instead of requiring
+ # going through the 'args' attribute.
+ args = (1, 2, 3)
+ exc = BaseException(*args)
+ self.failUnlessEqual(exc[:], args)
+
def testKeywordArgs(self):
# test that builtin exception don't take keyword args,
# but user-defined subclasses can if they want
Modified: python/branches/p3yk-noslice/Lib/test/test_extcall.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_extcall.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_extcall.py Fri Feb 23 18:29:35 2007
@@ -2,16 +2,16 @@
from UserList import UserList
def e(a, b):
- print a, b
+ print(a, b)
def f(*a, **k):
- print a, sortdict(k)
+ print(a, sortdict(k))
def g(x, *y, **z):
- print x, y, sortdict(z)
+ print(x, y, sortdict(z))
def h(j=1, a=2, h=3):
- print j, a, h
+ print(j, a, h)
f()
f(1)
@@ -31,28 +31,28 @@
except TypeError:
pass
else:
- print "should raise TypeError: e() got an unexpected keyword argument 'c'"
+ print("should raise TypeError: e() got an unexpected keyword argument 'c'")
try:
g()
except TypeError as err:
- print "TypeError:", err
+ print("TypeError:", err)
else:
- print "should raise TypeError: not enough arguments; expected 1, got 0"
+ print("should raise TypeError: not enough arguments; expected 1, got 0")
try:
g(*())
except TypeError as err:
- print "TypeError:", err
+ print("TypeError:", err)
else:
- print "should raise TypeError: not enough arguments; expected 1, got 0"
+ print("should raise TypeError: not enough arguments; expected 1, got 0")
try:
g(*(), **{})
except TypeError as err:
- print "TypeError:", err
+ print("TypeError:", err)
else:
- print "should raise TypeError: not enough arguments; expected 1, got 0"
+ print("should raise TypeError: not enough arguments; expected 1, got 0")
g(1)
g(1, 2)
@@ -64,7 +64,7 @@
except TypeError as attr:
pass
else:
- print "should raise TypeError"
+ print("should raise TypeError")
class Nothing:
def __len__(self):
@@ -74,7 +74,7 @@
except TypeError as attr:
pass
else:
- print "should raise TypeError"
+ print("should raise TypeError")
class Nothing:
def __len__(self):
@@ -96,7 +96,7 @@
except TypeError as attr:
pass
else:
- print "should raise TypeError"
+ print("should raise TypeError")
class Nothing:
def __init__(self):
@@ -116,8 +116,8 @@
d2 = d.copy()
verify(d == d2)
g(1, d=4, **d)
-print sortdict(d)
-print sortdict(d2)
+print(sortdict(d))
+print(sortdict(d2))
verify(d == d2, "function call modified dictionary")
# what about willful misconduct?
@@ -133,79 +133,79 @@
try:
g(1, 2, 3, **{'x':4, 'y':5})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: keyword parameter redefined"
+ print("should raise TypeError: keyword parameter redefined")
try:
g(1, 2, 3, a=4, b=5, *(6, 7), **{'a':8, 'b':9})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: keyword parameter redefined"
+ print("should raise TypeError: keyword parameter redefined")
try:
f(**{1:2})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: keywords must be strings"
+ print("should raise TypeError: keywords must be strings")
try:
h(**{'e': 2})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: unexpected keyword argument: e"
+ print("should raise TypeError: unexpected keyword argument: e")
try:
h(*h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: * argument must be a tuple"
+ print("should raise TypeError: * argument must be a tuple")
try:
dir(*h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: * argument must be a tuple"
+ print("should raise TypeError: * argument must be a tuple")
try:
None(*h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: * argument must be a tuple"
+ print("should raise TypeError: * argument must be a tuple")
try:
h(**h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: ** argument must be a dictionary"
+ print("should raise TypeError: ** argument must be a dictionary")
try:
dir(**h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: ** argument must be a dictionary"
+ print("should raise TypeError: ** argument must be a dictionary")
try:
None(**h)
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: ** argument must be a dictionary"
+ print("should raise TypeError: ** argument must be a dictionary")
try:
dir(b=1,**{'b':1})
except TypeError as err:
- print err
+ print(err)
else:
- print "should raise TypeError: dir() got multiple values for keyword argument 'b'"
+ print("should raise TypeError: dir() got multiple values for keyword argument 'b'")
def f2(*a, **b):
return a, b
@@ -215,27 +215,27 @@
key = 'k%d' % i
d[key] = i
a, b = f2(1, *(2, 3), **d)
-print len(a), len(b), b == d
+print(len(a), len(b), b == d)
class Foo:
def method(self, arg1, arg2):
return arg1 + arg2
x = Foo()
-print Foo.method(*(x, 1, 2))
-print Foo.method(x, *(1, 2))
+print(Foo.method(*(x, 1, 2)))
+print(Foo.method(x, *(1, 2)))
try:
- print Foo.method(*(1, 2, 3))
+ print(Foo.method(*(1, 2, 3)))
except TypeError as err:
pass
else:
- print 'expected a TypeError for unbound method call'
+ print('expected a TypeError for unbound method call')
try:
- print Foo.method(1, *(2, 3))
+ print(Foo.method(1, *(2, 3)))
except TypeError as err:
pass
else:
- print 'expected a TypeError for unbound method call'
+ print('expected a TypeError for unbound method call')
# A PyCFunction that takes only positional parameters should allow an
# empty keyword dictionary to pass without a complaint, but raise a
@@ -260,8 +260,8 @@
lambda x: '%s="%s"' % (x, x), defargs)
if vararg: arglist.append('*' + vararg)
if kwarg: arglist.append('**' + kwarg)
- decl = (('def %s(%s): print "ok %s", a, b, d, e, v, ' +
- 'type(k) is type ("") and k or sortdict(k)')
+ decl = (('def %s(%s): print("ok %s", a, b, d, e, v, ' +
+ 'type(k) is type ("") and k or sortdict(k))')
% (name, ', '.join(arglist), name))
exec(decl)
func = eval(name)
@@ -274,6 +274,6 @@
for kwargs in ['', 'a', 'd', 'ad', 'abde']:
kwdict = {}
for k in kwargs: kwdict[k] = k + k
- print func.func_name, args, sortdict(kwdict), '->',
+ print(func.func_name, args, sortdict(kwdict), '->', end=' ')
try: func(*args, **kwdict)
- except TypeError as err: print err
+ except TypeError as err: print(err)
Modified: python/branches/p3yk-noslice/Lib/test/test_fcntl.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_fcntl.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_fcntl.py Fri Feb 23 18:29:35 2007
@@ -41,18 +41,18 @@
lockdata = struct.pack('hh'+start_len+'hh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
if lockdata:
if verbose:
- print 'struct.pack: ', repr(lockdata)
+ print('struct.pack: ', repr(lockdata))
# the example from the library docs
f = open(filename, 'w')
rv = fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
if verbose:
- print 'Status from fcntl with O_NONBLOCK: ', rv
+ print('Status from fcntl with O_NONBLOCK: ', rv)
if sys.platform not in ['os2emx']:
rv = fcntl.fcntl(f.fileno(), fcntl.F_SETLKW, lockdata)
if verbose:
- print 'String from fcntl with F_SETLKW: ', repr(rv)
+ print('String from fcntl with F_SETLKW: ', repr(rv))
f.close()
os.unlink(filename)
Modified: python/branches/p3yk-noslice/Lib/test/test_file.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_file.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_file.py Fri Feb 23 18:29:35 2007
@@ -30,14 +30,10 @@
def testAttributes(self):
# verify expected attributes exist
f = self.f
- softspace = f.softspace
f.name # merely shouldn't blow up
f.mode # ditto
f.closed # ditto
- # verify softspace is writable
- f.softspace = softspace # merely shouldn't blow up
-
# verify the others aren't
for attr in 'name', 'mode', 'closed':
self.assertRaises((AttributeError, TypeError), setattr, f, attr, 'oops')
@@ -142,9 +138,9 @@
if sys.platform != 'osf1V5':
self.assertRaises(IOError, sys.stdin.seek, -1)
else:
- print >>sys.__stdout__, (
+ print((
' Skipping sys.stdin.seek(-1), it may crash the interpreter.'
- ' Test manually.')
+ ' Test manually.'), file=sys.__stdout__)
self.assertRaises(IOError, sys.stdin.truncate)
def testUnicodeOpen(self):
Modified: python/branches/p3yk-noslice/Lib/test/test_fileinput.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_fileinput.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_fileinput.py Fri Feb 23 18:29:35 2007
@@ -34,7 +34,7 @@
def runTests(t1, t2, t3, t4, bs=0, round=0):
start = 1 + round*6
if verbose:
- print '%s. Simple iteration (bs=%s)' % (start+0, bs)
+ print('%s. Simple iteration (bs=%s)' % (start+0, bs))
fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
lines = list(fi)
fi.close()
@@ -45,7 +45,7 @@
verify(fi.filename() == t4)
if verbose:
- print '%s. Status variables (bs=%s)' % (start+1, bs)
+ print('%s. Status variables (bs=%s)' % (start+1, bs))
fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
s = "x"
while s and s != 'Line 6 of file 2\n':
@@ -57,14 +57,14 @@
verify(not fi.isstdin())
if verbose:
- print '%s. Nextfile (bs=%s)' % (start+2, bs)
+ print('%s. Nextfile (bs=%s)' % (start+2, bs))
fi.nextfile()
verify(fi.readline() == 'Line 1 of file 3\n')
verify(fi.lineno() == 22)
fi.close()
if verbose:
- print '%s. Stdin (bs=%s)' % (start+3, bs)
+ print('%s. Stdin (bs=%s)' % (start+3, bs))
fi = FileInput(files=(t1, t2, t3, t4, '-'), bufsize=bs)
savestdin = sys.stdin
try:
@@ -78,7 +78,7 @@
sys.stdin = savestdin
if verbose:
- print '%s. Boundary conditions (bs=%s)' % (start+4, bs)
+ print('%s. Boundary conditions (bs=%s)' % (start+4, bs))
fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
verify(fi.lineno() == 0)
verify(fi.filename() == None)
@@ -87,13 +87,13 @@
verify(fi.filename() == None)
if verbose:
- print '%s. Inplace (bs=%s)' % (start+5, bs)
+ print('%s. Inplace (bs=%s)' % (start+5, bs))
savestdout = sys.stdout
try:
fi = FileInput(files=(t1, t2, t3, t4), inplace=1, bufsize=bs)
for line in fi:
line = line[:-1].upper()
- print line
+ print(line)
fi.close()
finally:
sys.stdout = savestdout
@@ -124,7 +124,7 @@
# Next, check for proper behavior with 0-byte files.
if verbose:
- print "13. 0-byte files"
+ print("13. 0-byte files")
try:
t1 = writeTmp(1, [""])
t2 = writeTmp(2, [""])
@@ -146,7 +146,7 @@
remove_tempfiles(t1, t2, t3, t4)
if verbose:
- print "14. Files that don't end with newline"
+ print("14. Files that don't end with newline")
try:
t1 = writeTmp(1, ["A\nB\nC"])
t2 = writeTmp(2, ["D\nE\nF"])
@@ -159,7 +159,7 @@
remove_tempfiles(t1, t2)
if verbose:
- print "15. Unicode filenames"
+ print("15. Unicode filenames")
try:
t1 = writeTmp(1, ["A\nB"])
encoding = sys.getfilesystemencoding()
@@ -172,7 +172,7 @@
remove_tempfiles(t1)
if verbose:
- print "16. fileno()"
+ print("16. fileno()")
try:
t1 = writeTmp(1, ["A\nB"])
t2 = writeTmp(2, ["C\nD"])
@@ -188,7 +188,7 @@
remove_tempfiles(t1, t2)
if verbose:
- print "17. Specify opening mode"
+ print("17. Specify opening mode")
try:
# invalid mode, should raise ValueError
fi = FileInput(mode="w")
@@ -205,7 +205,7 @@
remove_tempfiles(t1)
if verbose:
- print "18. Test file opening hook"
+ print("18. Test file opening hook")
try:
# cannot use openhook and inplace mode
fi = FileInput(inplace=1, openhook=lambda f,m: None)
Modified: python/branches/p3yk-noslice/Lib/test/test_format.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_format.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_format.py Fri Feb 23 18:29:35 2007
@@ -11,26 +11,26 @@
def testformat(formatstr, args, output=None):
if verbose:
if output:
- print "%s %% %s =? %s ..." %\
- (repr(formatstr), repr(args), repr(output)),
+ print("%s %% %s =? %s ..." %\
+ (repr(formatstr), repr(args), repr(output)), end=' ')
else:
- print "%s %% %s works? ..." % (repr(formatstr), repr(args)),
+ print("%s %% %s works? ..." % (repr(formatstr), repr(args)), end=' ')
try:
result = formatstr % args
except OverflowError:
if not overflowok:
raise
if verbose:
- print 'overflow (this is fine)'
+ print('overflow (this is fine)')
else:
if output and result != output:
if verbose:
- print 'no'
- print "%s %% %s == %s != %s" %\
- (repr(formatstr), repr(args), repr(result), repr(output))
+ print('no')
+ print("%s %% %s == %s != %s" %\
+ (repr(formatstr), repr(args), repr(result), repr(output)))
else:
if verbose:
- print 'yes'
+ print('yes')
def testboth(formatstr, *args):
testformat(formatstr, *args)
@@ -57,14 +57,14 @@
# Formatting of long integers. Overflow is not ok
overflowok = 0
-testboth("%x", 10L, "a")
-testboth("%x", 100000000000L, "174876e800")
-testboth("%o", 10L, "12")
-testboth("%o", 100000000000L, "1351035564000")
-testboth("%d", 10L, "10")
-testboth("%d", 100000000000L, "100000000000")
+testboth("%x", 10, "a")
+testboth("%x", 100000000000, "174876e800")
+testboth("%o", 10, "12")
+testboth("%o", 100000000000, "1351035564000")
+testboth("%d", 10, "10")
+testboth("%d", 100000000000, "100000000000")
-big = 123456789012345678901234567890L
+big = 123456789012345678901234567890
testboth("%d", big, "123456789012345678901234567890")
testboth("%d", -big, "-123456789012345678901234567890")
testboth("%5d", -big, "-123456789012345678901234567890")
@@ -83,7 +83,7 @@
testboth("%.31d", big, "0123456789012345678901234567890")
testboth("%32.31d", big, " 0123456789012345678901234567890")
-big = 0x1234567890abcdef12345L # 21 hex digits
+big = 0x1234567890abcdef12345 # 21 hex digits
testboth("%x", big, "1234567890abcdef12345")
testboth("%x", -big, "-1234567890abcdef12345")
testboth("%5x", -big, "-1234567890abcdef12345")
@@ -120,7 +120,7 @@
# same, except no 0 flag
testboth("%#+27.23X", big, " +0X001234567890ABCDEF12345")
-big = 012345670123456701234567012345670L # 32 octal digits
+big = 012345670123456701234567012345670 # 32 octal digits
testboth("%o", big, "12345670123456701234567012345670")
testboth("%o", -big, "-12345670123456701234567012345670")
testboth("%5o", -big, "-12345670123456701234567012345670")
@@ -163,38 +163,38 @@
# Some small ints, in both Python int and long flavors).
testboth("%d", 42, "42")
testboth("%d", -42, "-42")
-testboth("%d", 42L, "42")
-testboth("%d", -42L, "-42")
+testboth("%d", 42, "42")
+testboth("%d", -42, "-42")
testboth("%#x", 1, "0x1")
-testboth("%#x", 1L, "0x1")
+testboth("%#x", 1, "0x1")
+testboth("%#X", 1, "0X1")
testboth("%#X", 1, "0X1")
-testboth("%#X", 1L, "0X1")
testboth("%#o", 1, "01")
-testboth("%#o", 1L, "01")
+testboth("%#o", 1, "01")
+testboth("%#o", 0, "0")
testboth("%#o", 0, "0")
-testboth("%#o", 0L, "0")
testboth("%o", 0, "0")
-testboth("%o", 0L, "0")
+testboth("%o", 0, "0")
testboth("%d", 0, "0")
-testboth("%d", 0L, "0")
+testboth("%d", 0, "0")
+testboth("%#x", 0, "0x0")
testboth("%#x", 0, "0x0")
-testboth("%#x", 0L, "0x0")
testboth("%#X", 0, "0X0")
-testboth("%#X", 0L, "0X0")
+testboth("%#X", 0, "0X0")
testboth("%x", 0x42, "42")
testboth("%x", -0x42, "-42")
-testboth("%x", 0x42L, "42")
-testboth("%x", -0x42L, "-42")
+testboth("%x", 0x42, "42")
+testboth("%x", -0x42, "-42")
testboth("%o", 042, "42")
testboth("%o", -042, "-42")
-testboth("%o", 042L, "42")
-testboth("%o", -042L, "-42")
+testboth("%o", 042, "42")
+testboth("%o", -042, "-42")
# Test exception for unknown format characters
if verbose:
- print 'Testing exceptions'
+ print('Testing exceptions')
def test_exc(formatstr, args, exception, excmsg):
try:
@@ -202,13 +202,13 @@
except exception as exc:
if str(exc) == excmsg:
if verbose:
- print "yes"
+ print("yes")
else:
- if verbose: print 'no'
- print 'Unexpected ', exception, ':', repr(str(exc))
+ if verbose: print('no')
+ print('Unexpected ', exception, ':', repr(str(exc)))
except:
- if verbose: print 'no'
- print 'Unexpected exception'
+ if verbose: print('no')
+ print('Unexpected exception')
raise
else:
raise TestFailed, 'did not get expected exception: %s' % excmsg
@@ -230,13 +230,13 @@
test_exc(u'no format', u'1', TypeError,
"not all arguments converted during string formatting")
-class Foobar(long):
+class Foobar(int):
def __oct__(self):
# Returning a non-string should not blow up.
return self + 1
test_exc('%o', Foobar(), TypeError,
- "expected string or Unicode object, long found")
+ "expected string or Unicode object, int found")
if sys.maxint == 2**31-1:
# crashes 2.2.1 and earlier:
Modified: python/branches/p3yk-noslice/Lib/test/test_funcattrs.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_funcattrs.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_funcattrs.py Fri Feb 23 18:29:35 2007
@@ -204,7 +204,7 @@
pass
def temp():
- print 1
+ print(1)
if foo==bar:
raise TestFailed
@@ -235,7 +235,7 @@
def test_func_closure():
a = 12
- def f(): print a
+ def f(): print(a)
c = f.func_closure
verify(isinstance(c, tuple))
verify(len(c) == 1)
@@ -284,10 +284,10 @@
def test_func_code():
a = b = 24
def f(): pass
- def g(): print 12
- def f1(): print a
- def g1(): print b
- def f2(): print a, b
+ def g(): print(12)
+ def f1(): print(a)
+ def g1(): print(b)
+ def f2(): print(a, b)
verify(type(f.func_code) is types.CodeType)
f.func_code = g.func_code
cantset(f, "func_code", None)
Modified: python/branches/p3yk-noslice/Lib/test/test_functools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_functools.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_functools.py Fri Feb 23 18:29:35 2007
@@ -293,8 +293,8 @@
)
self.assertEqual(self.func(lambda x, y: x*y, range(2,8), 1), 5040)
self.assertEqual(
- self.func(lambda x, y: x*y, range(2,21), 1L),
- 2432902008176640000L
+ self.func(lambda x, y: x*y, range(2,21), 1),
+ 2432902008176640000
)
self.assertEqual(self.func(lambda x, y: x+y, Squares(10)), 285)
self.assertEqual(self.func(lambda x, y: x+y, Squares(10), 0), 285)
@@ -356,7 +356,7 @@
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == '__main__':
test_main(verbose=True)
Modified: python/branches/p3yk-noslice/Lib/test/test_gc.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_gc.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_gc.py Fri Feb 23 18:29:35 2007
@@ -14,10 +14,10 @@
def run_test(name, thunk):
if verbose:
- print "testing %s..." % name,
+ print("testing %s..." % name, end=' ')
thunk()
if verbose:
- print "ok"
+ print("ok")
def test_list():
l = []
@@ -612,7 +612,7 @@
def test():
if verbose:
- print "disabling automatic collection"
+ print("disabling automatic collection")
enabled = gc.isenabled()
gc.disable()
verify(not gc.isenabled())
@@ -625,7 +625,7 @@
gc.set_debug(debug)
# test gc.enable() even if GC is disabled by default
if verbose:
- print "restoring automatic collection"
+ print("restoring automatic collection")
# make sure to always test gc.enable()
gc.enable()
verify(gc.isenabled())
Modified: python/branches/p3yk-noslice/Lib/test/test_gdbm.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_gdbm.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_gdbm.py Fri Feb 23 18:29:35 2007
@@ -15,7 +15,7 @@
g['12345678910'] = '019237410982340912840198242'
a = g.keys()
if verbose:
- print 'Test gdbm file keys: ', a
+ print('Test gdbm file keys: ', a)
'a' in g
g.close()
Modified: python/branches/p3yk-noslice/Lib/test/test_generators.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_generators.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_generators.py Fri Feb 23 18:29:35 2007
@@ -6,7 +6,7 @@
... yield 2
>>> for i in f():
- ... print i
+ ... print(i)
1
2
>>> g = f()
@@ -78,7 +78,7 @@
... raise StopIteration
... except:
... yield 42
- >>> print list(g2())
+ >>> print(list(g2()))
[42]
This may be surprising at first:
@@ -105,13 +105,13 @@
>>> def creator():
... r = yrange(5)
- ... print "creator", r.next()
+ ... print("creator", r.next())
... return r
...
>>> def caller():
... r = creator()
... for i in r:
- ... print "caller", i
+ ... print("caller", i)
...
>>> caller()
creator 0
@@ -161,7 +161,7 @@
... return
... except:
... yield 1
- >>> print list(f1())
+ >>> print(list(f1()))
[]
because, as in any function, return simply exits, but
@@ -171,7 +171,7 @@
... raise StopIteration
... except:
... yield 42
- >>> print list(f2())
+ >>> print(list(f2()))
[42]
because StopIteration is captured by a bare "except", as is any
@@ -221,7 +221,7 @@
... finally:
... yield 10
... yield 11
- >>> print list(f())
+ >>> print(list(f()))
[1, 2, 4, 5, 8, 9, 10, 11]
>>>
@@ -270,8 +270,8 @@
>>> t = tree("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
>>> # Print the nodes of the tree in in-order.
>>> for x in t:
- ... print x,
- A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
+ ... print(' '+x, end='')
+ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
>>> # A non-recursive generator.
>>> def inorder(node):
@@ -291,8 +291,8 @@
>>> # Exercise the non-recursive generator.
>>> for x in t:
- ... print x,
- A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
+ ... print(' '+x, end='')
+ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
"""
@@ -345,9 +345,9 @@
>>> seq = range(1, 5)
>>> for k in range(len(seq) + 2):
-... print "%d-combs of %s:" % (k, seq)
+... print("%d-combs of %s:" % (k, seq))
... for c in gcomb(seq, k):
-... print " ", c
+... print(" ", c)
0-combs of [1, 2, 3, 4]:
[]
1-combs of [1, 2, 3, 4]:
@@ -383,7 +383,7 @@
<type 'generator'>
>>> [s for s in dir(i) if not s.startswith('_')]
['close', 'gi_frame', 'gi_running', 'next', 'send', 'throw']
->>> print i.next.__doc__
+>>> print(i.next.__doc__)
x.next() -> the next value, or raise StopIteration
>>> iter(i) is i
True
@@ -447,41 +447,41 @@
>>> gen = random.WichmannHill(42)
>>> while 1:
... for s in sets:
-... print "%s->%s" % (s, s.find()),
-... print
+... print(" %s->%s" % (s, s.find()), end='')
+... print()
... if len(roots) > 1:
... s1 = gen.choice(roots)
... roots.remove(s1)
... s2 = gen.choice(roots)
... s1.union(s2)
-... print "merged", s1, "into", s2
+... print("merged", s1, "into", s2)
... else:
... break
-A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M
+ A->A B->B C->C D->D E->E F->F G->G H->H I->I J->J K->K L->L M->M
merged D into G
-A->A B->B C->C D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M
+ A->A B->B C->C D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M
merged C into F
-A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M
+ A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->L M->M
merged L into A
-A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->A M->M
+ A->A B->B C->F D->G E->E F->F G->G H->H I->I J->J K->K L->A M->M
merged H into E
-A->A B->B C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M
+ A->A B->B C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M
merged B into E
-A->A B->E C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M
+ A->A B->E C->F D->G E->E F->F G->G H->E I->I J->J K->K L->A M->M
merged J into G
-A->A B->E C->F D->G E->E F->F G->G H->E I->I J->G K->K L->A M->M
+ A->A B->E C->F D->G E->E F->F G->G H->E I->I J->G K->K L->A M->M
merged E into G
-A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->M
+ A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->M
merged M into G
-A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->G
+ A->A B->G C->F D->G E->G F->F G->G H->G I->I J->G K->K L->A M->G
merged I into K
-A->A B->G C->F D->G E->G F->F G->G H->G I->K J->G K->K L->A M->G
+ A->A B->G C->F D->G E->G F->F G->G H->G I->K J->G K->K L->A M->G
merged K into A
-A->A B->G C->F D->G E->G F->F G->G H->G I->A J->G K->A L->A M->G
+ A->A B->G C->F D->G E->G F->F G->G H->G I->A J->G K->A L->A M->G
merged F into A
-A->A B->G C->A D->G E->G F->A G->G H->G I->A J->G K->A L->A M->G
+ A->A B->G C->A D->G E->G F->A G->G H->G I->A J->G K->A L->A M->G
merged A into G
-A->G B->G C->G D->G E->G F->G G->G H->G I->G J->G K->G L->G M->G
+ A->G B->G C->G D->G E->G F->G G->G H->G I->G J->G K->G L->G M->G
"""
# Emacs turd '
@@ -576,7 +576,7 @@
>>> result = m235()
>>> for i in range(3):
-... print firstn(result, 15)
+... print(firstn(result, 15))
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
@@ -613,7 +613,7 @@
>>> m235 = LazyList(m235())
>>> for i in range(5):
-... print [m235[j] for j in range(15*i, 15*(i+1))]
+... print([m235[j] for j in range(15*i, 15*(i+1))])
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
@@ -684,7 +684,7 @@
>>> it = m235()
>>> for i in range(5):
-... print firstn(it, 15)
+... print(firstn(it, 15))
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
@@ -890,13 +890,13 @@
... yield i
...
>>> g = f()
->>> print g.next()
+>>> print(g.next())
0
->>> print g.next()
+>>> print(g.next())
1
->>> print g.next()
+>>> print(g.next())
2
->>> print g.next()
+>>> print(g.next())
Traceback (most recent call last):
StopIteration
"""
@@ -1057,9 +1057,9 @@
# generates the possiblities for the columns in that row.
self.rowgenerators = []
for i in rangen:
- rowuses = [(1L << j) | # column ordinal
- (1L << (n + i-j + n-1)) | # NW-SE ordinal
- (1L << (n + 2*n-1 + i+j)) # NE-SW ordinal
+ rowuses = [(1 << j) | # column ordinal
+ (1 << (n + i-j + n-1)) | # NW-SE ordinal
+ (1 << (n + 2*n-1 + i+j)) # NE-SW ordinal
for j in rangen]
def rowgen(rowuses=rowuses):
@@ -1082,12 +1082,12 @@
n = self.n
assert n == len(row2col)
sep = "+" + "-+" * n
- print sep
+ print(sep)
for i in range(n):
squares = [" " for j in range(n)]
squares[row2col[i]] = "Q"
- print "|" + "|".join(squares) + "|"
- print sep
+ print("|" + "|".join(squares) + "|")
+ print(sep)
# A conjoin-based Knight's Tour solver. This is pretty sophisticated
# (e.g., when used with flat_conjoin above, and passing hard=1 to the
@@ -1279,11 +1279,11 @@
k += 1
sep = "+" + ("-" * w + "+") * n
- print sep
+ print(sep)
for i in range(m):
row = squares[i]
- print "|" + "|".join(row) + "|"
- print sep
+ print("|" + "|".join(row) + "|")
+ print(sep)
conjoin_tests = """
@@ -1291,7 +1291,7 @@
possible use of conjoin, just to generate the full cross-product.
>>> for c in conjoin([lambda: iter((0, 1))] * 3):
-... print c
+... print(c)
[0, 0, 0]
[0, 0, 1]
[0, 1, 0]
@@ -1311,7 +1311,7 @@
>>> for n in range(10):
... all = list(gencopy(conjoin([lambda: iter((0, 1))] * n)))
-... print n, len(all), all[0] == [0] * n, all[-1] == [1] * n
+... print(n, len(all), all[0] == [0] * n, all[-1] == [1] * n)
0 1 True True
1 2 True True
2 4 True True
@@ -1331,7 +1331,7 @@
>>> for row2col in q.solve():
... count += 1
... if count <= LIMIT:
-... print "Solution", count
+... print("Solution", count)
... q.printsolution(row2col)
Solution 1
+-+-+-+-+-+-+-+-+
@@ -1370,7 +1370,7 @@
| | | | |Q| | | |
+-+-+-+-+-+-+-+-+
->>> print count, "solutions in all."
+>>> print(count, "solutions in all.")
92 solutions in all.
And run a Knight's Tour on a 10x10 board. Note that there are about
@@ -1382,7 +1382,7 @@
>>> for x in k.solve():
... count += 1
... if count <= LIMIT:
-... print "Solution", count
+... print("Solution", count)
... k.printsolution(x)
... else:
... break
@@ -1460,7 +1460,7 @@
Sending a value into a started generator:
>>> def f():
-... print (yield 1)
+... print((yield 1))
... yield 2
>>> g = f()
>>> g.next()
@@ -1507,16 +1507,16 @@
>>> seq = []
>>> c = coroutine(seq)
>>> c.next()
->>> print seq
+>>> print(seq)
[]
>>> c.send(10)
->>> print seq
+>>> print(seq)
[10]
>>> c.send(10)
->>> print seq
+>>> print(seq)
[10, 20]
>>> c.send(10)
->>> print seq
+>>> print(seq)
[10, 20, 30]
@@ -1553,9 +1553,9 @@
>>> def f():
... while True:
... try:
-... print (yield)
+... print((yield))
... except ValueError as v:
-... print "caught ValueError (%s)" % (v),
+... print("caught ValueError (%s)" % (v))
>>> import sys
>>> g = f()
>>> g.next()
@@ -1616,7 +1616,7 @@
...
TypeError
->>> print g.gi_frame
+>>> print(g.gi_frame)
None
>>> g.send(2)
@@ -1639,7 +1639,7 @@
>>> def f():
... try: yield
... except GeneratorExit:
-... print "exiting"
+... print("exiting")
>>> g = f()
>>> g.next()
@@ -1660,7 +1660,7 @@
>>> def f():
... try: yield
... finally:
-... print "exiting"
+... print("exiting")
>>> g = f()
>>> g.next()
Modified: python/branches/p3yk-noslice/Lib/test/test_genexps.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_genexps.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_genexps.py Fri Feb 23 18:29:35 2007
@@ -157,12 +157,12 @@
>>> def creator():
... r = yrange(5)
- ... print "creator", r.next()
+ ... print("creator", r.next())
... return r
>>> def caller():
... r = creator()
... for i in r:
- ... print "caller", i
+ ... print("caller", i)
>>> caller()
creator 0
caller 1
@@ -221,7 +221,7 @@
>>> set(attr for attr in dir(g) if not attr.startswith('__')) >= expected
True
- >>> print g.next.__doc__
+ >>> print(g.next.__doc__)
x.next() -> the next value, or raise StopIteration
>>> import types
>>> isinstance(g, types.GeneratorType)
@@ -274,7 +274,7 @@
test_support.run_doctest(test_genexps, verbose)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
Modified: python/branches/p3yk-noslice/Lib/test/test_getargs2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_getargs2.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_getargs2.py Fri Feb 23 18:29:35 2007
@@ -45,7 +45,7 @@
"""
LARGE = 0x7FFFFFFF
-VERY_LARGE = 0xFF0000121212121212121242L
+VERY_LARGE = 0xFF0000121212121212121242
from _testcapi import UCHAR_MAX, USHRT_MAX, UINT_MAX, ULONG_MAX, INT_MAX, \
INT_MIN, LONG_MIN, LONG_MAX, PY_SSIZE_T_MIN, PY_SSIZE_T_MAX
@@ -57,7 +57,7 @@
class Long:
def __int__(self):
- return 99L
+ return 99
class Int:
def __int__(self):
@@ -77,7 +77,7 @@
self.assertRaises(OverflowError, getargs_b, UCHAR_MAX + 1)
self.failUnlessEqual(42, getargs_b(42))
- self.failUnlessEqual(42, getargs_b(42L))
+ self.failUnlessEqual(42, getargs_b(42))
self.assertRaises(OverflowError, getargs_b, VERY_LARGE)
def test_B(self):
@@ -88,13 +88,13 @@
self.failUnlessEqual(99, getargs_B(Int()))
self.failUnlessEqual(UCHAR_MAX, getargs_B(-1))
- self.failUnlessEqual(UCHAR_MAX, getargs_B(-1L))
+ self.failUnlessEqual(UCHAR_MAX, getargs_B(-1))
self.failUnlessEqual(0, getargs_B(0))
self.failUnlessEqual(UCHAR_MAX, getargs_B(UCHAR_MAX))
self.failUnlessEqual(0, getargs_B(UCHAR_MAX+1))
self.failUnlessEqual(42, getargs_B(42))
- self.failUnlessEqual(42, getargs_B(42L))
+ self.failUnlessEqual(42, getargs_B(42))
self.failUnlessEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE))
def test_H(self):
@@ -110,7 +110,7 @@
self.failUnlessEqual(0, getargs_H(USHRT_MAX+1))
self.failUnlessEqual(42, getargs_H(42))
- self.failUnlessEqual(42, getargs_H(42L))
+ self.failUnlessEqual(42, getargs_H(42))
self.failUnlessEqual(VERY_LARGE & USHRT_MAX, getargs_H(VERY_LARGE))
@@ -127,7 +127,7 @@
self.failUnlessEqual(0, getargs_I(UINT_MAX+1))
self.failUnlessEqual(42, getargs_I(42))
- self.failUnlessEqual(42, getargs_I(42L))
+ self.failUnlessEqual(42, getargs_I(42))
self.failUnlessEqual(VERY_LARGE & UINT_MAX, getargs_I(VERY_LARGE))
@@ -145,7 +145,7 @@
self.failUnlessEqual(0, getargs_k(ULONG_MAX+1))
self.failUnlessEqual(42, getargs_k(42))
- self.failUnlessEqual(42, getargs_k(42L))
+ self.failUnlessEqual(42, getargs_k(42))
self.failUnlessEqual(VERY_LARGE & ULONG_MAX, getargs_k(VERY_LARGE))
@@ -163,7 +163,7 @@
self.assertRaises(OverflowError, getargs_i, INT_MAX+1)
self.failUnlessEqual(42, getargs_i(42))
- self.failUnlessEqual(42, getargs_i(42L))
+ self.failUnlessEqual(42, getargs_i(42))
self.assertRaises(OverflowError, getargs_i, VERY_LARGE)
def test_l(self):
@@ -179,7 +179,7 @@
self.assertRaises(OverflowError, getargs_l, LONG_MAX+1)
self.failUnlessEqual(42, getargs_l(42))
- self.failUnlessEqual(42, getargs_l(42L))
+ self.failUnlessEqual(42, getargs_l(42))
self.assertRaises(OverflowError, getargs_l, VERY_LARGE)
def test_n(self):
@@ -196,7 +196,7 @@
self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MAX+1)
self.failUnlessEqual(42, getargs_n(42))
- self.failUnlessEqual(42, getargs_n(42L))
+ self.failUnlessEqual(42, getargs_n(42))
self.assertRaises(OverflowError, getargs_n, VERY_LARGE)
@@ -215,7 +215,7 @@
self.assertRaises(OverflowError, getargs_L, LLONG_MAX+1)
self.failUnlessEqual(42, getargs_L(42))
- self.failUnlessEqual(42, getargs_L(42L))
+ self.failUnlessEqual(42, getargs_L(42))
self.assertRaises(OverflowError, getargs_L, VERY_LARGE)
def test_K(self):
@@ -229,7 +229,7 @@
self.failUnlessEqual(0, getargs_K(ULLONG_MAX+1))
self.failUnlessEqual(42, getargs_K(42))
- self.failUnlessEqual(42, getargs_K(42L))
+ self.failUnlessEqual(42, getargs_K(42))
self.failUnlessEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE))
Modified: python/branches/p3yk-noslice/Lib/test/test_getopt.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_getopt.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_getopt.py Fri Feb 23 18:29:35 2007
@@ -21,14 +21,14 @@
del os.environ["POSIXLY_CORRECT"]
if verbose:
- print 'Running tests on getopt.short_has_arg'
+ print('Running tests on getopt.short_has_arg')
verify(getopt.short_has_arg('a', 'a:'))
verify(not getopt.short_has_arg('a', 'a'))
expectException("tmp = getopt.short_has_arg('a', 'b')", GetoptError)
expectException("tmp = getopt.short_has_arg('a', '')", GetoptError)
if verbose:
- print 'Running tests on getopt.long_has_args'
+ print('Running tests on getopt.long_has_args')
has_arg, option = getopt.long_has_args('abc', ['abc='])
verify(has_arg)
verify(option == 'abc')
@@ -47,7 +47,7 @@
GetoptError)
if verbose:
- print 'Running tests on getopt.do_shorts'
+ print('Running tests on getopt.do_shorts')
opts, args = getopt.do_shorts([], 'a', 'a', [])
verify(opts == [('-a', '')])
verify(args == [])
@@ -69,7 +69,7 @@
GetoptError)
if verbose:
- print 'Running tests on getopt.do_longs'
+ print('Running tests on getopt.do_longs')
opts, args = getopt.do_longs([], 'abc', ['abc'], [])
verify(opts == [('--abc', '')])
verify(args == [])
@@ -99,7 +99,7 @@
'--beta', 'arg1', 'arg2']
if verbose:
- print 'Running tests on getopt.getopt'
+ print('Running tests on getopt.getopt')
opts, args = getopt.getopt(cmdline, 'a:b', ['alpha=', 'beta'])
verify(opts == [('-a', '1'), ('-b', ''), ('--alpha', '2'), ('--beta', ''),
('-a', '3'), ('-a', ''), ('--beta', '')] )
@@ -113,7 +113,7 @@
# Test handling of GNU style scanning mode.
if verbose:
- print 'Running tests on getopt.gnu_getopt'
+ print('Running tests on getopt.gnu_getopt')
cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2']
# GNU style
opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
@@ -177,4 +177,4 @@
#------------------------------------------------------------------------------
if verbose:
- print "Module getopt: tests completed successfully."
+ print("Module getopt: tests completed successfully.")
Modified: python/branches/p3yk-noslice/Lib/test/test_gl.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_gl.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_gl.py Fri Feb 23 18:29:35 2007
@@ -91,60 +91,60 @@
# touch all the attributes of gl without doing anything
if verbose:
- print 'Touching gl module attributes...'
+ print('Touching gl module attributes...')
for attr in glattrs:
if verbose:
- print 'touching: ', attr
+ print('touching: ', attr)
getattr(gl, attr)
# create a small 'Crisscross' window
if verbose:
- print 'Creating a small "CrissCross" window...'
- print 'foreground'
+ print('Creating a small "CrissCross" window...')
+ print('foreground')
gl.foreground()
if verbose:
- print 'prefposition'
+ print('prefposition')
gl.prefposition(500, 900, 500, 900)
if verbose:
- print 'winopen "CrissCross"'
+ print('winopen "CrissCross"')
w = gl.winopen('CrissCross')
if verbose:
- print 'clear'
+ print('clear')
gl.clear()
if verbose:
- print 'ortho2'
+ print('ortho2')
gl.ortho2(0.0, 400.0, 0.0, 400.0)
if verbose:
- print 'color WHITE'
+ print('color WHITE')
gl.color(GL.WHITE)
if verbose:
- print 'color RED'
+ print('color RED')
gl.color(GL.RED)
if verbose:
- print 'bgnline'
+ print('bgnline')
gl.bgnline()
if verbose:
- print 'v2f'
+ print('v2f')
gl.v2f(0.0, 0.0)
gl.v2f(400.0, 400.0)
if verbose:
- print 'endline'
+ print('endline')
gl.endline()
if verbose:
- print 'bgnline'
+ print('bgnline')
gl.bgnline()
if verbose:
- print 'v2i'
+ print('v2i')
gl.v2i(400, 0)
gl.v2i(0, 400)
if verbose:
- print 'endline'
+ print('endline')
gl.endline()
if verbose:
- print 'Displaying window for 2 seconds...'
+ print('Displaying window for 2 seconds...')
time.sleep(2)
if verbose:
- print 'winclose'
+ print('winclose')
gl.winclose(w)
main()
Modified: python/branches/p3yk-noslice/Lib/test/test_grammar.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_grammar.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_grammar.py Fri Feb 23 18:29:35 2007
@@ -55,14 +55,14 @@
self.fail('Weird maxint value %r' % maxint)
def testLongIntegers(self):
- x = 0L
- x = 0l
- x = 0xffffffffffffffffL
- x = 0xffffffffffffffffl
- x = 077777777777777777L
- x = 077777777777777777l
- x = 123456789012345678901234567890L
- x = 123456789012345678901234567890l
+ x = 0
+ x = 0
+ x = 0xffffffffffffffff
+ x = 0xffffffffffffffff
+ x = 077777777777777777
+ x = 077777777777777777
+ x = 123456789012345678901234567890
+ x = 123456789012345678901234567890
def testFloats(self):
x = 3.14
@@ -327,7 +327,7 @@
l1 = lambda : 0
self.assertEquals(l1(), 0)
l2 = lambda : a[d] # XXX just testing the expression
- l3 = lambda : [2 < x for x in [-1, 3, 0L]]
+ l3 = lambda : [2 < x for x in [-1, 3, 0]]
self.assertEquals(l3(), [0, 1, 0])
l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
self.assertEquals(l4(), 1)
@@ -351,7 +351,7 @@
x = 1; pass; del x;
foo()
- ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
+ ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
# Tested below
def testExprStmt(self):
@@ -367,76 +367,6 @@
check_syntax_error(self, "x + 1 = 1")
check_syntax_error(self, "a + 1 = b + 2")
- def testPrintStmt(self):
- # 'print' (test ',')* [test]
- import StringIO
-
- # Can't test printing to real stdout without comparing output
- # which is not available in unittest.
- save_stdout = sys.stdout
- sys.stdout = StringIO.StringIO()
-
- print 1, 2, 3
- print 1, 2, 3,
- print
- print 0 or 1, 0 or 1,
- print 0 or 1
-
- # 'print' '>>' test ','
- print >> sys.stdout, 1, 2, 3
- print >> sys.stdout, 1, 2, 3,
- print >> sys.stdout
- print >> sys.stdout, 0 or 1, 0 or 1,
- print >> sys.stdout, 0 or 1
-
- # test printing to an instance
- class Gulp:
- def write(self, msg): pass
-
- gulp = Gulp()
- print >> gulp, 1, 2, 3
- print >> gulp, 1, 2, 3,
- print >> gulp
- print >> gulp, 0 or 1, 0 or 1,
- print >> gulp, 0 or 1
-
- # test print >> None
- def driver():
- oldstdout = sys.stdout
- sys.stdout = Gulp()
- try:
- tellme(Gulp())
- tellme()
- finally:
- sys.stdout = oldstdout
-
- # we should see this once
- def tellme(file=sys.stdout):
- print >> file, 'hello world'
-
- driver()
-
- # we should not see this at all
- def tellme(file=None):
- print >> file, 'goodbye universe'
-
- driver()
-
- self.assertEqual(sys.stdout.getvalue(), '''\
-1 2 3
-1 2 3
-1 1 1
-1 2 3
-1 2 3
-1 1 1
-hello world
-''')
- sys.stdout = save_stdout
-
- # syntax errors
- check_syntax_error(self, 'print ,')
- check_syntax_error(self, 'print >> x,')
-
def testDelStmt(self):
# 'del' exprlist
abc = [1,2,3]
@@ -902,7 +832,7 @@
# Test ifelse expressions in various cases
def _checkeval(msg, ret):
"helper to check that evaluation of expressions is done correctly"
- print x
+ print(x)
return ret
self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
Modified: python/branches/p3yk-noslice/Lib/test/test_grp.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_grp.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_grp.py Fri Feb 23 18:29:35 2007
@@ -50,7 +50,7 @@
bynames[n] = g
bygids[g] = n
- allnames = bynames.keys()
+ allnames = list(bynames.keys())
namei = 0
fakename = allnames[namei]
while fakename in bynames:
Modified: python/branches/p3yk-noslice/Lib/test/test_gzip.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_gzip.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_gzip.py Fri Feb 23 18:29:35 2007
@@ -138,7 +138,7 @@
y = f.read(10)
f.close()
self.assertEquals(y, data1[20:30])
-
+
def test_seek_write(self):
# Try seek, write test
f = gzip.GzipFile(self.filename, 'w')
@@ -153,6 +153,13 @@
self.assertEqual(f.myfileobj.mode, 'rb')
f.close()
+ def test_1647484(self):
+ for mode in ('wb', 'rb'):
+ f = gzip.GzipFile(self.filename, mode)
+ self.assert_(hasattr(f, "name"))
+ self.assertEqual(f.name, self.filename)
+ f.close()
+
def test_main(verbose=None):
test_support.run_unittest(TestGzip)
Modified: python/branches/p3yk-noslice/Lib/test/test_hash.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_hash.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_hash.py Fri Feb 23 18:29:35 2007
@@ -17,14 +17,14 @@
self.fail("hashed values differ: %r" % (objlist,))
def test_numeric_literals(self):
- self.same_hash(1, 1L, 1.0, 1.0+0.0j)
+ self.same_hash(1, 1, 1.0, 1.0+0.0j)
def test_coerced_integers(self):
- self.same_hash(int(1), long(1), float(1), complex(1),
+ self.same_hash(int(1), int(1), float(1), complex(1),
int('1'), float('1.0'))
def test_coerced_floats(self):
- self.same_hash(long(1.23e300), float(1.23e300))
+ self.same_hash(int(1.23e300), float(1.23e300))
self.same_hash(float(0.5), complex(0.5, 0.0))
Modified: python/branches/p3yk-noslice/Lib/test/test_heapq.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_heapq.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_heapq.py Fri Feb 23 18:29:35 2007
@@ -1,6 +1,6 @@
"""Unittests for heapq."""
-from heapq import heappush, heappop, heapify, heapreplace, nlargest, nsmallest
+from heapq import heappush, heappop, heapify, heapreplace, merge, nlargest, nsmallest
import random
import unittest
from test import test_support
@@ -103,6 +103,29 @@
heap_sorted = [heappop(heap) for i in range(size)]
self.assertEqual(heap_sorted, sorted(data))
+ def test_merge(self):
+ inputs = []
+ for i in xrange(random.randrange(5)):
+ row = sorted(random.randrange(1000) for j in range(random.randrange(10)))
+ inputs.append(row)
+ self.assertEqual(sorted(chain(*inputs)), list(merge(*inputs)))
+ self.assertEqual(list(merge()), [])
+
+ def test_merge_stability(self):
+ class Int(int):
+ pass
+ inputs = [[], [], [], []]
+ for i in range(20000):
+ stream = random.randrange(4)
+ x = random.randrange(500)
+ obj = Int(x)
+ obj.pair = (x, stream)
+ inputs[stream].append(obj)
+ for stream in inputs:
+ stream.sort()
+ result = [i.pair for i in merge(*inputs)]
+ self.assertEqual(result, sorted(result))
+
def test_nsmallest(self):
data = [(random.randrange(2000), i) for i in range(1000)]
for f in (None, lambda x: x[0] * 547 % 2000):
@@ -281,7 +304,7 @@
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
Modified: python/branches/p3yk-noslice/Lib/test/test_hexoct.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_hexoct.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_hexoct.py Fri Feb 23 18:29:35 2007
@@ -41,26 +41,26 @@
def test_hex_unsigned(self):
if platform_long_is_32_bits:
# Positive constants
- self.assertEqual(0x80000000, 2147483648L)
- self.assertEqual(0xffffffff, 4294967295L)
+ self.assertEqual(0x80000000, 2147483648)
+ self.assertEqual(0xffffffff, 4294967295)
# Ditto with a minus sign and parentheses
- self.assertEqual(-(0x80000000), -2147483648L)
- self.assertEqual(-(0xffffffff), -4294967295L)
+ self.assertEqual(-(0x80000000), -2147483648)
+ self.assertEqual(-(0xffffffff), -4294967295)
# Ditto with a minus sign and NO parentheses
# This failed in Python 2.2 through 2.2.2 and in 2.3a1
- self.assertEqual(-0x80000000, -2147483648L)
- self.assertEqual(-0xffffffff, -4294967295L)
+ self.assertEqual(-0x80000000, -2147483648)
+ self.assertEqual(-0xffffffff, -4294967295)
else:
# Positive constants
- self.assertEqual(0x8000000000000000, 9223372036854775808L)
- self.assertEqual(0xffffffffffffffff, 18446744073709551615L)
+ self.assertEqual(0x8000000000000000, 9223372036854775808)
+ self.assertEqual(0xffffffffffffffff, 18446744073709551615)
# Ditto with a minus sign and parentheses
- self.assertEqual(-(0x8000000000000000), -9223372036854775808L)
- self.assertEqual(-(0xffffffffffffffff), -18446744073709551615L)
+ self.assertEqual(-(0x8000000000000000), -9223372036854775808)
+ self.assertEqual(-(0xffffffffffffffff), -18446744073709551615)
# Ditto with a minus sign and NO parentheses
# This failed in Python 2.2 through 2.2.2 and in 2.3a1
- self.assertEqual(-0x8000000000000000, -9223372036854775808L)
- self.assertEqual(-0xffffffffffffffff, -18446744073709551615L)
+ self.assertEqual(-0x8000000000000000, -9223372036854775808)
+ self.assertEqual(-0xffffffffffffffff, -18446744073709551615)
def test_oct_baseline(self):
# Baseline tests
@@ -88,26 +88,26 @@
def test_oct_unsigned(self):
if platform_long_is_32_bits:
# Positive constants
- self.assertEqual(020000000000, 2147483648L)
- self.assertEqual(037777777777, 4294967295L)
+ self.assertEqual(020000000000, 2147483648)
+ self.assertEqual(037777777777, 4294967295)
# Ditto with a minus sign and parentheses
- self.assertEqual(-(020000000000), -2147483648L)
- self.assertEqual(-(037777777777), -4294967295L)
+ self.assertEqual(-(020000000000), -2147483648)
+ self.assertEqual(-(037777777777), -4294967295)
# Ditto with a minus sign and NO parentheses
# This failed in Python 2.2 through 2.2.2 and in 2.3a1
- self.assertEqual(-020000000000, -2147483648L)
- self.assertEqual(-037777777777, -4294967295L)
+ self.assertEqual(-020000000000, -2147483648)
+ self.assertEqual(-037777777777, -4294967295)
else:
# Positive constants
- self.assertEqual(01000000000000000000000, 9223372036854775808L)
- self.assertEqual(01777777777777777777777, 18446744073709551615L)
+ self.assertEqual(01000000000000000000000, 9223372036854775808)
+ self.assertEqual(01777777777777777777777, 18446744073709551615)
# Ditto with a minus sign and parentheses
- self.assertEqual(-(01000000000000000000000), -9223372036854775808L)
- self.assertEqual(-(01777777777777777777777), -18446744073709551615L)
+ self.assertEqual(-(01000000000000000000000), -9223372036854775808)
+ self.assertEqual(-(01777777777777777777777), -18446744073709551615)
# Ditto with a minus sign and NO parentheses
# This failed in Python 2.2 through 2.2.2 and in 2.3a1
- self.assertEqual(-01000000000000000000000, -9223372036854775808L)
- self.assertEqual(-01777777777777777777777, -18446744073709551615L)
+ self.assertEqual(-01000000000000000000000, -9223372036854775808)
+ self.assertEqual(-01777777777777777777777, -18446744073709551615)
def test_main():
test_support.run_unittest(TextHexOct)
Modified: python/branches/p3yk-noslice/Lib/test/test_imageop.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_imageop.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_imageop.py Fri Feb 23 18:29:35 2007
@@ -28,7 +28,7 @@
# Return the selected part of image, which should by width by height
# in size and consist of pixels of psize bytes.
if verbose:
- print 'crop'
+ print('crop')
newimage = imageop.crop (image, 4, width, height, 0, 0, 1, 1)
# Return image scaled to size newwidth by newheight. No interpolation
@@ -36,7 +36,7 @@
# Therefore, computer-generated images or dithered images will
# not look nice after scaling.
if verbose:
- print 'scale'
+ print('scale')
scaleimage = imageop.scale(image, 4, width, height, 1, 1)
# Run a vertical low-pass filter over an image. It does so by computing
@@ -44,34 +44,34 @@
# pixels. The main use of this routine is to forestall excessive flicker
# if the image two vertically-aligned source pixels, hence the name.
if verbose:
- print 'tovideo'
+ print('tovideo')
videoimage = imageop.tovideo (image, 4, width, height)
# Convert an rgb image to an 8 bit rgb
if verbose:
- print 'rgb2rgb8'
+ print('rgb2rgb8')
greyimage = imageop.rgb2rgb8(image, width, height)
# Convert an 8 bit rgb image to a 24 bit rgb image
if verbose:
- print 'rgb82rgb'
+ print('rgb82rgb')
image = imageop.rgb82rgb(greyimage, width, height)
# Convert an rgb image to an 8 bit greyscale image
if verbose:
- print 'rgb2grey'
+ print('rgb2grey')
greyimage = imageop.rgb2grey(image, width, height)
# Convert an 8 bit greyscale image to a 24 bit rgb image
if verbose:
- print 'grey2rgb'
+ print('grey2rgb')
image = imageop.grey2rgb(greyimage, width, height)
# Convert a 8-bit deep greyscale image to a 1-bit deep image by
# thresholding all the pixels. The resulting image is tightly packed
# and is probably only useful as an argument to mono2grey.
if verbose:
- print 'grey2mono'
+ print('grey2mono')
monoimage = imageop.grey2mono (greyimage, width, height, 0)
# monoimage, width, height = getimage('monotest.rgb')
@@ -81,42 +81,42 @@
# monochrome black-and-white image to greyscale pass the values 0 and
# 255 respectively.
if verbose:
- print 'mono2grey'
+ print('mono2grey')
greyimage = imageop.mono2grey (monoimage, width, height, 0, 255)
# Convert an 8-bit greyscale image to a 1-bit monochrome image using a
# (simple-minded) dithering algorithm.
if verbose:
- print 'dither2mono'
+ print('dither2mono')
monoimage = imageop.dither2mono (greyimage, width, height)
# Convert an 8-bit greyscale image to a 4-bit greyscale image without
# dithering.
if verbose:
- print 'grey2grey4'
+ print('grey2grey4')
grey4image = imageop.grey2grey4 (greyimage, width, height)
# Convert an 8-bit greyscale image to a 2-bit greyscale image without
# dithering.
if verbose:
- print 'grey2grey2'
+ print('grey2grey2')
grey2image = imageop.grey2grey2 (greyimage, width, height)
# Convert an 8-bit greyscale image to a 2-bit greyscale image with
# dithering. As for dither2mono, the dithering algorithm is currently
# very simple.
if verbose:
- print 'dither2grey2'
+ print('dither2grey2')
grey2image = imageop.dither2grey2 (greyimage, width, height)
# Convert a 4-bit greyscale image to an 8-bit greyscale image.
if verbose:
- print 'grey42grey'
+ print('grey42grey')
greyimage = imageop.grey42grey (grey4image, width, height)
# Convert a 2-bit greyscale image to an 8-bit greyscale image.
if verbose:
- print 'grey22grey'
+ print('grey22grey')
image = imageop.grey22grey (grey2image, width, height)
# Cleanup
@@ -134,7 +134,7 @@
name = get_qualified_path(name)
sizes = rgbimg.sizeofimage(name)
if verbose:
- print 'rgbimg opening test image: %s, sizes: %s' % (name, str(sizes))
+ print('rgbimg opening test image: %s, sizes: %s' % (name, str(sizes)))
image = rgbimg.longimagedata(name)
return (image, sizes[0], sizes[1])
@@ -152,7 +152,7 @@
name = get_qualified_path(name)
sizes = imgfile.getsizes(name)
if verbose:
- print 'imgfile opening test image: %s, sizes: %s' % (name, str(sizes))
+ print('imgfile opening test image: %s, sizes: %s' % (name, str(sizes)))
image = imgfile.read(name)
return (image, sizes[0], sizes[1])
Modified: python/branches/p3yk-noslice/Lib/test/test_imgfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_imgfile.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_imgfile.py Fri Feb 23 18:29:35 2007
@@ -51,7 +51,7 @@
name = os.sep.join(parts)
sizes = imgfile.getsizes(name)
if verbose:
- print 'Opening test image: %s, sizes: %s' % (name, str(sizes))
+ print('Opening test image: %s, sizes: %s' % (name, str(sizes)))
# This function reads and decodes the image on the specified file,
# and returns it as a python string. The string has either 1 byte
# greyscale pixels or 4 byte RGBA pixels. The bottom left pixel
@@ -65,12 +65,12 @@
# are stored as 4 byte values of which only the lower three
# bytes are used). These are the formats returned by gl.lrectread.
if verbose:
- print 'Writing output file'
+ print('Writing output file')
imgfile.write (outputfile, image, sizes[0], sizes[1], sizes[2])
if verbose:
- print 'Opening scaled test image: %s, sizes: %s' % (name, str(sizes))
+ print('Opening scaled test image: %s, sizes: %s' % (name, str(sizes)))
# This function is identical to read but it returns an image that
# is scaled to the given x and y sizes. If the filter and blur
# parameters are omitted scaling is done by simply dropping
@@ -84,7 +84,7 @@
# makes no attempt to keep the aspect ratio correct, so that
# is the users' responsibility.
if verbose:
- print 'Filtering with "impulse"'
+ print('Filtering with "impulse"')
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'impulse', 2.0)
# This function sets a global flag which defines whether the
@@ -92,23 +92,23 @@
# top (flag is zero, compatible with SGI GL) or from top to
# bottom(flag is one, compatible with X). The default is zero.
if verbose:
- print 'Switching to X compatibility'
+ print('Switching to X compatibility')
imgfile.ttob (1)
if verbose:
- print 'Filtering with "triangle"'
+ print('Filtering with "triangle"')
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'triangle', 3.0)
if verbose:
- print 'Switching back to SGI compatibility'
+ print('Switching back to SGI compatibility')
imgfile.ttob (0)
- if verbose: print 'Filtering with "quadratic"'
+ if verbose: print('Filtering with "quadratic"')
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'quadratic')
- if verbose: print 'Filtering with "gaussian"'
+ if verbose: print('Filtering with "gaussian"')
simage = imgfile.readscaled (name, sizes[0]/2, sizes[1]/2, 'gaussian', 1.0)
if verbose:
- print 'Writing output file'
+ print('Writing output file')
imgfile.write (outputfile, simage, sizes[0]/2, sizes[1]/2, sizes[2])
os.unlink(outputfile)
Modified: python/branches/p3yk-noslice/Lib/test/test_import.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_import.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_import.py Fri Feb 23 18:29:35 2007
@@ -45,11 +45,11 @@
pyc = TESTFN + os.extsep + "pyc"
f = open(source, "w")
- print >> f, "# This tests Python's ability to import a", ext, "file."
+ print("# This tests Python's ability to import a", ext, "file.", file=f)
a = random.randrange(1000)
b = random.randrange(1000)
- print >> f, "a =", a
- print >> f, "b =", b
+ print("a =", a, file=f)
+ print("b =", b, file=f)
f.close()
try:
@@ -130,7 +130,7 @@
def test_failing_import_sticks(self):
source = TESTFN + os.extsep + "py"
f = open(source, "w")
- print >> f, "a = 1/0"
+ print("a = 1/0", file=f)
f.close()
# New in 2.4, we shouldn't be able to import that no matter how often
@@ -153,8 +153,8 @@
# A failing reload should leave the module object in sys.modules.
source = TESTFN + os.extsep + "py"
f = open(source, "w")
- print >> f, "a = 1"
- print >> f, "b = 2"
+ print("a = 1", file=f)
+ print("b = 2", file=f)
f.close()
sys.path.insert(0, os.curdir)
@@ -172,8 +172,8 @@
# Now damage the module.
f = open(source, "w")
- print >> f, "a = 10"
- print >> f, "b = 20//0"
+ print("a = 10", file=f)
+ print("b = 20//0", file=f)
f.close()
self.assertRaises(ZeroDivisionError, reload, mod)
Modified: python/branches/p3yk-noslice/Lib/test/test_importhooks.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_importhooks.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_importhooks.py Fri Feb 23 18:29:35 2007
@@ -254,7 +254,7 @@
mnames = ("colorsys", "urlparse", "distutils.core", "compiler.misc")
for mname in mnames:
parent = mname.split(".")[0]
- for n in sys.modules.keys():
+ for n in list(sys.modules.keys()):
if n.startswith(parent):
del sys.modules[n]
for mname in mnames:
Modified: python/branches/p3yk-noslice/Lib/test/test_index.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_index.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_index.py Fri Feb 23 18:29:35 2007
@@ -15,7 +15,7 @@
def __index__(self):
return self
-class TrapLong(long):
+class TrapLong(int):
def __index__(self):
return self
@@ -44,7 +44,7 @@
self.o.ind = 4
self.n.ind = 5
self.assertEqual(6 .__index__(), 6)
- self.assertEqual(-7L.__index__(), -7)
+ self.assertEqual(-7 .__index__(), -7)
self.assertEqual(self.o.__index__(), 4)
self.assertEqual(self.n.__index__(), 5)
Modified: python/branches/p3yk-noslice/Lib/test/test_inspect.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_inspect.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_inspect.py Fri Feb 23 18:29:35 2007
@@ -61,7 +61,6 @@
self.istest(inspect.ismodule, 'mod')
self.istest(inspect.istraceback, 'tb')
self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
- self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
if hasattr(types, 'GetSetDescriptorType'):
self.istest(inspect.isgetsetdescriptor,
'type(tb.tb_frame).f_locals')
Modified: python/branches/p3yk-noslice/Lib/test/test_isinstance.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_isinstance.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_isinstance.py Fri Feb 23 18:29:35 2007
@@ -242,7 +242,7 @@
self.assertEqual(False, issubclass(NewChild, ()))
self.assertEqual(True, issubclass(NewSuper, (NewChild, (NewSuper,))))
- self.assertEqual(True, issubclass(int, (long, (float, int))))
+ self.assertEqual(True, issubclass(int, (int, (float, int))))
if test_support.have_unicode:
self.assertEqual(True, issubclass(str, (unicode, (Child, NewChild, basestring))))
Modified: python/branches/p3yk-noslice/Lib/test/test_iter.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_iter.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_iter.py Fri Feb 23 18:29:35 2007
@@ -225,7 +225,7 @@
dict = {}
for i in range(10):
dict[i] = None
- self.check_for_loop(dict, dict.keys())
+ self.check_for_loop(dict, list(dict.keys()))
# Test a file
def test_iter_file(self):
@@ -254,7 +254,7 @@
self.assertEqual(list(range(10, -1, -1)), range(10, -1, -1))
d = {"one": 1, "two": 2, "three": 3}
- self.assertEqual(list(d), d.keys())
+ self.assertEqual(list(d), list(d.keys()))
self.assertRaises(TypeError, list, list)
self.assertRaises(TypeError, list, 42)
@@ -319,7 +319,7 @@
self.assertEqual(filter(None, "abc"), "abc")
d = {"one": 1, "two": 2, "three": 3}
- self.assertEqual(filter(None, d), d.keys())
+ self.assertEqual(filter(None, d), list(d.keys()))
self.assertRaises(TypeError, filter, None, list)
self.assertRaises(TypeError, filter, None, 42)
@@ -365,8 +365,8 @@
d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(max(d), "two")
self.assertEqual(min(d), "one")
- self.assertEqual(max(d.itervalues()), 3)
- self.assertEqual(min(iter(d.itervalues())), 1)
+ self.assertEqual(max(d.values()), 3)
+ self.assertEqual(min(iter(d.values())), 1)
f = open(TESTFN, "w")
try:
@@ -393,16 +393,16 @@
self.assertEqual(map(lambda x: x+1, SequenceClass(5)), range(1, 6))
d = {"one": 1, "two": 2, "three": 3}
- self.assertEqual(map(None, d), d.keys())
- self.assertEqual(map(lambda k, d=d: (k, d[k]), d), d.items())
- dkeys = d.keys()
+ self.assertEqual(map(None, d), list(d.keys()))
+ self.assertEqual(map(lambda k, d=d: (k, d[k]), d), list(d.items()))
+ dkeys = list(d.keys())
expected = [(i < len(d) and dkeys[i] or None,
i,
i < len(d) and dkeys[i] or None)
for i in range(5)]
self.assertEqual(map(None, d,
SequenceClass(5),
- iter(d.iterkeys())),
+ iter(d.keys())),
expected)
f = open(TESTFN, "w")
@@ -437,7 +437,7 @@
[(0,), (1,), (2,)])
d = {"one": 1, "two": 2, "three": 3}
- self.assertEqual(d.items(), list(zip(d, d.itervalues())))
+ self.assertEqual(list(d.items()), list(zip(d, d.values())))
# Generate all ints starting at constructor arg.
class IntsFrom:
@@ -559,13 +559,13 @@
d = {"one": 1, "two": 2, "three": 3, 1j: 2j}
for k in d:
self.assert_(k in d)
- self.assert_(k not in d.itervalues())
+ self.assert_(k not in d.values())
for v in d.values():
- self.assert_(v in d.itervalues())
+ self.assert_(v in d.values())
self.assert_(v not in d)
- for k, v in d.iteritems():
- self.assert_((k, v) in d.iteritems())
- self.assert_((v, k) not in d.iteritems())
+ for k, v in d.items():
+ self.assert_((k, v) in d.items())
+ self.assert_((v, k) not in d.items())
f = open(TESTFN, "w")
try:
@@ -600,9 +600,9 @@
d = {"one": 3, "two": 3, "three": 3, 1j: 2j}
for k in d:
self.assertEqual(countOf(d, k), 1)
- self.assertEqual(countOf(d.itervalues(), 3), 3)
- self.assertEqual(countOf(d.itervalues(), 2j), 1)
- self.assertEqual(countOf(d.itervalues(), 1j), 0)
+ self.assertEqual(countOf(d.values(), 3), 3)
+ self.assertEqual(countOf(d.values(), 2j), 1)
+ self.assertEqual(countOf(d.values(), 1j), 0)
f = open(TESTFN, "w")
try:
@@ -744,7 +744,7 @@
else:
self.fail("should have raised TypeError")
- a, b, c = {1: 42, 2: 42, 3: 42}.itervalues()
+ a, b, c = {1: 42, 2: 42, 3: 42}.values()
self.assertEqual((a, b, c), (42, 42, 42))
f = open(TESTFN, "w")
@@ -841,7 +841,7 @@
# XXX For a more thorough test, see towards the end of:
# http://mail.python.org/pipermail/python-dev/2002-July/026512.html
a = {1:1, 2:2, 0:0, 4:4, 3:3}
- for b in iter(a), a.iterkeys(), a.iteritems(), a.itervalues():
+ for b in iter(a), a.keys(), a.items(), a.values():
b = iter(a)
self.assertEqual(len(list(b)), 5)
self.assertEqual(list(b), [])
Modified: python/branches/p3yk-noslice/Lib/test/test_iterlen.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_iterlen.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_iterlen.py Fri Feb 23 18:29:35 2007
@@ -139,14 +139,14 @@
def setUp(self):
d = dict.fromkeys(xrange(n))
- self.it = d.iteritems()
+ self.it = iter(d.items())
self.mutate = d.popitem
class TestDictValues(TestTemporarilyImmutable):
def setUp(self):
d = dict.fromkeys(xrange(n))
- self.it = d.itervalues()
+ self.it = iter(d.values())
self.mutate = d.popitem
class TestSet(TestTemporarilyImmutable):
Modified: python/branches/p3yk-noslice/Lib/test/test_itertools.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_itertools.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_itertools.py Fri Feb 23 18:29:35 2007
@@ -55,8 +55,7 @@
self.assertEqual(take(2, lzip('abc',count(3))), [('a', 3), ('b', 4)])
self.assertRaises(TypeError, count, 2, 3)
self.assertRaises(TypeError, count, 'a')
- c = count(sys.maxint-2) # verify that rollover doesn't crash
- c.next(); c.next(); c.next(); c.next(); c.next()
+ self.assertRaises(OverflowError, list, islice(count(sys.maxint-5), 10))
c = count(3)
self.assertEqual(repr(c), 'count(3)')
c.next()
@@ -203,6 +202,51 @@
ids = map(id, list(izip('abc', 'def')))
self.assertEqual(len(dict.fromkeys(ids)), len(ids))
+ def test_iziplongest(self):
+ for args in [
+ ['abc', range(6)],
+ [range(6), 'abc'],
+ [range(1000), range(2000,2100), range(3000,3050)],
+ [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
+ [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
+ ]:
+ target = map(None, *args)
+ self.assertEqual(list(izip_longest(*args)), target)
+ self.assertEqual(list(izip_longest(*args, **{})), target)
+ target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X'
+ self.assertEqual(list(izip_longest(*args, **dict(fillvalue='X'))), target)
+
+ self.assertEqual(take(3,izip_longest('abcdef', count())), list(zip('abcdef', range(3)))) # take 3 from infinite input
+
+ self.assertEqual(list(izip_longest()), list(zip()))
+ self.assertEqual(list(izip_longest([])), list(zip([])))
+ self.assertEqual(list(izip_longest('abcdef')), list(zip('abcdef')))
+
+ self.assertEqual(list(izip_longest('abc', 'defg', **{})), map(None, 'abc', 'defg')) # empty keyword dict
+ self.assertRaises(TypeError, izip_longest, 3)
+ self.assertRaises(TypeError, izip_longest, range(3), 3)
+
+ for stmt in [
+ "izip_longest('abc', fv=1)",
+ "izip_longest('abc', fillvalue=1, bogus_keyword=None)",
+ ]:
+ try:
+ eval(stmt, globals(), locals())
+ except TypeError:
+ pass
+ else:
+ self.fail('Did not raise Type in: ' + stmt)
+
+ # Check tuple re-use (implementation detail)
+ self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')],
+ list(zip('abc', 'def')))
+ self.assertEqual([pair for pair in izip_longest('abc', 'def')],
+ list(zip('abc', 'def')))
+ ids = map(id, izip_longest('abc', 'def'))
+ self.assertEqual(min(ids), max(ids))
+ ids = map(id, list(izip_longest('abc', 'def')))
+ self.assertEqual(len(dict.fromkeys(ids)), len(ids))
+
def test_repeat(self):
self.assertEqual(lzip(xrange(3),repeat('a')),
[(0, 'a'), (1, 'a'), (2, 'a')])
@@ -616,6 +660,15 @@
self.assertRaises(TypeError, izip, N(s))
self.assertRaises(ZeroDivisionError, list, izip(E(s)))
+ def test_iziplongest(self):
+ for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
+ for g in (G, I, Ig, S, L, R):
+ self.assertEqual(list(izip_longest(g(s))), list(zip(g(s))))
+ self.assertEqual(list(izip_longest(g(s), g(s))), list(zip(g(s), g(s))))
+ self.assertRaises(TypeError, izip_longest, X(s))
+ self.assertRaises(TypeError, izip_longest, N(s))
+ self.assertRaises(ZeroDivisionError, list, izip_longest(E(s)))
+
def test_imap(self):
for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
for g in (G, I, Ig, S, L, R):
@@ -744,29 +797,44 @@
self.assertRaises(AssertionError, list, cycle(gen1()))
self.assertEqual(hist, [0,1])
+class SubclassWithKwargsTest(unittest.TestCase):
+ def test_keywords_in_subclass(self):
+ # count is not subclassable...
+ for cls in (repeat, izip, ifilter, ifilterfalse, chain, imap,
+ starmap, islice, takewhile, dropwhile, cycle):
+ class Subclass(cls):
+ def __init__(self, newarg=None, *args):
+ cls.__init__(self, *args)
+ try:
+ Subclass(newarg=1)
+ except TypeError as err:
+ # we expect type errors because of wrong argument count
+ self.failIf("does not take keyword arguments" in err.args[0])
+
+
libreftest = """ Doctest for examples in the library reference: libitertools.tex
>>> 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
Check 1202 is for $823.14
>>> import operator
>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
-... print cube
-...
+... print(cube)
+...
1
8
27
>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
>>> for name in islice(reportlines, 3, None, 2):
-... print name.title()
-...
+... print(name.title())
+...
Alex
Laura
Martin
@@ -775,10 +843,10 @@
>>> from operator import itemgetter
>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
->>> di = sorted(sorted(d.iteritems()), key=itemgetter(1))
+>>> di = sorted(sorted(d.items()), key=itemgetter(1))
>>> for k, g in groupby(di, itemgetter(1)):
-... print k, map(itemgetter(0), g)
-...
+... print(k, map(itemgetter(0), g))
+...
1 ['a', 'c', 'e']
2 ['b', 'd', 'f']
3 ['g']
@@ -788,8 +856,8 @@
# 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 (i,x):i-x):
-... print map(operator.itemgetter(1), g)
-...
+... print(map(operator.itemgetter(1), g))
+...
[1]
[4, 5, 6]
[10]
@@ -808,7 +876,7 @@
... return imap(function, count())
>>> def iteritems(mapping):
-... return izip(mapping.iterkeys(), mapping.itervalues())
+... return izip(mapping.keys(), mapping.values())
>>> def nth(iterable, n):
... "Returns the nth item"
@@ -938,7 +1006,8 @@
def test_main(verbose=None):
test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC,
- RegressionTests, LengthTransparency)
+ RegressionTests, LengthTransparency,
+ SubclassWithKwargsTest)
test_support.run_unittest(*test_classes)
# verify reference counting
@@ -949,7 +1018,7 @@
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
# doctest the examples in the library reference
test_support.run_doctest(sys.modules[__name__], verbose)
Modified: python/branches/p3yk-noslice/Lib/test/test_largefile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_largefile.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_largefile.py Fri Feb 23 18:29:35 2007
@@ -19,7 +19,7 @@
# create >2GB file (2GB = 2147483648 bytes)
-size = 2500000000L
+size = 2500000000
name = test_support.TESTFN
@@ -37,7 +37,7 @@
f = open(test_support.TESTFN, 'wb')
try:
# 2**31 == 2147483648
- f.seek(2147483649L)
+ f.seek(2147483649)
# Seeking is not enough of a test: you must write and flush, too!
f.write("x")
f.flush()
@@ -52,22 +52,22 @@
def expect(got_this, expect_this):
if test_support.verbose:
- print '%r =?= %r ...' % (got_this, expect_this),
+ print('%r =?= %r ...' % (got_this, expect_this), end=' ')
if got_this != expect_this:
if test_support.verbose:
- print 'no'
+ print('no')
raise test_support.TestFailed, 'got %r, but expected %r' %\
(got_this, expect_this)
else:
if test_support.verbose:
- print 'yes'
+ print('yes')
# test that each file function works as expected for a large (i.e. >2GB, do
# we have to check >4GB) files
if test_support.verbose:
- print 'create large file via seek (may be sparse file) ...'
+ print('create large file via seek (may be sparse file) ...')
f = open(name, 'wb')
try:
f.write('z')
@@ -76,16 +76,16 @@
f.write('a')
f.flush()
if test_support.verbose:
- print 'check file size with os.fstat'
+ print('check file size with os.fstat')
expect(os.fstat(f.fileno())[stat.ST_SIZE], size+1)
finally:
f.close()
if test_support.verbose:
- print 'check file size with os.stat'
+ print('check file size with os.stat')
expect(os.stat(name)[stat.ST_SIZE], size+1)
if test_support.verbose:
- print 'play around with seek() and read() with the built largefile'
+ print('play around with seek() and read() with the built largefile')
f = open(name, 'rb')
try:
expect(f.tell(), 0)
@@ -119,7 +119,7 @@
f.close()
if test_support.verbose:
- print 'play around with os.lseek() with the built largefile'
+ print('play around with os.lseek() with the built largefile')
f = open(name, 'rb')
try:
expect(os.lseek(f.fileno(), 0, 0), 0)
@@ -136,7 +136,7 @@
if hasattr(f, 'truncate'):
if test_support.verbose:
- print 'try truncate'
+ print('try truncate')
f = open(name, 'r+b')
try:
f.seek(0, 2)
Modified: python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_linuxaudiodev.py Fri Feb 23 18:29:35 2007
@@ -22,7 +22,7 @@
fp.close()
if enc != SND_FORMAT_MULAW_8:
- print "Expect .au file with 8-bit mu-law samples"
+ print("Expect .au file with 8-bit mu-law samples")
return
try:
@@ -63,27 +63,27 @@
try:
a.setparameters(-1, size, nchannels, fmt)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, -2, nchannels, fmt)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, size, 3, fmt)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, size, nchannels, 177)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, size, nchannels, linuxaudiodev.AFMT_U16_LE)
except ValueError as msg:
- print msg
+ print(msg)
try:
a.setparameters(rate, 16, nchannels, fmt)
except ValueError as msg:
- print msg
+ print(msg)
def test():
play_sound_file(findfile('audiotest.au'))
Modified: python/branches/p3yk-noslice/Lib/test/test_list.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_list.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_list.py Fri Feb 23 18:29:35 2007
@@ -30,7 +30,7 @@
test_support.run_unittest(ListTest)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
Modified: python/branches/p3yk-noslice/Lib/test/test_locale.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_locale.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_locale.py Fri Feb 23 18:29:35 2007
@@ -23,19 +23,19 @@
def testformat(formatstr, value, grouping = 0, output=None, func=locale.format):
if verbose:
if output:
- print "%s %% %s =? %s ..." %\
- (repr(formatstr), repr(value), repr(output)),
+ print("%s %% %s =? %s ..." %\
+ (repr(formatstr), repr(value), repr(output)), end=' ')
else:
- print "%s %% %s works? ..." % (repr(formatstr), repr(value)),
+ print("%s %% %s works? ..." % (repr(formatstr), repr(value)), end=' ')
result = func(formatstr, value, grouping = grouping)
if output and result != output:
if verbose:
- print 'no'
- print "%s %% %s == %s != %s" %\
- (repr(formatstr), repr(value), repr(result), repr(output))
+ print('no')
+ print("%s %% %s == %s != %s" %\
+ (repr(formatstr), repr(value), repr(result), repr(output)))
else:
if verbose:
- print "yes"
+ print("yes")
try:
# On Solaris 10, the thousands_sep is the empty string
@@ -80,15 +80,15 @@
# Test BSD Rune locale's bug for isctype functions.
def teststrop(s, method, output):
if verbose:
- print "%s.%s() =? %s ..." % (repr(s), method, repr(output)),
+ print("%s.%s() =? %s ..." % (repr(s), method, repr(output)), end=' ')
result = getattr(s, method)()
if result != output:
if verbose:
- print "no"
- print "%s.%s() == %s != %s" % (repr(s), method, repr(result),
- repr(output))
+ print("no")
+ print("%s.%s() == %s != %s" % (repr(s), method, repr(result),
+ repr(output)))
elif verbose:
- print "yes"
+ print("yes")
try:
if sys.platform == 'sunos5':
Modified: python/branches/p3yk-noslice/Lib/test/test_long.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_long.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_long.py Fri Feb 23 18:29:35 2007
@@ -23,11 +23,11 @@
MAXDIGITS = 15
# build some special values
-special = map(long, [0, 1, 2, BASE, BASE >> 1])
-special.append(0x5555555555555555L)
-special.append(0xaaaaaaaaaaaaaaaaL)
+special = map(int, [0, 1, 2, BASE, BASE >> 1])
+special.append(0x5555555555555555)
+special.append(0xaaaaaaaaaaaaaaaa)
# some solid strings of one bits
-p2 = 4L # 0 and 1 already added
+p2 = 4 # 0 and 1 already added
for i in range(2*SHIFT):
special.append(p2 - 1)
p2 = p2 << 1
@@ -49,7 +49,7 @@
self.assert_(ndigits > 0)
nbits_hi = ndigits * SHIFT
nbits_lo = nbits_hi - SHIFT + 1
- answer = 0L
+ answer = 0
nbits = 0
r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start
while nbits < nbits_lo:
@@ -70,7 +70,7 @@
# BASE). The sign bit is also random.
def getran2(ndigits):
- answer = 0L
+ answer = 0
for i in xrange(ndigits):
answer = (answer << SHIFT) | random.randint(0, MASK)
if random.random() < 0.5:
@@ -98,7 +98,7 @@
for lenx in digits:
x = self.getran(lenx)
for leny in digits:
- y = self.getran(leny) or 1L
+ y = self.getran(leny) or 1
self.check_division(x, y)
def test_karatsuba(self):
@@ -110,15 +110,15 @@
# Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) ==
# 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check.
for abits in bits:
- a = (1L << abits) - 1
+ a = (1 << abits) - 1
for bbits in bits:
if bbits < abits:
continue
- b = (1L << bbits) - 1
+ b = (1 << bbits) - 1
x = a * b
- y = ((1L << (abits + bbits)) -
- (1L << abits) -
- (1L << bbits) +
+ y = ((1 << (abits + bbits)) -
+ (1 << abits) -
+ (1 << bbits) +
1)
self.assertEqual(x, y,
Frm("bad result for a*b: a=%r, b=%r, x=%r, y=%r", a, b, x, y))
@@ -141,7 +141,7 @@
eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x))
eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x))
for n in xrange(2*SHIFT):
- p2 = 2L ** n
+ p2 = 2 ** n
eq(x << n >> n, x,
Frm("x << n >> n != x for x=%r, n=%r", (x, n)))
eq(x // p2, x >> n,
@@ -217,7 +217,7 @@
msg = Frm("%s returned %r but expected %r for %r",
mapper.__name__, got, expected, x)
self.assertEqual(got, expected, msg)
- self.assertEqual(long(got, 0), x, Frm('long("%s", 0) != %r', got, x))
+ self.assertEqual(int(got, 0), x, Frm('long("%s", 0) != %r', got, x))
# str() has to be checked a little differently since there's no
# trailing "L"
got = str(x)
@@ -240,8 +240,8 @@
# check the extremes in int<->long conversion
hugepos = sys.maxint
hugeneg = -hugepos - 1
- hugepos_aslong = long(hugepos)
- hugeneg_aslong = long(hugeneg)
+ hugepos_aslong = int(hugepos)
+ hugeneg_aslong = int(hugeneg)
self.assertEqual(hugepos, hugepos_aslong, "long(sys.maxint) != sys.maxint")
self.assertEqual(hugeneg, hugeneg_aslong,
"long(-sys.maxint-1) != -sys.maxint-1")
@@ -270,7 +270,7 @@
y = int(x)
except OverflowError:
self.fail("int(long(sys.maxint) + 1) mustn't overflow")
- self.assert_(isinstance(y, long),
+ self.assert_(isinstance(y, int),
"int(long(sys.maxint) + 1) should have returned long")
x = hugeneg_aslong - 1
@@ -278,17 +278,16 @@
y = int(x)
except OverflowError:
self.fail("int(long(-sys.maxint-1) - 1) mustn't overflow")
- self.assert_(isinstance(y, long),
+ self.assert_(isinstance(y, int),
"int(long(-sys.maxint-1) - 1) should have returned long")
- class long2(long):
+ class long2(int):
pass
- x = long2(1L<<100)
+ x = long2(1<<100)
y = int(x)
- self.assert_(type(y) is long,
+ self.assert_(type(y) is int,
"overflowing int conversion must return long not long subtype")
-
# ----------------------------------- tests of auto int->long conversion
def test_auto_overflow(self):
@@ -305,14 +304,14 @@
Frm("for %r expected %r got %r", args, expected, got))
for x in special:
- longx = long(x)
+ longx = int(x)
expected = -longx
got = -x
checkit('-', x)
for y in special:
- longy = long(y)
+ longy = int(y)
expected = longx + longy
got = x + y
@@ -347,20 +346,20 @@
for z in special:
if z != 0 :
if y >= 0:
- expected = pow(longx, longy, long(z))
+ expected = pow(longx, longy, int(z))
got = pow(x, y, z)
checkit('pow', x, y, '%', z)
else:
- self.assertRaises(TypeError, pow,longx, longy, long(z))
+ self.assertRaises(TypeError, pow,longx, longy, int(z))
def test_float_overflow(self):
import math
for x in -2.0, -1.0, 0.0, 1.0, 2.0:
- self.assertEqual(float(long(x)), x)
+ self.assertEqual(float(int(x)), x)
shuge = '12345' * 120
- huge = 1L << 30000
+ huge = 1 << 30000
mhuge = -huge
namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math}
for test in ["float(huge)", "float(mhuge)",
@@ -400,7 +399,7 @@
log = math.log(value)
self.assertAlmostEqual(log, expected)
- for bad in -(1L << 10000), -2L, 0L:
+ for bad in -(1 << 10000), -2, 0:
self.assertRaises(ValueError, math.log, bad)
self.assertRaises(ValueError, math.log10, bad)
@@ -416,7 +415,7 @@
# represents all Python ints, longs and floats exactly).
class Rat:
def __init__(self, value):
- if isinstance(value, (int, long)):
+ if isinstance(value, (int, int)):
self.n = value
self.d = 1
elif isinstance(value, float):
@@ -465,12 +464,12 @@
# important boundary for IEEE double precision.
for t in 2.0**48, 2.0**50, 2.0**53:
cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
- long(t-1), long(t), long(t+1)])
+ int(t-1), int(t), int(t+1)])
cases.extend([0, 1, 2, sys.maxint, float(sys.maxint)])
# 1L<<20000 should exceed all double formats. long(1e200) is to
# check that we get equality with 1e200 above.
- t = long(1e200)
- cases.extend([0L, 1L, 2L, 1L << 20000, t-1, t, t+1])
+ t = int(1e200)
+ cases.extend([0, 1, 2, 1 << 20000, t-1, t, t+1])
cases.extend([-x for x in cases])
for x in cases:
Rx = Rat(x)
Modified: python/branches/p3yk-noslice/Lib/test/test_long_future.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_long_future.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_long_future.py Fri Feb 23 18:29:35 2007
@@ -7,17 +7,17 @@
def test_true_division():
if verbose:
- print "long true division"
- huge = 1L << 40000
+ print("long true division")
+ huge = 1 << 40000
mhuge = -huge
verify(huge / huge == 1.0)
verify(mhuge / mhuge == 1.0)
verify(huge / mhuge == -1.0)
verify(mhuge / huge == -1.0)
verify(1 / huge == 0.0)
- verify(1L / huge == 0.0)
+ verify(1 / huge == 0.0)
+ verify(1 / mhuge == 0.0)
verify(1 / mhuge == 0.0)
- verify(1L / mhuge == 0.0)
verify((666 * huge + (huge >> 1)) / huge == 666.5)
verify((666 * mhuge + (mhuge >> 1)) / mhuge == 666.5)
verify((666 * huge + (huge >> 1)) / mhuge == -666.5)
@@ -28,8 +28,8 @@
namespace = {'huge': huge, 'mhuge': mhuge}
for overflow in ["float(huge)", "float(mhuge)",
- "huge / 1", "huge / 2L", "huge / -1", "huge / -2L",
- "mhuge / 100", "mhuge / 100L"]:
+ "huge / 1", "huge / 2", "huge / -1", "huge / -2",
+ "mhuge / 100", "mhuge / 100"]:
try:
eval(overflow, namespace)
except OverflowError:
@@ -37,14 +37,14 @@
else:
raise TestFailed("expected OverflowError from %r" % overflow)
- for underflow in ["1 / huge", "2L / huge", "-1 / huge", "-2L / huge",
- "100 / mhuge", "100L / mhuge"]:
+ for underflow in ["1 / huge", "2 / huge", "-1 / huge", "-2 / huge",
+ "100 / mhuge", "100 / mhuge"]:
result = eval(underflow, namespace)
if result != 0.0:
raise TestFailed("expected underflow to 0 from %r" % underflow)
- for zero in ["huge / 0", "huge / 0L",
- "mhuge / 0", "mhuge / 0L"]:
+ for zero in ["huge / 0", "huge / 0",
+ "mhuge / 0", "mhuge / 0"]:
try:
eval(zero, namespace)
except ZeroDivisionError:
Modified: python/branches/p3yk-noslice/Lib/test/test_mailbox.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_mailbox.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_mailbox.py Fri Feb 23 18:29:35 2007
@@ -4,7 +4,7 @@
import stat
import socket
import email
-import email.Message
+import email.message
import rfc822
import re
import StringIO
@@ -22,15 +22,15 @@
def _check_sample(self, msg):
# Inspect a mailbox.Message representation of the sample message
- self.assert_(isinstance(msg, email.Message.Message))
+ self.assert_(isinstance(msg, email.message.Message))
self.assert_(isinstance(msg, mailbox.Message))
- for key, value in _sample_headers.iteritems():
+ for key, value in _sample_headers.items():
self.assert_(value in msg.get_all(key))
self.assert_(msg.is_multipart())
self.assert_(len(msg.get_payload()) == len(_sample_payloads))
for i, payload in enumerate(_sample_payloads):
part = msg.get_payload(i)
- self.assert_(isinstance(part, email.Message.Message))
+ self.assert_(isinstance(part, email.message.Message))
self.assert_(not isinstance(part, mailbox.Message))
self.assert_(part.get_payload() == payload)
@@ -174,7 +174,7 @@
def test_iterkeys(self):
# Get keys using iterkeys()
- self._check_iteration(self._box.iterkeys, do_keys=True, do_values=False)
+ self._check_iteration(self._box.keys, do_keys=True, do_values=False)
def test_keys(self):
# Get keys using keys()
@@ -182,7 +182,7 @@
def test_itervalues(self):
# Get values using itervalues()
- self._check_iteration(self._box.itervalues, do_keys=False,
+ self._check_iteration(self._box.values, do_keys=False,
do_values=True)
def test_iter(self):
@@ -196,7 +196,7 @@
def test_iteritems(self):
# Get keys and values using iteritems()
- self._check_iteration(self._box.iteritems, do_keys=True,
+ self._check_iteration(self._box.items, do_keys=True,
do_values=True)
def test_items(self):
@@ -424,12 +424,12 @@
self.assertRaises(NotImplementedError, lambda: box.__delitem__(''))
self.assertRaises(NotImplementedError, lambda: box.discard(''))
self.assertRaises(NotImplementedError, lambda: box.__setitem__('', ''))
- self.assertRaises(NotImplementedError, lambda: box.iterkeys())
self.assertRaises(NotImplementedError, lambda: box.keys())
- self.assertRaises(NotImplementedError, lambda: box.itervalues().next())
+ self.assertRaises(NotImplementedError, lambda: box.keys())
+ self.assertRaises(NotImplementedError, lambda: box.values().next())
self.assertRaises(NotImplementedError, lambda: box.__iter__().next())
self.assertRaises(NotImplementedError, lambda: box.values())
- self.assertRaises(NotImplementedError, lambda: box.iteritems().next())
+ self.assertRaises(NotImplementedError, lambda: box.items().next())
self.assertRaises(NotImplementedError, lambda: box.items())
self.assertRaises(NotImplementedError, lambda: box.get(''))
self.assertRaises(NotImplementedError, lambda: box.__getitem__(''))
@@ -674,11 +674,11 @@
box = self._factory(self._path, factory=dummy_factory)
folder = box.add_folder('folder1')
self.assert_(folder._factory is dummy_factory)
-
+
folder1_alias = box.get_folder('folder1')
self.assert_(folder1_alias._factory is dummy_factory)
-
+
class _TestMboxMMDF(TestMailbox):
@@ -709,7 +709,7 @@
mtime = os.path.getmtime(self._path)
self._box = self._factory(self._path)
self.assert_(len(self._box) == 3)
- for key in self._box.iterkeys():
+ for key in self._box.keys():
self.assert_(self._box.get_string(key) in values)
self._box.close()
self.assert_(mtime == os.path.getmtime(self._path))
@@ -798,7 +798,7 @@
def dummy_factory (s):
return None
self._box = self._factory(self._path, dummy_factory)
-
+
new_folder = self._box.add_folder('foo.bar')
folder0 = self._box.get_folder('foo.bar')
folder0.add(self._template % 'bar')
@@ -894,7 +894,7 @@
self.assert_(self._box.get_sequences() ==
{'foo':[1, 2, 3, 4, 5],
'unseen':[1], 'bar':[3], 'replied':[3]})
-
+
def _get_lock_path(self):
return os.path.join(self._path, '.mh_sequences.lock')
@@ -939,7 +939,7 @@
self._delete_recursively(self._path)
def test_initialize_with_eMM(self):
- # Initialize based on email.Message.Message instance
+ # Initialize based on email.message.Message instance
eMM = email.message_from_string(_sample_message)
msg = self._factory(eMM)
self._post_initialize_hook(msg)
@@ -965,7 +965,7 @@
# Initialize without arguments
msg = self._factory()
self._post_initialize_hook(msg)
- self.assert_(isinstance(msg, email.Message.Message))
+ self.assert_(isinstance(msg, email.message.Message))
self.assert_(isinstance(msg, mailbox.Message))
self.assert_(isinstance(msg, self._factory))
self.assert_(msg.keys() == [])
@@ -992,7 +992,7 @@
mailbox.BabylMessage, mailbox.MMDFMessage):
other_msg = class_()
msg._explain_to(other_msg)
- other_msg = email.Message.Message()
+ other_msg = email.message.Message()
self.assertRaises(TypeError, lambda: msg._explain_to(other_msg))
def _post_initialize_hook(self, msg):
@@ -1732,11 +1732,11 @@
def test_unix_mbox(self):
### should be better!
- import email.Parser
+ import email.parser
fname = self.createMessage("cur", True)
n = 0
for msg in mailbox.PortableUnixMailbox(open(fname),
- email.Parser.Parser().parse):
+ email.parser.Parser().parse):
n += 1
self.assertEqual(msg["subject"], "Simple Test")
self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE))
Modified: python/branches/p3yk-noslice/Lib/test/test_marshal.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_marshal.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_marshal.py Fri Feb 23 18:29:35 2007
@@ -33,7 +33,7 @@
value >>= 8
return ''.join(bytes)
- maxint64 = (1L << 63) - 1
+ maxint64 = (1 << 63) - 1
minint64 = -maxint64-1
for base in maxint64, minint64, -maxint64, -(minint64 >> 1):
@@ -152,7 +152,7 @@
d = {'astring': 'foo at bar.baz.spam',
'afloat': 7283.43,
'anint': 2**20,
- 'ashortlong': 2L,
+ 'ashortlong': 2,
'alist': ['.zyx.41'],
'atuple': ('.zyx.41',)*10,
'aboolean': False,
@@ -167,7 +167,7 @@
os.unlink(test_support.TESTFN)
def test_list(self):
- lst = self.d.items()
+ lst = list(self.d.items())
new = marshal.loads(marshal.dumps(lst))
self.assertEqual(lst, new)
marshal.dump(lst, open(test_support.TESTFN, "wb"))
@@ -204,7 +204,7 @@
def test_patch_873224(self):
self.assertRaises(Exception, marshal.loads, '0')
self.assertRaises(Exception, marshal.loads, 'f')
- self.assertRaises(Exception, marshal.loads, marshal.dumps(5L)[:-1])
+ self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1])
def test_version_argument(self):
# Python 2.4.0 crashes for any call to marshal.dumps(x, y)
Modified: python/branches/p3yk-noslice/Lib/test/test_mhlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_mhlib.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_mhlib.py Fri Feb 23 18:29:35 2007
@@ -46,7 +46,7 @@
return r
def writeProfile(dict):
- contents = [ "%s: %s\n" % (k, v) for k, v in dict.iteritems() ]
+ contents = [ "%s: %s\n" % (k, v) for k, v in dict.items() ]
writeFile(_mhprofile, "".join(contents))
def writeContext(folder):
@@ -61,7 +61,7 @@
def writeMessage(folder, n, headers, body):
folder = normF(folder)
- headers = "".join([ "%s: %s\n" % (k, v) for k, v in headers.iteritems() ])
+ headers = "".join([ "%s: %s\n" % (k, v) for k, v in headers.items() ])
contents = "%s\n%s\n" % (headers,body)
mkdirs(os.path.join(_mhpath, folder))
writeFile(os.path.join(_mhpath, folder, str(n)), contents)
Modified: python/branches/p3yk-noslice/Lib/test/test_minidom.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_minidom.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_minidom.py Fri Feb 23 18:29:35 2007
@@ -24,7 +24,7 @@
def confirm(test, testname = "Test"):
if not test:
- print "Failed " + testname
+ print("Failed " + testname)
raise Exception
def testParseFromFile():
@@ -140,29 +140,29 @@
try: dom.appendChild(text)
except xml.dom.HierarchyRequestErr: pass
else:
- print "dom.appendChild didn't raise HierarchyRequestErr"
+ print("dom.appendChild didn't raise HierarchyRequestErr")
dom.appendChild(elem)
try: dom.insertBefore(text, elem)
except xml.dom.HierarchyRequestErr: pass
else:
- print "dom.appendChild didn't raise HierarchyRequestErr"
+ print("dom.appendChild didn't raise HierarchyRequestErr")
try: dom.replaceChild(text, elem)
except xml.dom.HierarchyRequestErr: pass
else:
- print "dom.appendChild didn't raise HierarchyRequestErr"
+ print("dom.appendChild didn't raise HierarchyRequestErr")
nodemap = elem.attributes
try: nodemap.setNamedItem(text)
except xml.dom.HierarchyRequestErr: pass
else:
- print "NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr"
+ print("NamedNodeMap.setNamedItem didn't raise HierarchyRequestErr")
try: nodemap.setNamedItemNS(text)
except xml.dom.HierarchyRequestErr: pass
else:
- print "NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr"
+ print("NamedNodeMap.setNamedItemNS didn't raise HierarchyRequestErr")
elem.appendChild(text)
dom.unlink()
@@ -457,8 +457,8 @@
except xml.dom.HierarchyRequestErr:
pass
else:
- print "Failed to catch expected exception when" \
- " adding extra document element."
+ print("Failed to catch expected exception when" \
+ " adding extra document element.")
elem.unlink()
doc.unlink()
@@ -565,10 +565,8 @@
def _testCloneElementCopiesAttributes(e1, e2, test):
attrs1 = e1.attributes
attrs2 = e2.attributes
- keys1 = attrs1.keys()
- keys2 = attrs2.keys()
- keys1.sort()
- keys2.sort()
+ keys1 = sorted(attrs1.keys())
+ keys2 = sorted(attrs2.keys())
confirm(keys1 == keys2, "clone of element has same attribute keys")
for i in range(len(keys1)):
a1 = attrs1.item(i)
@@ -896,7 +894,7 @@
except UnicodeDecodeError:
pass
else:
- print 'parsing with bad encoding should raise a UnicodeDecodeError'
+ print('parsing with bad encoding should raise a UnicodeDecodeError')
doc.unlink()
@@ -1008,7 +1006,7 @@
except xml.dom.NamespaceErr:
pass
else:
- print "expected NamespaceErr"
+ print("expected NamespaceErr")
checkRenameNodeSharedConstraints(doc, attr)
doc.unlink()
@@ -1063,7 +1061,7 @@
except xml.dom.NamespaceErr:
pass
else:
- print "expected NamespaceErr"
+ print("expected NamespaceErr")
doc2 = parseString("<doc/>")
try:
@@ -1071,7 +1069,7 @@
except xml.dom.WrongDocumentErr:
pass
else:
- print "expected WrongDocumentErr"
+ print("expected WrongDocumentErr")
def testRenameOther():
# We have to create a comment node explicitly since not all DOM
@@ -1084,7 +1082,7 @@
except xml.dom.NotSupportedErr:
pass
else:
- print "expected NotSupportedErr when renaming comment node"
+ print("expected NotSupportedErr when renaming comment node")
doc.unlink()
def checkWholeText(node, s):
@@ -1351,8 +1349,7 @@
# --- MAIN PROGRAM
-names = globals().keys()
-names.sort()
+names = sorted(globals().keys())
failed = []
@@ -1368,13 +1365,13 @@
confirm(len(Node.allnodes) == 0,
"assertion: len(Node.allnodes) == 0")
if len(Node.allnodes):
- print "Garbage left over:"
+ print("Garbage left over:")
if verbose:
- print Node.allnodes.items()[0:10]
+ print(Node.allnodes.items()[0:10])
else:
# Don't print specific nodes if repeatable results
# are needed
- print len(Node.allnodes)
+ print(len(Node.allnodes))
Node.allnodes = {}
for name in names:
@@ -1385,13 +1382,13 @@
check_allnodes()
except:
failed.append(name)
- print "Test Failed: ", name
+ print("Test Failed: ", name)
sys.stdout.flush()
traceback.print_exception(*sys.exc_info())
- print repr(sys.exc_info()[1])
+ print(repr(sys.exc_info()[1]))
Node.allnodes = {}
if failed:
- print "\n\n\n**** Check for failures in these tests:"
+ print("\n\n\n**** Check for failures in these tests:")
for name in failed:
- print " " + name
+ print(" " + name)
Modified: python/branches/p3yk-noslice/Lib/test/test_module.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_module.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_module.py Fri Feb 23 18:29:35 2007
@@ -45,4 +45,4 @@
verify(foo.__dict__ is d)
if verbose:
- print "All OK"
+ print("All OK")
Modified: python/branches/p3yk-noslice/Lib/test/test_multibytecodec.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_multibytecodec.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_multibytecodec.py Fri Feb 23 18:29:35 2007
@@ -48,7 +48,7 @@
def test_codingspec(self):
try:
for enc in ALL_CJKENCODINGS:
- print >> open(TESTFN, 'w'), '# coding:', enc
+ print('# coding:', enc, file=open(TESTFN, 'w'))
execfile(TESTFN)
finally:
os.unlink(TESTFN)
Modified: python/branches/p3yk-noslice/Lib/test/test_multibytecodec_support.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_multibytecodec_support.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_multibytecodec_support.py Fri Feb 23 18:29:35 2007
@@ -98,7 +98,7 @@
def test_callback_long_index(self):
def myreplace(exc):
- return (u'x', long(exc.end))
+ return (u'x', int(exc.end))
codecs.register_error("test.cjktest", myreplace)
self.assertEqual(self.encode(u'abcd' + self.unmappedunicode + u'efgh',
'test.cjktest'), ('abcdxefgh', 9))
Modified: python/branches/p3yk-noslice/Lib/test/test_mutants.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_mutants.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_mutants.py Fri Feb 23 18:29:35 2007
@@ -116,7 +116,7 @@
for i in xrange(numentries):
d[Horrid(random.choice(candidates))] = \
Horrid(random.choice(candidates))
- return d.keys()
+ return list(d.keys())
# Test one pair of randomly generated dicts, each with n entries.
# Note that dict comparison is trivial if they don't have the same number
@@ -135,13 +135,13 @@
# same size.
mutate = 1
if verbose:
- print "trying w/ lengths", len(dict1), len(dict2),
+ print("trying w/ lengths", len(dict1), len(dict2), end=' ')
while dict1 and len(dict1) == len(dict2):
if verbose:
- print ".",
+ print(".", end=' ')
c = dict1 == dict2
if verbose:
- print
+ print()
# Run test_one n times. At the start (before the bugs were fixed), 20
# consecutive runs of this test each blew up on or before the sixth time
@@ -186,7 +186,7 @@
# the expected-output file doesn't need to change.
f = open(TESTFN, "w")
-print >> f, Parent().__dict__
+print(Parent().__dict__, file=f)
f.close()
os.unlink(TESTFN)
@@ -207,7 +207,7 @@
# Michael sez: "doesn't crash without this. don't know why."
# Tim sez: "luck of the draw; crashes with or without for me."
- print >> f
+ print(file=f)
return repr("machiavelli")
@@ -216,7 +216,7 @@
dict[Machiavelli()] = Machiavelli()
-print >> f, str(dict)
+print(str(dict), file=f)
f.close()
os.unlink(TESTFN)
del f, dict
@@ -280,7 +280,7 @@
f = open(TESTFN, "w")
try:
try:
- print >> f, dict[Machiavelli3(2)]
+ print(dict[Machiavelli3(2)], file=f)
except KeyError:
pass
finally:
Modified: python/branches/p3yk-noslice/Lib/test/test_new.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_new.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_new.py Fri Feb 23 18:29:35 2007
@@ -1,180 +1,158 @@
-from test.test_support import verbose, verify, TestFailed
-import sys
-import new
-
-class Eggs:
- def get_yolks(self):
- return self.yolks
-
-print 'new.module()'
-m = new.module('Spam')
-if verbose:
- print m
-m.Eggs = Eggs
-sys.modules['Spam'] = m
-import Spam
-
-def get_more_yolks(self):
- return self.yolks + 3
-
-print 'new.classobj()'
-C = new.classobj('Spam', (Spam.Eggs,), {'get_more_yolks': get_more_yolks})
-if verbose:
- print C
-
-def break_yolks(self):
- self.yolks = self.yolks - 2
-print 'new.instancemethod()'
-c = C()
-c.yolks = 3
-im = new.instancemethod(break_yolks, c, C)
-if verbose:
- print im
-
-verify(c.get_yolks() == 3 and c.get_more_yolks() == 6,
- 'Broken call of hand-crafted class instance')
-im()
-verify(c.get_yolks() == 1 and c.get_more_yolks() == 4,
- 'Broken call of hand-crafted instance method')
-
-im = new.instancemethod(break_yolks, c)
-im()
-verify(c.get_yolks() == -1)
-try:
- new.instancemethod(break_yolks, None)
-except TypeError:
- pass
-else:
- raise TestFailed, "dangerous instance method creation allowed"
-
-# Verify that instancemethod() doesn't allow keyword args
-try:
- new.instancemethod(break_yolks, c, kw=1)
-except TypeError:
- pass
-else:
- raise TestFailed, "instancemethod shouldn't accept keyword args"
-
-# It's unclear what the semantics should be for a code object compiled at
-# module scope, but bound and run in a function. In CPython, `c' is global
-# (by accident?) while in Jython, `c' is local. The intent of the test
-# clearly is to make `c' global, so let's be explicit about it.
-codestr = '''
-global c
-a = 1
-b = 2
-c = a + b
-'''
-
-ccode = compile(codestr, '<string>', 'exec')
-# Jython doesn't have a __builtins__, so use a portable alternative
-import __builtin__
-g = {'c': 0, '__builtins__': __builtin__}
-# this test could be more robust
-print 'new.function()'
-func = new.function(ccode, g)
-if verbose:
- print func
-func()
-verify(g['c'] == 3,
- 'Could not create a proper function object')
-
-# test the various extended flavors of function.new
-def f(x):
- def g(y):
- return x + y
- return g
-g = f(4)
-new.function(f.func_code, {}, "blah")
-g2 = new.function(g.func_code, {}, "blah", (2,), g.func_closure)
-verify(g2() == 6)
-g3 = new.function(g.func_code, {}, "blah", None, g.func_closure)
-verify(g3(5) == 9)
-def test_closure(func, closure, exc):
- try:
- new.function(func.func_code, {}, "", None, closure)
- except exc:
- pass
- else:
- print "corrupt closure accepted"
-
-test_closure(g, None, TypeError) # invalid closure
-test_closure(g, (1,), TypeError) # non-cell in closure
-test_closure(g, (1, 1), ValueError) # closure is wrong size
-test_closure(f, g.func_closure, ValueError) # no closure needed
-
-print 'new.code()'
-# bogus test of new.code()
-# Note: Jython will never have new.code()
-if hasattr(new, 'code'):
- def f(a): pass
-
- c = f.func_code
- argcount = c.co_argcount
- kwonlyargcount = c.co_kwonlyargcount
- nlocals = c.co_nlocals
- stacksize = c.co_stacksize
- flags = c.co_flags
- codestring = c.co_code
- constants = c.co_consts
- names = c.co_names
- varnames = c.co_varnames
- filename = c.co_filename
- name = c.co_name
- firstlineno = c.co_firstlineno
- lnotab = c.co_lnotab
- freevars = c.co_freevars
- cellvars = c.co_cellvars
-
- d = new.code(argcount, kwonlyargcount,
- nlocals, stacksize, flags, codestring,
- constants, names, varnames, filename, name,
- firstlineno, lnotab, freevars, cellvars)
-
- # test backwards-compatibility version with no freevars or cellvars
- d = new.code(argcount, kwonlyargcount,
- nlocals, stacksize, flags, codestring,
- constants, names, varnames, filename, name,
- firstlineno, lnotab)
-
- try: # this used to trigger a SystemError
- d = new.code(-argcount, kwonlyargcount,
- nlocals, stacksize, flags, codestring,
- constants, names, varnames, filename, name,
- firstlineno, lnotab)
- except ValueError:
- pass
- else:
- raise TestFailed, "negative co_argcount didn't trigger an exception"
-
- try: # this used to trigger a SystemError
- d = new.code(argcount, kwonlyargcount,
- -nlocals, stacksize, flags, codestring,
- constants, names, varnames, filename, name,
- firstlineno, lnotab)
- except ValueError:
- pass
- else:
- raise TestFailed, "negative co_nlocals didn't trigger an exception"
-
- try: # this used to trigger a Py_FatalError!
- d = new.code(argcount, kwonlyargcount,
- nlocals, stacksize, flags, codestring,
- constants, (5,), varnames, filename, name,
- firstlineno, lnotab)
- except TypeError:
- pass
- else:
- raise TestFailed, "non-string co_name didn't trigger an exception"
-
- # new.code used to be a way to mutate a tuple...
- class S(str): pass
- t = (S("ab"),)
- d = new.code(argcount, kwonlyargcount,
- nlocals, stacksize, flags, codestring,
- constants, t, varnames, filename, name,
- firstlineno, lnotab)
- verify(type(t[0]) is S, "eek, tuple changed under us!")
+import unittest
+from test import test_support
+import sys, new
+
+class NewTest(unittest.TestCase):
+ def test_spam(self):
+ class Eggs:
+ def get_yolks(self):
+ return self.yolks
+
+ m = new.module('Spam')
+ m.Eggs = Eggs
+ sys.modules['Spam'] = m
+ import Spam
+
+ def get_more_yolks(self):
+ return self.yolks + 3
+
+ # new.classobj()
+ C = new.classobj('Spam', (Spam.Eggs,), {'get_more_yolks': get_more_yolks})
+
+ def break_yolks(self):
+ self.yolks = self.yolks - 2
+
+ # new.instancemethod()
+ c = C()
+ c.yolks = 3
+ im = new.instancemethod(break_yolks, c, C)
+
+ self.assertEqual(c.get_yolks(), 3,
+ 'Broken call of hand-crafted class instance')
+ self.assertEqual(c.get_more_yolks(), 6,
+ 'Broken call of hand-crafted class instance')
+
+ im()
+ self.assertEqual(c.get_yolks(), 1,
+ 'Broken call of hand-crafted instance method')
+ self.assertEqual(c.get_more_yolks(), 4,
+ 'Broken call of hand-crafted instance method')
+
+ im = new.instancemethod(break_yolks, c)
+ im()
+ self.assertEqual(c.get_yolks(), -1)
+
+ # Verify that dangerous instance method creation is forbidden
+ self.assertRaises(TypeError, new.instancemethod, break_yolks, None)
+
+ # Verify that instancemethod() doesn't allow keyword args
+ self.assertRaises(TypeError, new.instancemethod, break_yolks, c, kw=1)
+
+ def test_scope(self):
+ # It's unclear what the semantics should be for a code object compiled
+ # at module scope, but bound and run in a function. In CPython, `c' is
+ # global (by accident?) while in Jython, `c' is local. The intent of
+ # the test clearly is to make `c' global, so let's be explicit about it.
+ codestr = '''
+ global c
+ a = 1
+ b = 2
+ c = a + b
+ '''
+
+ codestr = "\n".join(l.strip() for l in codestr.splitlines())
+
+ ccode = compile(codestr, '<string>', 'exec')
+ # Jython doesn't have a __builtins__, so use a portable alternative
+ import __builtin__
+ g = {'c': 0, '__builtins__': __builtin__}
+
+ # this test could be more robust
+ func = new.function(ccode, g)
+ func()
+ self.assertEqual(g['c'], 3, 'Could not create a proper function object')
+
+ def test_function(self):
+ # test the various extended flavors of function.new
+ def f(x):
+ def g(y):
+ return x + y
+ return g
+ g = f(4)
+ new.function(f.func_code, {}, "blah")
+ g2 = new.function(g.func_code, {}, "blah", (2,), g.func_closure)
+ self.assertEqual(g2(), 6)
+ g3 = new.function(g.func_code, {}, "blah", None, g.func_closure)
+ self.assertEqual(g3(5), 9)
+ def test_closure(func, closure, exc):
+ self.assertRaises(exc, new.function, func.func_code, {}, "", None, closure)
+
+ test_closure(g, None, TypeError) # invalid closure
+ test_closure(g, (1,), TypeError) # non-cell in closure
+ test_closure(g, (1, 1), ValueError) # closure is wrong size
+ test_closure(f, g.func_closure, ValueError) # no closure needed
+
+ # Note: Jython will never have new.code()
+ if hasattr(new, 'code'):
+ def test_code(self):
+ # bogus test of new.code()
+ def f(a): pass
+
+ c = f.func_code
+ argcount = c.co_argcount
+ kwonlyargcount = c.co_kwonlyargcount
+ nlocals = c.co_nlocals
+ stacksize = c.co_stacksize
+ flags = c.co_flags
+ codestring = c.co_code
+ constants = c.co_consts
+ names = c.co_names
+ varnames = c.co_varnames
+ filename = c.co_filename
+ name = c.co_name
+ firstlineno = c.co_firstlineno
+ lnotab = c.co_lnotab
+ freevars = c.co_freevars
+ cellvars = c.co_cellvars
+
+ d = new.code(argcount, kwonlyargcount, nlocals, stacksize, flags,
+ codestring, constants, names, varnames, filename,
+ name, firstlineno, lnotab, freevars, cellvars)
+
+ # test backwards-compatibility version with no freevars or cellvars
+ d = new.code(argcount, kwonlyargcount, nlocals, stacksize,
+ flags, codestring, constants, names, varnames,
+ filename, name, firstlineno, lnotab)
+
+ # negative co_argcount used to trigger a SystemError
+ self.assertRaises(ValueError, new.code,
+ -argcount, kwonlyargcount, nlocals, stacksize, flags,
+ codestring, constants, names, varnames, filename, name,
+ firstlineno, lnotab)
+
+ # negative co_nlocals used to trigger a SystemError
+ self.assertRaises(ValueError, new.code,
+ argcount, kwonlyargcount, -nlocals, stacksize, flags,
+ codestring, constants, names, varnames, filename, name,
+ firstlineno, lnotab)
+
+ # non-string co_name used to trigger a Py_FatalError
+ self.assertRaises(TypeError, new.code,
+ argcount, kwonlyargcount, nlocals, stacksize, flags,
+ codestring, constants, (5,), varnames, filename, name,
+ firstlineno, lnotab)
+
+ # new.code used to be a way to mutate a tuple...
+ class S(str):
+ pass
+ t = (S("ab"),)
+ d = new.code(argcount, kwonlyargcount, nlocals, stacksize,
+ flags, codestring, constants, t, varnames,
+ filename, name, firstlineno, lnotab)
+ self.assert_(type(t[0]) is S, "eek, tuple changed under us!")
- if verbose:
- print d
+def test_main():
+ test_support.run_unittest(NewTest)
+
+if __name__ == "__main__":
+ test_main()
Modified: python/branches/p3yk-noslice/Lib/test/test_normalization.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_normalization.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_normalization.py Fri Feb 23 18:29:35 2007
@@ -58,7 +58,7 @@
continue
if verbose:
- print line
+ print(line)
# Perform tests
verify(c2 == NFC(c1) == NFC(c2) == NFC(c3), line)
Modified: python/branches/p3yk-noslice/Lib/test/test_ntpath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_ntpath.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_ntpath.py Fri Feb 23 18:29:35 2007
@@ -9,11 +9,11 @@
fn = fn.replace("\\", "\\\\")
gotResult = eval(fn)
if wantResult != gotResult:
- print "error!"
- print "evaluated: " + str(fn)
- print "should be: " + str(wantResult)
- print " returned: " + str(gotResult)
- print ""
+ print("error!")
+ print("evaluated: " + str(fn))
+ print("should be: " + str(wantResult))
+ print(" returned: " + str(gotResult))
+ print("")
errors = errors + 1
tester('ntpath.splitext("foo.ext")', ('foo', '.ext'))
@@ -115,6 +115,28 @@
tester("ntpath.normpath('C:////a/b')", r'C:\a\b')
tester("ntpath.normpath('//machine/share//a/b')", r'\\machine\share\a\b')
+oldenv = os.environ.copy()
+try:
+ os.environ.clear()
+ os.environ["foo"] = "bar"
+ os.environ["{foo"] = "baz1"
+ os.environ["{foo}"] = "baz2"
+ tester('ntpath.expandvars("foo")', "foo")
+ tester('ntpath.expandvars("$foo bar")', "bar bar")
+ tester('ntpath.expandvars("${foo}bar")', "barbar")
+ tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar")
+ tester('ntpath.expandvars("$bar bar")', "$bar bar")
+ tester('ntpath.expandvars("$?bar")', "$?bar")
+ tester('ntpath.expandvars("${foo}bar")', "barbar")
+ tester('ntpath.expandvars("$foo}bar")', "bar}bar")
+ tester('ntpath.expandvars("${foo")', "${foo")
+ tester('ntpath.expandvars("${{foo}}")', "baz1}")
+ tester('ntpath.expandvars("$foo$foo")', "barbar")
+ tester('ntpath.expandvars("$bar$bar")', "$bar$bar")
+finally:
+ os.environ.clear()
+ os.environ.update(oldenv)
+
# ntpath.abspath() can only be used on a system with the "nt" module
# (reasonably), so we protect this test with "import nt". This allows
# the rest of the tests for the ntpath module to be run to completion
@@ -130,4 +152,4 @@
if errors:
raise TestFailed(str(errors) + " errors.")
elif verbose:
- print "No errors. Thank your lucky stars."
+ print("No errors. Thank your lucky stars.")
Modified: python/branches/p3yk-noslice/Lib/test/test_old_mailbox.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_old_mailbox.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_old_mailbox.py Fri Feb 23 18:29:35 2007
@@ -109,11 +109,44 @@
self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE))
self.assertEqual(n, 1)
+class MboxTestCase(unittest.TestCase):
+ def setUp(self):
+ # create a new maildir mailbox to work with:
+ self._path = test_support.TESTFN
+
+ def tearDown(self):
+ os.unlink(self._path)
+
+ def test_from_regex (self):
+ # Testing new regex from bug #1633678
+ f = open(self._path, 'w')
+ f.write("""From fred at example.com Mon May 31 13:24:50 2004 +0200
+Subject: message 1
+
+body1
+From fred at example.com Mon May 31 13:24:50 2004 -0200
+Subject: message 2
+
+body2
+From fred at example.com Mon May 31 13:24:50 2004
+Subject: message 3
+
+body3
+From fred at example.com Mon May 31 13:24:50 2004
+Subject: message 4
+
+body4
+""")
+ f.close()
+ box = mailbox.UnixMailbox(open(self._path, 'r'))
+ self.assert_(len(list(iter(box))) == 4)
+
+
# XXX We still need more tests!
def test_main():
- test_support.run_unittest(MaildirTestCase)
+ test_support.run_unittest(MaildirTestCase, MboxTestCase)
if __name__ == "__main__":
Modified: python/branches/p3yk-noslice/Lib/test/test_operations.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_operations.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_operations.py Fri Feb 23 18:29:35 2007
@@ -1,11 +1,11 @@
# Python test set -- part 3, built-in operations.
-print '3. Operations'
-print 'XXX Mostly not yet implemented'
+print('3. Operations')
+print('XXX Mostly not yet implemented')
-print '3.1 Dictionary lookups fail if __cmp__() raises an exception'
+print('3.1 Dictionary lookups fail if __cmp__() raises an exception')
class BadDictKey:
@@ -14,7 +14,7 @@
def __eq__(self, other):
if isinstance(other, self.__class__):
- print "raising error"
+ print("raising error")
raise RuntimeError, "gotcha"
return other
@@ -32,9 +32,9 @@
try:
exec(stmt)
except RuntimeError:
- print "%s: caught the RuntimeError outside" % (stmt,)
+ print("%s: caught the RuntimeError outside" % (stmt,))
else:
- print "%s: No exception passed through!" % (stmt,) # old CPython behavior
+ print("%s: No exception passed through!" % (stmt,)) # old CPython behavior
# Dict resizing bug, found by Jack Jansen in 2.2 CVS development.
@@ -74,4 +74,4 @@
resizing = True
d[9] = 6
-print 'resize bugs not triggered.'
+print('resize bugs not triggered.')
Modified: python/branches/p3yk-noslice/Lib/test/test_operator.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_operator.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_operator.py Fri Feb 23 18:29:35 2007
@@ -199,7 +199,7 @@
self.failUnlessRaises(TypeError, operator.isNumberType)
self.failUnless(operator.isNumberType(8))
self.failUnless(operator.isNumberType(8j))
- self.failUnless(operator.isNumberType(8L))
+ self.failUnless(operator.isNumberType(8))
self.failUnless(operator.isNumberType(8.3))
self.failIf(operator.isNumberType(dir()))
@@ -210,6 +210,8 @@
self.failUnless(operator.isSequenceType(xrange(10)))
self.failUnless(operator.isSequenceType('yeahbuddy'))
self.failIf(operator.isSequenceType(3))
+ class Dict(dict): pass
+ self.failIf(operator.isSequenceType(Dict()))
def test_lshift(self):
self.failUnlessRaises(TypeError, operator.lshift)
@@ -468,7 +470,7 @@
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
Modified: python/branches/p3yk-noslice/Lib/test/test_optparse.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_optparse.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_optparse.py Fri Feb 23 18:29:35 2007
@@ -1500,8 +1500,16 @@
self.assertHelpEquals(_expected_help_long_opts_first)
def test_help_title_formatter(self):
- self.parser.formatter = TitledHelpFormatter()
- self.assertHelpEquals(_expected_help_title_formatter)
+ save = os.environ.get("COLUMNS")
+ try:
+ os.environ["COLUMNS"] = "80"
+ self.parser.formatter = TitledHelpFormatter()
+ self.assertHelpEquals(_expected_help_title_formatter)
+ finally:
+ if save is not None:
+ os.environ["COLUMNS"] = save
+ else:
+ del os.environ["COLUMNS"]
def test_wrap_columns(self):
# Ensure that wrapping respects $COLUMNS environment variable.
@@ -1590,7 +1598,7 @@
def setUp(self):
self.parser = InterceptingOptionParser()
self.parser.add_option("-n", type=int)
- self.parser.add_option("-l", type=long)
+ self.parser.add_option("-l", type=int)
def test_parse_num_fail(self):
self.assertRaises(
@@ -1598,17 +1606,17 @@
ValueError,
re.compile(r"invalid literal for int().*: '?'?"))
self.assertRaises(
- _parse_num, ("0xOoops", long), {},
+ _parse_num, ("0xOoops", int), {},
ValueError,
- re.compile(r"invalid literal for long().*: '?0xOoops'?"))
+ re.compile(r"invalid literal for int().*: '?0xOoops'?"))
def test_parse_num_ok(self):
self.assertEqual(_parse_num("0", int), 0)
self.assertEqual(_parse_num("0x10", int), 16)
- self.assertEqual(_parse_num("0XA", long), 10L)
- self.assertEqual(_parse_num("010", long), 8L)
+ self.assertEqual(_parse_num("0XA", int), 10)
+ self.assertEqual(_parse_num("010", int), 8)
self.assertEqual(_parse_num("0b11", int), 3)
- self.assertEqual(_parse_num("0b", long), 0L)
+ self.assertEqual(_parse_num("0b", int), 0)
def test_numeric_options(self):
self.assertParseOK(["-n", "42", "-l", "0x20"],
@@ -1618,9 +1626,9 @@
self.assertParseFail(["-n008"],
"option -n: invalid integer value: '008'")
self.assertParseFail(["-l0b0123"],
- "option -l: invalid long integer value: '0b0123'")
+ "option -l: invalid integer value: '0b0123'")
self.assertParseFail(["-l", "0x12x"],
- "option -l: invalid long integer value: '0x12x'")
+ "option -l: invalid integer value: '0x12x'")
def _testclasses():
Modified: python/branches/p3yk-noslice/Lib/test/test_ossaudiodev.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_ossaudiodev.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_ossaudiodev.py Fri Feb 23 18:29:35 2007
@@ -33,7 +33,7 @@
fp.close()
if enc != SND_FORMAT_MULAW_8:
- print "Expect .au file with 8-bit mu-law samples"
+ print("Expect .au file with 8-bit mu-law samples")
return
# Convert the data to 16-bit signed.
@@ -78,8 +78,8 @@
# set parameters based on .au file headers
dsp.setparameters(AFMT_S16_NE, nchannels, rate)
- print ("playing test sound file (expected running time: %.2f sec)"
- % expected_time)
+ print(("playing test sound file (expected running time: %.2f sec)"
+ % expected_time))
t1 = time.time()
dsp.write(data)
dsp.close()
@@ -143,7 +143,7 @@
result = dsp.setparameters(fmt, channels, rate, True)
raise AssertionError("setparameters: expected OSSAudioError")
except ossaudiodev.OSSAudioError as err:
- print "setparameters: got OSSAudioError as expected"
+ print("setparameters: got OSSAudioError as expected")
def test():
(data, rate, ssize, nchannels) = read_sound_file(findfile('audiotest.au'))
Modified: python/branches/p3yk-noslice/Lib/test/test_parser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_parser.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_parser.py Fri Feb 23 18:29:35 2007
@@ -85,14 +85,6 @@
self.check_expr("(x for x in range(10))")
self.check_expr("foo(x for x in range(10))")
- def test_print(self):
- self.check_suite("print")
- self.check_suite("print 1")
- self.check_suite("print 1,")
- self.check_suite("print >>fp")
- self.check_suite("print >>fp, 1")
- self.check_suite("print >>fp, 1,")
-
def test_simple_expression(self):
# expr_stmt
self.check_suite("a")
@@ -359,29 +351,6 @@
(0, ''))))
self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
- def test_print_chevron_comma(self):
- # Illegal input: print >>fp,
- tree = \
- (257,
- (264,
- (265,
- (266,
- (268,
- (1, 'print'),
- (35, '>>'),
- (290,
- (291,
- (292,
- (293,
- (295,
- (296,
- (297,
- (298, (299, (300, (301, (302, (303, (1, 'fp')))))))))))))),
- (12, ','))),
- (4, ''))),
- (0, ''))
- self.check_bad_tree(tree, "print >>fp,")
-
def test_a_comma_comma_c(self):
# Illegal input: a,,c
tree = \
Modified: python/branches/p3yk-noslice/Lib/test/test_peepholer.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_peepholer.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_peepholer.py Fri Feb 23 18:29:35 2007
@@ -211,7 +211,7 @@
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
Modified: python/branches/p3yk-noslice/Lib/test/test_pep247.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pep247.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_pep247.py Fri Feb 23 18:29:35 2007
@@ -41,7 +41,7 @@
hd2 += "%02x" % ord(byte)
assert hd2 == hexdigest, "hexdigest doesn't appear correct"
- print 'Module', module.__name__, 'seems to comply with PEP 247'
+ print('Module', module.__name__, 'seems to comply with PEP 247')
if __name__ == '__main__':
Modified: python/branches/p3yk-noslice/Lib/test/test_pep277.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pep277.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_pep277.py Fri Feb 23 18:29:35 2007
@@ -83,7 +83,7 @@
f2 = os.listdir(unicode(test_support.TESTFN,
sys.getfilesystemencoding()))
f2.sort()
- print f2
+ print(f2)
def test_rename(self):
for name in self.files:
@@ -99,7 +99,7 @@
f = open(filename, 'w')
f.write((filename + '\n').encode("utf-8"))
f.close()
- print repr(filename)
+ print(repr(filename))
os.access(filename,os.R_OK)
os.remove(filename)
os.chdir(oldwd)
Modified: python/branches/p3yk-noslice/Lib/test/test_pep352.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pep352.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_pep352.py Fri Feb 23 18:29:35 2007
@@ -2,7 +2,7 @@
import __builtin__
import exceptions
import warnings
-from test.test_support import run_unittest
+from test.test_support import run_unittest, guard_warnings_filter
import os
from platform import system as platform_system
@@ -113,13 +113,11 @@
"""Test usage of exceptions"""
- def setUp(self):
- self._filters = warnings.filters[:]
-
- def tearDown(self):
- warnings.filters = self._filters[:]
-
def test_raise_new_style_non_exception(self):
+ # You cannot raise a new-style class that does not inherit from
+ # BaseException; the ability was not possible until BaseException's
+ # introduction so no need to support new-style objects that do not
+ # inherit from it.
class NewStyleClass(object):
pass
try:
@@ -127,13 +125,51 @@
except TypeError:
pass
except:
- self.fail("unable to raise new-style class")
+ self.fail("able to raise new-style class")
try:
raise NewStyleClass()
except TypeError:
pass
except:
- self.fail("unable to raise new-style class instance")
+ self.fail("able to raise new-style class instance")
+
+ def test_raise_string(self):
+ # Raising a string raises TypeError.
+ try:
+ raise "spam"
+ except TypeError:
+ pass
+ except:
+ self.fail("was able to raise a string exception")
+
+ def test_catch_string(self):
+ # Catching a string should trigger a DeprecationWarning.
+ with guard_warnings_filter():
+ warnings.resetwarnings()
+ warnings.filterwarnings("error")
+ str_exc = "spam"
+ try:
+ try:
+ raise StandardError
+ except str_exc:
+ pass
+ except DeprecationWarning:
+ pass
+ except StandardError:
+ self.fail("catching a string exception did not raise "
+ "DeprecationWarning")
+ # Make sure that even if the string exception is listed in a tuple
+ # that a warning is raised.
+ try:
+ try:
+ raise StandardError
+ except (AssertionError, str_exc):
+ pass
+ except DeprecationWarning:
+ pass
+ except StandardError:
+ self.fail("catching a string exception specified in a tuple did "
+ "not raise DeprecationWarning")
def test_main():
run_unittest(ExceptionClassTests, UsageTests)
Modified: python/branches/p3yk-noslice/Lib/test/test_pkg.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pkg.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_pkg.py Fri Feb 23 18:29:35 2007
@@ -18,7 +18,7 @@
if contents is None:
mkdir(fullname)
else:
- if verbose: print "write", fullname
+ if verbose: print("write", fullname)
f = open(fullname, "w")
f.write(contents)
if contents and contents[-1] != '\n':
@@ -26,7 +26,7 @@
f.close()
def mkdir(x):
- if verbose: print "mkdir", x
+ if verbose: print("mkdir", x)
os.mkdir(x)
def cleanout(root):
@@ -40,7 +40,7 @@
rmdir(root)
def rmdir(x):
- if verbose: print "rmdir", x
+ if verbose: print("rmdir", x)
os.rmdir(x)
def fixdir(lst):
@@ -61,7 +61,7 @@
os.close(fd)
try:
sys.path.insert(0, root)
- if verbose: print "sys.path =", sys.path
+ if verbose: print("sys.path =", sys.path)
try:
execfile(fname, globals(), {})
except:
@@ -81,122 +81,122 @@
("t2", [
("t2", None),
- ("t2 __init__"+os.extsep+"py", "'doc for t2'; print __name__, 'loading'"),
+ ("t2 __init__"+os.extsep+"py", "'doc for t2'; print(__name__, 'loading')"),
("t2 sub", None),
("t2 sub __init__"+os.extsep+"py", ""),
("t2 sub subsub", None),
- ("t2 sub subsub __init__"+os.extsep+"py", "print __name__, 'loading'; spam = 1"),
+ ("t2 sub subsub __init__"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"),
],
"""
import t2
-print t2.__doc__
+print(t2.__doc__)
import t2.sub
import t2.sub.subsub
-print t2.__name__, t2.sub.__name__, t2.sub.subsub.__name__
+print(t2.__name__, t2.sub.__name__, t2.sub.subsub.__name__)
import t2
from t2 import *
-print dir()
+print(dir())
from t2 import sub
from t2.sub import subsub
from t2.sub.subsub import spam
-print sub.__name__, subsub.__name__
-print sub.subsub.__name__
-print dir()
+print(sub.__name__, subsub.__name__)
+print(sub.subsub.__name__)
+print(dir())
import t2.sub
import t2.sub.subsub
-print t2.__name__, t2.sub.__name__, t2.sub.subsub.__name__
+print(t2.__name__, t2.sub.__name__, t2.sub.subsub.__name__)
from t2 import *
-print dir()
+print(dir())
"""),
("t3", [
("t3", None),
- ("t3 __init__"+os.extsep+"py", "print __name__, 'loading'"),
+ ("t3 __init__"+os.extsep+"py", "print(__name__, 'loading')"),
("t3 sub", None),
("t3 sub __init__"+os.extsep+"py", ""),
("t3 sub subsub", None),
- ("t3 sub subsub __init__"+os.extsep+"py", "print __name__, 'loading'; spam = 1"),
+ ("t3 sub subsub __init__"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"),
],
"""
import t3.sub.subsub
-print t3.__name__, t3.sub.__name__, t3.sub.subsub.__name__
+print(t3.__name__, t3.sub.__name__, t3.sub.subsub.__name__)
reload(t3)
reload(t3.sub)
reload(t3.sub.subsub)
"""),
("t4", [
- ("t4"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (t4"+os.extsep+"py)'"),
+ ("t4"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (t4"+os.extsep+"py)')"),
("t4", None),
- ("t4 __init__"+os.extsep+"py", "print __name__, 'loading'"),
- ("t4 sub"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (sub"+os.extsep+"py)'"),
+ ("t4 __init__"+os.extsep+"py", "print(__name__, 'loading')"),
+ ("t4 sub"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (sub"+os.extsep+"py)')"),
("t4 sub", None),
("t4 sub __init__"+os.extsep+"py", ""),
- ("t4 sub subsub"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (subsub"+os.extsep+"py)'"),
+ ("t4 sub subsub"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (subsub"+os.extsep+"py)')"),
("t4 sub subsub", None),
- ("t4 sub subsub __init__"+os.extsep+"py", "print __name__, 'loading'; spam = 1"),
+ ("t4 sub subsub __init__"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"),
],
"""
from t4.sub.subsub import *
-print "t4.sub.subsub.spam =", spam
+print("t4.sub.subsub.spam =", spam)
"""),
("t5", [
("t5", None),
("t5 __init__"+os.extsep+"py", "import t5.foo"),
- ("t5 string"+os.extsep+"py", "print __name__, 'loading'; spam = 1"),
+ ("t5 string"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"),
("t5 foo"+os.extsep+"py",
- "print __name__, 'loading'; from . import string; print string.spam"),
+ "print(__name__, 'loading'); from . import string; print(string.spam)"),
],
"""
import t5
from t5 import *
-print dir()
+print(dir())
import t5
-print fixdir(dir(t5))
-print fixdir(dir(t5.foo))
-print fixdir(dir(t5.string))
+print(fixdir(dir(t5)))
+print(fixdir(dir(t5.foo)))
+print(fixdir(dir(t5.string)))
"""),
("t6", [
("t6", None),
("t6 __init__"+os.extsep+"py", "__all__ = ['spam', 'ham', 'eggs']"),
- ("t6 spam"+os.extsep+"py", "print __name__, 'loading'"),
- ("t6 ham"+os.extsep+"py", "print __name__, 'loading'"),
- ("t6 eggs"+os.extsep+"py", "print __name__, 'loading'"),
+ ("t6 spam"+os.extsep+"py", "print(__name__, 'loading')"),
+ ("t6 ham"+os.extsep+"py", "print(__name__, 'loading')"),
+ ("t6 eggs"+os.extsep+"py", "print(__name__, 'loading')"),
],
"""
import t6
-print fixdir(dir(t6))
+print(fixdir(dir(t6)))
from t6 import *
-print fixdir(dir(t6))
-print dir()
+print(fixdir(dir(t6)))
+print(dir())
"""),
("t7", [
- ("t7"+os.extsep+"py", "print 'Importing t7"+os.extsep+"py'"),
+ ("t7"+os.extsep+"py", "print('Importing t7"+os.extsep+"py')"),
("t7", None),
- ("t7 __init__"+os.extsep+"py", "print __name__, 'loading'"),
- ("t7 sub"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (sub"+os.extsep+"py)'"),
+ ("t7 __init__"+os.extsep+"py", "print(__name__, 'loading')"),
+ ("t7 sub"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (sub"+os.extsep+"py)')"),
("t7 sub", None),
("t7 sub __init__"+os.extsep+"py", ""),
- ("t7 sub subsub"+os.extsep+"py", "print 'THIS SHOULD NOT BE PRINTED (subsub"+os.extsep+"py)'"),
+ ("t7 sub subsub"+os.extsep+"py", "print('THIS SHOULD NOT BE PRINTED (subsub"+os.extsep+"py)')"),
("t7 sub subsub", None),
- ("t7 sub subsub __init__"+os.extsep+"py", "print __name__, 'loading'; spam = 1"),
+ ("t7 sub subsub __init__"+os.extsep+"py", "print(__name__, 'loading'); spam = 1"),
],
"""
t7, sub, subsub = None, None, None
import t7 as tas
-print fixdir(dir(tas))
+print(fixdir(dir(tas)))
verify(not t7)
from t7 import sub as subpar
-print fixdir(dir(subpar))
+print(fixdir(dir(subpar)))
verify(not t7 and not sub)
from t7.sub import subsub as subsubsub
-print fixdir(dir(subsubsub))
+print(fixdir(dir(subsubsub)))
verify(not t7 and not sub and not subsub)
from t7.sub.subsub import spam as ham
-print "t7.sub.subsub.spam =", ham
+print("t7.sub.subsub.spam =", ham)
verify(not t7 and not sub and not subsub)
"""),
@@ -242,9 +242,9 @@
for name, hier, code in tests:
if args and name not in args:
- print "skipping test", name
+ print("skipping test", name)
continue
- print "running test", name
+ print("running test", name)
runtest(hier, code)
# Test
Modified: python/branches/p3yk-noslice/Lib/test/test_poll.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_poll.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_poll.py Fri Feb 23 18:29:35 2007
@@ -143,7 +143,7 @@
pollster = select.poll()
pollster.register(1)
- self.assertRaises(OverflowError, pollster.poll, 1L << 64)
+ self.assertRaises(OverflowError, pollster.poll, 1 << 64)
x = 2 + 3
if x != 5:
Modified: python/branches/p3yk-noslice/Lib/test/test_popen.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_popen.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_popen.py Fri Feb 23 18:29:35 2007
@@ -4,10 +4,9 @@
Particularly useful for platforms that fake popen.
"""
-import os
-import sys
-from test.test_support import TestSkipped, reap_children
-from os import popen
+import unittest
+from test import test_support
+import os, sys
# Test that command-lines get down as we expect.
# To do this we execute:
@@ -17,24 +16,32 @@
python = sys.executable
if ' ' in python:
python = '"' + python + '"' # quote embedded space for cmdline
-def _do_test_commandline(cmdline, expected):
- cmd = '%s -c "import sys;print sys.argv" %s' % (python, cmdline)
- data = popen(cmd).read()
- got = eval(data)[1:] # strip off argv[0]
- if got != expected:
- print "Error in popen commandline handling."
- print " executed '%s', expected '%r', but got '%r'" \
- % (cmdline, expected, got)
-
-def _test_commandline():
- _do_test_commandline("foo bar", ["foo", "bar"])
- _do_test_commandline('foo "spam and eggs" "silly walk"', ["foo", "spam and eggs", "silly walk"])
- _do_test_commandline('foo "a \\"quoted\\" arg" bar', ["foo", 'a "quoted" arg', "bar"])
- print "popen seemed to process the command-line correctly"
-
-def main():
- print "Test popen:"
- _test_commandline()
- reap_children()
-main()
+class PopenTest(unittest.TestCase):
+ def _do_test_commandline(self, cmdline, expected):
+ cmd = '%s -c "import sys; print(sys.argv)" %s' % (python, cmdline)
+ data = os.popen(cmd).read()
+ got = eval(data)[1:] # strip off argv[0]
+ self.assertEqual(got, expected)
+
+ def test_popen(self):
+ self.assertRaises(TypeError, os.popen)
+ self._do_test_commandline(
+ "foo bar",
+ ["foo", "bar"]
+ )
+ self._do_test_commandline(
+ 'foo "spam and eggs" "silly walk"',
+ ["foo", "spam and eggs", "silly walk"]
+ )
+ self._do_test_commandline(
+ 'foo "a \\"quoted\\" arg" bar',
+ ["foo", 'a "quoted" arg', "bar"]
+ )
+ test_support.reap_children()
+
+def test_main():
+ test_support.run_unittest(PopenTest)
+
+if __name__ == "__main__":
+ test_main()
Modified: python/branches/p3yk-noslice/Lib/test/test_popen2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_popen2.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_popen2.py Fri Feb 23 18:29:35 2007
@@ -13,7 +13,7 @@
# subprocess.
def main():
- print "Test popen2 module:"
+ print("Test popen2 module:")
if (sys.platform[:4] == 'beos' or sys.platform[:6] == 'atheos') \
and __name__ != '__main__':
# Locks get messed up or something. Generally we're supposed
@@ -33,7 +33,7 @@
def _test():
# same test as popen2._test(), but using the os.popen*() API
- print "Testing os module:"
+ print("Testing os module:")
import popen2
# When the test runs, there shouldn't be any open pipes
popen2._cleanup()
@@ -46,14 +46,14 @@
# sometimes adding an extra newline at the start or the
# end. So we strip whitespace off both ends for comparison.
expected = teststr.strip()
- print "testing popen2..."
+ print("testing popen2...")
w, r = os.popen2(cmd)
w.write(teststr)
w.close()
got = r.read()
if got.strip() != expected:
raise ValueError("wrote %r read %r" % (teststr, got))
- print "testing popen3..."
+ print("testing popen3...")
try:
w, r, e = os.popen3([cmd])
except:
@@ -71,7 +71,7 @@
popen2._cleanup()
if popen2._active:
raise ValueError("_active not empty")
- print "All OK"
+ print("All OK")
main()
_test()
Modified: python/branches/p3yk-noslice/Lib/test/test_posix.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_posix.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_posix.py Fri Feb 23 18:29:35 2007
@@ -192,6 +192,18 @@
posix.utime(test_support.TESTFN, (int(now), int(now)))
posix.utime(test_support.TESTFN, (now, now))
+ def test_chflags(self):
+ if hasattr(posix, 'chflags'):
+ st = os.stat(test_support.TESTFN)
+ if hasattr(st, 'st_flags'):
+ posix.chflags(test_support.TESTFN, st.st_flags)
+
+ def test_lchflags(self):
+ if hasattr(posix, 'lchflags'):
+ st = os.stat(test_support.TESTFN)
+ if hasattr(st, 'st_flags'):
+ posix.lchflags(test_support.TESTFN, st.st_flags)
+
def test_main():
test_support.run_unittest(PosixTester)
Modified: python/branches/p3yk-noslice/Lib/test/test_posixpath.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_posixpath.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_posixpath.py Fri Feb 23 18:29:35 2007
@@ -374,6 +374,8 @@
self.assertEqual(posixpath.expandvars("$foo}bar"), "bar}bar")
self.assertEqual(posixpath.expandvars("${foo"), "${foo")
self.assertEqual(posixpath.expandvars("${{foo}}"), "baz1}")
+ self.assertEqual(posixpath.expandvars("$foo$foo"), "barbar")
+ self.assertEqual(posixpath.expandvars("$bar$bar"), "$bar$bar")
finally:
os.environ.clear()
os.environ.update(oldenv)
Modified: python/branches/p3yk-noslice/Lib/test/test_pow.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pow.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_pow.py Fri Feb 23 18:29:35 2007
@@ -18,14 +18,14 @@
self.assertEquals(pow(2, i), pow2)
if i != 30 : pow2 = pow2*2
- for othertype in int, long:
+ for othertype in int, int:
for i in range(-10, 0) + range(1, 10):
ii = type(i)
for j in range(1, 11):
jj = -othertype(j)
pow(ii, jj)
- for othertype in int, long, float:
+ for othertype in int, int, float:
for i in range(1, 100):
zero = type(0)
exp = -othertype(i/10.0)
@@ -42,7 +42,7 @@
asseq = self.assertAlmostEqual
elif type == int:
jl = 0
- elif type == long:
+ elif type == int:
jl, jh = 0, 15
for i in range(il, ih+1):
for j in range(jl, jh+1):
@@ -60,7 +60,7 @@
self.powtest(int)
def test_powlong(self):
- self.powtest(long)
+ self.powtest(int)
def test_powfloat(self):
self.powtest(float)
@@ -74,12 +74,12 @@
self.assertEquals(pow(-3,3) % -8, pow(-3,3,-8))
self.assertEquals(pow(5,2) % -8, pow(5,2,-8))
- self.assertEquals(pow(3L,3L) % 8, pow(3L,3L,8))
- self.assertEquals(pow(3L,3L) % -8, pow(3L,3L,-8))
- self.assertEquals(pow(3L,2) % -2, pow(3L,2,-2))
- self.assertEquals(pow(-3L,3L) % 8, pow(-3L,3L,8))
- self.assertEquals(pow(-3L,3L) % -8, pow(-3L,3L,-8))
- self.assertEquals(pow(5L,2) % -8, pow(5L,2,-8))
+ self.assertEquals(pow(3,3) % 8, pow(3,3,8))
+ self.assertEquals(pow(3,3) % -8, pow(3,3,-8))
+ self.assertEquals(pow(3,2) % -2, pow(3,2,-2))
+ self.assertEquals(pow(-3,3) % 8, pow(-3,3,8))
+ self.assertEquals(pow(-3,3) % -8, pow(-3,3,-8))
+ self.assertEquals(pow(5,2) % -8, pow(5,2,-8))
for i in range(-10, 11):
for j in range(0, 6):
@@ -91,8 +91,8 @@
)
if j >= 0 and k != 0:
self.assertEquals(
- pow(long(i),j) % k,
- pow(long(i),j,k)
+ pow(int(i),j) % k,
+ pow(int(i),j,k)
)
def test_bug643260(self):
Modified: python/branches/p3yk-noslice/Lib/test/test_pprint.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pprint.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_pprint.py Fri Feb 23 18:29:35 2007
@@ -114,12 +114,12 @@
# multiple lines. For that reason, dicts with more than one element
# aren't tested here.
verify = self.assert_
- for simple in (0, 0L, 0+0j, 0.0, "", uni(""),
+ for simple in (0, 0, 0+0j, 0.0, "", uni(""),
(), tuple2(), tuple3(),
[], list2(), list3(),
{}, dict2(), dict3(),
verify, pprint,
- -6, -6L, -6-6j, -1.5, "x", uni("x"), (3,), [3], {3: 6},
+ -6, -6, -6-6j, -1.5, "x", uni("x"), (3,), [3], {3: 6},
(1,2), [3,4], {5: 6, 7: 8},
tuple2((1,2)), tuple3((1,2)), tuple3(range(100)),
[3,4], list2([3,4]), list3([3,4]), list3(range(100)),
Modified: python/branches/p3yk-noslice/Lib/test/test_pty.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pty.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_pty.py Fri Feb 23 18:29:35 2007
@@ -6,7 +6,7 @@
if verbose:
def debug(msg):
- print msg
+ print(msg)
else:
def debug(msg):
pass
@@ -120,7 +120,7 @@
##if False and lines != ['In child, calling os.setsid()',
## 'Good: OSError was raised.', '']:
## raise TestFailed("Unexpected output from child: %r" % line)
-
+
(pid, status) = os.waitpid(pid, 0)
res = status >> 8
debug("Child (%d) exited with status %d (%d)."%(pid, res, status))
@@ -140,8 +140,8 @@
## pass
##else:
## raise TestFailed("Read from master_fd did not raise exception")
-
-
+
+
os.close(master_fd)
# pty.fork() passed.
Modified: python/branches/p3yk-noslice/Lib/test/test_pwd.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pwd.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_pwd.py Fri Feb 23 18:29:35 2007
@@ -55,7 +55,7 @@
bynames[n] = u
byuids[u] = n
- allnames = bynames.keys()
+ allnames = list(bynames.keys())
namei = 0
fakename = allnames[namei]
while fakename in bynames:
Modified: python/branches/p3yk-noslice/Lib/test/test_pyclbr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pyclbr.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_pyclbr.py Fri Feb 23 18:29:35 2007
@@ -28,13 +28,13 @@
''' succeed iff {l1} - {ignore} == {l2} - {ignore} '''
missing = (set(l1) ^ set(l2)) - set(ignore)
if missing:
- print >>sys.stderr, "l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore)
+ print("l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore), file=sys.stderr)
self.fail("%r missing" % missing.pop())
def assertHasattr(self, obj, attr, ignore):
''' succeed iff hasattr(obj,attr) or attr in ignore. '''
if attr in ignore: return
- if not hasattr(obj, attr): print "???", attr
+ if not hasattr(obj, attr): print("???", attr)
self.failUnless(hasattr(obj, attr),
'expected hasattr(%r, %r)' % (obj, attr))
@@ -43,8 +43,8 @@
''' succeed iff key in obj or key in ignore. '''
if key in ignore: return
if key not in obj:
- print >>sys.stderr, "***",key
- self.failUnless(key) in obj
+ print("***",key, file=sys.stderr)
+ self.failUnless(key in obj)
def assertEqualsOrIgnored(self, a, b, ignore):
''' succeed iff a == b or a in ignore or b in ignore '''
@@ -110,7 +110,7 @@
try:
self.assertListEq(real_bases, pyclbr_bases, ignore)
except:
- print >>sys.stderr, "class=%s" % py_item
+ print("class=%s" % py_item, file=sys.stderr)
raise
actualMethods = []
@@ -132,7 +132,7 @@
ignore)
# can't check file or lineno
except:
- print >>sys.stderr, "class=%s" % py_item
+ print("class=%s" % py_item, file=sys.stderr)
raise
# Now check for missing stuff.
Modified: python/branches/p3yk-noslice/Lib/test/test_pyexpat.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_pyexpat.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_pyexpat.py Fri Feb 23 18:29:35 2007
@@ -10,50 +10,50 @@
class Outputter:
def StartElementHandler(self, name, attrs):
- print 'Start element:\n\t', repr(name), sortdict(attrs)
+ print('Start element:\n\t' + repr(name), sortdict(attrs))
def EndElementHandler(self, name):
- print 'End element:\n\t', repr(name)
+ print('End element:\n\t' + repr(name))
def CharacterDataHandler(self, data):
data = data.strip()
if data:
- print 'Character data:'
- print '\t', repr(data)
+ print('Character data:')
+ print('\t' + repr(data))
def ProcessingInstructionHandler(self, target, data):
- print 'PI:\n\t', repr(target), repr(data)
+ print('PI:\n\t' + repr(target), repr(data))
def StartNamespaceDeclHandler(self, prefix, uri):
- print 'NS decl:\n\t', repr(prefix), repr(uri)
+ print('NS decl:\n\t' + repr(prefix), repr(uri))
def EndNamespaceDeclHandler(self, prefix):
- print 'End of NS decl:\n\t', repr(prefix)
+ print('End of NS decl:\n\t' + repr(prefix))
def StartCdataSectionHandler(self):
- print 'Start of CDATA section'
+ print('Start of CDATA section')
def EndCdataSectionHandler(self):
- print 'End of CDATA section'
+ print('End of CDATA section')
def CommentHandler(self, text):
- print 'Comment:\n\t', repr(text)
+ print('Comment:\n\t' + repr(text))
def NotationDeclHandler(self, *args):
name, base, sysid, pubid = args
- print 'Notation declared:', args
+ print('Notation declared:', args)
def UnparsedEntityDeclHandler(self, *args):
entityName, base, systemId, publicId, notationName = args
- print 'Unparsed entity decl:\n\t', args
+ print('Unparsed entity decl:\n\t' + str(args))
def NotStandaloneHandler(self, userData):
- print 'Not standalone'
+ print('Not standalone')
return 1
def ExternalEntityRefHandler(self, *args):
context, base, sysId, pubId = args
- print 'External entity ref:', args[1:]
+ print('External entity ref:', args[1:])
return 1
def DefaultHandler(self, userData):
@@ -65,9 +65,9 @@
def confirm(ok):
if ok:
- print "OK."
+ print("OK.")
else:
- print "Not OK."
+ print("Not OK.")
out = Outputter()
parser = expat.ParserCreate(namespace_separator='!')
@@ -131,10 +131,10 @@
try:
parser.Parse(data, 1)
except expat.error:
- print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)
- print '** Line', parser.ErrorLineNumber
- print '** Column', parser.ErrorColumnNumber
- print '** Byte', parser.ErrorByteIndex
+ print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode))
+ print('** Line', parser.ErrorLineNumber)
+ print('** Column', parser.ErrorColumnNumber)
+ print('** Byte', parser.ErrorByteIndex)
# Try the parse again, this time producing Unicode output
parser = expat.ParserCreate(namespace_separator='!')
@@ -145,10 +145,10 @@
try:
parser.Parse(data, 1)
except expat.error:
- print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)
- print '** Line', parser.ErrorLineNumber
- print '** Column', parser.ErrorColumnNumber
- print '** Byte', parser.ErrorByteIndex
+ print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode))
+ print('** Line', parser.ErrorLineNumber)
+ print('** Column', parser.ErrorColumnNumber)
+ print('** Byte', parser.ErrorByteIndex)
# Try parsing a file
parser = expat.ParserCreate(namespace_separator='!')
@@ -161,35 +161,35 @@
try:
parser.ParseFile(file)
except expat.error:
- print '** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode)
- print '** Line', parser.ErrorLineNumber
- print '** Column', parser.ErrorColumnNumber
- print '** Byte', parser.ErrorByteIndex
+ print('** Error', parser.ErrorCode, expat.ErrorString(parser.ErrorCode))
+ print('** Line', parser.ErrorLineNumber)
+ print('** Column', parser.ErrorColumnNumber)
+ print('** Byte', parser.ErrorByteIndex)
# Tests that make sure we get errors when the namespace_separator value
# is illegal, and that we don't for good values:
-print
-print "Testing constructor for proper handling of namespace_separator values:"
+print()
+print("Testing constructor for proper handling of namespace_separator values:")
expat.ParserCreate()
expat.ParserCreate(namespace_separator=None)
expat.ParserCreate(namespace_separator=' ')
-print "Legal values tested o.k."
+print("Legal values tested o.k.")
try:
expat.ParserCreate(namespace_separator=42)
except TypeError as e:
- print "Caught expected TypeError:"
- print e
+ print("Caught expected TypeError:")
+ print(e)
else:
- print "Failed to catch expected TypeError."
+ print("Failed to catch expected TypeError.")
try:
expat.ParserCreate(namespace_separator='too long')
except ValueError as e:
- print "Caught expected ValueError:"
- print e
+ print("Caught expected ValueError:")
+ print(e)
else:
- print "Failed to catch expected ValueError."
+ print("Failed to catch expected ValueError.")
# ParserCreate() needs to accept a namespace_separator of zero length
# to satisfy the requirements of RDF applications that are required
@@ -211,12 +211,12 @@
p.Parse("<e> <e/> <e></e> </e>", 1)
tag = L[0]
if len(L) != 6:
- print "L should only contain 6 entries; found", len(L)
+ print("L should only contain 6 entries; found", len(L))
for entry in L:
if tag is not entry:
- print "expected L to contain many references to the same string",
- print "(it didn't)"
- print "L =", repr(L)
+ print("expected L to contain many references to the same string", end=' ')
+ print("(it didn't)")
+ print("L =", repr(L))
break
# Tests of the buffer_text attribute.
@@ -323,9 +323,9 @@
parser.Parse("<a><b><c/></b></a>", 1)
except RuntimeError as e:
if e.args[0] != "a":
- print "Expected RuntimeError for element 'a'; found %r" % e.args[0]
+ print("Expected RuntimeError for element 'a'; found %r" % e.args[0])
else:
- print "Expected RuntimeError for 'a'"
+ print("Expected RuntimeError for 'a'")
# Test Current* members:
class PositionTest:
Modified: python/branches/p3yk-noslice/Lib/test/test_queue.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_queue.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_queue.py Fri Feb 23 18:29:35 2007
@@ -271,11 +271,11 @@
SimpleQueueTest(q)
SimpleQueueTest(q)
if verbose:
- print "Simple Queue tests seemed to work"
+ print("Simple Queue tests seemed to work")
q = FailingQueue(QUEUE_SIZE)
FailingQueueTest(q)
FailingQueueTest(q)
if verbose:
- print "Failing Queue tests seemed to work"
+ print("Failing Queue tests seemed to work")
test()
Modified: python/branches/p3yk-noslice/Lib/test/test_random.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_random.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_random.py Fri Feb 23 18:29:35 2007
@@ -34,7 +34,7 @@
self.assertEqual(randseq, self.randomlist(N))
def test_seedargs(self):
- for arg in [None, 0, 0L, 1, 1L, -1, -1L, 10**20, -(10**20),
+ for arg in [None, 0, 0, 1, 1, -1, -1, 10**20, -(10**20),
3.14, 1+2j, 'a', tuple('abc')]:
self.gen.seed(arg)
for arg in [range(3), dict(one=1)]:
@@ -268,7 +268,7 @@
# show that: k = int(1.001 + _log(n, 2))
# is equal to or one greater than the number of bits in n
for i in xrange(1, 1000):
- n = 1L << i # check an exact power of two
+ n = 1 << i # check an exact power of two
numbits = i+1
k = int(1.00001 + _log(n, 2))
self.assertEqual(k, numbits)
@@ -327,7 +327,7 @@
0.089215024911993401,
0.78486196105372907]
- self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96))
+ self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
actual = self.randomlist(2000)[-10:]
for a, e in zip(actual, expected):
self.assertAlmostEqual(a,e,places=14)
@@ -339,20 +339,20 @@
# no rounding errors -- all results are exact).
from math import ldexp
- expected = [0x0eab3258d2231fL,
- 0x1b89db315277a5L,
- 0x1db622a5518016L,
- 0x0b7f9af0d575bfL,
- 0x029e4c4db82240L,
- 0x04961892f5d673L,
- 0x02b291598e4589L,
- 0x11388382c15694L,
- 0x02dad977c9e1feL,
- 0x191d96d4d334c6L]
- self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96))
+ expected = [0x0eab3258d2231f,
+ 0x1b89db315277a5,
+ 0x1db622a5518016,
+ 0x0b7f9af0d575bf,
+ 0x029e4c4db82240,
+ 0x04961892f5d673,
+ 0x02b291598e4589,
+ 0x11388382c15694,
+ 0x02dad977c9e1fe,
+ 0x191d96d4d334c6]
+ self.gen.seed(61731 + (24903<<32) + (614<<64) + (42143<<96))
actual = self.randomlist(2000)[-10:]
for a, e in zip(actual, expected):
- self.assertEqual(long(ldexp(a, 53)), e)
+ self.assertEqual(int(ldexp(a, 53)), e)
def test_long_seed(self):
# This is most interesting to run in debug mode, just to make sure
@@ -360,7 +360,7 @@
# is allocated, consuming space proportional to the number of bits
# in the seed. Unfortunately, that's a quadratic-time algorithm,
# so don't make this horribly big.
- seed = (1L << (10000 * 8)) - 1 # about 10K bytes
+ seed = (1 << (10000 * 8)) - 1 # about 10K bytes
self.gen.seed(seed)
def test_53_bits_per_float(self):
@@ -399,7 +399,7 @@
# Verify cross-platform repeatability
self.gen.seed(1234567)
self.assertEqual(self.gen.getrandbits(100),
- 97904845777343510404718956115L)
+ 97904845777343510404718956115)
# Verify ranges
for k in xrange(1, 1000):
self.assert_(0 <= self.gen.getrandbits(k) < 2**k)
@@ -424,7 +424,7 @@
# show that: k = int(1.001 + _log(n, 2))
# is equal to or one greater than the number of bits in n
for i in xrange(1, 1000):
- n = 1L << i # check an exact power of two
+ n = 1 << i # check an exact power of two
numbits = i+1
k = int(1.00001 + _log(n, 2))
self.assertEqual(k, numbits)
@@ -517,6 +517,14 @@
# tests validity but not completeness of the __all__ list
self.failUnless(set(random.__all__) <= set(dir(random)))
+ def test_random_subclass_with_kwargs(self):
+ # SF bug #1486663 -- this used to erroneously raise a TypeError
+ class Subclass(random.Random):
+ def __init__(self, newarg=None):
+ random.Random.__init__(self)
+ Subclass(newarg=1)
+
+
def test_main(verbose=None):
testclasses = [WichmannHill_TestBasicOps,
MersenneTwister_TestBasicOps,
@@ -539,7 +547,7 @@
for i in xrange(len(counts)):
test_support.run_unittest(*testclasses)
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
Modified: python/branches/p3yk-noslice/Lib/test/test_re.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_re.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_re.py Fri Feb 23 18:29:35 2007
@@ -603,7 +603,7 @@
def run_re_tests():
from test.re_tests import benchmarks, tests, SUCCEED, FAIL, SYNTAX_ERROR
if verbose:
- print 'Running re_tests test suite'
+ print('Running re_tests test suite')
else:
# To save time, only run the first and last 10 tests
#tests = tests[:10] + tests[-10:]
@@ -624,23 +624,23 @@
except re.error:
if outcome == SYNTAX_ERROR: pass # Expected a syntax error
else:
- print '=== Syntax error:', t
+ print('=== Syntax error:', t)
except KeyboardInterrupt: raise KeyboardInterrupt
except:
- print '*** Unexpected error ***', t
+ print('*** Unexpected error ***', t)
if verbose:
traceback.print_exc(file=sys.stdout)
else:
try:
result = obj.search(s)
except re.error as msg:
- print '=== Unexpected exception', t, repr(msg)
+ print('=== Unexpected exception', t, repr(msg))
if outcome == SYNTAX_ERROR:
# This should have been a syntax error; forget it.
pass
elif outcome == FAIL:
if result is None: pass # No match, as expected
- else: print '=== Succeeded incorrectly', t
+ else: print('=== Succeeded incorrectly', t)
elif outcome == SUCCEED:
if result is not None:
# Matched, as expected, so now we compute the
@@ -668,17 +668,17 @@
vardict[i] = gi
repl = eval(repl, vardict)
if repl != expected:
- print '=== grouping error', t,
- print repr(repl) + ' should be ' + repr(expected)
+ print('=== grouping error', t, end=' ')
+ print(repr(repl) + ' should be ' + repr(expected))
else:
- print '=== Failed incorrectly', t
+ print('=== Failed incorrectly', t)
# Try the match on a unicode string, and check that it
# still succeeds.
try:
result = obj.search(unicode(s, "latin-1"))
if result is None:
- print '=== Fails on unicode match', t
+ print('=== Fails on unicode match', t)
except NameError:
continue # 1.5.2
except TypeError:
@@ -689,7 +689,7 @@
obj=re.compile(unicode(pattern, "latin-1"))
result = obj.search(s)
if result is None:
- print '=== Fails on unicode pattern match', t
+ print('=== Fails on unicode pattern match', t)
# Try the match with the search area limited to the extent
# of the match and see if it still succeeds. \B will
@@ -701,28 +701,28 @@
obj = re.compile(pattern)
result = obj.search(s, result.start(0), result.end(0) + 1)
if result is None:
- print '=== Failed on range-limited match', t
+ print('=== Failed on range-limited match', t)
# Try the match with IGNORECASE enabled, and check that it
# still succeeds.
obj = re.compile(pattern, re.IGNORECASE)
result = obj.search(s)
if result is None:
- print '=== Fails on case-insensitive match', t
+ print('=== Fails on case-insensitive match', t)
# Try the match with LOCALE enabled, and check that it
# still succeeds.
obj = re.compile(pattern, re.LOCALE)
result = obj.search(s)
if result is None:
- print '=== Fails on locale-sensitive match', t
+ print('=== Fails on locale-sensitive match', t)
# Try the match with UNICODE locale enabled, and check
# that it still succeeds.
obj = re.compile(pattern, re.UNICODE)
result = obj.search(s)
if result is None:
- print '=== Fails on unicode-sensitive match', t
+ print('=== Fails on unicode-sensitive match', t)
def test_main():
run_unittest(ReTests)
Modified: python/branches/p3yk-noslice/Lib/test/test_repr.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_repr.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_repr.py Fri Feb 23 18:29:35 2007
@@ -90,10 +90,10 @@
def test_numbers(self):
eq = self.assertEquals
eq(r(123), repr(123))
- eq(r(123L), repr(123L))
+ eq(r(123), repr(123))
eq(r(1.0/3), repr(1.0/3))
- n = 10L**100
+ n = 10**100
expected = repr(n)[:18] + "..." + repr(n)[-19:]
eq(r(n), expected)
Modified: python/branches/p3yk-noslice/Lib/test/test_resource.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_resource.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_resource.py Fri Feb 23 18:29:35 2007
@@ -1,56 +1,96 @@
-import os
-import resource
+import unittest
+from test import test_support
-from test.test_support import TESTFN
-# This test is checking a few specific problem spots. RLIMIT_FSIZE
-# should be RLIM_INFINITY, which will be a really big number on a
-# platform with large file support. On these platforms, we need to
-# test that the get/setrlimit functions properly convert the number to
-# a C long long and that the conversion doesn't raise an error.
-
-try:
- cur, max = resource.getrlimit(resource.RLIMIT_FSIZE)
-except AttributeError:
- pass
-else:
- print resource.RLIM_INFINITY == max
- resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
-
-# Now check to see what happens when the RLIMIT_FSIZE is small. Some
-# versions of Python were terminated by an uncaught SIGXFSZ, but
-# pythonrun.c has been fixed to ignore that exception. If so, the
-# write() should return EFBIG when the limit is exceeded.
-
-# At least one platform has an unlimited RLIMIT_FSIZE and attempts to
-# change it raise ValueError instead.
-
-try:
- try:
- resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max))
- limit_set = 1
- except ValueError:
- limit_set = 0
- f = open(TESTFN, "wb")
- f.write("X" * 1024)
- try:
- f.write("Y")
- f.flush()
- except IOError:
- if not limit_set:
- raise
- f.close()
- os.unlink(TESTFN)
-finally:
- resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
-
-# And be sure that setrlimit is checking for really large values
-too_big = 10L**50
-try:
- resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max))
-except (OverflowError, ValueError):
- pass
-try:
- resource.setrlimit(resource.RLIMIT_FSIZE, (max, too_big))
-except (OverflowError, ValueError):
- pass
+import os, resource
+
+# This test is checking a few specific problem spots with the resource module.
+
+class ResourceTest(unittest.TestCase):
+
+ def test_args(self):
+ self.assertRaises(TypeError, resource.getrlimit)
+ self.assertRaises(TypeError, resource.getrlimit, 42, 42)
+ self.assertRaises(TypeError, resource.setrlimit)
+ self.assertRaises(TypeError, resource.setrlimit, 42, 42, 42)
+
+ def test_fsize_ismax(self):
+
+ try:
+ (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE)
+ except AttributeError:
+ pass
+ else:
+ # RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really big
+ # number on a platform with large file support. On these platforms,
+ # we need to test that the get/setrlimit functions properly convert
+ # the number to a C long long and that the conversion doesn't raise
+ # an error.
+ self.assertEqual(resource.RLIM_INFINITY, max)
+ resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
+
+ def test_fsize_enforced(self):
+ try:
+ (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE)
+ except AttributeError:
+ pass
+ else:
+ # Check to see what happens when the RLIMIT_FSIZE is small. Some
+ # versions of Python were terminated by an uncaught SIGXFSZ, but
+ # pythonrun.c has been fixed to ignore that exception. If so, the
+ # write() should return EFBIG when the limit is exceeded.
+
+ # At least one platform has an unlimited RLIMIT_FSIZE and attempts
+ # to change it raise ValueError instead.
+ try:
+ try:
+ resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max))
+ limit_set = True
+ except ValueError:
+ limit_set = False
+ f = open(test_support.TESTFN, "wb")
+ f.write("X" * 1024)
+ try:
+ f.write("Y")
+ f.flush()
+ except IOError:
+ if not limit_set:
+ raise
+ f.close()
+ os.unlink(test_support.TESTFN)
+ finally:
+ resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max))
+
+ def test_fsize_toobig(self):
+ # Be sure that setrlimit is checking for really large values
+ too_big = 10**50
+ try:
+ (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE)
+ except AttributeError:
+ pass
+ else:
+ try:
+ resource.setrlimit(resource.RLIMIT_FSIZE, (too_big, max))
+ except (OverflowError, ValueError):
+ pass
+ try:
+ resource.setrlimit(resource.RLIMIT_FSIZE, (max, too_big))
+ except (OverflowError, ValueError):
+ pass
+
+ def test_getrusage(self):
+ self.assertRaises(TypeError, resource.getrusage)
+ self.assertRaises(TypeError, resource.getrusage, 42, 42)
+ usageself = resource.getrusage(resource.RUSAGE_SELF)
+ usagechildren = resource.getrusage(resource.RUSAGE_CHILDREN)
+ # May not be available on all systems.
+ try:
+ usageboth = resource.getrusage(resource.RUSAGE_BOTH)
+ except (ValueError, AttributeError):
+ pass
+
+def test_main(verbose=None):
+ test_support.run_unittest(ResourceTest)
+
+if __name__ == "__main__":
+ test_main()
Modified: python/branches/p3yk-noslice/Lib/test/test_rfc822.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_rfc822.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_rfc822.py Fri Feb 23 18:29:35 2007
@@ -42,7 +42,7 @@
try:
mn, ma = results[i][0], results[i][1]
except IndexError:
- print 'extra parsed address:', repr(n), repr(a)
+ print('extra parsed address:', repr(n), repr(a))
continue
i = i + 1
self.assertEqual(mn, n,
@@ -52,7 +52,7 @@
if mn == n and ma == a:
pass
else:
- print 'not found:', repr(n), repr(a)
+ print('not found:', repr(n), repr(a))
out = m.getdate('date')
if out:
Modified: python/branches/p3yk-noslice/Lib/test/test_rgbimg.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_rgbimg.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_rgbimg.py Fri Feb 23 18:29:35 2007
@@ -14,7 +14,7 @@
class error(Exception):
pass
-print 'RGBimg test suite:'
+print('RGBimg test suite:')
def testimg(rgb_file, raw_file):
rgb_file = findfile(rgb_file)
@@ -40,11 +40,11 @@
source = findfile(source)
target = findfile(target)
if verbose:
- print "uudecoding", source, "->", target, "..."
+ print("uudecoding", source, "->", target, "...")
uu.decode(source, target)
if verbose:
- print "testing..."
+ print("testing...")
ttob = rgbimg.ttob(0)
if ttob != 0:
Modified: python/branches/p3yk-noslice/Lib/test/test_richcmp.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_richcmp.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_richcmp.py Fri Feb 23 18:29:35 2007
@@ -131,7 +131,7 @@
self.checkequal("gt", a, b, [False, False, False, True, True ])
self.checkequal("ge", a, b, [False, False, True, True, True ])
- for ops in opmap.itervalues():
+ for ops in opmap.values():
for op in ops:
# calls __bool__, which should fail
self.assertRaises(TypeError, bool, op(a, b))
@@ -150,7 +150,7 @@
continue # the combination int, int is useless
ta = typea(a)
tb = typeb(b)
- for ops in opmap.itervalues():
+ for ops in opmap.values():
for op in ops:
realoutcome = op(a, b)
testoutcome = op(ta, tb)
@@ -265,7 +265,7 @@
imag1a = {}
for i in range(50):
imag1a[random.randrange(100)*1j] = random.randrange(100)*1j
- items = imag1a.items()
+ items = list(imag1a.items())
random.shuffle(items)
imag1b = {}
for k, v in items:
Modified: python/branches/p3yk-noslice/Lib/test/test_runpy.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_runpy.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_runpy.py Fri Feb 23 18:29:35 2007
@@ -92,22 +92,22 @@
init_fname = "__init__"+os.extsep+"py"
test_fname = "runpy_test"+os.extsep+"py"
pkg_dir = sub_dir = tempfile.mkdtemp()
- if verbose: print " Package tree in:", sub_dir
+ if verbose: print(" Package tree in:", sub_dir)
sys.path.insert(0, pkg_dir)
- if verbose: print " Updated sys.path:", sys.path[0]
+ if verbose: print(" Updated sys.path:", sys.path[0])
for i in range(depth):
sub_dir = os.path.join(sub_dir, pkg_name)
os.mkdir(sub_dir)
- if verbose: print " Next level in:", sub_dir
+ if verbose: print(" Next level in:", sub_dir)
pkg_fname = os.path.join(sub_dir, init_fname)
pkg_file = open(pkg_fname, "w")
pkg_file.close()
- if verbose: print " Created:", pkg_fname
+ if verbose: print(" Created:", pkg_fname)
mod_fname = os.path.join(sub_dir, test_fname)
mod_file = open(mod_fname, "w")
mod_file.write(source)
mod_file.close()
- if verbose: print " Created:", mod_fname
+ if verbose: print(" Created:", mod_fname)
mod_name = (pkg_name+".")*depth + "runpy_test"
return pkg_dir, mod_fname, mod_name
@@ -118,49 +118,49 @@
try:
del sys.modules[entry]
except KeyError as ex:
- if verbose: print ex # Persist with cleaning up
- if verbose: print " Removed sys.modules entries"
+ if verbose: print(ex) # Persist with cleaning up
+ if verbose: print(" Removed sys.modules entries")
del sys.path[0]
- if verbose: print " Removed sys.path entry"
+ if verbose: print(" Removed sys.path entry")
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
try:
os.remove(os.path.join(root, name))
except OSError as ex:
- if verbose: print ex # Persist with cleaning up
+ if verbose: print(ex) # Persist with cleaning up
for name in dirs:
fullname = os.path.join(root, name)
try:
os.rmdir(fullname)
except OSError as ex:
- if verbose: print ex # Persist with cleaning up
+ if verbose: print(ex) # Persist with cleaning up
try:
os.rmdir(top)
- if verbose: print " Removed package tree"
+ if verbose: print(" Removed package tree")
except OSError as ex:
- if verbose: print ex # Persist with cleaning up
+ if verbose: print(ex) # Persist with cleaning up
def _check_module(self, depth):
pkg_dir, mod_fname, mod_name = (
self._make_pkg("x=1\n", depth))
try:
- if verbose: print "Running from source:", mod_name
+ if verbose: print("Running from source:", mod_name)
d1 = run_module(mod_name) # Read from source
self.failUnless(d1["x"] == 1)
del d1 # Ensure __loader__ entry doesn't keep file open
__import__(mod_name)
os.remove(mod_fname)
- if verbose: print "Running from compiled:", mod_name
+ if verbose: print("Running from compiled:", mod_name)
d2 = run_module(mod_name) # Read from bytecode
self.failUnless(d2["x"] == 1)
del d2 # Ensure __loader__ entry doesn't keep file open
finally:
self._del_pkg(pkg_dir, depth, mod_name)
- if verbose: print "Module executed successfully"
+ if verbose: print("Module executed successfully")
def test_run_module(self):
for depth in range(4):
- if verbose: print "Testing package depth:", depth
+ if verbose: print("Testing package depth:", depth)
self._check_module(depth)
Modified: python/branches/p3yk-noslice/Lib/test/test_sax.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_sax.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_sax.py Fri Feb 23 18:29:35 2007
@@ -27,7 +27,7 @@
tests = tests + 1
if outcome:
if verbose:
- print "Passed", name
+ print("Passed", name)
else:
failures.append(name)
@@ -216,7 +216,44 @@
('<ns1:doc xmlns:ns1="%s"><udoc></udoc></ns1:doc>' %
ns_uri)
-# ===== XMLFilterBase
+def test_1463026_1():
+ result = StringIO()
+ gen = XMLGenerator(result)
+
+ gen.startDocument()
+ gen.startElementNS((None, 'a'), 'a', {(None, 'b'):'c'})
+ gen.endElementNS((None, 'a'), 'a')
+ gen.endDocument()
+
+ return result.getvalue() == start+'<a b="c"></a>'
+
+def test_1463026_2():
+ result = StringIO()
+ gen = XMLGenerator(result)
+
+ gen.startDocument()
+ gen.startPrefixMapping(None, 'qux')
+ gen.startElementNS(('qux', 'a'), 'a', {})
+ gen.endElementNS(('qux', 'a'), 'a')
+ gen.endPrefixMapping(None)
+ gen.endDocument()
+
+ return result.getvalue() == start+'<a xmlns="qux"></a>'
+
+def test_1463026_3():
+ result = StringIO()
+ gen = XMLGenerator(result)
+
+ gen.startDocument()
+ gen.startPrefixMapping('my', 'qux')
+ gen.startElementNS(('qux', 'a'), 'a', {(None, 'b'):'c'})
+ gen.endElementNS(('qux', 'a'), 'a')
+ gen.endPrefixMapping('my')
+ gen.endDocument()
+
+ return result.getvalue() == start+'<my:a xmlns:my="qux" b="c"></my:a>'
+
+# ===== Xmlfilterbase
def test_filter_basic():
result = StringIO()
@@ -358,11 +395,11 @@
(attrs.getQNames() == [] or attrs.getQNames() == ["ns:attr"]) and \
len(attrs) == 1 and \
(ns_uri, "attr") in attrs and \
- attrs.keys() == [(ns_uri, "attr")] and \
+ list(attrs.keys()) == [(ns_uri, "attr")] and \
attrs.get((ns_uri, "attr")) == "val" and \
attrs.get((ns_uri, "attr"), 25) == "val" and \
- attrs.items() == [((ns_uri, "attr"), "val")] and \
- attrs.values() == ["val"] and \
+ list(attrs.items()) == [((ns_uri, "attr"), "val")] and \
+ list(attrs.values()) == ["val"] and \
attrs.getValue((ns_uri, "attr")) == "val" and \
attrs[(ns_uri, "attr")] == "val"
@@ -698,7 +735,7 @@
# Bug report: http://www.python.org/sf/1511497
import sys
old_modules = sys.modules.copy()
- for modname in sys.modules.keys():
+ for modname in list(sys.modules.keys()):
if modname.startswith("xml."):
del sys.modules[modname]
try:
@@ -734,8 +771,7 @@
outf.write(result.getvalue())
outf.close()
-items = locals().items()
-items.sort()
+items = sorted(locals().items())
for (name, value) in items:
if name[ : 5] == "test_":
confirm(value(), name)
@@ -745,7 +781,7 @@
del items
if verbose:
- print "%d tests, %d failures" % (tests, len(failures))
+ print("%d tests, %d failures" % (tests, len(failures)))
if failures:
raise TestFailed("%d of %d tests failed: %s"
% (len(failures), tests, ", ".join(failures)))
Modified: python/branches/p3yk-noslice/Lib/test/test_scope.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_scope.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_scope.py Fri Feb 23 18:29:35 2007
@@ -269,7 +269,7 @@
def testUnboundLocal(self):
def errorInOuter():
- print y
+ print(y)
def inner():
return y
y = 1
@@ -530,18 +530,18 @@
def testListCompLocalVars(self):
try:
- print bad
+ print(bad)
except NameError:
pass
else:
- print "bad should not be defined"
+ print("bad should not be defined")
def x():
[bad for s in 'a b' for bad in s.split()]
x()
try:
- print bad
+ print(bad)
except NameError:
pass
Modified: python/branches/p3yk-noslice/Lib/test/test_select.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_select.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_select.py Fri Feb 23 18:29:35 2007
@@ -9,7 +9,7 @@
except TypeError:
pass
else:
- print 'expected TypeError exception not raised'
+ print('expected TypeError exception not raised')
class Nope:
pass
@@ -23,47 +23,47 @@
except TypeError:
pass
else:
- print 'expected TypeError exception not raised'
+ print('expected TypeError exception not raised')
try:
rfd, wfd, xfd = select.select([Almost()], [], [])
except TypeError:
pass
else:
- print 'expected TypeError exception not raised'
+ print('expected TypeError exception not raised')
try:
rfd, wfd, xfd = select.select([], [], [], 'not a number')
except TypeError:
pass
else:
- print 'expected TypeError exception not raised'
+ print('expected TypeError exception not raised')
def test():
import sys
if sys.platform[:3] in ('win', 'mac', 'os2', 'riscos'):
if verbose:
- print "Can't test select easily on", sys.platform
+ print("Can't test select easily on", sys.platform)
return
cmd = 'for i in 0 1 2 3 4 5 6 7 8 9; do echo testing...; sleep 1; done'
p = os.popen(cmd, 'r')
for tout in (0, 1, 2, 4, 8, 16) + (None,)*10:
if verbose:
- print 'timeout =', tout
+ print('timeout =', tout)
rfd, wfd, xfd = select.select([p], [], [], tout)
if (rfd, wfd, xfd) == ([], [], []):
continue
if (rfd, wfd, xfd) == ([p], [], []):
line = p.readline()
if verbose:
- print repr(line)
+ print(repr(line))
if not line:
if verbose:
- print 'EOF'
+ print('EOF')
break
continue
- print 'Unexpected return values from select():', rfd, wfd, xfd
+ print('Unexpected return values from select():', rfd, wfd, xfd)
p.close()
reap_children()
Modified: python/branches/p3yk-noslice/Lib/test/test_set.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_set.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_set.py Fri Feb 23 18:29:35 2007
@@ -26,6 +26,14 @@
def __repr__(self):
return repr(self.value)
+class HashCountingInt(int):
+ 'int-like object that counts the number of times __hash__ is called'
+ def __init__(self, *args):
+ self.hash_count = 0
+ def __hash__(self):
+ self.hash_count += 1
+ return int.__hash__(self)
+
class TestJointOps(unittest.TestCase):
# Tests common to both set and frozenset
@@ -265,7 +273,7 @@
w.value = s
try:
fo = open(test_support.TESTFN, "wb")
- print >> fo, s,
+ fo.write(str(s))
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), repr(s))
@@ -273,6 +281,18 @@
fo.close()
os.remove(test_support.TESTFN)
+ def test_do_not_rehash_dict_keys(self):
+ n = 10
+ d = dict.fromkeys(map(HashCountingInt, xrange(n)))
+ self.assertEqual(sum(elem.hash_count for elem in d), n)
+ s = self.thetype(d)
+ self.assertEqual(sum(elem.hash_count for elem in d), n)
+ s.difference(d)
+ self.assertEqual(sum(elem.hash_count for elem in d), n)
+ if hasattr(s, 'symmetric_difference_update'):
+ s.symmetric_difference_update(d)
+ self.assertEqual(sum(elem.hash_count for elem in d), n)
+
class TestSet(TestJointOps):
thetype = set
@@ -476,6 +496,16 @@
class TestSetSubclass(TestSet):
thetype = SetSubclass
+class SetSubclassWithKeywordArgs(set):
+ def __init__(self, iterable=[], newarg=None):
+ set.__init__(self, iterable)
+
+class TestSetSubclassWithKeywordArgs(TestSet):
+
+ def test_keywords_in_subclass(self):
+ 'SF bug #1486663 -- this used to erroneously raise a TypeError'
+ SetSubclassWithKeywordArgs(newarg=1)
+
class TestFrozenSet(TestJointOps):
thetype = frozenset
@@ -584,7 +614,7 @@
def test_print(self):
try:
fo = open(test_support.TESTFN, "wb")
- print >> fo, self.set,
+ fo.write(str(self.set))
fo.close()
fo = open(test_support.TESTFN, "rb")
self.assertEqual(fo.read(), repr(self.set))
@@ -1454,6 +1484,7 @@
test_classes = (
TestSet,
TestSetSubclass,
+ TestSetSubclassWithKeywordArgs,
TestFrozenSet,
TestFrozenSetSubclass,
TestSetOfSets,
@@ -1495,7 +1526,7 @@
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
Modified: python/branches/p3yk-noslice/Lib/test/test_signal.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_signal.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_signal.py Fri Feb 23 18:29:35 2007
@@ -15,7 +15,7 @@
pid = os.getpid()
if verbose:
- print "test runner's pid is", pid
+ print("test runner's pid is", pid)
# Shell script that will send us asynchronous signals
script = """
@@ -36,7 +36,7 @@
global a_called
a_called = True
if verbose:
- print "handlerA invoked", args
+ print("handlerA invoked", args)
class HandlerBCalled(Exception):
pass
@@ -45,7 +45,7 @@
global b_called
b_called = True
if verbose:
- print "handlerB invoked", args
+ print("handlerB invoked", args)
raise HandlerBCalled, args
# Set up a child to send signals to us (the parent) after waiting long
@@ -69,10 +69,10 @@
# time for the normal sequence of events to occur. This is
# just a stop-gap to try to prevent the test from hanging.
time.sleep(MAX_DURATION + 5)
- print >> sys.__stdout__, ' child should not have to kill parent'
+ print(' child should not have to kill parent', file=sys.__stdout__)
for signame in "SIGHUP", "SIGUSR1", "SIGUSR2", "SIGALRM":
os.kill(pid, getattr(signal, signame))
- print >> sys.__stdout__, " child sent", signame, "to", pid
+ print(" child sent", signame, "to", pid, file=sys.__stdout__)
time.sleep(1)
finally:
os._exit(0)
@@ -126,27 +126,27 @@
# KeyboardInterrupt, finally getting us out of the loop.
os.system(script)
try:
- print "starting pause() loop..."
+ print("starting pause() loop...")
while 1:
try:
if verbose:
- print "call pause()..."
+ print("call pause()...")
signal.pause()
if verbose:
- print "pause() returned"
+ print("pause() returned")
except HandlerBCalled:
if verbose:
- print "HandlerBCalled exception caught"
+ print("HandlerBCalled exception caught")
except KeyboardInterrupt:
if verbose:
- print "KeyboardInterrupt (the alarm() went off)"
+ print("KeyboardInterrupt (the alarm() went off)")
if not a_called:
- print 'HandlerA not called'
+ print('HandlerA not called')
if not b_called:
- print 'HandlerB not called'
+ print('HandlerB not called')
finally:
# Forcibly kill the child we created to ping us if there was a test error.
Modified: python/branches/p3yk-noslice/Lib/test/test_site.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_site.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_site.py Fri Feb 23 18:29:35 2007
@@ -119,11 +119,11 @@
"""
FILE = open(self.file_path, 'w')
try:
- print>>FILE, "#import @bad module name"
- print>>FILE, "\n"
- print>>FILE, "import %s" % self.imported
- print>>FILE, self.good_dirname
- print>>FILE, self.bad_dirname
+ print("#import @bad module name", file=FILE)
+ print("\n", file=FILE)
+ print("import %s" % self.imported, file=FILE)
+ print(self.good_dirname, file=FILE)
+ print(self.bad_dirname, file=FILE)
finally:
FILE.close()
os.mkdir(self.good_dir_path)
@@ -204,7 +204,7 @@
if sys.platform == "win32":
import locale
if locale.getdefaultlocale()[1].startswith('cp'):
- for value in encodings.aliases.aliases.itervalues():
+ for value in encodings.aliases.aliases.values():
if value == "mbcs":
break
else:
Modified: python/branches/p3yk-noslice/Lib/test/test_slice.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_slice.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_slice.py Fri Feb 23 18:29:35 2007
@@ -86,11 +86,11 @@
slice(100, -100, -1).indices(10),
slice(None, None, -1).indices(10)
)
- self.assertEqual(slice(-100L, 100L, 2L).indices(10), (0, 10, 2))
+ self.assertEqual(slice(-100, 100, 2).indices(10), (0, 10, 2))
self.assertEqual(range(10)[::sys.maxint - 1], [0])
- self.assertRaises(OverflowError, slice(None).indices, 1L<<100)
+ self.assertRaises(OverflowError, slice(None).indices, 1<<100)
def test_main():
test_support.run_unittest(SliceTest)
Modified: python/branches/p3yk-noslice/Lib/test/test_socket.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_socket.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_socket.py Fri Feb 23 18:29:35 2007
@@ -302,13 +302,27 @@
sizes = {socket.htonl: 32, socket.ntohl: 32,
socket.htons: 16, socket.ntohs: 16}
for func, size in sizes.items():
- mask = (1L<<size) - 1
+ mask = (1<<size) - 1
for i in (0, 1, 0xffff, ~0xffff, 2, 0x01234567, 0x76543210):
self.assertEqual(i & mask, func(func(i&mask)) & mask)
swapped = func(mask)
self.assertEqual(swapped & mask, mask)
- self.assertRaises(OverflowError, func, 1L<<34)
+ self.assertRaises(OverflowError, func, 1<<34)
+
+ def testNtoHErrors(self):
+ good_values = [ 1, 2, 3, 1, 2, 3 ]
+ bad_values = [ -1, -2, -3, -1, -2, -3 ]
+ for k in good_values:
+ socket.ntohl(k)
+ socket.ntohs(k)
+ socket.htonl(k)
+ socket.htons(k)
+ for k in bad_values:
+ self.assertRaises(OverflowError, socket.ntohl, k)
+ self.assertRaises(OverflowError, socket.ntohs, k)
+ self.assertRaises(OverflowError, socket.htonl, k)
+ self.assertRaises(OverflowError, socket.htons, k)
def testGetServBy(self):
eq = self.assertEqual
@@ -795,6 +809,31 @@
bufsize = 2 # Exercise the buffering code
+
+class Urllib2FileobjectTest(unittest.TestCase):
+
+ # urllib2.HTTPHandler has "borrowed" socket._fileobject, and requires that
+ # it close the socket if the close c'tor argument is true
+
+ def testClose(self):
+ class MockSocket:
+ closed = False
+ def flush(self): pass
+ def close(self): self.closed = True
+
+ # must not close unless we request it: the original use of _fileobject
+ # by module socket requires that the underlying socket not be closed until
+ # the _socketobject that created the _fileobject is closed
+ s = MockSocket()
+ f = socket._fileobject(s)
+ f.close()
+ self.assert_(not s.closed)
+
+ s = MockSocket()
+ f = socket._fileobject(s, close=True)
+ f.close()
+ self.assert_(s.closed)
+
class TCPTimeoutTest(SocketTCPTest):
def testTCPTimeout(self):
@@ -947,7 +986,8 @@
FileObjectClassTestCase,
UnbufferedFileObjectClassTestCase,
LineBufferedFileObjectClassTestCase,
- SmallBufferedFileObjectClassTestCase
+ SmallBufferedFileObjectClassTestCase,
+ Urllib2FileobjectTest,
])
if hasattr(socket, "socketpair"):
tests.append(BasicSocketPairTest)
Modified: python/branches/p3yk-noslice/Lib/test/test_socket_ssl.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_socket_ssl.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_socket_ssl.py Fri Feb 23 18:29:35 2007
@@ -16,7 +16,7 @@
import urllib
if test_support.verbose:
- print "test_basic ..."
+ print("test_basic ...")
socket.RAND_status()
try:
@@ -24,7 +24,7 @@
except TypeError:
pass
else:
- print "didn't raise TypeError"
+ print("didn't raise TypeError")
socket.RAND_add("this is a random string", 75.0)
f = urllib.urlopen('https://sf.net')
@@ -35,14 +35,14 @@
test_support.requires('network')
def error_msg(extra_msg):
- print >> sys.stderr, """\
+ print("""\
WARNING: an attempt to connect to %r %s, in
test_timeout. That may be legitimate, but is not the outcome we hoped
for. If this message is seen often, test_timeout should be changed to
- use a more reliable address.""" % (ADDR, extra_msg)
+ use a more reliable address.""" % (ADDR, extra_msg), file=sys.stderr)
if test_support.verbose:
- print "test_timeout ..."
+ print("test_timeout ...")
# A service which issues a welcome banner (without need to write
# anything).
@@ -73,7 +73,7 @@
def test_rude_shutdown():
if test_support.verbose:
- print "test_rude_shutdown ..."
+ print("test_rude_shutdown ...")
try:
import threading
Modified: python/branches/p3yk-noslice/Lib/test/test_socketserver.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_socketserver.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_socketserver.py Fri Feb 23 18:29:35 2007
@@ -77,16 +77,16 @@
def run(self):
class svrcls(MyMixinServer, self.__svrcls):
pass
- if verbose: print "thread: creating server"
+ if verbose: print("thread: creating server")
svr = svrcls(self.__addr, self.__hdlrcls)
# pull the address out of the server in case it changed
# this can happen if another process is using the port
addr = getattr(svr, 'server_address')
if addr:
self.__addr = addr
- if verbose: print "thread: serving three times"
+ if verbose: print("thread: serving three times")
svr.serve_a_few()
- if verbose: print "thread: done"
+ if verbose: print("thread: done")
seed = 0
def pickport():
@@ -129,19 +129,19 @@
for svrcls in servers:
addr = pickaddr(proto)
if verbose:
- print "ADDR =", addr
- print "CLASS =", svrcls
+ print("ADDR =", addr)
+ print("CLASS =", svrcls)
t = ServerThread(addr, svrcls, hdlrcls)
- if verbose: print "server created"
+ if verbose: print("server created")
t.start()
- if verbose: print "server running"
+ if verbose: print("server running")
for i in range(NREQ):
time.sleep(DELAY)
- if verbose: print "test client", i
+ if verbose: print("test client", i)
testfunc(proto, addr)
- if verbose: print "waiting for server"
+ if verbose: print("waiting for server")
t.join()
- if verbose: print "done"
+ if verbose: print("done")
class ForgivingTCPServer(TCPServer):
# prevent errors if another process is using the port we want
@@ -159,8 +159,7 @@
(err, msg) = e
if err != errno.EADDRINUSE:
raise
- print >>sys.__stderr__, \
- ' WARNING: failed to listen on port %d, trying another' % port
+ print(' WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__)
tcpservers = [ForgivingTCPServer, ThreadingTCPServer]
if hasattr(os, 'fork') and os.name not in ('os2',):
Deleted: /python/branches/p3yk-noslice/Lib/test/test_softspace.py
==============================================================================
--- /python/branches/p3yk-noslice/Lib/test/test_softspace.py Fri Feb 23 18:29:35 2007
+++ (empty file)
@@ -1,14 +0,0 @@
-from test import test_support
-import StringIO
-
-# SF bug 480215: softspace confused in nested print
-f = StringIO.StringIO()
-class C:
- def __str__(self):
- print >> f, 'a'
- return 'b'
-
-print >> f, C(), 'c ', 'd\t', 'e'
-print >> f, 'f', 'g'
-# In 2.2 & earlier, this printed ' a\nbc d\te\nf g\n'
-test_support.vereq(f.getvalue(), 'a\nb c d\te\nf g\n')
Modified: python/branches/p3yk-noslice/Lib/test/test_sort.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_sort.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_sort.py Fri Feb 23 18:29:35 2007
@@ -10,7 +10,7 @@
global nerrors
if verbose:
- print " checking", tag
+ print(" checking", tag)
orig = raw[:] # save input in case of error
if compare:
@@ -19,22 +19,22 @@
raw.sort()
if len(expected) != len(raw):
- print "error in", tag
- print "length mismatch;", len(expected), len(raw)
- print expected
- print orig
- print raw
+ print("error in", tag)
+ print("length mismatch;", len(expected), len(raw))
+ print(expected)
+ print(orig)
+ print(raw)
nerrors += 1
return
for i, good in enumerate(expected):
maybe = raw[i]
if good is not maybe:
- print "error in", tag
- print "out of order at index", i, good, maybe
- print expected
- print orig
- print raw
+ print("error in", tag)
+ print("out of order at index", i, good, maybe)
+ print(expected)
+ print(orig)
+ print(raw)
nerrors += 1
return
@@ -56,7 +56,7 @@
def __lt__(self, other):
if Complains.maybe_complain and random.random() < 0.001:
if verbose:
- print " complaining at", self, other
+ print(" complaining at", self, other)
raise RuntimeError
return self.i < other.i
@@ -77,7 +77,7 @@
for n in sizes:
x = range(n)
if verbose:
- print "Testing size", n
+ print("Testing size", n)
s = x[:]
check("identity", x, s)
@@ -96,8 +96,8 @@
check("reversed via function", y, s, lambda a, b: cmp(b, a))
if verbose:
- print " Checking against an insane comparison function."
- print " If the implementation isn't careful, this may segfault."
+ print(" Checking against an insane comparison function.")
+ print(" If the implementation isn't careful, this may segfault.")
s = x[:]
s.sort(lambda a, b: int(random.random() * 3) - 1)
check("an insane function left some permutation", x, s)
@@ -285,7 +285,7 @@
test_support.run_unittest(*test_classes)
gc.collect()
counts[i] = sys.gettotalrefcount()
- print counts
+ print(counts)
if __name__ == "__main__":
test_main(verbose=True)
Modified: python/branches/p3yk-noslice/Lib/test/test_strftime.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_strftime.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_strftime.py Fri Feb 23 18:29:35 2007
@@ -40,8 +40,8 @@
def strftest(now):
if verbose:
- print "strftime test for", time.ctime(now)
- nowsecs = str(long(now))[:-1]
+ print("strftime test for", time.ctime(now))
+ nowsecs = str(int(now))[:-1]
gmt = time.gmtime(now)
now = time.localtime(now)
@@ -113,42 +113,42 @@
)
if verbose:
- print "Strftime test, platform: %s, Python version: %s" % \
- (sys.platform, sys.version.split()[0])
+ print("Strftime test, platform: %s, Python version: %s" % \
+ (sys.platform, sys.version.split()[0]))
for e in expectations:
try:
result = time.strftime(e[0], now)
except ValueError as error:
- print "Standard '%s' format gave error:" % e[0], error
+ print("Standard '%s' format gave error:" % e[0], error)
continue
if re.match(escapestr(e[1], ampm), result): continue
if not result or result[0] == '%':
- print "Does not support standard '%s' format (%s)" % (e[0], e[2])
+ print("Does not support standard '%s' format (%s)" % (e[0], e[2]))
else:
- print "Conflict for %s (%s):" % (e[0], e[2])
- print " Expected %s, but got %s" % (e[1], result)
+ print("Conflict for %s (%s):" % (e[0], e[2]))
+ print(" Expected %s, but got %s" % (e[1], result))
for e in nonstandard_expectations:
try:
result = time.strftime(e[0], now)
except ValueError as result:
if verbose:
- print "Error for nonstandard '%s' format (%s): %s" % \
- (e[0], e[2], str(result))
+ print("Error for nonstandard '%s' format (%s): %s" % \
+ (e[0], e[2], str(result)))
continue
if re.match(escapestr(e[1], ampm), result):
if verbose:
- print "Supports nonstandard '%s' format (%s)" % (e[0], e[2])
+ print("Supports nonstandard '%s' format (%s)" % (e[0], e[2]))
elif not result or result[0] == '%':
if verbose:
- print "Does not appear to support '%s' format (%s)" % (e[0],
- e[2])
+ print("Does not appear to support '%s' format (%s)" % (e[0],
+ e[2]))
else:
if verbose:
- print "Conflict for nonstandard '%s' format (%s):" % (e[0],
- e[2])
- print " Expected %s, but got %s" % (e[1], result)
+ print("Conflict for nonstandard '%s' format (%s):" % (e[0],
+ e[2]))
+ print(" Expected %s, but got %s" % (e[1], result))
def fixasctime(s):
if s[8] == ' ':
Modified: python/branches/p3yk-noslice/Lib/test/test_string.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_string.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_string.py Fri Feb 23 18:29:35 2007
@@ -83,7 +83,7 @@
self.assertRaises(ValueError, string.atoi, " x1 ")
def test_atol(self):
- self.assertEqual(string.atol(" 1 "), 1L)
+ self.assertEqual(string.atol(" 1 "), 1)
self.assertRaises(ValueError, string.atol, " 1x ")
self.assertRaises(ValueError, string.atol, " x1 ")
Modified: python/branches/p3yk-noslice/Lib/test/test_strop.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_strop.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_strop.py Fri Feb 23 18:29:35 2007
@@ -15,7 +15,7 @@
self.assertRaises(ValueError, strop.atoi, " x1 ")
def test_atol(self):
- self.assert_(strop.atol(" 1 ") == 1L)
+ self.assert_(strop.atol(" 1 ") == 1)
self.assertRaises(ValueError, strop.atol, " 1x")
self.assertRaises(ValueError, strop.atol, " x1 ")
Modified: python/branches/p3yk-noslice/Lib/test/test_strptime.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_strptime.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_strptime.py Fri Feb 23 18:29:35 2007
@@ -463,6 +463,10 @@
"of the year")
test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and "
"ending on Monday")
+ test_helper((2007, 01, 07), "First Sunday of 2007")
+ test_helper((2007, 01, 14), "Second Sunday of 2007")
+ test_helper((2006, 12, 31), "Last Sunday of 2006")
+ test_helper((2006, 12, 24), "Second to last Sunday of 2006")
class CacheTests(unittest.TestCase):
Modified: python/branches/p3yk-noslice/Lib/test/test_struct.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_struct.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_struct.py Fri Feb 23 18:29:35 2007
@@ -84,8 +84,8 @@
if sz * 3 != struct.calcsize('iii'):
raise TestFailed, 'inconsistent sizes'
-fmt = 'cbxxxxxxhhhhiillffd'
-fmt3 = '3c3b18x12h6i6l6f3d'
+fmt = 'cbxxxxxxhhhhiillffdt'
+fmt3 = '3c3b18x12h6i6l6f3d3t'
sz = struct.calcsize(fmt)
sz3 = struct.calcsize(fmt3)
if sz * 3 != sz3:
@@ -108,19 +108,21 @@
l = 65536
f = 3.1415
d = 3.1415
+t = True
for prefix in ('', '@', '<', '>', '=', '!'):
- for format in ('xcbhilfd', 'xcBHILfd'):
+ for format in ('xcbhilfdt', 'xcBHILfdt'):
format = prefix + format
if verbose:
- print "trying:", format
- s = struct.pack(format, c, b, h, i, l, f, d)
- cp, bp, hp, ip, lp, fp, dp = struct.unpack(format, s)
+ print("trying:", format)
+ s = struct.pack(format, c, b, h, i, l, f, d, t)
+ cp, bp, hp, ip, lp, fp, dp, tp = struct.unpack(format, s)
if (cp != c or bp != b or hp != h or ip != i or lp != l or
- int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d)):
+ int(100 * fp) != int(100 * f) or int(100 * dp) != int(100 * d) or
+ tp != t):
# ^^^ calculate only to two decimal places
raise TestFailed, "unpack/pack not transitive (%s, %s)" % (
- str(format), str((cp, bp, hp, ip, lp, fp, dp)))
+ str(format), str((cp, bp, hp, ip, lp, fp, dp, tp)))
# Test some of the new features in detail
@@ -146,23 +148,28 @@
('H', 0x10000-700, '\375D', 'D\375', 0),
('i', 70000000, '\004,\035\200', '\200\035,\004', 0),
('i', -70000000, '\373\323\342\200', '\200\342\323\373', 0),
- ('I', 70000000L, '\004,\035\200', '\200\035,\004', 0),
- ('I', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0),
+ ('I', 70000000, '\004,\035\200', '\200\035,\004', 0),
+ ('I', 0x100000000-70000000, '\373\323\342\200', '\200\342\323\373', 0),
('l', 70000000, '\004,\035\200', '\200\035,\004', 0),
('l', -70000000, '\373\323\342\200', '\200\342\323\373', 0),
- ('L', 70000000L, '\004,\035\200', '\200\035,\004', 0),
- ('L', 0x100000000L-70000000, '\373\323\342\200', '\200\342\323\373', 0),
+ ('L', 70000000, '\004,\035\200', '\200\035,\004', 0),
+ ('L', 0x100000000-70000000, '\373\323\342\200', '\200\342\323\373', 0),
('f', 2.0, '@\000\000\000', '\000\000\000@', 0),
('d', 2.0, '@\000\000\000\000\000\000\000',
'\000\000\000\000\000\000\000@', 0),
('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0),
('d', -2.0, '\300\000\000\000\000\000\000\000',
'\000\000\000\000\000\000\000\300', 0),
+ ('t', 0, '\0', '\0', 0),
+ ('t', 3, '\1', '\1', 1),
+ ('t', True, '\1', '\1', 0),
+ ('t', [], '\0', '\0', 1),
+ ('t', (1,), '\1', '\1', 1),
]
for fmt, arg, big, lil, asy in tests:
if verbose:
- print "%r %r %r %r" % (fmt, arg, big, lil)
+ print("%r %r %r %r" % (fmt, arg, big, lil))
for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
('='+fmt, ISBIGENDIAN and big or lil)]:
res = struct.pack(xfmt, arg)
@@ -188,7 +195,7 @@
has_native_qQ = 0
if verbose:
- print "Platform has native q/Q?", has_native_qQ and "Yes." or "No."
+ print("Platform has native q/Q?", has_native_qQ and "Yes." or "No.")
any_err(struct.pack, "Q", -1) # can't pack -1 as unsigned regardless
simple_err(struct.pack, "q", "a") # can't pack string as 'q' regardless
@@ -203,9 +210,9 @@
('q', -1, '\xff' * bytes),
('q', 0, '\x00' * bytes),
('Q', 0, '\x00' * bytes),
- ('q', 1L, '\x00' * (bytes-1) + '\x01'),
- ('Q', (1L << (8*bytes))-1, '\xff' * bytes),
- ('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))):
+ ('q', 1, '\x00' * (bytes-1) + '\x01'),
+ ('Q', (1 << (8*bytes))-1, '\xff' * bytes),
+ ('q', (1 << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))):
got = struct.pack(format, input)
native_expected = bigendian_to_native(expected)
verify(got == native_expected,
@@ -243,23 +250,23 @@
self.bitsize = bytesize * 8
self.signed_code, self.unsigned_code = formatpair
self.unsigned_min = 0
- self.unsigned_max = 2L**self.bitsize - 1
- self.signed_min = -(2L**(self.bitsize-1))
- self.signed_max = 2L**(self.bitsize-1) - 1
+ self.unsigned_max = 2**self.bitsize - 1
+ self.signed_min = -(2**(self.bitsize-1))
+ self.signed_max = 2**(self.bitsize-1) - 1
def test_one(self, x, pack=struct.pack,
unpack=struct.unpack,
unhexlify=binascii.unhexlify):
if verbose:
- print "trying std", self.formatpair, "on", x, "==", hex(x)
+ print("trying std", self.formatpair, "on", x, "==", hex(x))
# Try signed.
code = self.signed_code
if self.signed_min <= x <= self.signed_max:
# Try big-endian.
- expected = long(x)
+ expected = int(x)
if x < 0:
- expected += 1L << self.bitsize
+ expected += 1 << self.bitsize
assert expected > 0
expected = hex(expected)[2:] # chop "0x"
if len(expected) & 1:
@@ -306,7 +313,7 @@
# x is out of range -- verify pack realizes that.
if not PY_STRUCT_RANGE_CHECKING and code in self.BUGGY_RANGE_CHECK:
if verbose:
- print "Skipping buggy range check for code", code
+ print("Skipping buggy range check for code", code)
else:
deprecated_err(pack, ">" + code, x)
deprecated_err(pack, "<" + code, x)
@@ -316,7 +323,7 @@
if self.unsigned_min <= x <= self.unsigned_max:
# Try big-endian.
format = ">" + code
- expected = long(x)
+ expected = int(x)
expected = hex(expected)[2:] # chop "0x"
if len(expected) & 1:
expected = "0" + expected
@@ -361,7 +368,7 @@
# x is out of range -- verify pack realizes that.
if not PY_STRUCT_RANGE_CHECKING and code in self.BUGGY_RANGE_CHECK:
if verbose:
- print "Skipping buggy range check for code", code
+ print("Skipping buggy range check for code", code)
else:
deprecated_err(pack, ">" + code, x)
deprecated_err(pack, "<" + code, x)
@@ -372,11 +379,11 @@
# Create all interesting powers of 2.
values = []
for exp in range(self.bitsize + 3):
- values.append(1L << exp)
+ values.append(1 << exp)
# Add some random values.
for i in range(self.bitsize):
- val = 0L
+ val = 0
for j in range(self.bytesize):
val = (val << 8) | randrange(256)
values.append(val)
@@ -485,15 +492,15 @@
def test_1229380():
import sys
for endian in ('', '>', '<'):
- for cls in (int, long):
+ for cls in (int, int):
for fmt in ('B', 'H', 'I', 'L'):
deprecated_err(struct.pack, endian + fmt, cls(-1))
deprecated_err(struct.pack, endian + 'B', cls(300))
deprecated_err(struct.pack, endian + 'H', cls(70000))
- deprecated_err(struct.pack, endian + 'I', sys.maxint * 4L)
- deprecated_err(struct.pack, endian + 'L', sys.maxint * 4L)
+ deprecated_err(struct.pack, endian + 'I', sys.maxint * 4)
+ deprecated_err(struct.pack, endian + 'L', sys.maxint * 4)
if PY_STRUCT_RANGE_CHECKING:
test_1229380()
@@ -612,3 +619,50 @@
test_unpack_from()
test_pack_into()
test_pack_into_fn()
+
+def test_bool():
+ for prefix in tuple("<>!=")+('',):
+ false = (), [], [], '', 0
+ true = [1], 'test', 5, -1, 0xffffffff+1, 0xffffffff/2
+
+ falseFormat = prefix + 't' * len(false)
+ if verbose:
+ print('trying bool pack/unpack on', false, 'using format', falseFormat)
+ packedFalse = struct.pack(falseFormat, *false)
+ unpackedFalse = struct.unpack(falseFormat, packedFalse)
+
+ trueFormat = prefix + 't' * len(true)
+ if verbose:
+ print('trying bool pack/unpack on', true, 'using format', trueFormat)
+ packedTrue = struct.pack(trueFormat, *true)
+ unpackedTrue = struct.unpack(trueFormat, packedTrue)
+
+ if len(true) != len(unpackedTrue):
+ raise TestFailed('unpacked true array is not of same size as input')
+ if len(false) != len(unpackedFalse):
+ raise TestFailed('unpacked false array is not of same size as input')
+
+ for t in unpackedFalse:
+ if t is not False:
+ raise TestFailed('%r did not unpack as False' % t)
+ for t in unpackedTrue:
+ if t is not True:
+ raise TestFailed('%r did not unpack as false' % t)
+
+ if prefix and verbose:
+ print('trying size of bool with format %r' % (prefix+'t'))
+ packed = struct.pack(prefix+'t', 1)
+
+ if len(packed) != struct.calcsize(prefix+'t'):
+ raise TestFailed('packed length is not equal to calculated size')
+
+ if len(packed) != 1 and prefix:
+ raise TestFailed('encoded bool is not one byte: %r' % packed)
+ elif not prefix and verbose:
+ print('size of bool in native format is %i' % (len(packed)))
+
+ for c in '\x01\x7f\xff\x0f\xf0':
+ if struct.unpack('>t', c)[0] is not True:
+ raise TestFailed('%c did not unpack as True' % c)
+
+test_bool()
Modified: python/branches/p3yk-noslice/Lib/test/test_subprocess.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_subprocess.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_subprocess.py Fri Feb 23 18:29:35 2007
@@ -84,7 +84,7 @@
def test_stdin_none(self):
# .stdin is None when not redirected
- p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
+ p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
self.assertEqual(p.stdin, None)
@@ -92,16 +92,16 @@
def test_stdout_none(self):
# .stdout is None when not redirected
p = subprocess.Popen([sys.executable, "-c",
- 'print " this bit of output is from a '
+ 'print(" this bit of output is from a '
'test of stdout in a different '
- 'process ..."'],
+ 'process ...")'],
stdin=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
self.assertEqual(p.stdout, None)
def test_stderr_none(self):
# .stderr is None when not redirected
- p = subprocess.Popen([sys.executable, "-c", 'print "banana"'],
+ p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.wait()
self.assertEqual(p.stderr, None)
@@ -430,6 +430,8 @@
'"a\\\\b c" d e')
self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
'"a\\\\b\\ c" d e')
+ self.assertEqual(subprocess.list2cmdline(['ab', '']),
+ 'ab ""')
def test_poll(self):
Modified: python/branches/p3yk-noslice/Lib/test/test_sundry.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_sundry.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_sundry.py Fri Feb 23 18:29:35 2007
@@ -68,7 +68,7 @@
import tty # not available on Windows
except ImportError:
if verbose:
- print "skipping tty"
+ print("skipping tty")
# Can't test the "user" module -- if the user has a ~/.pythonrc.py, it
# can screw up all sorts of things (esp. if it prints!).
Modified: python/branches/p3yk-noslice/Lib/test/test_support.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_support.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_support.py Fri Feb 23 18:29:35 2007
@@ -106,8 +106,7 @@
(err, msg) = e
if err != errno.EADDRINUSE:
raise
- print >>sys.__stderr__, \
- ' WARNING: failed to listen on port %d, trying another' % port
+ print(' WARNING: failed to listen on port %d, trying another' % port, file=sys.__stderr__)
raise TestFailed, 'unable to find port to listen on'
FUZZ = 1e-6
@@ -178,10 +177,9 @@
except UnicodeEncodeError:
pass
else:
- print \
- 'WARNING: The filename %r CAN be encoded by the filesystem. ' \
+ print('WARNING: The filename %r CAN be encoded by the filesystem. ' \
'Unicode filename tests may not be effective' \
- % TESTFN_UNICODE_UNENCODEABLE
+ % TESTFN_UNICODE_UNENCODEABLE)
# Make sure we can write to TESTFN, try in /tmp if we can't
fp = None
@@ -194,8 +192,8 @@
TESTFN = TMP_TESTFN
del TMP_TESTFN
except IOError:
- print ('WARNING: tests will fail, unable to write to: %s or %s' %
- (TESTFN, TMP_TESTFN))
+ print(('WARNING: tests will fail, unable to write to: %s or %s' %
+ (TESTFN, TMP_TESTFN)))
if fp is not None:
fp.close()
unlink(TESTFN)
@@ -241,8 +239,7 @@
def sortdict(dict):
"Like repr(dict), but in sorted order."
- items = dict.items()
- items.sort()
+ items = sorted(dict.items())
reprpairs = ["%r: %r" % pair for pair in items]
withcommas = ", ".join(reprpairs)
return "{%s}" % withcommas
@@ -267,10 +264,10 @@
return open(fn)
requires('urlfetch')
- print >> get_original_stdout(), '\tfetching %s ...' % url
+ print('\tfetching %s ...' % url, file=get_original_stdout())
fn, _ = urllib.urlretrieve(url, filename)
return open(fn)
-
+
@contextmanager
def guard_warnings_filter():
"""Guard the warnings filter from being permanently changed."""
@@ -307,7 +304,7 @@
return self
def __exit__(self, *ignore_exc):
- for envvar, value in self._reset.iteritems():
+ for envvar, value in self._reset.items():
self._environ[envvar] = value
for unset in self._unset:
del self._environ[unset]
@@ -511,7 +508,7 @@
finally:
sys.stdout = save_stdout
if verbose:
- print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t)
+ print('doctest (%s) ... %d tests with zero failures' % (module.__name__, t))
return f, t
#=======================================================================
Modified: python/branches/p3yk-noslice/Lib/test/test_syntax.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_syntax.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_syntax.py Fri Feb 23 18:29:35 2007
@@ -247,7 +247,7 @@
... finally:
... for abc in range(10):
... continue
- ... print abc
+ ... print(abc)
>>> test()
9
@@ -328,11 +328,11 @@
isn't, there should be a syntax error.
>>> try:
- ... print 1
+ ... print(1)
... break
- ... print 2
+ ... print(2)
... finally:
- ... print 3
+ ... print(3)
Traceback (most recent call last):
...
SyntaxError: 'break' outside loop (<doctest test.test_syntax[42]>, line 3)
@@ -423,7 +423,7 @@
source = re.sub('(?m)^ *:', '', """\
:def foo(x):
: def bar():
- : print x
+ : print(x)
: del x
:""")
self._check_error(source, "nested scope")
Modified: python/branches/p3yk-noslice/Lib/test/test_tarfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_tarfile.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_tarfile.py Fri Feb 23 18:29:35 2007
@@ -305,6 +305,61 @@
self.assertEqual(self.dst.getnames(), [], "added the archive to itself")
+class AppendTest(unittest.TestCase):
+ # Test append mode (cp. patch #1652681).
+
+ def setUp(self):
+ self.tarname = tmpname()
+ if os.path.exists(self.tarname):
+ os.remove(self.tarname)
+
+ def _add_testfile(self, fileobj=None):
+ tar = tarfile.open(self.tarname, "a", fileobj=fileobj)
+ tar.addfile(tarfile.TarInfo("bar"))
+ tar.close()
+
+ def _create_testtar(self):
+ src = tarfile.open(tarname())
+ t = src.getmember("0-REGTYPE")
+ t.name = "foo"
+ f = src.extractfile(t)
+ tar = tarfile.open(self.tarname, "w")
+ tar.addfile(t, f)
+ tar.close()
+
+ def _test(self, names=["bar"], fileobj=None):
+ tar = tarfile.open(self.tarname, fileobj=fileobj)
+ self.assert_(tar.getnames() == names)
+
+ def test_non_existing(self):
+ self._add_testfile()
+ self._test()
+
+ def test_empty(self):
+ open(self.tarname, "wb").close()
+ self._add_testfile()
+ self._test()
+
+ def test_empty_fileobj(self):
+ fobj = StringIO.StringIO()
+ self._add_testfile(fobj)
+ fobj.seek(0)
+ self._test(fileobj=fobj)
+
+ def test_fileobj(self):
+ self._create_testtar()
+ data = open(self.tarname, "rb").read()
+ fobj = StringIO.StringIO(data)
+ self._add_testfile(fobj)
+ fobj.seek(0)
+ self._test(names=["foo", "bar"], fileobj=fobj)
+
+ def test_existing(self):
+ self._create_testtar()
+ self._add_testfile()
+ self._test(names=["foo", "bar"])
+
+
class Write100Test(BaseTest):
# The name field in a tar header stores strings of at most 100 chars.
# If a string is shorter than 100 chars it has to be padded with '\0',
@@ -711,6 +766,7 @@
ReadAsteriskTest,
ReadStreamAsteriskTest,
WriteTest,
+ AppendTest,
Write100Test,
WriteSize0Test,
WriteStreamTest,
Modified: python/branches/p3yk-noslice/Lib/test/test_thread.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_thread.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_thread.py Fri Feb 23 18:29:35 2007
@@ -21,10 +21,10 @@
delay = random.random() * numtasks
rmutex.release()
if verbose:
- print 'task', ident, 'will run for', round(delay, 1), 'sec'
+ print('task', ident, 'will run for', round(delay, 1), 'sec')
time.sleep(delay)
if verbose:
- print 'task', ident, 'done'
+ print('task', ident, 'done')
mutex.acquire()
running = running - 1
if running == 0:
@@ -37,7 +37,7 @@
mutex.acquire()
next_ident = next_ident + 1
if verbose:
- print 'creating task', next_ident
+ print('creating task', next_ident)
thread.start_new_thread(task, (next_ident,))
running = running + 1
mutex.release()
@@ -45,9 +45,9 @@
for i in range(numtasks):
newtask()
-print 'waiting for all tasks to complete'
+print('waiting for all tasks to complete')
done.acquire()
-print 'all tasks done'
+print('all tasks done')
class barrier:
def __init__(self, n):
@@ -89,13 +89,13 @@
delay = random.random() * numtasks
rmutex.release()
if verbose:
- print 'task', ident, 'will run for', round(delay, 1), 'sec'
+ print('task', ident, 'will run for', round(delay, 1), 'sec')
time.sleep(delay)
if verbose:
- print 'task', ident, 'entering barrier', i
+ print('task', ident, 'entering barrier', i)
bar.enter()
if verbose:
- print 'task', ident, 'leaving barrier', i
+ print('task', ident, 'leaving barrier', i)
mutex.acquire()
running -= 1
# Must release mutex before releasing done, else the main thread can
@@ -106,7 +106,7 @@
if finished:
done.release()
-print '\n*** Barrier Test ***'
+print('\n*** Barrier Test ***')
if done.acquire(0):
raise ValueError, "'done' should have remained acquired"
bar = barrier(numtasks)
@@ -114,10 +114,10 @@
for i in range(numtasks):
thread.start_new_thread(task2, (i,))
done.acquire()
-print 'all tasks done'
+print('all tasks done')
# not all platforms support changing thread stack size
-print '\n*** Changing thread stack size ***'
+print('\n*** Changing thread stack size ***')
if thread.stack_size() != 0:
raise ValueError, "initial stack_size not 0"
@@ -132,10 +132,10 @@
try:
thread.stack_size(4096)
except ValueError:
- print 'caught expected ValueError setting stack_size(4096)'
+ print('caught expected ValueError setting stack_size(4096)')
except thread.error:
tss_supported = 0
- print 'platform does not support changing thread stack size'
+ print('platform does not support changing thread stack size')
if tss_supported:
failed = lambda s, e: s != e
@@ -144,17 +144,17 @@
thread.stack_size(tss)
if failed(thread.stack_size(), tss):
raise ValueError, fail_msg % tss
- print 'successfully set stack_size(%d)' % tss
+ print('successfully set stack_size(%d)' % tss)
for tss in (262144, 0x100000):
- print 'trying stack_size = %d' % tss
+ print('trying stack_size = %d' % tss)
next_ident = 0
for i in range(numtasks):
newtask()
- print 'waiting for all tasks to complete'
+ print('waiting for all tasks to complete')
done.acquire()
- print 'all tasks done'
+ print('all tasks done')
# reset stack size to default
thread.stack_size(0)
Modified: python/branches/p3yk-noslice/Lib/test/test_threaded_import.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_threaded_import.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_threaded_import.py Fri Feb 23 18:29:35 2007
@@ -28,14 +28,14 @@
def test_import_hangers():
import sys
if verbose:
- print "testing import hangers ...",
+ print("testing import hangers ...", end=' ')
import test.threaded_import_hangers
try:
if test.threaded_import_hangers.errors:
raise TestFailed(test.threaded_import_hangers.errors)
elif verbose:
- print "OK."
+ print("OK.")
finally:
# In case this test is run again, make sure the helper module
# gets loaded from scratch again.
@@ -61,12 +61,12 @@
done.acquire()
for N in (20, 50) * 3:
if verbose:
- print "Trying", N, "threads ...",
+ print("Trying", N, "threads ...", end=' ')
for i in range(N):
thread.start_new_thread(task, ())
done.acquire()
if verbose:
- print "OK."
+ print("OK.")
done.release()
test_import_hangers()
Modified: python/branches/p3yk-noslice/Lib/test/test_threadedtempfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_threadedtempfile.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_threadedtempfile.py Fri Feb 23 18:29:35 2007
@@ -50,26 +50,26 @@
threads = []
thread_info = threading_setup()
- print "Creating"
+ print("Creating")
for i in range(NUM_THREADS):
t = TempFileGreedy()
threads.append(t)
t.start()
- print "Starting"
+ print("Starting")
startEvent.set()
- print "Reaping"
+ print("Reaping")
ok = errors = 0
for t in threads:
t.join()
ok += t.ok_count
errors += t.error_count
if t.error_count:
- print '%s errors:\n%s' % (t.getName(), t.errors.getvalue())
+ print('%s errors:\n%s' % (t.getName(), t.errors.getvalue()))
msg = "Done: errors %d ok %d" % (errors, ok)
- print msg
+ print(msg)
if errors:
raise TestFailed(msg)
Modified: python/branches/p3yk-noslice/Lib/test/test_threading.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_threading.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_threading.py Fri Feb 23 18:29:35 2007
@@ -30,27 +30,27 @@
def run(self):
delay = random.random() * 2
if verbose:
- print 'task', self.getName(), 'will run for', delay, 'sec'
+ print('task', self.getName(), 'will run for', delay, 'sec')
self.sema.acquire()
self.mutex.acquire()
self.nrunning.inc()
if verbose:
- print self.nrunning.get(), 'tasks are running'
+ print(self.nrunning.get(), 'tasks are running')
self.testcase.assert_(self.nrunning.get() <= 3)
self.mutex.release()
time.sleep(delay)
if verbose:
- print 'task', self.getName(), 'done'
+ print('task', self.getName(), 'done')
self.mutex.acquire()
self.nrunning.dec()
self.testcase.assert_(self.nrunning.get() >= 0)
if verbose:
- print self.getName(), 'is finished.', self.nrunning.get(), \
- 'tasks are running'
+ print(self.getName(), 'is finished.', self.nrunning.get(), \
+ 'tasks are running')
self.mutex.release()
self.sema.release()
@@ -77,23 +77,23 @@
t.start()
if verbose:
- print 'waiting for all tasks to complete'
+ print('waiting for all tasks to complete')
for t in threads:
t.join(NUMTASKS)
self.assert_(not t.isAlive())
if verbose:
- print 'all tasks done'
+ print('all tasks done')
self.assertEqual(numrunning.get(), 0)
# run with a small(ish) thread stack size (256kB)
def test_various_ops_small_stack(self):
if verbose:
- print 'with 256kB thread stack size...'
+ print('with 256kB thread stack size...')
try:
threading.stack_size(262144)
except thread.error:
if verbose:
- print 'platform does not support changing thread stack size'
+ print('platform does not support changing thread stack size')
return
self.test_various_ops()
threading.stack_size(0)
@@ -101,12 +101,12 @@
# run with a large thread stack size (1MB)
def test_various_ops_large_stack(self):
if verbose:
- print 'with 1MB thread stack size...'
+ print('with 1MB thread stack size...')
try:
threading.stack_size(0x100000)
except thread.error:
if verbose:
- print 'platform does not support changing thread stack size'
+ print('platform does not support changing thread stack size')
return
self.test_various_ops()
threading.stack_size(0)
@@ -138,7 +138,7 @@
import ctypes
except ImportError:
if verbose:
- print "test_PyThreadState_SetAsyncExc can't import ctypes"
+ print("test_PyThreadState_SetAsyncExc can't import ctypes")
return # can't do anything
set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
@@ -172,31 +172,31 @@
t.setDaemon(True) # so if this fails, we don't hang Python at shutdown
t.start()
if verbose:
- print " started worker thread"
+ print(" started worker thread")
# Try a thread id that doesn't make sense.
if verbose:
- print " trying nonsensical thread id"
+ print(" trying nonsensical thread id")
result = set_async_exc(ctypes.c_long(-1), exception)
self.assertEqual(result, 0) # no thread states modified
# Now raise an exception in the worker thread.
if verbose:
- print " waiting for worker thread to get started"
+ print(" waiting for worker thread to get started")
worker_started.wait()
if verbose:
- print " verifying worker hasn't exited"
+ print(" verifying worker hasn't exited")
self.assert_(not t.finished)
if verbose:
- print " attempting to raise asynch exception in worker"
+ print(" attempting to raise asynch exception in worker")
result = set_async_exc(ctypes.c_long(t.id), exception)
self.assertEqual(result, 1) # one thread state modified
if verbose:
- print " waiting for worker to say it caught the exception"
+ print(" waiting for worker to say it caught the exception")
worker_saw_exception.wait(timeout=10)
self.assert_(t.finished)
if verbose:
- print " all OK -- joining worker"
+ print(" all OK -- joining worker")
if t.finished:
t.join()
# else the thread is still running, and we have no way to kill it
Modified: python/branches/p3yk-noslice/Lib/test/test_time.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_time.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_time.py Fri Feb 23 18:29:35 2007
@@ -20,8 +20,8 @@
def test_conversions(self):
self.assert_(time.ctime(self.t)
== time.asctime(time.localtime(self.t)))
- self.assert_(long(time.mktime(time.localtime(self.t)))
- == long(self.t))
+ self.assert_(int(time.mktime(time.localtime(self.t)))
+ == int(self.t))
def test_sleep(self):
time.sleep(1.2)
Modified: python/branches/p3yk-noslice/Lib/test/test_timeout.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_timeout.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_timeout.py Fri Feb 23 18:29:35 2007
@@ -46,7 +46,7 @@
def testTypeCheck(self):
# Test type checking by settimeout()
self.sock.settimeout(0)
- self.sock.settimeout(0L)
+ self.sock.settimeout(0)
self.sock.settimeout(0.0)
self.sock.settimeout(None)
self.assertRaises(TypeError, self.sock.settimeout, "")
@@ -59,7 +59,7 @@
def testRangeCheck(self):
# Test range checking by settimeout()
self.assertRaises(ValueError, self.sock.settimeout, -1)
- self.assertRaises(ValueError, self.sock.settimeout, -1L)
+ self.assertRaises(ValueError, self.sock.settimeout, -1)
self.assertRaises(ValueError, self.sock.settimeout, -1.0)
def testTimeoutThenBlocking(self):
Modified: python/branches/p3yk-noslice/Lib/test/test_tokenize.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_tokenize.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_tokenize.py Fri Feb 23 18:29:35 2007
@@ -43,9 +43,9 @@
There are some standard formatting practices that are easy to get right.
>>> roundtrip("if x == 1:\\n"
-... " print x\\n")
+... " print(x)\\n")
if x == 1:
- print x
+ print(x)
Some people use different formatting conventions, which makes
untokenize a little trickier. Note that this test involves trailing
@@ -53,29 +53,29 @@
two trailing blanks apparent in the expected output.
>>> roundtrip("if x == 1 : \\n"
-... " print x\\n")
+... " print(x)\\n")
if x == 1 :\x20\x20
- print x
+ print(x)
Comments need to go in the right place.
>>> roundtrip("if x == 1:\\n"
... " # A comment by itself.\\n"
-... " print x # Comment here, too.\\n"
+... " print(x) # Comment here, too.\\n"
... " # Another comment.\\n"
... "after_if = True\\n")
if x == 1:
# A comment by itself.
- print x # Comment here, too.
+ print(x) # Comment here, too.
# Another comment.
after_if = True
>>> roundtrip("if (x # The comments need to go in the right place\\n"
... " == 1):\\n"
-... " print 'x == 1'\\n")
+... " print('x == 1')\\n")
if (x # The comments need to go in the right place
== 1):
- print 'x == 1'
+ print('x == 1')
"""
@@ -118,21 +118,21 @@
if type == ENDMARKER:
break
type = tok_name[type]
- print "%(type)-10.10s %(token)-13.13r %(start)s %(end)s" % locals()
+ print("%(type)-10.10s %(token)-13.13r %(start)s %(end)s" % locals())
def roundtrip(s):
f = StringIO(s)
source = untokenize(generate_tokens(f.readline))
- print source,
+ print(source, end="")
# This is an example from the docs, set up as a doctest.
def decistmt(s):
"""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'))"
The format of the exponent is inherited from the platform C library.
Known cases are "e-007" (Windows) and "e-07" (not Windows). Since
@@ -165,7 +165,7 @@
def test_main():
if verbose:
- print 'starting...'
+ print('starting...')
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
@@ -191,7 +191,7 @@
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
- print >>sys.__stdout__, ' test_main still working, be patient...'
+ print(' test_main still working, be patient...', file=sys.__stdout__)
sys.__stdout__.flush()
test_roundtrip(f)
@@ -217,7 +217,7 @@
run_doctest(test_tokenize, verbose)
if verbose:
- print 'finished'
+ print('finished')
def test_rarrow():
"""
Modified: python/branches/p3yk-noslice/Lib/test/test_trace.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_trace.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_trace.py Fri Feb 23 18:29:35 2007
@@ -309,7 +309,7 @@
def test_trash_stack(self):
def f():
for i in range(5):
- print i # line tracing will raise an exception at this line
+ print(i) # line tracing will raise an exception at this line
def g(frame, why, extra):
if (why == 'line' and
Modified: python/branches/p3yk-noslice/Lib/test/test_traceback.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_traceback.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_traceback.py Fri Feb 23 18:29:35 2007
@@ -25,7 +25,7 @@
import test.badsyntax_nocaret
def syntax_error_bad_indentation(self):
- compile("def spam():\n print 1\n print 2", "?", "exec")
+ compile("def spam():\n print(1)\n print(2)", "?", "exec")
def test_caret(self):
err = self.get_exception_format(self.syntax_error_with_caret,
@@ -48,9 +48,9 @@
err = self.get_exception_format(self.syntax_error_bad_indentation,
IndentationError)
self.assert_(len(err) == 4)
- self.assert_(err[1].strip() == "print 2")
+ self.assert_(err[1].strip() == "print(2)")
self.assert_("^" in err[2])
- self.assert_(err[1].find("2") == err[2].find("^"))
+ self.assert_(err[1].find(")") == err[2].find("^"))
def test_bug737473(self):
import sys, os, tempfile, time
@@ -60,9 +60,9 @@
try:
sys.path.insert(0, testdir)
testfile = os.path.join(testdir, 'test_bug737473.py')
- print >> open(testfile, 'w'), """
+ print("""
def test():
- raise ValueError"""
+ raise ValueError""", file=open(testfile, 'w'))
if 'test_bug737473' in sys.modules:
del sys.modules['test_bug737473']
@@ -82,9 +82,9 @@
# three seconds are needed for this test to pass reliably :-(
time.sleep(4)
- print >> open(testfile, 'w'), """
+ print("""
def test():
- raise NotImplementedError"""
+ raise NotImplementedError""", file=open(testfile, 'w'))
reload(test_bug737473)
try:
test_bug737473.test()
Modified: python/branches/p3yk-noslice/Lib/test/test_types.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_types.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_types.py Fri Feb 23 18:29:35 2007
@@ -9,11 +9,11 @@
def test_truth_values(self):
if None: self.fail('None is true instead of false')
if 0: self.fail('0 is true instead of false')
- if 0L: self.fail('0L is true instead of false')
+ if 0: self.fail('0L is true instead of false')
if 0.0: self.fail('0.0 is true instead of false')
if '': self.fail('\'\' is true instead of false')
if not 1: self.fail('1 is false instead of true')
- if not 1L: self.fail('1L is false instead of true')
+ if not 1: self.fail('1L is false instead of true')
if not 1.0: self.fail('1.0 is false instead of true')
if not 'x': self.fail('\'x\' is false instead of true')
if not {'x': 1}: self.fail('{\'x\': 1} is false instead of true')
@@ -35,7 +35,7 @@
def test_comparisons(self):
if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass
else: self.fail('int comparisons failed')
- if 0L < 1L <= 1L == 1L >= 1L > 0L != 1L: pass
+ if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass
else: self.fail('long int comparisons failed')
if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass
else: self.fail('float comparisons failed')
@@ -61,30 +61,30 @@
except ZeroDivisionError: pass
else: self.fail("5.0 % 0.0 didn't raise ZeroDivisionError")
- try: 5 / 0L
+ try: 5 / 0
except ZeroDivisionError: pass
else: self.fail("5 / 0L didn't raise ZeroDivisionError")
- try: 5 // 0L
+ try: 5 // 0
except ZeroDivisionError: pass
else: self.fail("5 // 0L didn't raise ZeroDivisionError")
- try: 5 % 0L
+ try: 5 % 0
except ZeroDivisionError: pass
else: self.fail("5 % 0L didn't raise ZeroDivisionError")
def test_numeric_types(self):
- if 0 != 0L or 0 != 0.0 or 0L != 0.0: self.fail('mixed comparisons')
- if 1 != 1L or 1 != 1.0 or 1L != 1.0: self.fail('mixed comparisons')
- if -1 != -1L or -1 != -1.0 or -1L != -1.0:
+ if 0 != 0 or 0 != 0.0 or 0 != 0.0: self.fail('mixed comparisons')
+ if 1 != 1 or 1 != 1.0 or 1 != 1.0: self.fail('mixed comparisons')
+ if -1 != -1 or -1 != -1.0 or -1 != -1.0:
self.fail('int/long/float value not equal')
# calling built-in types without argument must return 0
if int() != 0: self.fail('int() does not return 0')
- if long() != 0L: self.fail('long() does not return 0L')
+ if int() != 0: self.fail('long() does not return 0L')
if float() != 0.0: self.fail('float() does not return 0.0')
if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass
else: self.fail('int() does not round properly')
- if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass
+ if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass
else: self.fail('long() does not round properly')
if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass
else: self.fail('float() does not work properly')
@@ -118,7 +118,7 @@
for divisor in 1, 2, 4, 8, 16, 32:
j = m // divisor - 1
prod = divisor * j
- if type(prod) is not long:
+ if type(prod) is not int:
self.fail("expected type(%r) to be long, not %r" %
(prod, type(prod)))
# Check for expected * overflow to long.
@@ -126,35 +126,35 @@
for divisor in 1, 2, 4, 8, 16, 32:
j = m // divisor + 1
prod = divisor * j
- if type(prod) is not long:
+ if type(prod) is not int:
self.fail("expected type(%r) to be long, not %r" %
(prod, type(prod)))
def test_long_integers(self):
- if 12L + 24L != 36L: self.fail('long op')
- if 12L + (-24L) != -12L: self.fail('long op')
- if (-12L) + 24L != 12L: self.fail('long op')
- if (-12L) + (-24L) != -36L: self.fail('long op')
- if not 12L < 24L: self.fail('long op')
- if not -24L < -12L: self.fail('long op')
+ if 12 + 24 != 36: self.fail('long op')
+ if 12 + (-24) != -12: self.fail('long op')
+ if (-12) + 24 != 12: self.fail('long op')
+ if (-12) + (-24) != -36: self.fail('long op')
+ if not 12 < 24: self.fail('long op')
+ if not -24 < -12: self.fail('long op')
x = sys.maxint
- if int(long(x)) != x: self.fail('long op')
- try: y = int(long(x)+1L)
+ if int(int(x)) != x: self.fail('long op')
+ try: y = int(int(x)+1)
except OverflowError: self.fail('long op')
- if not isinstance(y, long): self.fail('long op')
+ if not isinstance(y, int): self.fail('long op')
x = -x
- if int(long(x)) != x: self.fail('long op')
+ if int(int(x)) != x: self.fail('long op')
x = x-1
- if int(long(x)) != x: self.fail('long op')
- try: y = int(long(x)-1L)
+ if int(int(x)) != x: self.fail('long op')
+ try: y = int(int(x)-1)
except OverflowError: self.fail('long op')
- if not isinstance(y, long): self.fail('long op')
+ if not isinstance(y, int): self.fail('long op')
try: 5 << -5
except ValueError: pass
else: self.fail('int negative shift <<')
- try: 5L << -5L
+ try: 5 << -5
except ValueError: pass
else: self.fail('long negative shift <<')
@@ -162,7 +162,7 @@
except ValueError: pass
else: self.fail('int negative shift >>')
- try: 5L >> -5L
+ try: 5 >> -5
except ValueError: pass
else: self.fail('long negative shift >>')
@@ -197,7 +197,7 @@
self.assertEqual(a[3::-2], '31')
self.assertEqual(a[-100:100:], a)
self.assertEqual(a[100:-100:-1], a[::-1])
- self.assertEqual(a[-100L:100L:2L], '02468')
+ self.assertEqual(a[-100:100:2], '02468')
if have_unicode:
a = unicode('0123456789', 'ascii')
@@ -209,7 +209,7 @@
self.assertEqual(a[3::-2], unicode('31', 'ascii'))
self.assertEqual(a[-100:100:], a)
self.assertEqual(a[100:-100:-1], a[::-1])
- self.assertEqual(a[-100L:100L:2L], unicode('02468', 'ascii'))
+ self.assertEqual(a[-100:100:2], unicode('02468', 'ascii'))
def test_type_function(self):
Modified: python/branches/p3yk-noslice/Lib/test/test_unary.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_unary.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_unary.py Fri Feb 23 18:29:35 2007
@@ -9,7 +9,7 @@
self.assert_(-2 == 0 - 2)
self.assert_(-0 == 0)
self.assert_(--2 == 2)
- self.assert_(-2L == 0 - 2L)
+ self.assert_(-2 == 0 - 2)
self.assert_(-2.0 == 0 - 2.0)
self.assert_(-2j == 0 - 2j)
@@ -17,7 +17,7 @@
self.assert_(+2 == 2)
self.assert_(+0 == 0)
self.assert_(++2 == 2)
- self.assert_(+2L == 2L)
+ self.assert_(+2 == 2)
self.assert_(+2.0 == 2.0)
self.assert_(+2j == 2j)
@@ -25,13 +25,13 @@
self.assert_(-2 == 0 - 2)
self.assert_(-0 == 0)
self.assert_(--2 == 2)
- self.assert_(-2L == 0 - 2L)
+ self.assert_(-2 == 0 - 2)
def test_no_overflow(self):
nines = "9" * 32
- self.assert_(eval("+" + nines) == eval("+" + nines + "L"))
- self.assert_(eval("-" + nines) == eval("-" + nines + "L"))
- self.assert_(eval("~" + nines) == eval("~" + nines + "L"))
+ self.assert_(eval("+" + nines) == 10**32-1)
+ self.assert_(eval("-" + nines) == -(10**32-1))
+ self.assert_(eval("~" + nines) == ~(10**32-1))
def test_negation_of_exponentiation(self):
# Make sure '**' does the right thing; these form a
Modified: python/branches/p3yk-noslice/Lib/test/test_unicode.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_unicode.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_unicode.py Fri Feb 23 18:29:35 2007
@@ -483,7 +483,7 @@
UnicodeCompat(u"u'%s' % obj falls back to obj.__str__()"),
u"u'%s' % obj falls back to obj.__str__()")
- for obj in (123, 123.45, 123L):
+ for obj in (123, 123.45, 123):
self.assertEqual(unicode(obj), unicode(str(obj)))
# unicode(obj, encoding, error) tests (this maps to
@@ -732,15 +732,15 @@
pass
out = BitBucket()
- print >>out, u'abc'
- print >>out, u'abc', u'def'
- print >>out, u'abc', 'def'
- print >>out, 'abc', u'def'
- print >>out, u'abc\n'
- print >>out, u'abc\n',
- print >>out, u'abc\n',
- print >>out, u'def\n'
- print >>out, u'def\n'
+ print(u'abc', file=out)
+ print(u'abc', u'def', file=out)
+ print(u'abc', 'def', file=out)
+ print('abc', u'def', file=out)
+ print(u'abc\n', file=out)
+ print(u'abc\n', end=' ', file=out)
+ print(u'abc\n', end=' ', file=out)
+ print(u'def\n', file=out)
+ print(u'def\n', file=out)
def test_ucs4(self):
if sys.maxunicode == 0xFFFF:
Modified: python/branches/p3yk-noslice/Lib/test/test_urllib2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_urllib2.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_urllib2.py Fri Feb 23 18:29:35 2007
@@ -90,8 +90,7 @@
>>> r.header_items()
[('Spam-eggs', 'blah')]
>>> r.add_header("Foo-Bar", "baz")
- >>> items = r.header_items()
- >>> items.sort()
+ >>> items = sorted(r.header_items())
>>> items
[('Foo-bar', 'baz'), ('Spam-eggs', 'blah')]
@@ -101,7 +100,7 @@
>>> r.has_header("Not-there")
False
- >>> print r.get_header("Not-there")
+ >>> print(r.get_header("Not-there"))
None
>>> r.get_header("Not-there", "default")
'default'
@@ -235,7 +234,7 @@
class MockHeaders(dict):
def getheaders(self, name):
- return self.values()
+ return list(self.values())
class MockResponse(StringIO.StringIO):
def __init__(self, code, msg, headers, data, url=None):
Modified: python/branches/p3yk-noslice/Lib/test/test_urllib2net.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_urllib2net.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_urllib2net.py Fri Feb 23 18:29:35 2007
@@ -64,6 +64,27 @@
# urllib2.urlopen, "http://evil:thing@example.com")
+class CloseSocketTest(unittest.TestCase):
+
+ def test_close(self):
+ import socket, httplib, gc
+
+ # calling .close() on urllib2's response objects should close the
+ # underlying socket
+
+ # delve deep into response to fetch socket._socketobject
+ response = urllib2.urlopen("http://www.python.org/")
+ abused_fileobject = response.fp
+ self.assert_(abused_fileobject.__class__ is socket._fileobject)
+ httpresponse = abused_fileobject._sock
+ self.assert_(httpresponse.__class__ is httplib.HTTPResponse)
+ fileobject = httpresponse.fp
+ self.assert_(fileobject.__class__ is socket._fileobject)
+
+ self.assert_(not fileobject.closed)
+ response.close()
+ self.assert_(fileobject.closed)
+
class urlopenNetworkTests(unittest.TestCase):
"""Tests urllib2.urlopen using the network.
@@ -263,8 +284,12 @@
def test_main():
test_support.requires("network")
- test_support.run_unittest(URLTimeoutTest, urlopenNetworkTests,
- AuthTests, OtherNetworkTests)
+ test_support.run_unittest(URLTimeoutTest,
+ urlopenNetworkTests,
+ AuthTests,
+ OtherNetworkTests,
+ CloseSocketTest,
+ )
if __name__ == "__main__":
test_main()
Modified: python/branches/p3yk-noslice/Lib/test/test_userdict.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_userdict.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_userdict.py Fri Feb 23 18:29:35 2007
@@ -79,7 +79,7 @@
self.assertEqual(u2b, u2c)
class MyUserDict(UserDict.UserDict):
- def display(self): print self
+ def display(self): print(self)
m2 = MyUserDict(u2)
m2a = m2.copy()
@@ -92,7 +92,7 @@
# Test keys, items, values
self.assertEqual(u2.keys(), d2.keys())
self.assertEqual(u2.items(), d2.items())
- self.assertEqual(u2.values(), d2.values())
+ self.assertEqual(list(u2.values()), list(d2.values()))
# Test "in".
for i in u2.keys():
@@ -208,7 +208,7 @@
if other is not None:
for (key, value) in other:
self[key] = value
- for (key, value) in kwargs.iteritems():
+ for (key, value) in kwargs.items():
self[key] = value
def __getitem__(self, key):
try:
@@ -234,7 +234,7 @@
return list(self.keylist)
def copy(self):
d = self.__class__()
- for key, value in self.iteritems():
+ for key, value in self.items():
d[key] = value
return d
@classmethod
@@ -278,13 +278,13 @@
self.assertEqual(len(s), 2)
# iteritems
- self.assertEqual(list(s.iteritems()), [(10,'ten'), (30, 'thirty')])
+ self.assertEqual(list(s.items()), [(10,'ten'), (30, 'thirty')])
# iterkeys
- self.assertEqual(list(s.iterkeys()), [10, 30])
+ self.assertEqual(list(s.keys()), [10, 30])
# itervalues
- self.assertEqual(list(s.itervalues()), ['ten', 'thirty'])
+ self.assertEqual(list(s.values()), ['ten', 'thirty'])
# values
self.assertEqual(s.values(), ['ten', 'thirty'])
Modified: python/branches/p3yk-noslice/Lib/test/test_uu.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_uu.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_uu.py Fri Feb 23 18:29:35 2007
@@ -114,11 +114,11 @@
def test_encode(self):
try:
- fin = open(self.tmpin, 'w')
+ fin = open(self.tmpin, 'wb')
fin.write(plaintext)
fin.close()
- fin = open(self.tmpin, 'r')
+ fin = open(self.tmpin, 'rb')
fout = open(self.tmpout, 'w')
uu.encode(fin, fout, self.tmpin, mode=0644)
fin.close()
Modified: python/branches/p3yk-noslice/Lib/test/test_uuid.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_uuid.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_uuid.py Fri Feb 23 18:29:35 2007
@@ -32,19 +32,19 @@
'000102030405060708090a0b0c0d0e0f',
'\0\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\x0d\x0e\x0f',
'\x03\x02\x01\0\x05\x04\x07\x06\x08\t\n\x0b\x0c\x0d\x0e\x0f',
- (0x00010203L, 0x0405, 0x0607, 8, 9, 0x0a0b0c0d0e0fL),
- 0x000102030405060708090a0b0c0d0e0fL,
+ (0x00010203, 0x0405, 0x0607, 8, 9, 0x0a0b0c0d0e0f),
+ 0x000102030405060708090a0b0c0d0e0f,
'urn:uuid:00010203-0405-0607-0809-0a0b0c0d0e0f',
- 0x607040500010203L, 0x809, uuid.RESERVED_NCS, None),
+ 0x607040500010203, 0x809, uuid.RESERVED_NCS, None),
('02d9e6d5-9467-382e-8f9b-9300a64ac3cd',
'{02d9e6d5-9467-382e-8f9b-9300a64ac3cd}',
'02d9e6d59467382e8f9b9300a64ac3cd',
'\x02\xd9\xe6\xd5\x94\x67\x38\x2e\x8f\x9b\x93\x00\xa6\x4a\xc3\xcd',
'\xd5\xe6\xd9\x02\x67\x94\x2e\x38\x8f\x9b\x93\x00\xa6\x4a\xc3\xcd',
- (0x02d9e6d5L, 0x9467, 0x382e, 0x8f, 0x9b, 0x9300a64ac3cdL),
- 0x02d9e6d59467382e8f9b9300a64ac3cdL,
+ (0x02d9e6d5, 0x9467, 0x382e, 0x8f, 0x9b, 0x9300a64ac3cd),
+ 0x02d9e6d59467382e8f9b9300a64ac3cd,
'urn:uuid:02d9e6d5-9467-382e-8f9b-9300a64ac3cd',
- 0x82e946702d9e6d5L, 0xf9b, uuid.RFC_4122, 3),
+ 0x82e946702d9e6d5, 0xf9b, uuid.RFC_4122, 3),
('12345678-1234-5678-1234-567812345678',
'{12345678-1234-5678-1234-567812345678}',
'12345678123456781234567812345678',
@@ -53,97 +53,97 @@
(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678),
0x12345678123456781234567812345678,
'urn:uuid:12345678-1234-5678-1234-567812345678',
- 0x678123412345678L, 0x1234, uuid.RESERVED_NCS, None),
+ 0x678123412345678, 0x1234, uuid.RESERVED_NCS, None),
('6ba7b810-9dad-11d1-80b4-00c04fd430c8',
'{6ba7b810-9dad-11d1-80b4-00c04fd430c8}',
'6ba7b8109dad11d180b400c04fd430c8',
'\x6b\xa7\xb8\x10\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
'\x10\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
- (0x6ba7b810L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L),
- 0x6ba7b8109dad11d180b400c04fd430c8L,
+ (0x6ba7b810, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8),
+ 0x6ba7b8109dad11d180b400c04fd430c8,
'urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8',
- 0x1d19dad6ba7b810L, 0xb4, uuid.RFC_4122, 1),
+ 0x1d19dad6ba7b810, 0xb4, uuid.RFC_4122, 1),
('6ba7b811-9dad-11d1-80b4-00c04fd430c8',
'{6ba7b811-9dad-11d1-80b4-00c04fd430c8}',
'6ba7b8119dad11d180b400c04fd430c8',
'\x6b\xa7\xb8\x11\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
'\x11\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
- (0x6ba7b811L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L),
- 0x6ba7b8119dad11d180b400c04fd430c8L,
+ (0x6ba7b811, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8),
+ 0x6ba7b8119dad11d180b400c04fd430c8,
'urn:uuid:6ba7b811-9dad-11d1-80b4-00c04fd430c8',
- 0x1d19dad6ba7b811L, 0xb4, uuid.RFC_4122, 1),
+ 0x1d19dad6ba7b811, 0xb4, uuid.RFC_4122, 1),
('6ba7b812-9dad-11d1-80b4-00c04fd430c8',
'{6ba7b812-9dad-11d1-80b4-00c04fd430c8}',
'6ba7b8129dad11d180b400c04fd430c8',
'\x6b\xa7\xb8\x12\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
'\x12\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
- (0x6ba7b812L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L),
- 0x6ba7b8129dad11d180b400c04fd430c8L,
+ (0x6ba7b812, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8),
+ 0x6ba7b8129dad11d180b400c04fd430c8,
'urn:uuid:6ba7b812-9dad-11d1-80b4-00c04fd430c8',
- 0x1d19dad6ba7b812L, 0xb4, uuid.RFC_4122, 1),
+ 0x1d19dad6ba7b812, 0xb4, uuid.RFC_4122, 1),
('6ba7b814-9dad-11d1-80b4-00c04fd430c8',
'{6ba7b814-9dad-11d1-80b4-00c04fd430c8}',
'6ba7b8149dad11d180b400c04fd430c8',
'\x6b\xa7\xb8\x14\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
'\x14\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
- (0x6ba7b814L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L),
- 0x6ba7b8149dad11d180b400c04fd430c8L,
+ (0x6ba7b814, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8),
+ 0x6ba7b8149dad11d180b400c04fd430c8,
'urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8',
- 0x1d19dad6ba7b814L, 0xb4, uuid.RFC_4122, 1),
+ 0x1d19dad6ba7b814, 0xb4, uuid.RFC_4122, 1),
('7d444840-9dc0-11d1-b245-5ffdce74fad2',
'{7d444840-9dc0-11d1-b245-5ffdce74fad2}',
'7d4448409dc011d1b2455ffdce74fad2',
'\x7d\x44\x48\x40\x9d\xc0\x11\xd1\xb2\x45\x5f\xfd\xce\x74\xfa\xd2',
'\x40\x48\x44\x7d\xc0\x9d\xd1\x11\xb2\x45\x5f\xfd\xce\x74\xfa\xd2',
- (0x7d444840L, 0x9dc0, 0x11d1, 0xb2, 0x45, 0x5ffdce74fad2L),
- 0x7d4448409dc011d1b2455ffdce74fad2L,
+ (0x7d444840, 0x9dc0, 0x11d1, 0xb2, 0x45, 0x5ffdce74fad2),
+ 0x7d4448409dc011d1b2455ffdce74fad2,
'urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2',
- 0x1d19dc07d444840L, 0x3245, uuid.RFC_4122, 1),
+ 0x1d19dc07d444840, 0x3245, uuid.RFC_4122, 1),
('e902893a-9d22-3c7e-a7b8-d6e313b71d9f',
'{e902893a-9d22-3c7e-a7b8-d6e313b71d9f}',
'e902893a9d223c7ea7b8d6e313b71d9f',
'\xe9\x02\x89\x3a\x9d\x22\x3c\x7e\xa7\xb8\xd6\xe3\x13\xb7\x1d\x9f',
'\x3a\x89\x02\xe9\x22\x9d\x7e\x3c\xa7\xb8\xd6\xe3\x13\xb7\x1d\x9f',
- (0xe902893aL, 0x9d22, 0x3c7e, 0xa7, 0xb8, 0xd6e313b71d9fL),
- 0xe902893a9d223c7ea7b8d6e313b71d9fL,
+ (0xe902893a, 0x9d22, 0x3c7e, 0xa7, 0xb8, 0xd6e313b71d9f),
+ 0xe902893a9d223c7ea7b8d6e313b71d9f,
'urn:uuid:e902893a-9d22-3c7e-a7b8-d6e313b71d9f',
- 0xc7e9d22e902893aL, 0x27b8, uuid.RFC_4122, 3),
+ 0xc7e9d22e902893a, 0x27b8, uuid.RFC_4122, 3),
('eb424026-6f54-4ef8-a4d0-bb658a1fc6cf',
'{eb424026-6f54-4ef8-a4d0-bb658a1fc6cf}',
'eb4240266f544ef8a4d0bb658a1fc6cf',
'\xeb\x42\x40\x26\x6f\x54\x4e\xf8\xa4\xd0\xbb\x65\x8a\x1f\xc6\xcf',
'\x26\x40\x42\xeb\x54\x6f\xf8\x4e\xa4\xd0\xbb\x65\x8a\x1f\xc6\xcf',
- (0xeb424026L, 0x6f54, 0x4ef8, 0xa4, 0xd0, 0xbb658a1fc6cfL),
- 0xeb4240266f544ef8a4d0bb658a1fc6cfL,
+ (0xeb424026, 0x6f54, 0x4ef8, 0xa4, 0xd0, 0xbb658a1fc6cf),
+ 0xeb4240266f544ef8a4d0bb658a1fc6cf,
'urn:uuid:eb424026-6f54-4ef8-a4d0-bb658a1fc6cf',
- 0xef86f54eb424026L, 0x24d0, uuid.RFC_4122, 4),
+ 0xef86f54eb424026, 0x24d0, uuid.RFC_4122, 4),
('f81d4fae-7dec-11d0-a765-00a0c91e6bf6',
'{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}',
'f81d4fae7dec11d0a76500a0c91e6bf6',
'\xf8\x1d\x4f\xae\x7d\xec\x11\xd0\xa7\x65\x00\xa0\xc9\x1e\x6b\xf6',
'\xae\x4f\x1d\xf8\xec\x7d\xd0\x11\xa7\x65\x00\xa0\xc9\x1e\x6b\xf6',
- (0xf81d4faeL, 0x7dec, 0x11d0, 0xa7, 0x65, 0x00a0c91e6bf6L),
- 0xf81d4fae7dec11d0a76500a0c91e6bf6L,
+ (0xf81d4fae, 0x7dec, 0x11d0, 0xa7, 0x65, 0x00a0c91e6bf6),
+ 0xf81d4fae7dec11d0a76500a0c91e6bf6,
'urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6',
- 0x1d07decf81d4faeL, 0x2765, uuid.RFC_4122, 1),
+ 0x1d07decf81d4fae, 0x2765, uuid.RFC_4122, 1),
('fffefdfc-fffe-fffe-fffe-fffefdfcfbfa',
'{fffefdfc-fffe-fffe-fffe-fffefdfcfbfa}',
'fffefdfcfffefffefffefffefdfcfbfa',
'\xff\xfe\xfd\xfc\xff\xfe\xff\xfe\xff\xfe\xff\xfe\xfd\xfc\xfb\xfa',
'\xfc\xfd\xfe\xff\xfe\xff\xfe\xff\xff\xfe\xff\xfe\xfd\xfc\xfb\xfa',
- (0xfffefdfcL, 0xfffe, 0xfffe, 0xff, 0xfe, 0xfffefdfcfbfaL),
- 0xfffefdfcfffefffefffefffefdfcfbfaL,
+ (0xfffefdfc, 0xfffe, 0xfffe, 0xff, 0xfe, 0xfffefdfcfbfa),
+ 0xfffefdfcfffefffefffefffefdfcfbfa,
'urn:uuid:fffefdfc-fffe-fffe-fffe-fffefdfcfbfa',
- 0xffefffefffefdfcL, 0x3ffe, uuid.RESERVED_FUTURE, None),
+ 0xffefffefffefdfc, 0x3ffe, uuid.RESERVED_FUTURE, None),
('ffffffff-ffff-ffff-ffff-ffffffffffff',
'{ffffffff-ffff-ffff-ffff-ffffffffffff}',
'ffffffffffffffffffffffffffffffff',
'\xff'*16,
'\xff'*16,
- (0xffffffffL, 0xffffL, 0xffffL, 0xff, 0xff, 0xffffffffffffL),
- 0xffffffffffffffffffffffffffffffffL,
+ (0xffffffff, 0xffff, 0xffff, 0xff, 0xff, 0xffffffffffff),
+ 0xffffffffffffffffffffffffffffffff,
'urn:uuid:ffffffff-ffff-ffff-ffff-ffffffffffff',
- 0xfffffffffffffffL, 0x3fff, uuid.RESERVED_FUTURE, None),
+ 0xfffffffffffffff, 0x3fff, uuid.RESERVED_FUTURE, None),
]:
equivalents = []
# Construct each UUID in several different ways.
@@ -217,17 +217,17 @@
# Field values out of range.
badvalue(lambda: uuid.UUID(fields=(-1, 0, 0, 0, 0, 0)))
- badvalue(lambda: uuid.UUID(fields=(0x100000000L, 0, 0, 0, 0, 0)))
+ badvalue(lambda: uuid.UUID(fields=(0x100000000, 0, 0, 0, 0, 0)))
badvalue(lambda: uuid.UUID(fields=(0, -1, 0, 0, 0, 0)))
- badvalue(lambda: uuid.UUID(fields=(0, 0x10000L, 0, 0, 0, 0)))
+ badvalue(lambda: uuid.UUID(fields=(0, 0x10000, 0, 0, 0, 0)))
badvalue(lambda: uuid.UUID(fields=(0, 0, -1, 0, 0, 0)))
- badvalue(lambda: uuid.UUID(fields=(0, 0, 0x10000L, 0, 0, 0)))
+ badvalue(lambda: uuid.UUID(fields=(0, 0, 0x10000, 0, 0, 0)))
badvalue(lambda: uuid.UUID(fields=(0, 0, 0, -1, 0, 0)))
- badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0x100L, 0, 0)))
+ badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0x100, 0, 0)))
badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, -1, 0)))
- badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0x100L, 0)))
+ badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0x100, 0)))
badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0, -1)))
- badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0, 0x1000000000000L)))
+ badvalue(lambda: uuid.UUID(fields=(0, 0, 0, 0, 0, 0x1000000000000)))
# Version number out of range.
badvalue(lambda: uuid.UUID('00'*16, version=0))
@@ -235,7 +235,7 @@
# Integer value out of range.
badvalue(lambda: uuid.UUID(int=-1))
- badvalue(lambda: uuid.UUID(int=1<<128L))
+ badvalue(lambda: uuid.UUID(int=1<<128))
# Must supply exactly one of hex, bytes, fields, int.
h, b, f, i = '00'*16, '\0'*16, (0, 0, 0, 0, 0, 0), 0
@@ -281,21 +281,21 @@
badtype(lambda: setattr(u, 'node', 0))
def check_node(self, node, source):
- individual_group_bit = (node >> 40L) & 1
- universal_local_bit = (node >> 40L) & 2
+ individual_group_bit = (node >> 40) & 1
+ universal_local_bit = (node >> 40) & 2
message = "%012x doesn't look like a real MAC address" % node
self.assertEqual(individual_group_bit, 0, message)
self.assertEqual(universal_local_bit, 0, message)
self.assertNotEqual(node, 0, message)
- self.assertNotEqual(node, 0xffffffffffffL, message)
+ self.assertNotEqual(node, 0xffffffffffff, message)
self.assert_(0 <= node, message)
- self.assert_(node < (1L << 48), message)
+ self.assert_(node < (1 << 48), message)
TestUUID.source2node[source] = node
if TestUUID.last_node:
if TestUUID.last_node != node:
msg = "different sources disagree on node:\n"
- for s, n in TestUUID.source2node.iteritems():
+ for s, n in TestUUID.source2node.items():
msg += " from source %r, node was %012x\n" % (s, n)
# There's actually no reason to expect the MAC addresses
# to agree across various methods -- e.g., a box may have
@@ -307,9 +307,8 @@
def test_ifconfig_getnode(self):
import sys
- print >>sys.__stdout__, \
-""" WARNING: uuid._ifconfig_getnode is unreliable on many platforms.
- It is disabled until the code and/or test can be fixed properly."""
+ print(""" WARNING: uuid._ifconfig_getnode is unreliable on many platforms.
+ It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__)
return
import os
@@ -332,13 +331,12 @@
def test_random_getnode(self):
node = uuid._random_getnode()
self.assert_(0 <= node)
- self.assert_(node < (1L <<48))
+ self.assert_(node < (1 <<48))
def test_unixdll_getnode(self):
import sys
- print >>sys.__stdout__, \
-""" WARNING: uuid._unixdll_getnode is unreliable on many platforms.
- It is disabled until the code and/or test can be fixed properly."""
+ print(""" WARNING: uuid._unixdll_getnode is unreliable on many platforms.
+ It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__)
return
import os
@@ -352,9 +350,8 @@
def test_getnode(self):
import sys
- print >>sys.__stdout__, \
-""" WARNING: uuid.getnode is unreliable on many platforms.
- It is disabled until the code and/or test can be fixed properly."""
+ print(""" WARNING: uuid.getnode is unreliable on many platforms.
+ It is disabled until the code and/or test can be fixed properly.""", file=sys.__stdout__)
return
node1 = uuid.getnode()
Modified: python/branches/p3yk-noslice/Lib/test/test_weakref.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_weakref.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_weakref.py Fri Feb 23 18:29:35 2007
@@ -6,6 +6,8 @@
from test import test_support
+# Used in ReferencesTestCase.test_ref_created_during_del() .
+ref_from_del = None
class C:
def method(self):
@@ -630,6 +632,18 @@
finally:
gc.set_threshold(*thresholds)
+ def test_ref_created_during_del(self):
+ # Bug #1377858
+ # A weakref created in an object's __del__() would crash the
+ # interpreter when the weakref was cleaned up since it would refer to
+ # non-existent memory. This test should not segfault the interpreter.
+ class Target(object):
+ def __del__(self):
+ global ref_from_del
+ ref_from_del = weakref.ref(self)
+
+ w = Target()
+
class SubclassableWeakrefTestCase(unittest.TestCase):
@@ -825,25 +839,25 @@
def check_iters(self, dict):
# item iterator:
items = dict.items()
- for item in dict.iteritems():
+ for item in dict.items():
items.remove(item)
self.assert_(len(items) == 0, "iteritems() did not touch all items")
# key iterator, via __iter__():
- keys = dict.keys()
+ keys = list(dict.keys())
for k in dict:
keys.remove(k)
self.assert_(len(keys) == 0, "__iter__() did not touch all keys")
# key iterator, via iterkeys():
- keys = dict.keys()
- for k in dict.iterkeys():
+ keys = list(dict.keys())
+ for k in dict.keys():
keys.remove(k)
self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
# value iterator:
- values = dict.values()
- for v in dict.itervalues():
+ values = list(dict.values())
+ for v in dict.values():
values.remove(v)
self.assert_(len(values) == 0,
"itervalues() did not touch all values")
@@ -1058,7 +1072,7 @@
...
>>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
>>> r = weakref.ref(obj)
->>> print r() is obj
+>>> print(r() is obj)
True
>>> import weakref
@@ -1071,7 +1085,7 @@
>>> o is o2
True
>>> del o, o2
->>> print r()
+>>> print(r())
None
>>> import weakref
@@ -1079,7 +1093,7 @@
... def __init__(self, ob, callback=None, **annotations):
... super(ExtendedRef, self).__init__(ob, callback)
... self.__counter = 0
-... for k, v in annotations.iteritems():
+... for k, v in annotations.items():
... setattr(self, k, v)
... def __call__(self):
... '''Return a pair containing the referent and the number of
@@ -1090,7 +1104,7 @@
... self.__counter += 1
... ob = (ob, self.__counter)
... return ob
-...
+...
>>> class A: # not in docs from here, just testing the ExtendedRef
... pass
...
@@ -1126,9 +1140,9 @@
>>> try:
... id2obj(a_id)
... except KeyError:
-... print 'OK'
+... print('OK')
... else:
-... print 'WeakValueDictionary error'
+... print('WeakValueDictionary error')
OK
"""
Modified: python/branches/p3yk-noslice/Lib/test/test_winreg.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_winreg.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_winreg.py Fri Feb 23 18:29:35 2007
@@ -133,7 +133,7 @@
# Test on my local machine.
TestAll(HKEY_CURRENT_USER)
-print "Local registry tests worked"
+print("Local registry tests worked")
try:
remote_name = sys.argv[sys.argv.index("--remote")+1]
except (IndexError, ValueError):
@@ -143,14 +143,14 @@
try:
remote_key = ConnectRegistry(remote_name, HKEY_CURRENT_USER)
except EnvironmentError as exc:
- print "Could not connect to the remote machine -", exc.strerror
+ print("Could not connect to the remote machine -", exc.strerror)
remote_key = None
if remote_key is not None:
TestAll(remote_key)
- print "Remote registry tests worked"
+ print("Remote registry tests worked")
else:
- print "Remote registry calls can be tested using",
- print "'test_winreg.py --remote \\\\machine_name'"
+ print("Remote registry calls can be tested using", end=' ')
+ print("'test_winreg.py --remote \\\\machine_name'")
# perform minimal ConnectRegistry test which just invokes it
h = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
h.Close()
Modified: python/branches/p3yk-noslice/Lib/test/test_with.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_with.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_with.py Fri Feb 23 18:29:35 2007
@@ -550,13 +550,13 @@
def testSingleComplexTarget(self):
targets = {1: [0, 1, 2]}
with mock_contextmanager_generator() as targets[1][0]:
- self.assertEqual(targets.keys(), [1])
+ self.assertEqual(list(targets.keys()), [1])
self.assertEqual(targets[1][0].__class__, MockResource)
- with mock_contextmanager_generator() as targets.values()[0][1]:
- self.assertEqual(targets.keys(), [1])
+ with mock_contextmanager_generator() as list(targets.values())[0][1]:
+ self.assertEqual(list(targets.keys()), [1])
self.assertEqual(targets[1][1].__class__, MockResource)
with mock_contextmanager_generator() as targets[2]:
- keys = targets.keys()
+ keys = list(targets.keys())
keys.sort()
self.assertEqual(keys, [1, 2])
class C: pass
@@ -571,7 +571,7 @@
targets = {1: [0, 1, 2]}
with C() as (targets[1][0], targets[1][1], targets[1][2]):
self.assertEqual(targets, {1: [1, 2, 3]})
- with C() as (targets.values()[0][2], targets.values()[0][1], targets.values()[0][0]):
+ with C() as (list(targets.values())[0][2], list(targets.values())[0][1], list(targets.values())[0][0]):
self.assertEqual(targets, {1: [3, 2, 1]})
with C() as (targets[1], targets[2], targets[3]):
self.assertEqual(targets, {1: 1, 2: 2, 3: 3})
Modified: python/branches/p3yk-noslice/Lib/test/test_xdrlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_xdrlib.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_xdrlib.py Fri Feb 23 18:29:35 2007
@@ -15,7 +15,7 @@
p.pack_uint(9)
p.pack_bool(True)
p.pack_bool(False)
- p.pack_uhyper(45L)
+ p.pack_uhyper(45)
p.pack_float(1.9)
p.pack_double(1.9)
p.pack_string(s)
@@ -40,7 +40,7 @@
up.set_position(pos)
self.assert_(up.unpack_bool() is False)
- self.assertEqual(up.unpack_uhyper(), 45L)
+ self.assertEqual(up.unpack_uhyper(), 45)
self.assertAlmostEqual(up.unpack_float(), 1.9)
self.assertAlmostEqual(up.unpack_double(), 1.9)
self.assertEqual(up.unpack_string(), s)
Modified: python/branches/p3yk-noslice/Lib/test/test_xml_etree.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_xml_etree.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_xml_etree.py Fri Feb 23 18:29:35 2007
@@ -37,7 +37,7 @@
def check_method(method):
if not callable(method):
- print method, "not callable"
+ print(method, "not callable")
def serialize(ET, elem, encoding=None):
import StringIO
@@ -184,9 +184,9 @@
>>> element = ET.fromstring("<html><body>text</body></html>")
>>> ET.ElementTree(element).write(sys.stdout)
<html><body>text</body></html>
- >>> print ET.tostring(element)
+ >>> print(ET.tostring(element))
<html><body>text</body></html>
- >>> print ET.tostring(element, "ascii")
+ >>> print(ET.tostring(element, "ascii"))
<?xml version='1.0' encoding='ascii'?>
<html><body>text</body></html>
>>> _, ids = ET.XMLID("<html><body>text</body></html>")
@@ -301,7 +301,7 @@
>>> document = xinclude_loader("C1.xml")
>>> ElementInclude.include(document, xinclude_loader)
- >>> print serialize(ET, document) # C1
+ >>> print(serialize(ET, document)) # C1
<document>
<p>120 Mz is adequate for an average home user.</p>
<disclaimer>
@@ -315,7 +315,7 @@
>>> document = xinclude_loader("C2.xml")
>>> ElementInclude.include(document, xinclude_loader)
- >>> print serialize(ET, document) # C2
+ >>> print(serialize(ET, document)) # C2
<document>
<p>This document has been accessed
324387 times.</p>
@@ -325,7 +325,7 @@
>>> document = xinclude_loader("C3.xml")
>>> ElementInclude.include(document, xinclude_loader)
- >>> print serialize(ET, document) # C3
+ >>> print(serialize(ET, document)) # C3
<document>
<p>The following is the source of the "data.xml" resource:</p>
<example><?xml version='1.0'?>
Modified: python/branches/p3yk-noslice/Lib/test/test_xml_etree_c.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_xml_etree_c.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_xml_etree_c.py Fri Feb 23 18:29:35 2007
@@ -35,7 +35,7 @@
def check_method(method):
if not callable(method):
- print method, "not callable"
+ print(method, "not callable")
def serialize(ET, elem, encoding=None):
import StringIO
@@ -176,9 +176,9 @@
>>> element = ET.fromstring("<html><body>text</body></html>")
>>> ET.ElementTree(element).write(sys.stdout)
<html><body>text</body></html>
- >>> print ET.tostring(element)
+ >>> print(ET.tostring(element))
<html><body>text</body></html>
- >>> print ET.tostring(element, "ascii")
+ >>> print(ET.tostring(element, "ascii"))
<?xml version='1.0' encoding='ascii'?>
<html><body>text</body></html>
>>> _, ids = ET.XMLID("<html><body>text</body></html>")
Modified: python/branches/p3yk-noslice/Lib/test/test_xmlrpc.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_xmlrpc.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_xmlrpc.py Fri Feb 23 18:29:35 2007
@@ -14,7 +14,7 @@
alist = [{'astring': 'foo at bar.baz.spam',
'afloat': 7283.43,
'anint': 2**20,
- 'ashortlong': 2L,
+ 'ashortlong': 2,
'anotherlist': ['.zyx.41'],
'abase64': xmlrpclib.Binary("my dog has fleas"),
'boolean': xmlrpclib.False,
@@ -96,15 +96,15 @@
self.assertEquals(t2, t.__dict__)
def test_dump_big_long(self):
- self.assertRaises(OverflowError, xmlrpclib.dumps, (2L**99,))
+ self.assertRaises(OverflowError, xmlrpclib.dumps, (2**99,))
def test_dump_bad_dict(self):
self.assertRaises(TypeError, xmlrpclib.dumps, ({(1,2,3): 1},))
def test_dump_big_int(self):
- if sys.maxint > 2L**31-1:
+ if sys.maxint > 2**31-1:
self.assertRaises(OverflowError, xmlrpclib.dumps,
- (int(2L**34),))
+ (int(2**34),))
def test_dump_none(self):
value = alist + [None]
@@ -145,7 +145,7 @@
if not setdefaultencoding_existed:
del sys.setdefaultencoding
- items = d.items()
+ items = list(d.items())
if have_unicode:
self.assertEquals(s, u"abc \x95")
self.assert_(isinstance(s, unicode))
Modified: python/branches/p3yk-noslice/Lib/test/test_xrange.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_xrange.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_xrange.py Fri Feb 23 18:29:35 2007
@@ -21,7 +21,7 @@
c = 50
self.assertEqual(list(xrange(a, a+2)), [a, a+1])
- self.assertEqual(list(xrange(a+2, a, -1L)), [a+2, a+1])
+ self.assertEqual(list(xrange(a+2, a, -1)), [a+2, a+1])
self.assertEqual(list(xrange(a+4, a, -2)), [a+4, a+2])
seq = list(xrange(a, b, c))
Modified: python/branches/p3yk-noslice/Lib/test/test_zipfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_zipfile.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_zipfile.py Fri Feb 23 18:29:35 2007
@@ -282,11 +282,11 @@
os.mkdir(TESTFN2)
try:
fp = open(os.path.join(TESTFN2, "mod1.py"), "w")
- fp.write("print 42\n")
+ fp.write("print(42)\n")
fp.close()
fp = open(os.path.join(TESTFN2, "mod2.py"), "w")
- fp.write("print 42 * 42\n")
+ fp.write("print(42 * 42)\n")
fp.close()
fp = open(os.path.join(TESTFN2, "mod2.txt"), "w")
@@ -307,6 +307,28 @@
class OtherTests(unittest.TestCase):
+ def testCreateNonExistentFileForAppend(self):
+ if os.path.exists(TESTFN):
+ os.unlink(TESTFN)
+
+ filename = 'testfile.txt'
+ content = 'hello, world. this is some content.'
+
+ try:
+ zf = zipfile.ZipFile(TESTFN, 'a')
+ zf.writestr(filename, content)
+ zf.close()
+ except IOError:
+ self.fail('Could not append data to a non-existent zip file.')
+
+ self.assert_(os.path.exists(TESTFN))
+
+ zf = zipfile.ZipFile(TESTFN, 'r')
+ self.assertEqual(zf.read(filename), content)
+ zf.close()
+
+ os.unlink(TESTFN)
+
def testCloseErroneousFile(self):
# This test checks that the ZipFile constructor closes the file object
# it opens if there's an error in the file. If it doesn't, the traceback
@@ -349,8 +371,49 @@
# and report that the first file in the archive was corrupt.
self.assertRaises(RuntimeError, zipf.testzip)
+
+class DecryptionTests(unittest.TestCase):
+ # This test checks that ZIP decryption works. Since the library does not
+ # support encryption at the moment, we use a pre-generated encrypted
+ # ZIP file
+
+ data = (
+ 'PK\x03\x04\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00\x1a\x00'
+ '\x00\x00\x08\x00\x00\x00test.txt\xfa\x10\xa0gly|\xfa-\xc5\xc0=\xf9y'
+ '\x18\xe0\xa8r\xb3Z}Lg\xbc\xae\xf9|\x9b\x19\xe4\x8b\xba\xbb)\x8c\xb0\xdbl'
+ 'PK\x01\x02\x14\x00\x14\x00\x01\x00\x00\x00n\x92i.#y\xef?&\x00\x00\x00'
+ '\x1a\x00\x00\x00\x08\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\xb6\x81'
+ '\x00\x00\x00\x00test.txtPK\x05\x06\x00\x00\x00\x00\x01\x00\x01\x006\x00'
+ '\x00\x00L\x00\x00\x00\x00\x00' )
+
+ plain = 'zipfile.py encryption test'
+
+ def setUp(self):
+ fp = open(TESTFN, "wb")
+ fp.write(self.data)
+ fp.close()
+ self.zip = zipfile.ZipFile(TESTFN, "r")
+
+ def tearDown(self):
+ self.zip.close()
+ os.unlink(TESTFN)
+
+ def testNoPassword(self):
+ # Reading the encrypted file without password
+ # must generate a RunTime exception
+ self.assertRaises(RuntimeError, self.zip.read, "test.txt")
+
+ def testBadPassword(self):
+ self.zip.setpassword("perl")
+ self.assertRaises(RuntimeError, self.zip.read, "test.txt")
+
+ def testGoodPassword(self):
+ self.zip.setpassword("python")
+ self.assertEquals(self.zip.read("test.txt"), self.plain)
+
def test_main():
- run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests, PyZipFileTests)
+ run_unittest(TestsWithSourceFile, TestZip64InSmallFiles, OtherTests,
+ PyZipFileTests, DecryptionTests)
#run_unittest(TestZip64InSmallFiles)
if __name__ == "__main__":
Modified: python/branches/p3yk-noslice/Lib/test/test_zipfile64.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_zipfile64.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_zipfile64.py Fri Feb 23 18:29:35 2007
@@ -57,9 +57,9 @@
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
- print >>sys.__stdout__, (
+ print((
' zipTest still writing %d of %d, be patient...' %
- (num, filecount))
+ (num, filecount)), file=sys.__stdout__)
sys.__stdout__.flush()
zipfp.close()
@@ -70,9 +70,9 @@
# Print still working message since this test can be really slow
if next_time <= time.time():
next_time = time.time() + _PRINT_WORKING_MSG_INTERVAL
- print >>sys.__stdout__, (
+ print((
' zipTest still reading %d of %d, be patient...' %
- (num, filecount))
+ (num, filecount)), file=sys.__stdout__)
sys.__stdout__.flush()
zipfp.close()
Modified: python/branches/p3yk-noslice/Lib/test/test_zipimport.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_zipimport.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_zipimport.py Fri Feb 23 18:29:35 2007
@@ -31,7 +31,7 @@
if mtime < 0x7fffffff:
mtime = int(mtime)
else:
- mtime = int(-0x100000000L + long(mtime))
+ mtime = int(-0x100000000 + int(mtime))
pyc = imp.get_magic() + struct.pack("<i", int(mtime)) + data
return pyc
Modified: python/branches/p3yk-noslice/Lib/test/test_zlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/test_zlib.py (original)
+++ python/branches/p3yk-noslice/Lib/test/test_zlib.py Fri Feb 23 18:29:35 2007
@@ -43,10 +43,10 @@
def assertEqual32(self, seen, expected):
# 32-bit values masked -- checksums on 32- vs 64- bit machines
# This is important if bit 31 (0x08000000L) is set.
- self.assertEqual(seen & 0x0FFFFFFFFL, expected & 0x0FFFFFFFFL)
+ self.assertEqual(seen & 0x0FFFFFFFF, expected & 0x0FFFFFFFF)
def test_penguins(self):
- self.assertEqual32(zlib.crc32("penguin", 0), 0x0e5c1a120L)
+ self.assertEqual32(zlib.crc32("penguin", 0), 0x0e5c1a120)
self.assertEqual32(zlib.crc32("penguin", 1), 0x43b6aa94)
self.assertEqual32(zlib.adler32("penguin", 0), 0x0bcf02f6)
self.assertEqual32(zlib.adler32("penguin", 1), 0x0bd602f7)
Modified: python/branches/p3yk-noslice/Lib/test/time_hashlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/test/time_hashlib.py (original)
+++ python/branches/p3yk-noslice/Lib/test/time_hashlib.py Fri Feb 23 18:29:35 2007
@@ -18,7 +18,7 @@
x = localCF(longStr).digest()
end = time.time()
- print ('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name
+ print(('%2.2f' % (end-start)), "seconds", iterations, "x", len(longStr), "bytes", name)
def test_create():
start = time.time()
@@ -26,7 +26,7 @@
d = creatorFunc()
end = time.time()
- print ('%2.2f' % (end-start)), "seconds", '[20000 creations]'
+ print(('%2.2f' % (end-start)), "seconds", '[20000 creations]')
def test_zero():
start = time.time()
@@ -34,7 +34,7 @@
x = creatorFunc().digest()
end = time.time()
- print ('%2.2f' % (end-start)), "seconds", '[20000 "" digests]'
+ print(('%2.2f' % (end-start)), "seconds", '[20000 "" digests]')
@@ -46,33 +46,33 @@
if hName in ('_md5', '_sha'):
exec('import '+hName)
exec('creatorFunc = '+hName+'.new')
- print "testing speed of old", hName, "legacy interface"
+ print("testing speed of old", hName, "legacy interface")
elif hName == '_hashlib' and len(sys.argv) > 3:
import _hashlib
exec('creatorFunc = _hashlib.%s' % sys.argv[2])
- print "testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2])
+ print("testing speed of _hashlib.%s" % sys.argv[2], getattr(_hashlib, sys.argv[2]))
elif hName == '_hashlib' and len(sys.argv) == 3:
import _hashlib
exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2])
- print "testing speed of _hashlib.new(%r)" % sys.argv[2]
+ print("testing speed of _hashlib.new(%r)" % sys.argv[2])
elif hasattr(hashlib, hName) and callable(getattr(hashlib, hName)):
creatorFunc = getattr(hashlib, hName)
- print "testing speed of hashlib."+hName, getattr(hashlib, hName)
+ print("testing speed of hashlib."+hName, getattr(hashlib, hName))
else:
exec("creatorFunc = lambda x=hashlib.new : x(%r)" % hName)
- print "testing speed of hashlib.new(%r)" % hName
+ print("testing speed of hashlib.new(%r)" % hName)
try:
test_create()
except ValueError:
- print
- print "pass argument(s) naming the hash to run a speed test on:"
- print " '_md5' and '_sha' test the legacy builtin md5 and sha"
- print " '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib"
- print " '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)"
- print " 'hName' tests the hashlib.hName() implementation if it exists"
- print " otherwise it uses hashlib.new(hName)."
- print
+ print()
+ print("pass argument(s) naming the hash to run a speed test on:")
+ print(" '_md5' and '_sha' test the legacy builtin md5 and sha")
+ print(" '_hashlib' 'openssl_hName' 'fast' tests the builtin _hashlib")
+ print(" '_hashlib' 'hName' tests builtin _hashlib.new(shaFOO)")
+ print(" 'hName' tests the hashlib.hName() implementation if it exists")
+ print(" otherwise it uses hashlib.new(hName).")
+ print()
raise
test_zero()
Modified: python/branches/p3yk-noslice/Lib/textwrap.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/textwrap.py (original)
+++ python/branches/p3yk-noslice/Lib/textwrap.py Fri Feb 23 18:29:35 2007
@@ -371,4 +371,4 @@
if __name__ == "__main__":
#print dedent("\tfoo\n\tbar")
#print dedent(" \thello there\n \t how are you?")
- print dedent("Hello there.\n This is indented.")
+ print(dedent("Hello there.\n This is indented."))
Modified: python/branches/p3yk-noslice/Lib/this.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/this.py (original)
+++ python/branches/p3yk-noslice/Lib/this.py Fri Feb 23 18:29:35 2007
@@ -25,4 +25,4 @@
for i in range(26):
d[chr(i+c)] = chr((i+13) % 26 + c)
-print "".join([d.get(c, c) for c in s])
+print("".join([d.get(c, c) for c in s]))
Modified: python/branches/p3yk-noslice/Lib/threading.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/threading.py (original)
+++ python/branches/p3yk-noslice/Lib/threading.py Fri Feb 23 18:29:35 2007
@@ -477,19 +477,19 @@
# Lib/traceback.py)
exc_type, exc_value, exc_tb = self.__exc_info()
try:
- print>>self.__stderr, (
+ print((
"Exception in thread " + self.getName() +
- " (most likely raised during interpreter shutdown):")
- print>>self.__stderr, (
- "Traceback (most recent call last):")
+ " (most likely raised during interpreter shutdown):"), file=self.__stderr)
+ print((
+ "Traceback (most recent call last):"), file=self.__stderr)
while exc_tb:
- print>>self.__stderr, (
+ print((
' File "%s", line %s, in %s' %
(exc_tb.tb_frame.f_code.co_filename,
exc_tb.tb_lineno,
- exc_tb.tb_frame.f_code.co_name))
+ exc_tb.tb_frame.f_code.co_name)), file=self.__stderr)
exc_tb = exc_tb.tb_next
- print>>self.__stderr, ("%s: %s" % (exc_type, exc_value))
+ print(("%s: %s" % (exc_type, exc_value)), file=self.__stderr)
# Make sure that exc_tb gets deleted since it is a memory
# hog; deleting everything else is just for thoroughness
finally:
@@ -707,7 +707,7 @@
def enumerate():
_active_limbo_lock.acquire()
- active = _active.values() + _limbo.values()
+ active = list(_active.values()) + list(_limbo.values())
_active_limbo_lock.release()
return active
@@ -790,7 +790,7 @@
def run(self):
while self.count > 0:
item = self.queue.get()
- print item
+ print(item)
self.count = self.count - 1
NP = 3
Modified: python/branches/p3yk-noslice/Lib/timeit.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/timeit.py (original)
+++ python/branches/p3yk-noslice/Lib/timeit.py Fri Feb 23 18:29:35 2007
@@ -210,8 +210,8 @@
["number=", "setup=", "repeat=",
"time", "clock", "verbose", "help"])
except getopt.error as err:
- print err
- print "use -h/--help for command line help"
+ print(err)
+ print("use -h/--help for command line help")
return 2
timer = default_timer
stmt = "\n".join(args) or "pass"
@@ -238,7 +238,7 @@
precision += 1
verbose += 1
if o in ("-h", "--help"):
- print __doc__,
+ print(__doc__, end=' ')
return 0
setup = "\n".join(setup) or "pass"
# Include the current directory, so that local imports work (sys.path
@@ -257,7 +257,7 @@
t.print_exc()
return 1
if verbose:
- print "%d loops -> %.*g secs" % (number, precision, x)
+ print("%d loops -> %.*g secs" % (number, precision, x))
if x >= 0.2:
break
try:
@@ -267,18 +267,18 @@
return 1
best = min(r)
if verbose:
- print "raw times:", " ".join(["%.*g" % (precision, x) for x in r])
- print "%d loops," % number,
+ print("raw times:", " ".join(["%.*g" % (precision, x) for x in r]))
+ print("%d loops," % number, end=' ')
usec = best * 1e6 / number
if usec < 1000:
- print "best of %d: %.*g usec per loop" % (repeat, precision, usec)
+ print("best of %d: %.*g usec per loop" % (repeat, precision, usec))
else:
msec = usec / 1000
if msec < 1000:
- print "best of %d: %.*g msec per loop" % (repeat, precision, msec)
+ print("best of %d: %.*g msec per loop" % (repeat, precision, msec))
else:
sec = msec / 1000
- print "best of %d: %.*g sec per loop" % (repeat, precision, sec)
+ print("best of %d: %.*g sec per loop" % (repeat, precision, sec))
return None
if __name__ == "__main__":
Modified: python/branches/p3yk-noslice/Lib/token.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/token.py (original)
+++ python/branches/p3yk-noslice/Lib/token.py Fri Feb 23 18:29:35 2007
@@ -68,7 +68,7 @@
#--end constants--
tok_name = {}
-for _name, _value in globals().items():
+for _name, _value in list(globals().items()):
if type(_value) is type(0):
tok_name[_value] = _name
Modified: python/branches/p3yk-noslice/Lib/tokenize.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/tokenize.py (original)
+++ python/branches/p3yk-noslice/Lib/tokenize.py Fri Feb 23 18:29:35 2007
@@ -133,8 +133,8 @@
class StopTokenizing(Exception): pass
def printtoken(type, token, (srow, scol), (erow, ecol), line): # for testing
- print "%d,%d-%d,%d:\t%s\t%s" % \
- (srow, scol, erow, ecol, tok_name[type], repr(token))
+ print("%d,%d-%d,%d:\t%s\t%s" % \
+ (srow, scol, erow, ecol, tok_name[type], repr(token)))
def tokenize(readline, tokeneater=printtoken):
"""
Modified: python/branches/p3yk-noslice/Lib/trace.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/trace.py (original)
+++ python/branches/p3yk-noslice/Lib/trace.py Fri Feb 23 18:29:35 2007
@@ -221,8 +221,8 @@
pickle.load(open(self.infile, 'rb'))
self.update(self.__class__(counts, calledfuncs, callers))
except (IOError, EOFError, ValueError) as err:
- print >> sys.stderr, ("Skipping counts file %r: %s"
- % (self.infile, err))
+ print(("Skipping counts file %r: %s"
+ % (self.infile, err)), file=sys.stderr)
def update(self, other):
"""Merge in the data from another CoverageResults"""
@@ -247,30 +247,30 @@
@param coverdir
"""
if self.calledfuncs:
- print
- print "functions called:"
+ print()
+ print("functions called:")
calls = self.calledfuncs.keys()
calls.sort()
for filename, modulename, funcname in calls:
- print ("filename: %s, modulename: %s, funcname: %s"
- % (filename, modulename, funcname))
+ print(("filename: %s, modulename: %s, funcname: %s"
+ % (filename, modulename, funcname)))
if self.callers:
- print
- print "calling relationships:"
+ print()
+ print("calling relationships:")
calls = self.callers.keys()
calls.sort()
lastfile = lastcfile = ""
for ((pfile, pmod, pfunc), (cfile, cmod, cfunc)) in calls:
if pfile != lastfile:
- print
- print "***", pfile, "***"
+ print()
+ print("***", pfile, "***")
lastfile = pfile
lastcfile = ""
if cfile != pfile and lastcfile != cfile:
- print " -->", cfile
+ print(" -->", cfile)
lastcfile = cfile
- print " %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc)
+ print(" %s.%s -> %s.%s" % (pmod, pfunc, cmod, cfunc))
# turn the counts data ("(filename, lineno) = count") into something
# accessible on a per-file basis
@@ -282,7 +282,7 @@
# accumulate summary info, if needed
sums = {}
- for filename, count in per_file.iteritems():
+ for filename, count in per_file.items():
# skip some "files" we don't care about...
if filename == "<string>":
continue
@@ -318,10 +318,10 @@
if summary and sums:
mods = sums.keys()
mods.sort()
- print "lines cov% module (path)"
+ print("lines cov% module (path)")
for m in mods:
n_lines, percent, modulename, filename = sums[m]
- print "%5d %3d%% %s (%s)" % sums[m]
+ print("%5d %3d%% %s (%s)" % sums[m])
if self.outfile:
# try and store counts and module info into self.outfile
@@ -329,7 +329,7 @@
pickle.dump((self.counts, self.calledfuncs, self.callers),
open(self.outfile, 'wb'), 1)
except IOError as err:
- print >> sys.stderr, "Can't save counts files because %s" % err
+ print("Can't save counts files because %s" % err, file=sys.stderr)
def write_results_file(self, path, lines, lnotab, lines_hit):
"""Return a coverage results file in path."""
@@ -337,8 +337,8 @@
try:
outfile = open(path, "w")
except IOError as err:
- print >> sys.stderr, ("trace: Could not open %r for writing: %s"
- "- skipping" % (path, err))
+ print(("trace: Could not open %r for writing: %s"
+ "- skipping" % (path, err)), file=sys.stderr)
return 0, 0
n_lines = 0
@@ -423,8 +423,8 @@
try:
prog = open(filename, "rU").read()
except IOError as err:
- print >> sys.stderr, ("Not printing coverage data for %r: %s"
- % (filename, err))
+ print(("Not printing coverage data for %r: %s"
+ % (filename, err)), file=sys.stderr)
return {}
code = compile(prog, filename, "exec")
strs = find_strings(filename)
@@ -587,7 +587,7 @@
"""
if why == 'call':
code = frame.f_code
- filename = code.co_filename
+ filename = frame.f_globals.get('__file__', None)
if filename:
# XXX modname() doesn't work right for packages, so
# the ignore support won't work right for packages
@@ -596,8 +596,8 @@
ignore_it = self.ignore.names(filename, modulename)
if not ignore_it:
if self.trace:
- print (" --- modulename: %s, funcname: %s"
- % (modulename, code.co_name))
+ print((" --- modulename: %s, funcname: %s"
+ % (modulename, code.co_name)))
return self.localtrace
else:
return None
@@ -611,8 +611,8 @@
self.counts[key] = self.counts.get(key, 0) + 1
bname = os.path.basename(filename)
- print "%s(%d): %s" % (bname, lineno,
- linecache.getline(filename, lineno)),
+ print("%s(%d): %s" % (bname, lineno,
+ linecache.getline(filename, lineno)), end=' ')
return self.localtrace
def localtrace_trace(self, frame, why, arg):
@@ -622,8 +622,8 @@
lineno = frame.f_lineno
bname = os.path.basename(filename)
- print "%s(%d): %s" % (bname, lineno,
- linecache.getline(filename, lineno)),
+ print("%s(%d): %s" % (bname, lineno,
+ linecache.getline(filename, lineno)), end=' ')
return self.localtrace
def localtrace_count(self, frame, why, arg):
Modified: python/branches/p3yk-noslice/Lib/types.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/types.py (original)
+++ python/branches/p3yk-noslice/Lib/types.py Fri Feb 23 18:29:35 2007
@@ -14,7 +14,7 @@
ObjectType = object
IntType = int
-LongType = long
+LongType = int
FloatType = float
BooleanType = bool
try:
Modified: python/branches/p3yk-noslice/Lib/unittest.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/unittest.py (original)
+++ python/branches/p3yk-noslice/Lib/unittest.py Fri Feb 23 18:29:35 2007
@@ -759,8 +759,8 @@
self.runTests()
def usageExit(self, msg=None):
- if msg: print msg
- print self.USAGE % self.__dict__
+ if msg: print(msg)
+ print(self.USAGE % self.__dict__)
sys.exit(2)
def parseArgs(self, argv):
Modified: python/branches/p3yk-noslice/Lib/urllib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/urllib.py (original)
+++ python/branches/p3yk-noslice/Lib/urllib.py Fri Feb 23 18:29:35 2007
@@ -452,7 +452,7 @@
def open_local_file(self, url):
"""Use local file."""
- import mimetypes, mimetools, email.Utils
+ import mimetypes, mimetools, email.utils
try:
from cStringIO import StringIO
except ImportError:
@@ -464,7 +464,7 @@
except OSError as e:
raise IOError(e.errno, e.strerror, e.filename)
size = stats.st_size
- modified = email.Utils.formatdate(stats.st_mtime, usegmt=True)
+ modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
mtype = mimetypes.guess_type(url)[0]
headers = mimetools.Message(StringIO(
'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
@@ -777,7 +777,7 @@
(user, realm, host))
return user, passwd
except KeyboardInterrupt:
- print
+ print()
return None, None
@@ -1453,17 +1453,17 @@
uqs = unquote(qs)
t1 = time.time()
if uqs != s:
- print 'Wrong!'
- print repr(s)
- print repr(qs)
- print repr(uqs)
- print round(t1 - t0, 3), 'sec'
+ print('Wrong!')
+ print(repr(s))
+ print(repr(qs))
+ print(repr(uqs))
+ print(round(t1 - t0, 3), 'sec')
def reporthook(blocknum, blocksize, totalsize):
# Report during remote transfers
- print "Block number: %d, Block size: %d, Total size: %d" % (
- blocknum, blocksize, totalsize)
+ print("Block number: %d, Block size: %d, Total size: %d" % (
+ blocknum, blocksize, totalsize))
# Test program
def test(args=[]):
@@ -1480,22 +1480,22 @@
args.append('https://synergy.as.cmu.edu/~geek/')
try:
for url in args:
- print '-'*10, url, '-'*10
+ print('-'*10, url, '-'*10)
fn, h = urlretrieve(url, None, reporthook)
- print fn
+ print(fn)
if h:
- print '======'
- for k in h.keys(): print k + ':', h[k]
- print '======'
+ print('======')
+ for k in h.keys(): print(k + ':', h[k])
+ print('======')
fp = open(fn, 'rb')
data = fp.read()
del fp
if '\r' in data:
table = string.maketrans("", "")
data = data.translate(table, "\r")
- print data
+ print(data)
fn, h = None, None
- print '-'*40
+ print('-'*40)
finally:
urlcleanup()
@@ -1504,17 +1504,17 @@
try:
opts, args = getopt.getopt(sys.argv[1:], "th")
except getopt.error as msg:
- print msg
- print "Use -h for help"
+ print(msg)
+ print("Use -h for help")
return
t = 0
for o, a in opts:
if o == '-t':
t = t + 1
if o == '-h':
- print "Usage: python urllib.py [-t] [url ...]"
- print "-t runs self-test;",
- print "otherwise, contents of urls are printed"
+ print("Usage: python urllib.py [-t] [url ...]")
+ print("-t runs self-test;", end=' ')
+ print("otherwise, contents of urls are printed")
return
if t:
if t > 1:
@@ -1522,9 +1522,9 @@
test(args)
else:
if not args:
- print "Use -h for help"
+ print("Use -h for help")
for url in args:
- print urlopen(url).read(),
+ print(urlopen(url).read(), end=' ')
# Run test program when run as a script
if __name__ == '__main__':
Modified: python/branches/p3yk-noslice/Lib/urllib2.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/urllib2.py (original)
+++ python/branches/p3yk-noslice/Lib/urllib2.py Fri Feb 23 18:29:35 2007
@@ -281,7 +281,7 @@
def header_items(self):
hdrs = self.unredirected_hdrs.copy()
hdrs.update(self.headers)
- return hdrs.items()
+ return list(hdrs.items())
class OpenerDirector:
def __init__(self):
@@ -710,7 +710,7 @@
domains = self.passwd.get(realm, {})
for default_port in True, False:
reduced_authuri = self.reduce_uri(authuri, default_port)
- for uris, authinfo in domains.iteritems():
+ for uris, authinfo in domains.items():
for uri in uris:
if self.is_suburi(uri, reduced_authuri):
return authinfo
@@ -1087,7 +1087,7 @@
# out of socket._fileobject() and into a base class.
r.recv = r.read
- fp = socket._fileobject(r)
+ fp = socket._fileobject(r, close=True)
resp = addinfourl(fp, r.msg, req.get_full_url())
resp.code = r.status
@@ -1209,14 +1209,14 @@
# not entirely sure what the rules are here
def open_local_file(self, req):
- import email.Utils
+ import email.utils
import mimetypes
host = req.get_host()
file = req.get_selector()
localfile = url2pathname(file)
stats = os.stat(localfile)
size = stats.st_size
- modified = email.Utils.formatdate(stats.st_mtime, usegmt=True)
+ modified = email.utils.formatdate(stats.st_mtime, usegmt=True)
mtype = mimetypes.guess_type(file)[0]
headers = mimetools.Message(StringIO(
'Content-type: %s\nContent-length: %d\nLast-modified: %s\n' %
@@ -1318,21 +1318,21 @@
# first check for old ones
t = time.time()
if self.soonest <= t:
- for k, v in self.timeout.items():
+ for k, v in list(self.timeout.items()):
if v < t:
self.cache[k].close()
del self.cache[k]
del self.timeout[k]
- self.soonest = min(self.timeout.values())
+ self.soonest = min(list(self.timeout.values()))
# then check the size
if len(self.cache) == self.max_conns:
- for k, v in self.timeout.items():
+ for k, v in list(self.timeout.items()):
if v == self.soonest:
del self.cache[k]
del self.timeout[k]
break
- self.soonest = min(self.timeout.values())
+ self.soonest = min(list(self.timeout.values()))
class GopherHandler(BaseHandler):
def gopher_open(self, req):
Modified: python/branches/p3yk-noslice/Lib/urlparse.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/urlparse.py (original)
+++ python/branches/p3yk-noslice/Lib/urlparse.py Fri Feb 23 18:29:35 2007
@@ -361,15 +361,15 @@
continue
url = words[0]
parts = urlparse(url)
- print '%-10s : %s' % (url, parts)
+ print('%-10s : %s' % (url, parts))
abs = urljoin(base, url)
if not base:
base = abs
wrapped = '<URL:%s>' % abs
- print '%-10s = %s' % (url, wrapped)
+ print('%-10s = %s' % (url, wrapped))
if len(words) == 3 and words[1] == '=':
if wrapped != words[2]:
- print 'EXPECTED', words[2], '!!!!!!!!!!'
+ print('EXPECTED', words[2], '!!!!!!!!!!')
if __name__ == '__main__':
test()
Modified: python/branches/p3yk-noslice/Lib/uu.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/uu.py (original)
+++ python/branches/p3yk-noslice/Lib/uu.py Fri Feb 23 18:29:35 2007
@@ -170,7 +170,7 @@
if isinstance(output, basestring):
output = open(output, 'w')
else:
- print sys.argv[0], ': cannot do -t to stdout'
+ print(sys.argv[0], ': cannot do -t to stdout')
sys.exit(1)
decode(input, output)
else:
@@ -178,7 +178,7 @@
if isinstance(input, basestring):
input = open(input, 'r')
else:
- print sys.argv[0], ': cannot do -t from stdin'
+ print(sys.argv[0], ': cannot do -t from stdin')
sys.exit(1)
encode(input, output)
Modified: python/branches/p3yk-noslice/Lib/uuid.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/uuid.py (original)
+++ python/branches/p3yk-noslice/Lib/uuid.py Fri Feb 23 18:29:35 2007
@@ -50,6 +50,8 @@
'reserved for NCS compatibility', 'specified in RFC 4122',
'reserved for Microsoft compatibility', 'reserved for future definition']
+int_ = int # The built-in int function
+
class UUID(object):
"""Instances of the UUID class represent UUIDs as specified in RFC 4122.
UUID objects are immutable, hashable, and usable as dictionary keys.
@@ -132,7 +134,7 @@
hex = hex.strip('{}').replace('-', '')
if len(hex) != 32:
raise ValueError('badly formed hexadecimal UUID string')
- int = long(hex, 16)
+ int = int_(hex, 16)
if bytes_le is not None:
if len(bytes_le) != 16:
raise ValueError('bytes_le is not a 16-char string')
@@ -142,39 +144,39 @@
if bytes is not None:
if len(bytes) != 16:
raise ValueError('bytes is not a 16-char string')
- int = long(('%02x'*16) % tuple(map(ord, bytes)), 16)
+ int = int_(('%02x'*16) % tuple(map(ord, bytes)), 16)
if fields is not None:
if len(fields) != 6:
raise ValueError('fields is not a 6-tuple')
(time_low, time_mid, time_hi_version,
clock_seq_hi_variant, clock_seq_low, node) = fields
- if not 0 <= time_low < 1<<32L:
+ if not 0 <= time_low < 1<<32:
raise ValueError('field 1 out of range (need a 32-bit value)')
- if not 0 <= time_mid < 1<<16L:
+ if not 0 <= time_mid < 1<<16:
raise ValueError('field 2 out of range (need a 16-bit value)')
- if not 0 <= time_hi_version < 1<<16L:
+ if not 0 <= time_hi_version < 1<<16:
raise ValueError('field 3 out of range (need a 16-bit value)')
- if not 0 <= clock_seq_hi_variant < 1<<8L:
+ if not 0 <= clock_seq_hi_variant < 1<<8:
raise ValueError('field 4 out of range (need an 8-bit value)')
- if not 0 <= clock_seq_low < 1<<8L:
+ if not 0 <= clock_seq_low < 1<<8:
raise ValueError('field 5 out of range (need an 8-bit value)')
- if not 0 <= node < 1<<48L:
+ if not 0 <= node < 1<<48:
raise ValueError('field 6 out of range (need a 48-bit value)')
- clock_seq = (clock_seq_hi_variant << 8L) | clock_seq_low
- int = ((time_low << 96L) | (time_mid << 80L) |
- (time_hi_version << 64L) | (clock_seq << 48L) | node)
+ clock_seq = (clock_seq_hi_variant << 8) | clock_seq_low
+ int = ((time_low << 96) | (time_mid << 80) |
+ (time_hi_version << 64) | (clock_seq << 48) | node)
if int is not None:
- if not 0 <= int < 1<<128L:
+ if not 0 <= int < 1<<128:
raise ValueError('int is out of range (need a 128-bit value)')
if version is not None:
if not 1 <= version <= 5:
raise ValueError('illegal version number')
# Set the variant to RFC 4122.
- int &= ~(0xc000 << 48L)
- int |= 0x8000 << 48L
+ int &= ~(0xc000 << 48)
+ int |= 0x8000 << 48
# Set the version number.
- int &= ~(0xf000 << 64L)
- int |= version << 76L
+ int &= ~(0xf000 << 64)
+ int |= version << 76
self.__dict__['int'] = int
def __eq__(self, other):
@@ -248,38 +250,38 @@
fields = property(get_fields)
def get_time_low(self):
- return self.int >> 96L
+ return self.int >> 96
time_low = property(get_time_low)
def get_time_mid(self):
- return (self.int >> 80L) & 0xffff
+ return (self.int >> 80) & 0xffff
time_mid = property(get_time_mid)
def get_time_hi_version(self):
- return (self.int >> 64L) & 0xffff
+ return (self.int >> 64) & 0xffff
time_hi_version = property(get_time_hi_version)
def get_clock_seq_hi_variant(self):
- return (self.int >> 56L) & 0xff
+ return (self.int >> 56) & 0xff
clock_seq_hi_variant = property(get_clock_seq_hi_variant)
def get_clock_seq_low(self):
- return (self.int >> 48L) & 0xff
+ return (self.int >> 48) & 0xff
clock_seq_low = property(get_clock_seq_low)
def get_time(self):
- return (((self.time_hi_version & 0x0fffL) << 48L) |
- (self.time_mid << 32L) | self.time_low)
+ return (((self.time_hi_version & 0x0fff) << 48) |
+ (self.time_mid << 32) | self.time_low)
time = property(get_time)
def get_clock_seq(self):
- return (((self.clock_seq_hi_variant & 0x3fL) << 8L) |
+ return (((self.clock_seq_hi_variant & 0x3f) << 8) |
self.clock_seq_low)
clock_seq = property(get_clock_seq)
@@ -300,11 +302,11 @@
urn = property(get_urn)
def get_variant(self):
- if not self.int & (0x8000 << 48L):
+ if not self.int & (0x8000 << 48):
return RESERVED_NCS
- elif not self.int & (0x4000 << 48L):
+ elif not self.int & (0x4000 << 48):
return RFC_4122
- elif not self.int & (0x2000 << 48L):
+ elif not self.int & (0x2000 << 48):
return RESERVED_MICROSOFT
else:
return RESERVED_FUTURE
@@ -314,7 +316,7 @@
def get_version(self):
# The version bits are only meaningful for RFC 4122 UUIDs.
if self.variant == RFC_4122:
- return int((self.int >> 76L) & 0xf)
+ return int((self.int >> 76) & 0xf)
version = property(get_version)
@@ -411,8 +413,8 @@
continue
status._unpack()
bytes = map(ord, status.adapter_address)
- return ((bytes[0]<<40L) + (bytes[1]<<32L) + (bytes[2]<<24L) +
- (bytes[3]<<16L) + (bytes[4]<<8L) + bytes[5])
+ return ((bytes[0]<<40) + (bytes[1]<<32) + (bytes[2]<<24) +
+ (bytes[3]<<16) + (bytes[4]<<8) + bytes[5])
# Thanks to Thomas Heller for ctypes and for his help with its use here.
@@ -464,7 +466,7 @@
def _random_getnode():
"""Get a random node ID, with eighth bit set as suggested by RFC 4122."""
import random
- return random.randrange(0, 1<<48L) | 0x010000000000L
+ return random.randrange(0, 1<<48) | 0x010000000000
_node = None
@@ -514,18 +516,18 @@
nanoseconds = int(time.time() * 1e9)
# 0x01b21dd213814000 is the number of 100-ns intervals between the
# UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
- timestamp = int(nanoseconds/100) + 0x01b21dd213814000L
+ timestamp = int(nanoseconds/100) + 0x01b21dd213814000
if _last_timestamp is not None and timestamp <= _last_timestamp:
timestamp = _last_timestamp + 1
_last_timestamp = timestamp
if clock_seq is None:
import random
- clock_seq = random.randrange(1<<14L) # instead of stable storage
- time_low = timestamp & 0xffffffffL
- time_mid = (timestamp >> 32L) & 0xffffL
- time_hi_version = (timestamp >> 48L) & 0x0fffL
- clock_seq_low = clock_seq & 0xffL
- clock_seq_hi_variant = (clock_seq >> 8L) & 0x3fL
+ clock_seq = random.randrange(1<<14) # instead of stable storage
+ time_low = timestamp & 0xffffffff
+ time_mid = (timestamp >> 32) & 0xffff
+ time_hi_version = (timestamp >> 48) & 0x0fff
+ clock_seq_low = clock_seq & 0xff
+ clock_seq_hi_variant = (clock_seq >> 8) & 0x3f
if node is None:
node = getnode()
return UUID(fields=(time_low, time_mid, time_hi_version,
Modified: python/branches/p3yk-noslice/Lib/warnings.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/warnings.py (original)
+++ python/branches/p3yk-noslice/Lib/warnings.py Fri Feb 23 18:29:35 2007
@@ -193,7 +193,7 @@
try:
_setoption(arg)
except _OptionError as msg:
- print >>sys.stderr, "Invalid -W option ignored:", msg
+ print("Invalid -W option ignored:", msg, file=sys.stderr)
# Helper for _processoptions()
def _setoption(arg):
Modified: python/branches/p3yk-noslice/Lib/weakref.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/weakref.py (original)
+++ python/branches/p3yk-noslice/Lib/weakref.py Fri Feb 23 18:29:35 2007
@@ -100,16 +100,16 @@
return L
def iteritems(self):
- for wr in self.data.itervalues():
+ for wr in self.data.values():
value = wr()
if value is not None:
yield wr.key, value
def iterkeys(self):
- return self.data.iterkeys()
+ return iter(self.data.keys())
def __iter__(self):
- return self.data.iterkeys()
+ return iter(self.data.keys())
def itervaluerefs(self):
"""Return an iterator that yields the weak references to the values.
@@ -121,10 +121,10 @@
keep the values around longer than needed.
"""
- return self.data.itervalues()
+ return self.data.values()
def itervalues(self):
- for wr in self.data.itervalues():
+ for wr in self.data.values():
obj = wr()
if obj is not None:
yield obj
@@ -268,7 +268,7 @@
return L
def iteritems(self):
- for wr, value in self.data.iteritems():
+ for wr, value in self.data.items():
key = wr()
if key is not None:
yield key, value
@@ -283,19 +283,19 @@
keep the keys around longer than needed.
"""
- return self.data.iterkeys()
+ return self.data.keys()
def iterkeys(self):
- for wr in self.data.iterkeys():
+ for wr in self.data.keys():
obj = wr()
if obj is not None:
yield obj
def __iter__(self):
- return self.iterkeys()
+ return iter(self.keys())
def itervalues(self):
- return self.data.itervalues()
+ return iter(self.data.values())
def keyrefs(self):
"""Return a list of weak references to the keys.
Modified: python/branches/p3yk-noslice/Lib/webbrowser.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/webbrowser.py (original)
+++ python/branches/p3yk-noslice/Lib/webbrowser.py Fri Feb 23 18:29:35 2007
@@ -626,21 +626,21 @@
try:
opts, args = getopt.getopt(sys.argv[1:], 'ntd')
except getopt.error as msg:
- print >>sys.stderr, msg
- print >>sys.stderr, usage
+ print(msg, file=sys.stderr)
+ print(usage, file=sys.stderr)
sys.exit(1)
new_win = 0
for o, a in opts:
if o == '-n': new_win = 1
elif o == '-t': new_win = 2
if len(args) != 1:
- print >>sys.stderr, usage
+ print(usage, file=sys.stderr)
sys.exit(1)
url = args[0]
open(url, new_win)
- print "\a"
+ print("\a")
if __name__ == "__main__":
main()
Modified: python/branches/p3yk-noslice/Lib/whichdb.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/whichdb.py (original)
+++ python/branches/p3yk-noslice/Lib/whichdb.py Fri Feb 23 18:29:35 2007
@@ -114,4 +114,4 @@
if __name__ == "__main__":
for filename in sys.argv[1:]:
- print whichdb(filename) or "UNKNOWN", filename
+ print(whichdb(filename) or "UNKNOWN", filename)
Modified: python/branches/p3yk-noslice/Lib/wsgiref/simple_server.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/wsgiref/simple_server.py (original)
+++ python/branches/p3yk-noslice/Lib/wsgiref/simple_server.py Fri Feb 23 18:29:35 2007
@@ -165,11 +165,11 @@
def demo_app(environ,start_response):
from StringIO import StringIO
stdout = StringIO()
- print >>stdout, "Hello world!"
- print >>stdout
+ print("Hello world!", file=stdout)
+ print(file=stdout)
h = environ.items(); h.sort()
for k,v in h:
- print >>stdout, k,'=',repr(v)
+ print(k,'=',repr(v), file=stdout)
start_response("200 OK", [('Content-Type','text/plain')])
return [stdout.getvalue()]
@@ -186,7 +186,7 @@
if __name__ == '__main__':
httpd = make_server('', 8000, demo_app)
sa = httpd.socket.getsockname()
- print "Serving HTTP on", sa[0], "port", sa[1], "..."
+ print("Serving HTTP on", sa[0], "port", sa[1], "...")
import webbrowser
webbrowser.open('http://localhost:8000/xyz?abc')
httpd.handle_request() # serve one request, then exit
Modified: python/branches/p3yk-noslice/Lib/xdrlib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xdrlib.py (original)
+++ python/branches/p3yk-noslice/Lib/xdrlib.py Fri Feb 23 18:29:35 2007
@@ -61,8 +61,8 @@
else: self.__buf.write('\0\0\0\0')
def pack_uhyper(self, x):
- self.pack_uint(x>>32 & 0xffffffffL)
- self.pack_uint(x & 0xffffffffL)
+ self.pack_uint(x>>32 & 0xffffffff)
+ self.pack_uint(x & 0xffffffff)
pack_hyper = pack_uhyper
@@ -164,12 +164,12 @@
def unpack_uhyper(self):
hi = self.unpack_uint()
lo = self.unpack_uint()
- return long(hi)<<32 | lo
+ return int(hi)<<32 | lo
def unpack_hyper(self):
x = self.unpack_uhyper()
- if x >= 0x8000000000000000L:
- x = x - 0x10000000000000000L
+ if x >= 0x8000000000000000:
+ x = x - 0x10000000000000000
return x
def unpack_float(self):
Modified: python/branches/p3yk-noslice/Lib/xml/dom/NodeFilter.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xml/dom/NodeFilter.py (original)
+++ python/branches/p3yk-noslice/Lib/xml/dom/NodeFilter.py Fri Feb 23 18:29:35 2007
@@ -9,7 +9,7 @@
FILTER_REJECT = 2
FILTER_SKIP = 3
- SHOW_ALL = 0xFFFFFFFFL
+ SHOW_ALL = 0xFFFFFFFF
SHOW_ELEMENT = 0x00000001
SHOW_ATTRIBUTE = 0x00000002
SHOW_TEXT = 0x00000004
Modified: python/branches/p3yk-noslice/Lib/xml/dom/minidom.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xml/dom/minidom.py (original)
+++ python/branches/p3yk-noslice/Lib/xml/dom/minidom.py Fri Feb 23 18:29:35 2007
@@ -256,7 +256,7 @@
def _call_user_data_handler(self, operation, src, dst):
if hasattr(self, "_user_data"):
- for key, (data, handler) in self._user_data.items():
+ for key, (data, handler) in list(self._user_data.items()):
if handler is not None:
handler.handle(operation, key, data, src, dst)
@@ -480,7 +480,7 @@
def item(self, index):
try:
- return self[self._attrs.keys()[index]]
+ return self[list(self._attrs.keys())[index]]
except IndexError:
return None
@@ -672,7 +672,7 @@
return self.tagName
def unlink(self):
- for attr in self._attrs.values():
+ for attr in list(self._attrs.values()):
attr.unlink()
self._attrs = None
self._attrsNS = None
@@ -805,8 +805,7 @@
writer.write(indent+"<" + self.tagName)
attrs = self._get_attributes()
- a_names = attrs.keys()
- a_names.sort()
+ a_names = sorted(attrs.keys())
for a_name in a_names:
writer.write(" %s=\"" % a_name)
Modified: python/branches/p3yk-noslice/Lib/xml/dom/pulldom.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xml/dom/pulldom.py (original)
+++ python/branches/p3yk-noslice/Lib/xml/dom/pulldom.py Fri Feb 23 18:29:35 2007
@@ -201,7 +201,7 @@
class ErrorHandler:
def warning(self, exception):
- print exception
+ print(exception)
def error(self, exception):
raise exception
def fatalError(self, exception):
Modified: python/branches/p3yk-noslice/Lib/xml/etree/ElementTree.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xml/etree/ElementTree.py (original)
+++ python/branches/p3yk-noslice/Lib/xml/etree/ElementTree.py Fri Feb 23 18:29:35 2007
@@ -645,7 +645,7 @@
elif tag is ProcessingInstruction:
file.write("<?%s?>" % _escape_cdata(node.text, encoding))
else:
- items = node.items()
+ items = list(node.items())
xmlns_items = [] # new namespaces in this scope
try:
if isinstance(tag, QName) or tag[:1] == "{":
Modified: python/branches/p3yk-noslice/Lib/xml/sax/handler.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xml/sax/handler.py (original)
+++ python/branches/p3yk-noslice/Lib/xml/sax/handler.py Fri Feb 23 18:29:35 2007
@@ -39,7 +39,7 @@
def warning(self, exception):
"Handle a warning."
- print exception
+ print(exception)
# ===== CONTENTHANDLER =====
Modified: python/branches/p3yk-noslice/Lib/xml/sax/saxutils.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xml/sax/saxutils.py (original)
+++ python/branches/p3yk-noslice/Lib/xml/sax/saxutils.py Fri Feb 23 18:29:35 2007
@@ -100,6 +100,17 @@
else:
self._out.write(text.encode(self._encoding, _error_handling))
+ def _qname(self, name):
+ """Builds a qualified name from a (ns_url, localname) pair"""
+ if name[0]:
+ # The name is in a non-empty namespace
+ prefix = self._current_context[name[0]]
+ if prefix:
+ # If it is not the default namespace, prepend the prefix
+ return prefix + ":" + name[1]
+ # Return the unqualified name
+ return name[1]
+
# ContentHandler methods
def startDocument(self):
@@ -125,29 +136,21 @@
self._write('</%s>' % name)
def startElementNS(self, name, qname, attrs):
- if name[0] is None:
- # if the name was not namespace-scoped, use the unqualified part
- name = name[1]
- else:
- # else try to restore the original prefix from the namespace
- name = self._current_context[name[0]] + ":" + name[1]
- self._write('<' + name)
+ self._write('<' + self._qname(name))
- for pair in self._undeclared_ns_maps:
- self._write(' xmlns:%s="%s"' % pair)
+ for prefix, uri in self._undeclared_ns_maps:
+ if prefix:
+ self._out.write(' xmlns:%s="%s"' % (prefix, uri))
+ else:
+ self._out.write(' xmlns="%s"' % uri)
self._undeclared_ns_maps = []
for (name, value) in attrs.items():
- name = self._current_context[name[0]] + ":" + name[1]
- self._write(' %s=%s' % (name, quoteattr(value)))
+ self._write(' %s=%s' % (self._qname(name), quoteattr(value)))
self._write('>')
def endElementNS(self, name, qname):
- if name[0] is None:
- name = name[1]
- else:
- name = self._current_context[name[0]] + ":" + name[1]
- self._write('</%s>' % name)
+ self._write('</%s>' % self._qname(name))
def characters(self, content):
self._write(escape(content))
Modified: python/branches/p3yk-noslice/Lib/xml/sax/xmlreader.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xml/sax/xmlreader.py (original)
+++ python/branches/p3yk-noslice/Lib/xml/sax/xmlreader.py Fri Feb 23 18:29:35 2007
@@ -304,10 +304,10 @@
return name
def getNames(self):
- return self._attrs.keys()
+ return list(self._attrs.keys())
def getQNames(self):
- return self._attrs.keys()
+ return list(self._attrs.keys())
def __len__(self):
return len(self._attrs)
@@ -316,7 +316,7 @@
return self._attrs[name]
def keys(self):
- return self._attrs.keys()
+ return list(self._attrs.keys())
def __contains__(self, name):
return name in self._attrs
@@ -328,10 +328,10 @@
return self.__class__(self._attrs)
def items(self):
- return self._attrs.items()
+ return list(self._attrs.items())
def values(self):
- return self._attrs.values()
+ return list(self._attrs.values())
# ===== ATTRIBUTESNSIMPL =====
@@ -363,7 +363,7 @@
return self._qnames[name]
def getQNames(self):
- return self._qnames.values()
+ return list(self._qnames.values())
def copy(self):
return self.__class__(self._attrs, self._qnames)
Modified: python/branches/p3yk-noslice/Lib/xmllib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xmllib.py (original)
+++ python/branches/p3yk-noslice/Lib/xmllib.py Fri Feb 23 18:29:35 2007
@@ -809,11 +809,11 @@
def handle_xml(self, encoding, standalone):
self.flush()
- print 'xml: encoding =',encoding,'standalone =',standalone
+ print('xml: encoding =',encoding,'standalone =',standalone)
def handle_doctype(self, tag, pubid, syslit, data):
self.flush()
- print 'DOCTYPE:',tag, repr(data)
+ print('DOCTYPE:',tag, repr(data))
def handle_data(self, data):
self.testdata = self.testdata + data
@@ -824,47 +824,47 @@
data = self.testdata
if data:
self.testdata = ""
- print 'data:', repr(data)
+ print('data:', repr(data))
def handle_cdata(self, data):
self.flush()
- print 'cdata:', repr(data)
+ print('cdata:', repr(data))
def handle_proc(self, name, data):
self.flush()
- print 'processing:',name,repr(data)
+ print('processing:',name,repr(data))
def handle_comment(self, data):
self.flush()
r = repr(data)
if len(r) > 68:
r = r[:32] + '...' + r[-32:]
- print 'comment:', r
+ print('comment:', r)
def syntax_error(self, message):
- print 'error at line %d:' % self.lineno, message
+ print('error at line %d:' % self.lineno, message)
def unknown_starttag(self, tag, attrs):
self.flush()
if not attrs:
- print 'start tag: <' + tag + '>'
+ print('start tag: <' + tag + '>')
else:
- print 'start tag: <' + tag,
+ print('start tag: <' + tag, end=' ')
for name, value in attrs.items():
- print name + '=' + '"' + value + '"',
- print '>'
+ print(name + '=' + '"' + value + '"', end=' ')
+ print('>')
def unknown_endtag(self, tag):
self.flush()
- print 'end tag: </' + tag + '>'
+ print('end tag: </' + tag + '>')
def unknown_entityref(self, ref):
self.flush()
- print '*** unknown entity ref: &' + ref + ';'
+ print('*** unknown entity ref: &' + ref + ';')
def unknown_charref(self, ref):
self.flush()
- print '*** unknown char ref: &#' + ref + ';'
+ print('*** unknown char ref: &#' + ref + ';')
def close(self):
XMLParser.close(self)
@@ -897,7 +897,7 @@
try:
f = open(file, 'r')
except IOError as msg:
- print file, ":", msg
+ print(file, ":", msg)
sys.exit(1)
data = f.read()
@@ -916,13 +916,13 @@
x.close()
except Error as msg:
t1 = time()
- print msg
+ print(msg)
if do_time:
- print 'total time: %g' % (t1-t0)
+ print('total time: %g' % (t1-t0))
sys.exit(1)
t1 = time()
if do_time:
- print 'total time: %g' % (t1-t0)
+ print('total time: %g' % (t1-t0))
if __name__ == '__main__':
Modified: python/branches/p3yk-noslice/Lib/xmlrpclib.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/xmlrpclib.py (original)
+++ python/branches/p3yk-noslice/Lib/xmlrpclib.py Fri Feb 23 18:29:35 2007
@@ -183,8 +183,8 @@
__version__ = "1.0.1"
# xmlrpc integer limits
-MAXINT = 2L**31-1
-MININT = -2L**31
+MAXINT = 2**31-1
+MININT = -2**31
# --------------------------------------------------------------------
# Error constants (from Dan Libby's specification at
@@ -1310,7 +1310,7 @@
if not response:
break
if self.verbose:
- print "body:", repr(response)
+ print("body:", repr(response))
p.feed(response)
file.close()
@@ -1450,18 +1450,18 @@
# server = ServerProxy("http://localhost:8000") # local server
server = ServerProxy("http://time.xmlrpc.com/RPC2")
- print server
+ print(server)
try:
- print server.currentTime.getCurrentTime()
+ print(server.currentTime.getCurrentTime())
except Error as v:
- print "ERROR", v
+ print("ERROR", v)
multi = MultiCall(server)
multi.currentTime.getCurrentTime()
multi.currentTime.getCurrentTime()
try:
for response in multi():
- print response
+ print(response)
except Error as v:
- print "ERROR", v
+ print("ERROR", v)
Modified: python/branches/p3yk-noslice/Lib/zipfile.py
==============================================================================
--- python/branches/p3yk-noslice/Lib/zipfile.py (original)
+++ python/branches/p3yk-noslice/Lib/zipfile.py Fri Feb 23 18:29:35 2007
@@ -280,15 +280,15 @@
idx = 0
# ZIP64 extension (large files and/or large archives)
- if self.file_size == -1 or self.file_size == 0xFFFFFFFFL:
+ if self.file_size == -1 or self.file_size == 0xFFFFFFFF:
self.file_size = counts[idx]
idx += 1
- if self.compress_size == -1 or self.compress_size == 0xFFFFFFFFL:
+ if self.compress_size == -1 or self.compress_size == 0xFFFFFFFF:
self.compress_size = counts[idx]
idx += 1
- if self.header_offset == -1 or self.header_offset == 0xffffffffL:
+ if self.header_offset == -1 or self.header_offset == 0xffffffff:
old = self.header_offset
self.header_offset = counts[idx]
idx+=1
@@ -296,6 +296,65 @@
extra = extra[ln+4:]
+class _ZipDecrypter:
+ """Class to handle decryption of files stored within a ZIP archive.
+
+ ZIP supports a password-based form of encryption. Even though known
+ plaintext attacks have been found against it, it is still useful
+ for low-level securicy.
+
+ Usage:
+ zd = _ZipDecrypter(mypwd)
+ plain_char = zd(cypher_char)
+ plain_text = map(zd, cypher_text)
+ """
+
+ def _GenerateCRCTable():
+ """Generate a CRC-32 table.
+
+ ZIP encryption uses the CRC32 one-byte primitive for scrambling some
+ internal keys. We noticed that a direct implementation is faster than
+ relying on binascii.crc32().
+ """
+ poly = 0xedb88320
+ table = [0] * 256
+ for i in range(256):
+ crc = i
+ for j in range(8):
+ if crc & 1:
+ crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly
+ else:
+ crc = ((crc >> 1) & 0x7FFFFFFF)
+ table[i] = crc
+ return table
+ crctable = _GenerateCRCTable()
+
+ def _crc32(self, ch, crc):
+ """Compute the CRC32 primitive on one byte."""
+ return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff]
+
+ def __init__(self, pwd):
+ self.key0 = 305419896
+ self.key1 = 591751049
+ self.key2 = 878082192
+ for p in pwd:
+ self._UpdateKeys(p)
+
+ def _UpdateKeys(self, c):
+ self.key0 = self._crc32(c, self.key0)
+ self.key1 = (self.key1 + (self.key0 & 255)) & 4294967295
+ self.key1 = (self.key1 * 134775813 + 1) & 4294967295
+ self.key2 = self._crc32(chr((self.key1 >> 24) & 255), self.key2)
+
+ def __call__(self, c):
+ """Decrypt a single character."""
+ c = ord(c)
+ k = self.key2 | 2
+ c = c ^ (((k * (k^1)) >> 8) & 255)
+ c = chr(c)
+ self._UpdateKeys(c)
+ return c
+
class ZipFile:
""" Class with methods to open, read, write, close, list zip files.
@@ -330,13 +389,21 @@
self.filelist = [] # List of ZipInfo instances for archive
self.compression = compression # Method of compression
self.mode = key = mode.replace('b', '')[0]
+ self.pwd = None
# Check if we were passed a file-like object
if isinstance(file, basestring):
self._filePassed = 0
self.filename = file
modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'}
- self.fp = open(file, modeDict[mode])
+ try:
+ self.fp = open(file, modeDict[mode])
+ except IOError:
+ if mode == 'a':
+ mode = key = 'w'
+ self.fp = open(file, modeDict[mode])
+ else:
+ raise
else:
self._filePassed = 1
self.fp = file
@@ -377,7 +444,7 @@
if not endrec:
raise BadZipfile, "File is not a zip file"
if self.debug > 1:
- print endrec
+ print(endrec)
size_cd = endrec[5] # bytes in central directory
offset_cd = endrec[6] # offset of central directory
self.comment = endrec[8] # archive comment
@@ -389,7 +456,7 @@
# "concat" is zero, unless zip was concatenated to another file
concat = x - offset_cd
if self.debug > 2:
- print "given, inferred, offset", offset_cd, x, concat
+ print("given, inferred, offset", offset_cd, x, concat)
# self.start_dir: Position of start of central directory
self.start_dir = offset_cd + concat
fp.seek(self.start_dir, 0)
@@ -403,7 +470,7 @@
raise BadZipfile, "Bad magic number for central directory"
centdir = struct.unpack(structCentralDir, centdir)
if self.debug > 2:
- print centdir
+ print(centdir)
filename = fp.read(centdir[_CD_FILENAME_LENGTH])
# Create ZipInfo instance to store file information
x = ZipInfo(filename)
@@ -426,7 +493,7 @@
self.filelist.append(x)
self.NameToInfo[x.filename] = x
if self.debug > 2:
- print "total", total
+ print("total", total)
def namelist(self):
@@ -443,10 +510,10 @@
def printdir(self):
"""Print a table of contents for the zip file."""
- print "%-46s %19s %12s" % ("File Name", "Modified ", "Size")
+ print("%-46s %19s %12s" % ("File Name", "Modified ", "Size"))
for zinfo in self.filelist:
date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time
- print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)
+ print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size))
def testzip(self):
"""Read all the files and check the CRC."""
@@ -461,7 +528,11 @@
"""Return the instance of ZipInfo given 'name'."""
return self.NameToInfo[name]
- def read(self, name):
+ def setpassword(self, pwd):
+ """Set default password for encrypted files."""
+ self.pwd = pwd
+
+ def read(self, name, pwd=None):
"""Return file bytes (as a string) for name."""
if self.mode not in ("r", "a"):
raise RuntimeError, 'read() requires mode "r" or "a"'
@@ -469,6 +540,13 @@
raise RuntimeError, \
"Attempt to read ZIP archive that was already closed"
zinfo = self.getinfo(name)
+ is_encrypted = zinfo.flag_bits & 0x1
+ if is_encrypted:
+ if not pwd:
+ pwd = self.pwd
+ if not pwd:
+ raise RuntimeError, "File %s is encrypted, " \
+ "password required for extraction" % name
filepos = self.fp.tell()
self.fp.seek(zinfo.header_offset, 0)
@@ -489,6 +567,18 @@
zinfo.orig_filename, fname)
bytes = self.fp.read(zinfo.compress_size)
+ # Go with decryption
+ if is_encrypted:
+ zd = _ZipDecrypter(pwd)
+ # The first 12 bytes in the cypher stream is an encryption header
+ # used to strengthen the algorithm. The first 11 bytes are
+ # completely random, while the 12th contains the MSB of the CRC,
+ # and is used to check the correctness of the password.
+ h = map(zd, bytes[0:12])
+ if ord(h[11]) != ((zinfo.CRC>>24)&255):
+ raise RuntimeError, "Bad password for file %s" % name
+ bytes = "".join(map(zd, bytes[12:]))
+ # Go with decompression
self.fp.seek(filepos, 0)
if zinfo.compress_type == ZIP_STORED:
pass
@@ -516,7 +606,7 @@
"""Check for errors before writing a file to the archive."""
if zinfo.filename in self.NameToInfo:
if self.debug: # Warning for duplicate names
- print "Duplicate name:", zinfo.filename
+ print("Duplicate name:", zinfo.filename)
if self.mode not in ("w", "a"):
raise RuntimeError, 'write() requires mode "w" or "a"'
if not self.fp:
@@ -548,7 +638,7 @@
while arcname[0] in (os.sep, os.altsep):
arcname = arcname[1:]
zinfo = ZipInfo(arcname, date_time)
- zinfo.external_attr = (st[0] & 0xFFFF) << 16L # Unix attributes
+ zinfo.external_attr = (st[0] & 0xFFFF) << 16 # Unix attributes
if compress_type is None:
zinfo.compress_type = self.compression
else:
@@ -749,10 +839,10 @@
else:
basename = name
if self.debug:
- print "Adding package in", pathname, "as", basename
+ print("Adding package in", pathname, "as", basename)
fname, arcname = self._get_codename(initname[0:-3], basename)
if self.debug:
- print "Adding", arcname
+ print("Adding", arcname)
self.write(fname, arcname)
dirlist = os.listdir(pathname)
dirlist.remove("__init__.py")
@@ -768,12 +858,12 @@
fname, arcname = self._get_codename(path[0:-3],
basename)
if self.debug:
- print "Adding", arcname
+ print("Adding", arcname)
self.write(fname, arcname)
else:
# This is NOT a package directory, add its files at top level
if self.debug:
- print "Adding files from directory", pathname
+ print("Adding files from directory", pathname)
for filename in os.listdir(pathname):
path = os.path.join(pathname, filename)
root, ext = os.path.splitext(filename)
@@ -781,7 +871,7 @@
fname, arcname = self._get_codename(path[0:-3],
basename)
if self.debug:
- print "Adding", arcname
+ print("Adding", arcname)
self.write(fname, arcname)
else:
if pathname[-3:] != ".py":
@@ -789,7 +879,7 @@
'Files added with writepy() must end with ".py"'
fname, arcname = self._get_codename(pathname[0:-3], basename)
if self.debug:
- print "Adding file", arcname
+ print("Adding file", arcname)
self.write(fname, arcname)
def _get_codename(self, pathname, basename):
@@ -809,11 +899,11 @@
os.stat(file_pyc).st_mtime < os.stat(file_py).st_mtime:
import py_compile
if self.debug:
- print "Compiling", file_py
+ print("Compiling", file_py)
try:
py_compile.compile(file_py, file_pyc, None, True)
except py_compile.PyCompileError as err:
- print err.msg
+ print(err.msg)
fname = file_pyc
else:
fname = file_pyc
@@ -836,12 +926,12 @@
args = sys.argv[1:]
if not args or args[0] not in ('-l', '-c', '-e', '-t'):
- print USAGE
+ print(USAGE)
sys.exit(1)
if args[0] == '-l':
if len(args) != 2:
- print USAGE
+ print(USAGE)
sys.exit(1)
zf = ZipFile(args[1], 'r')
zf.printdir()
@@ -849,15 +939,15 @@
elif args[0] == '-t':
if len(args) != 2:
- print USAGE
+ print(USAGE)
sys.exit(1)
zf = ZipFile(args[1], 'r')
zf.testzip()
- print "Done testing"
+ print("Done testing")
elif args[0] == '-e':
if len(args) != 3:
- print USAGE
+ print(USAGE)
sys.exit(1)
zf = ZipFile(args[1], 'r')
@@ -878,7 +968,7 @@
elif args[0] == '-c':
if len(args) < 3:
- print USAGE
+ print(USAGE)
sys.exit(1)
def addToZip(zf, path, zippath):
Modified: python/branches/p3yk-noslice/Makefile.pre.in
==============================================================================
--- python/branches/p3yk-noslice/Makefile.pre.in (original)
+++ python/branches/p3yk-noslice/Makefile.pre.in Fri Feb 23 18:29:35 2007
@@ -341,7 +341,7 @@
$(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST)
platform: $(BUILDPYTHON)
- $(RUNSHARED) ./$(BUILDPYTHON) -E -c 'import sys ; from distutils.util import get_platform ; print get_platform()+"-"+sys.version[0:3]' >platform
+ $(RUNSHARED) ./$(BUILDPYTHON) -E -c 'import sys ; from distutils.util import get_platform ; print(get_platform()+"-"+sys.version[0:3])' >platform
# Build the shared modules
@@ -484,6 +484,8 @@
Parser/tokenizer_pgen.o: $(srcdir)/Parser/tokenizer.c
+Parser/pgenmain.o: $(srcdir)/Include/parsetok.h
+
$(AST_H): $(AST_ASDL) $(ASDLGEN_FILES)
$(ASDLGEN) -h $(AST_H_DIR) $(AST_ASDL)
@@ -537,6 +539,7 @@
Include/moduleobject.h \
Include/object.h \
Include/objimpl.h \
+ Include/parsetok.h \
Include/patchlevel.h \
Include/pyarena.h \
Include/pydebug.h \
Modified: python/branches/p3yk-noslice/Misc/ACKS
==============================================================================
--- python/branches/p3yk-noslice/Misc/ACKS (original)
+++ python/branches/p3yk-noslice/Misc/ACKS Fri Feb 23 18:29:35 2007
@@ -377,6 +377,7 @@
Kip Lehman
Joerg Lehmann
Marc-Andre Lemburg
+Mark Levinson
William Lewis
Robert van Liere
Martin Ligr
@@ -521,6 +522,7 @@
Nicholas Riley
Jean-Claude Rimbault
Anthony Roach
+Mark Roberts
Andy Robinson
Jim Robinson
Kevin Rodgers
Modified: python/branches/p3yk-noslice/Misc/NEWS
==============================================================================
--- python/branches/p3yk-noslice/Misc/NEWS (original)
+++ python/branches/p3yk-noslice/Misc/NEWS Fri Feb 23 18:29:35 2007
@@ -14,28 +14,42 @@
- See PEP 3000, 3100.
-- Test merging certain changes from the 2.5 HEAD code.
-
- Weed really old/weird stuff from the library.
- Unify range() and xrange().
-- Revamp the dict API: keys(), values(), items() return iterators, etc.
-
-- Add the bytes type.
-
- Rework the standard I/O library to use bytes for binary files.
- Make strings all Unicode.
-- Get rid of classic class implementation.
-
- Get rid of various compatibility-related flags (e.g. division flags).
Core and Builtins
-----------------
+- PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone;
+ and .keys(), .items(), .values() return dict views.
+
+- PEP 3105: print is now a function. Also (not in the PEP) the
+ 'softspace' attribute of files is now gone (since print() doesn't use
+ it). A side effect of this change is that you can get incomplete
+ output lines in interactive sessions:
+
+ >>> print(42, end="")
+ 42>>>
+
+ We may be able to fix this after the I/O library rewrite.
+
+- PEP 3102: keyword-only arguments.
+
+- Int/Long unification is complete. The 'long' built-in type
+ and literals with trailing 'L' or 'l' have been removed.
+ Performance may be sub-optimal (haven't really benchmarked).
+
+- 'except E, V' must now be spelled as 'except E as V' and deletes V
+ at the end of the except clause; V must be a simple name.
+
- Added function annotations per PEP 3107.
- Moved intern() to sys.intern().
Modified: python/branches/p3yk-noslice/Modules/_csv.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_csv.c (original)
+++ python/branches/p3yk-noslice/Modules/_csv.c Fri Feb 23 18:29:35 2007
@@ -219,7 +219,7 @@
if (src == NULL)
*target = dflt;
else {
- if (!PyInt_Check(src)) {
+ if (!PyInt_CheckExact(src)) {
PyErr_Format(PyExc_TypeError,
"\"%s\" must be an integer", name);
return -1;
@@ -1410,7 +1410,7 @@
if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit))
return NULL;
if (new_limit != NULL) {
- if (!PyInt_Check(new_limit)) {
+ if (!PyInt_CheckExact(new_limit)) {
PyErr_Format(PyExc_TypeError,
"limit must be an integer");
return NULL;
Modified: python/branches/p3yk-noslice/Modules/_ctypes/_ctypes.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/_ctypes.c (original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/_ctypes.c Fri Feb 23 18:29:35 2007
@@ -991,7 +991,7 @@
return NULL;
proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */
- if (!proto || !PyInt_Check(proto)) {
+ if (!proto || !PyInt_CheckExact(proto)) {
PyErr_SetString(PyExc_AttributeError,
"class must define a '_length_' attribute, "
"which must be a positive integer");
@@ -4979,7 +4979,7 @@
#endif
PyModule_AddObject(m, "FUNCFLAG_CDECL", PyInt_FromLong(FUNCFLAG_CDECL));
PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyInt_FromLong(FUNCFLAG_PYTHONAPI));
- PyModule_AddStringConstant(m, "__version__", "1.0.1");
+ PyModule_AddStringConstant(m, "__version__", "1.1.0");
PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove));
PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset));
Modified: python/branches/p3yk-noslice/Modules/_ctypes/_ctypes_test.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/_ctypes_test.c (original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/_ctypes_test.c Fri Feb 23 18:29:35 2007
@@ -68,22 +68,25 @@
EXPORT(int) _testfunc_i_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
-// printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n",
-// b, h, i, l, f, d);
+/* printf("_testfunc_i_bhilfd got %d %d %d %ld %f %f\n",
+ b, h, i, l, f, d);
+*/
return (int)(b + h + i + l + f + d);
}
EXPORT(float) _testfunc_f_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
-// printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n",
-// b, h, i, l, f, d);
+/* printf("_testfunc_f_bhilfd got %d %d %d %ld %f %f\n",
+ b, h, i, l, f, d);
+*/
return (float)(b + h + i + l + f + d);
}
EXPORT(double) _testfunc_d_bhilfd(signed char b, short h, int i, long l, float f, double d)
{
-// printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
-// b, h, i, l, f, d);
+/* printf("_testfunc_d_bhilfd got %d %d %d %ld %f %f\n",
+ b, h, i, l, f, d);
+*/
return (double)(b + h + i + l + f + d);
}
@@ -378,8 +381,9 @@
}
PyMethodDef module_methods[] = {
-// {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS},
-// {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS},
+/* {"get_last_tf_arg_s", get_last_tf_arg_s, METH_NOARGS},
+ {"get_last_tf_arg_u", get_last_tf_arg_u, METH_NOARGS},
+*/
{"func_si", py_func_si, METH_VARARGS},
{"func", py_func, METH_NOARGS},
{ NULL, NULL, 0, NULL},
Modified: python/branches/p3yk-noslice/Modules/_ctypes/callproc.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/callproc.c (original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/callproc.c Fri Feb 23 18:29:35 2007
@@ -496,12 +496,6 @@
return 0;
}
- if (PyInt_Check(obj)) {
- pa->ffi_type = &ffi_type_sint;
- pa->value.i = PyInt_AS_LONG(obj);
- return 0;
- }
-
if (PyLong_Check(obj)) {
pa->ffi_type = &ffi_type_sint;
pa->value.i = (long)PyLong_AsUnsignedLong(obj);
Modified: python/branches/p3yk-noslice/Modules/_ctypes/cfield.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/cfield.c (original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/cfield.c Fri Feb 23 18:29:35 2007
@@ -1432,10 +1432,19 @@
#endif
#ifdef MS_WIN32
+/* We cannot use SysFreeString as the PyCObject_FromVoidPtr
+ because of different calling convention
+*/
+static void _my_SysFreeString(void *p)
+{
+ SysFreeString((BSTR)p);
+}
+
static PyObject *
BSTR_set(void *ptr, PyObject *value, unsigned size)
{
BSTR bstr;
+ PyObject *result;
/* convert value into a PyUnicodeObject or NULL */
if (Py_None == value) {
@@ -1463,15 +1472,19 @@
} else
bstr = NULL;
- /* free the previous contents, if any */
- if (*(BSTR *)ptr)
- SysFreeString(*(BSTR *)ptr);
-
- /* and store it */
- *(BSTR *)ptr = bstr;
+ if (bstr) {
+ result = PyCObject_FromVoidPtr((void *)bstr, _my_SysFreeString);
+ if (result == NULL) {
+ SysFreeString(bstr);
+ return NULL;
+ }
+ } else {
+ result = Py_None;
+ Py_INCREF(result);
+ }
- /* We don't need to keep any other object */
- _RET(value);
+ *(BSTR *)ptr = bstr;
+ return result;
}
Modified: python/branches/p3yk-noslice/Modules/_ctypes/libffi_msvc/ffi.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_ctypes/libffi_msvc/ffi.c (original)
+++ python/branches/p3yk-noslice/Modules/_ctypes/libffi_msvc/ffi.c Fri Feb 23 18:29:35 2007
@@ -224,7 +224,8 @@
#else
case FFI_SYSV:
/*@-usedef@*/
- return ffi_call_AMD64(ffi_prep_args, &ecif, cif->bytes,
+ /* Function call needs at least 40 bytes stack size, on win64 AMD64 */
+ return ffi_call_AMD64(ffi_prep_args, &ecif, cif->bytes ? cif->bytes : 40,
cif->flags, ecif.rvalue, fn);
/*@=usedef@*/
break;
Modified: python/branches/p3yk-noslice/Modules/_cursesmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_cursesmodule.c (original)
+++ python/branches/p3yk-noslice/Modules/_cursesmodule.c Fri Feb 23 18:29:35 2007
@@ -193,7 +193,7 @@
static int
PyCurses_ConvertToChtype(PyObject *obj, chtype *ch)
{
- if (PyInt_Check(obj)) {
+ if (PyInt_CheckExact(obj)) {
*ch = (chtype) PyInt_AsLong(obj);
} else if(PyString_Check(obj)
&& (PyString_Size(obj) == 1)) {
@@ -2364,7 +2364,7 @@
if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL;
- if (PyInt_Check(temp))
+ if (PyInt_CheckExact(temp))
ch = (chtype) PyInt_AsLong(temp);
else if (PyString_Check(temp))
ch = (chtype) *PyString_AsString(temp);
@@ -2386,7 +2386,7 @@
if (!PyArg_ParseTuple(args,"O;ch or int",&temp)) return NULL;
- if (PyInt_Check(temp))
+ if (PyInt_CheckExact(temp))
ch = (int) PyInt_AsLong(temp);
else if (PyString_Check(temp))
ch = (int) *PyString_AsString(temp);
Modified: python/branches/p3yk-noslice/Modules/_randommodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_randommodule.c (original)
+++ python/branches/p3yk-noslice/Modules/_randommodule.c Fri Feb 23 18:29:35 2007
@@ -481,7 +481,7 @@
RandomObject *self;
PyObject *tmp;
- if (!_PyArg_NoKeywords("Random()", kwds))
+ if (type == &Random_Type && !_PyArg_NoKeywords("Random()", kwds))
return NULL;
self = (RandomObject *)type->tp_alloc(type, 0);
Modified: python/branches/p3yk-noslice/Modules/_sqlite/cache.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/cache.c (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/cache.c Fri Feb 23 18:29:35 2007
@@ -25,11 +25,11 @@
#include <limits.h>
/* only used internally */
-Node* new_node(PyObject* key, PyObject* data)
+pysqlite_Node* pysqlite_new_node(PyObject* key, PyObject* data)
{
- Node* node;
+ pysqlite_Node* node;
- node = (Node*) (NodeType.tp_alloc(&NodeType, 0));
+ node = (pysqlite_Node*) (pysqlite_NodeType.tp_alloc(&pysqlite_NodeType, 0));
if (!node) {
return NULL;
}
@@ -46,7 +46,7 @@
return node;
}
-void node_dealloc(Node* self)
+void pysqlite_node_dealloc(pysqlite_Node* self)
{
Py_DECREF(self->key);
Py_DECREF(self->data);
@@ -54,7 +54,7 @@
self->ob_type->tp_free((PyObject*)self);
}
-int cache_init(Cache* self, PyObject* args, PyObject* kwargs)
+int pysqlite_cache_init(pysqlite_Cache* self, PyObject* args, PyObject* kwargs)
{
PyObject* factory;
int size = 10;
@@ -86,10 +86,10 @@
return 0;
}
-void cache_dealloc(Cache* self)
+void pysqlite_cache_dealloc(pysqlite_Cache* self)
{
- Node* node;
- Node* delete_node;
+ pysqlite_Node* node;
+ pysqlite_Node* delete_node;
if (!self->factory) {
/* constructor failed, just get out of here */
@@ -112,14 +112,14 @@
self->ob_type->tp_free((PyObject*)self);
}
-PyObject* cache_get(Cache* self, PyObject* args)
+PyObject* pysqlite_cache_get(pysqlite_Cache* self, PyObject* args)
{
PyObject* key = args;
- Node* node;
- Node* ptr;
+ pysqlite_Node* node;
+ pysqlite_Node* ptr;
PyObject* data;
- node = (Node*)PyDict_GetItem(self->mapping, key);
+ node = (pysqlite_Node*)PyDict_GetItem(self->mapping, key);
if (node) {
/* an entry for this key already exists in the cache */
@@ -186,7 +186,7 @@
return NULL;
}
- node = new_node(key, data);
+ node = pysqlite_new_node(key, data);
if (!node) {
return NULL;
}
@@ -211,9 +211,9 @@
return node->data;
}
-PyObject* cache_display(Cache* self, PyObject* args)
+PyObject* pysqlite_cache_display(pysqlite_Cache* self, PyObject* args)
{
- Node* ptr;
+ pysqlite_Node* ptr;
PyObject* prevkey;
PyObject* nextkey;
PyObject* fmt_args;
@@ -265,20 +265,20 @@
}
static PyMethodDef cache_methods[] = {
- {"get", (PyCFunction)cache_get, METH_O,
+ {"get", (PyCFunction)pysqlite_cache_get, METH_O,
PyDoc_STR("Gets an entry from the cache or calls the factory function to produce one.")},
- {"display", (PyCFunction)cache_display, METH_NOARGS,
+ {"display", (PyCFunction)pysqlite_cache_display, METH_NOARGS,
PyDoc_STR("For debugging only.")},
{NULL, NULL}
};
-PyTypeObject NodeType = {
+PyTypeObject pysqlite_NodeType = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
MODULE_NAME "Node", /* tp_name */
- sizeof(Node), /* tp_basicsize */
+ sizeof(pysqlite_Node), /* tp_basicsize */
0, /* tp_itemsize */
- (destructor)node_dealloc, /* tp_dealloc */
+ (destructor)pysqlite_node_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
@@ -315,13 +315,13 @@
0 /* tp_free */
};
-PyTypeObject CacheType = {
+PyTypeObject pysqlite_CacheType = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
MODULE_NAME ".Cache", /* tp_name */
- sizeof(Cache), /* tp_basicsize */
+ sizeof(pysqlite_Cache), /* tp_basicsize */
0, /* tp_itemsize */
- (destructor)cache_dealloc, /* tp_dealloc */
+ (destructor)pysqlite_cache_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
@@ -352,24 +352,24 @@
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
- (initproc)cache_init, /* tp_init */
+ (initproc)pysqlite_cache_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0 /* tp_free */
};
-extern int cache_setup_types(void)
+extern int pysqlite_cache_setup_types(void)
{
int rc;
- NodeType.tp_new = PyType_GenericNew;
- CacheType.tp_new = PyType_GenericNew;
+ pysqlite_NodeType.tp_new = PyType_GenericNew;
+ pysqlite_CacheType.tp_new = PyType_GenericNew;
- rc = PyType_Ready(&NodeType);
+ rc = PyType_Ready(&pysqlite_NodeType);
if (rc < 0) {
return rc;
}
- rc = PyType_Ready(&CacheType);
+ rc = PyType_Ready(&pysqlite_CacheType);
return rc;
}
Modified: python/branches/p3yk-noslice/Modules/_sqlite/cache.h
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/cache.h (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/cache.h Fri Feb 23 18:29:35 2007
@@ -29,15 +29,15 @@
* dictionary. The list items are of type 'Node' and the dictionary has the
* nodes as values. */
-typedef struct _Node
+typedef struct _pysqlite_Node
{
PyObject_HEAD
PyObject* key;
PyObject* data;
long count;
- struct _Node* prev;
- struct _Node* next;
-} Node;
+ struct _pysqlite_Node* prev;
+ struct _pysqlite_Node* next;
+} pysqlite_Node;
typedef struct
{
@@ -50,24 +50,24 @@
/* the factory callable */
PyObject* factory;
- Node* first;
- Node* last;
+ pysqlite_Node* first;
+ pysqlite_Node* last;
/* if set, decrement the factory function when the Cache is deallocated.
* this is almost always desirable, but not in the pysqlite context */
int decref_factory;
-} Cache;
+} pysqlite_Cache;
-extern PyTypeObject NodeType;
-extern PyTypeObject CacheType;
+extern PyTypeObject pysqlite_NodeType;
+extern PyTypeObject pysqlite_CacheType;
-int node_init(Node* self, PyObject* args, PyObject* kwargs);
-void node_dealloc(Node* self);
+int pysqlite_node_init(pysqlite_Node* self, PyObject* args, PyObject* kwargs);
+void pysqlite_node_dealloc(pysqlite_Node* self);
-int cache_init(Cache* self, PyObject* args, PyObject* kwargs);
-void cache_dealloc(Cache* self);
-PyObject* cache_get(Cache* self, PyObject* args);
+int pysqlite_cache_init(pysqlite_Cache* self, PyObject* args, PyObject* kwargs);
+void pysqlite_cache_dealloc(pysqlite_Cache* self);
+PyObject* pysqlite_cache_get(pysqlite_Cache* self, PyObject* args);
-int cache_setup_types(void);
+int pysqlite_cache_setup_types(void);
#endif
Modified: python/branches/p3yk-noslice/Modules/_sqlite/connection.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/connection.c (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/connection.c Fri Feb 23 18:29:35 2007
@@ -32,7 +32,7 @@
#include "pythread.h"
-static int connection_set_isolation_level(Connection* self, PyObject* isolation_level);
+static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level);
void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len)
@@ -43,11 +43,11 @@
#if SQLITE_VERSION_NUMBER >= 3003003
sqlite3_result_error(ctx, errmsg, len);
#else
- PyErr_SetString(OperationalError, errmsg);
+ PyErr_SetString(pysqlite_OperationalError, errmsg);
#endif
}
-int connection_init(Connection* self, PyObject* args, PyObject* kwargs)
+int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
static char *kwlist[] = {"database", "timeout", "detect_types", "isolation_level", "check_same_thread", "factory", "cached_statements", NULL, NULL};
@@ -82,7 +82,7 @@
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK) {
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
return -1;
}
@@ -95,10 +95,10 @@
Py_INCREF(isolation_level);
}
self->isolation_level = NULL;
- connection_set_isolation_level(self, isolation_level);
+ pysqlite_connection_set_isolation_level(self, isolation_level);
Py_DECREF(isolation_level);
- self->statement_cache = (Cache*)PyObject_CallFunction((PyObject*)&CacheType, "Oi", self, cached_statements);
+ self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
if (PyErr_Occurred()) {
return -1;
}
@@ -135,41 +135,41 @@
return -1;
}
- self->Warning = Warning;
- self->Error = Error;
- self->InterfaceError = InterfaceError;
- self->DatabaseError = DatabaseError;
- self->DataError = DataError;
- self->OperationalError = OperationalError;
- self->IntegrityError = IntegrityError;
- self->InternalError = InternalError;
- self->ProgrammingError = ProgrammingError;
- self->NotSupportedError = NotSupportedError;
+ self->Warning = pysqlite_Warning;
+ self->Error = pysqlite_Error;
+ self->InterfaceError = pysqlite_InterfaceError;
+ self->DatabaseError = pysqlite_DatabaseError;
+ self->DataError = pysqlite_DataError;
+ self->OperationalError = pysqlite_OperationalError;
+ self->IntegrityError = pysqlite_IntegrityError;
+ self->InternalError = pysqlite_InternalError;
+ self->ProgrammingError = pysqlite_ProgrammingError;
+ self->NotSupportedError = pysqlite_NotSupportedError;
return 0;
}
/* Empty the entire statement cache of this connection */
-void flush_statement_cache(Connection* self)
+void pysqlite_flush_statement_cache(pysqlite_Connection* self)
{
- Node* node;
- Statement* statement;
+ pysqlite_Node* node;
+ pysqlite_Statement* statement;
node = self->statement_cache->first;
while (node) {
- statement = (Statement*)(node->data);
- (void)statement_finalize(statement);
+ statement = (pysqlite_Statement*)(node->data);
+ (void)pysqlite_statement_finalize(statement);
node = node->next;
}
Py_DECREF(self->statement_cache);
- self->statement_cache = (Cache*)PyObject_CallFunction((PyObject*)&CacheType, "O", self);
+ self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "O", self);
Py_DECREF(self);
self->statement_cache->decref_factory = 0;
}
-void reset_all_statements(Connection* self)
+void pysqlite_reset_all_statements(pysqlite_Connection* self)
{
int i;
PyObject* weakref;
@@ -179,12 +179,12 @@
weakref = PyList_GetItem(self->statements, i);
statement = PyWeakref_GetObject(weakref);
if (statement != Py_None) {
- (void)statement_reset((Statement*)statement);
+ (void)pysqlite_statement_reset((pysqlite_Statement*)statement);
}
}
}
-void connection_dealloc(Connection* self)
+void pysqlite_connection_dealloc(pysqlite_Connection* self)
{
Py_XDECREF(self->statement_cache);
@@ -208,7 +208,7 @@
self->ob_type->tp_free((PyObject*)self);
}
-PyObject* connection_cursor(Connection* self, PyObject* args, PyObject* kwargs)
+PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
static char *kwlist[] = {"factory", NULL, NULL};
PyObject* factory = NULL;
@@ -220,34 +220,34 @@
return NULL;
}
- if (!check_thread(self) || !check_connection(self)) {
+ if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (factory == NULL) {
- factory = (PyObject*)&CursorType;
+ factory = (PyObject*)&pysqlite_CursorType;
}
cursor = PyObject_CallFunction(factory, "O", self);
if (cursor && self->row_factory != Py_None) {
- Py_XDECREF(((Cursor*)cursor)->row_factory);
+ Py_XDECREF(((pysqlite_Cursor*)cursor)->row_factory);
Py_INCREF(self->row_factory);
- ((Cursor*)cursor)->row_factory = self->row_factory;
+ ((pysqlite_Cursor*)cursor)->row_factory = self->row_factory;
}
return cursor;
}
-PyObject* connection_close(Connection* self, PyObject* args)
+PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args)
{
int rc;
- if (!check_thread(self)) {
+ if (!pysqlite_check_thread(self)) {
return NULL;
}
- flush_statement_cache(self);
+ pysqlite_flush_statement_cache(self);
if (self->db) {
Py_BEGIN_ALLOW_THREADS
@@ -255,7 +255,7 @@
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK) {
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
return NULL;
} else {
self->db = NULL;
@@ -271,17 +271,17 @@
*
* 0 => error; 1 => ok
*/
-int check_connection(Connection* con)
+int pysqlite_check_connection(pysqlite_Connection* con)
{
if (!con->db) {
- PyErr_SetString(ProgrammingError, "Cannot operate on a closed database.");
+ PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
return 0;
} else {
return 1;
}
}
-PyObject* _connection_begin(Connection* self)
+PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
{
int rc;
const char* tail;
@@ -292,7 +292,7 @@
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK) {
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
goto error;
}
@@ -300,7 +300,7 @@
if (rc == SQLITE_DONE) {
self->inTransaction = 1;
} else {
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
}
Py_BEGIN_ALLOW_THREADS
@@ -308,7 +308,7 @@
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK && !PyErr_Occurred()) {
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
}
error:
@@ -320,13 +320,13 @@
}
}
-PyObject* connection_commit(Connection* self, PyObject* args)
+PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
{
int rc;
const char* tail;
sqlite3_stmt* statement;
- if (!check_thread(self) || !check_connection(self)) {
+ if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
@@ -335,7 +335,7 @@
rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK) {
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
goto error;
}
@@ -343,14 +343,14 @@
if (rc == SQLITE_DONE) {
self->inTransaction = 0;
} else {
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
}
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_finalize(statement);
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK && !PyErr_Occurred()) {
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
}
}
@@ -364,24 +364,24 @@
}
}
-PyObject* connection_rollback(Connection* self, PyObject* args)
+PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
{
int rc;
const char* tail;
sqlite3_stmt* statement;
- if (!check_thread(self) || !check_connection(self)) {
+ if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (self->inTransaction) {
- reset_all_statements(self);
+ pysqlite_reset_all_statements(self);
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail);
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK) {
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
goto error;
}
@@ -389,14 +389,14 @@
if (rc == SQLITE_DONE) {
self->inTransaction = 0;
} else {
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
}
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_finalize(statement);
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK && !PyErr_Occurred()) {
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
}
}
@@ -410,7 +410,7 @@
}
}
-void _set_result(sqlite3_context* context, PyObject* py_val)
+void _pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
{
long longval;
const char* buffer;
@@ -445,7 +445,7 @@
}
}
-PyObject* _build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
+PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
{
PyObject* args;
int i;
@@ -512,7 +512,7 @@
return args;
}
-void _func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
+void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
{
PyObject* args;
PyObject* py_func;
@@ -524,14 +524,14 @@
py_func = (PyObject*)sqlite3_user_data(context);
- args = _build_py_params(context, argc, argv);
+ args = _pysqlite_build_py_params(context, argc, argv);
if (args) {
py_retval = PyObject_CallObject(py_func, args);
Py_DECREF(args);
}
if (py_retval) {
- _set_result(context, py_retval);
+ _pysqlite_set_result(context, py_retval);
Py_DECREF(py_retval);
} else {
if (_enable_callback_tracebacks) {
@@ -545,7 +545,7 @@
PyGILState_Release(threadstate);
}
-static void _step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
+static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
{
PyObject* args;
PyObject* function_result = NULL;
@@ -581,7 +581,7 @@
goto error;
}
- args = _build_py_params(context, argc, params);
+ args = _pysqlite_build_py_params(context, argc, params);
if (!args) {
goto error;
}
@@ -605,7 +605,7 @@
PyGILState_Release(threadstate);
}
-void _final_callback(sqlite3_context* context)
+void _pysqlite_final_callback(sqlite3_context* context)
{
PyObject* function_result = NULL;
PyObject** aggregate_instance;
@@ -634,7 +634,7 @@
}
_sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
} else {
- _set_result(context, function_result);
+ _pysqlite_set_result(context, function_result);
}
error:
@@ -644,7 +644,7 @@
PyGILState_Release(threadstate);
}
-void _drop_unused_statement_references(Connection* self)
+void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
{
PyObject* new_list;
PyObject* weakref;
@@ -676,7 +676,7 @@
self->statements = new_list;
}
-PyObject* connection_create_function(Connection* self, PyObject* args, PyObject* kwargs)
+PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
@@ -691,11 +691,11 @@
return NULL;
}
- rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _func_callback, NULL, NULL);
+ rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _pysqlite_func_callback, NULL, NULL);
if (rc != SQLITE_OK) {
/* Workaround for SQLite bug: no error code or string is available here */
- PyErr_SetString(OperationalError, "Error creating function");
+ PyErr_SetString(pysqlite_OperationalError, "Error creating function");
return NULL;
} else {
PyDict_SetItem(self->function_pinboard, func, Py_None);
@@ -705,7 +705,7 @@
}
}
-PyObject* connection_create_aggregate(Connection* self, PyObject* args, PyObject* kwargs)
+PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
PyObject* aggregate_class;
@@ -719,10 +719,10 @@
return NULL;
}
- rc = sqlite3_create_function(self->db, name, n_arg, SQLITE_UTF8, (void*)aggregate_class, 0, &_step_callback, &_final_callback);
+ rc = sqlite3_create_function(self->db, name, n_arg, SQLITE_UTF8, (void*)aggregate_class, 0, &_pysqlite_step_callback, &_pysqlite_final_callback);
if (rc != SQLITE_OK) {
/* Workaround for SQLite bug: no error code or string is available here */
- PyErr_SetString(OperationalError, "Error creating aggregate");
+ PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
return NULL;
} else {
PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None);
@@ -732,7 +732,7 @@
}
}
-int _authorizer_callback(void* user_arg, int action, const char* arg1, const char* arg2 , const char* dbname, const char* access_attempt_source)
+static int _authorizer_callback(void* user_arg, int action, const char* arg1, const char* arg2 , const char* dbname, const char* access_attempt_source)
{
PyObject *ret;
int rc;
@@ -762,7 +762,7 @@
return rc;
}
-PyObject* connection_set_authorizer(Connection* self, PyObject* args, PyObject* kwargs)
+PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
PyObject* authorizer_cb;
@@ -777,7 +777,7 @@
rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
if (rc != SQLITE_OK) {
- PyErr_SetString(OperationalError, "Error setting authorizer callback");
+ PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
return NULL;
} else {
PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None);
@@ -787,11 +787,11 @@
}
}
-int check_thread(Connection* self)
+int pysqlite_check_thread(pysqlite_Connection* self)
{
if (self->check_same_thread) {
if (PyThread_get_thread_ident() != self->thread_ident) {
- PyErr_Format(ProgrammingError,
+ PyErr_Format(pysqlite_ProgrammingError,
"SQLite objects created in a thread can only be used in that same thread."
"The object was created in thread id %ld and this is thread id %ld",
self->thread_ident, PyThread_get_thread_ident());
@@ -803,22 +803,22 @@
return 1;
}
-static PyObject* connection_get_isolation_level(Connection* self, void* unused)
+static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
{
Py_INCREF(self->isolation_level);
return self->isolation_level;
}
-static PyObject* connection_get_total_changes(Connection* self, void* unused)
+static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
{
- if (!check_connection(self)) {
+ if (!pysqlite_check_connection(self)) {
return NULL;
} else {
return Py_BuildValue("i", sqlite3_total_changes(self->db));
}
}
-static int connection_set_isolation_level(Connection* self, PyObject* isolation_level)
+static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level)
{
PyObject* res;
PyObject* begin_statement;
@@ -834,7 +834,7 @@
Py_INCREF(Py_None);
self->isolation_level = Py_None;
- res = connection_commit(self, NULL);
+ res = pysqlite_connection_commit(self, NULL);
if (!res) {
return -1;
}
@@ -866,10 +866,10 @@
return 0;
}
-PyObject* connection_call(Connection* self, PyObject* args, PyObject* kwargs)
+PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
PyObject* sql;
- Statement* statement;
+ pysqlite_Statement* statement;
PyObject* weakref;
int rc;
@@ -877,22 +877,22 @@
return NULL;
}
- _drop_unused_statement_references(self);
+ _pysqlite_drop_unused_statement_references(self);
- statement = PyObject_New(Statement, &StatementType);
+ statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
if (!statement) {
return NULL;
}
- rc = statement_create(statement, self, sql);
+ rc = pysqlite_statement_create(statement, self, sql);
if (rc != SQLITE_OK) {
if (rc == PYSQLITE_TOO_MUCH_SQL) {
- PyErr_SetString(Warning, "You can only execute one statement at a time.");
+ PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
} else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
- PyErr_SetString(Warning, "SQL is of wrong type. Must be string or unicode.");
+ PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string or unicode.");
} else {
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
}
Py_DECREF(statement);
@@ -918,7 +918,7 @@
return (PyObject*)statement;
}
-PyObject* connection_execute(Connection* self, PyObject* args, PyObject* kwargs)
+PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
PyObject* cursor = 0;
PyObject* result = 0;
@@ -949,7 +949,7 @@
return cursor;
}
-PyObject* connection_executemany(Connection* self, PyObject* args, PyObject* kwargs)
+PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
PyObject* cursor = 0;
PyObject* result = 0;
@@ -980,7 +980,7 @@
return cursor;
}
-PyObject* connection_executescript(Connection* self, PyObject* args, PyObject* kwargs)
+PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
PyObject* cursor = 0;
PyObject* result = 0;
@@ -1014,7 +1014,7 @@
/* ------------------------- COLLATION CODE ------------------------ */
static int
-collation_callback(
+pysqlite_collation_callback(
void* context,
int text1_length, const void* text1_data,
int text2_length, const void* text2_data)
@@ -1063,11 +1063,11 @@
}
static PyObject *
-connection_interrupt(Connection* self, PyObject* args)
+pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
{
PyObject* retval = NULL;
- if (!check_connection(self)) {
+ if (!pysqlite_check_connection(self)) {
goto finally;
}
@@ -1081,7 +1081,7 @@
}
static PyObject *
-connection_create_collation(Connection* self, PyObject* args)
+pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
{
PyObject* callable;
PyObject* uppercase_name = 0;
@@ -1090,7 +1090,7 @@
char* chk;
int rc;
- if (!check_thread(self) || !check_connection(self)) {
+ if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
goto finally;
}
@@ -1111,7 +1111,7 @@
{
chk++;
} else {
- PyErr_SetString(ProgrammingError, "invalid character in collation name");
+ PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
goto finally;
}
}
@@ -1131,10 +1131,10 @@
PyString_AsString(uppercase_name),
SQLITE_UTF8,
(callable != Py_None) ? callable : NULL,
- (callable != Py_None) ? collation_callback : NULL);
+ (callable != Py_None) ? pysqlite_collation_callback : NULL);
if (rc != SQLITE_OK) {
PyDict_DelItem(self->collations, uppercase_name);
- _seterror(self->db);
+ _pysqlite_seterror(self->db);
goto finally;
}
@@ -1155,63 +1155,63 @@
PyDoc_STR("SQLite database connection object.");
static PyGetSetDef connection_getset[] = {
- {"isolation_level", (getter)connection_get_isolation_level, (setter)connection_set_isolation_level},
- {"total_changes", (getter)connection_get_total_changes, (setter)0},
+ {"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
+ {"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
{NULL}
};
static PyMethodDef connection_methods[] = {
- {"cursor", (PyCFunction)connection_cursor, METH_VARARGS|METH_KEYWORDS,
+ {"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Return a cursor for the connection.")},
- {"close", (PyCFunction)connection_close, METH_NOARGS,
+ {"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
PyDoc_STR("Closes the connection.")},
- {"commit", (PyCFunction)connection_commit, METH_NOARGS,
+ {"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
PyDoc_STR("Commit the current transaction.")},
- {"rollback", (PyCFunction)connection_rollback, METH_NOARGS,
+ {"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
PyDoc_STR("Roll back the current transaction.")},
- {"create_function", (PyCFunction)connection_create_function, METH_VARARGS|METH_KEYWORDS,
+ {"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Creates a new function. Non-standard.")},
- {"create_aggregate", (PyCFunction)connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
+ {"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Creates a new aggregate. Non-standard.")},
- {"set_authorizer", (PyCFunction)connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
+ {"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Sets authorizer callback. Non-standard.")},
- {"execute", (PyCFunction)connection_execute, METH_VARARGS,
+ {"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
PyDoc_STR("Executes a SQL statement. Non-standard.")},
- {"executemany", (PyCFunction)connection_executemany, METH_VARARGS,
+ {"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
- {"executescript", (PyCFunction)connection_executescript, METH_VARARGS,
+ {"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
- {"create_collation", (PyCFunction)connection_create_collation, METH_VARARGS,
+ {"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
PyDoc_STR("Creates a collation function. Non-standard.")},
- {"interrupt", (PyCFunction)connection_interrupt, METH_NOARGS,
+ {"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
PyDoc_STR("Abort any pending database operation. Non-standard.")},
{NULL, NULL}
};
static struct PyMemberDef connection_members[] =
{
- {"Warning", T_OBJECT, offsetof(Connection, Warning), RO},
- {"Error", T_OBJECT, offsetof(Connection, Error), RO},
- {"InterfaceError", T_OBJECT, offsetof(Connection, InterfaceError), RO},
- {"DatabaseError", T_OBJECT, offsetof(Connection, DatabaseError), RO},
- {"DataError", T_OBJECT, offsetof(Connection, DataError), RO},
- {"OperationalError", T_OBJECT, offsetof(Connection, OperationalError), RO},
- {"IntegrityError", T_OBJECT, offsetof(Connection, IntegrityError), RO},
- {"InternalError", T_OBJECT, offsetof(Connection, InternalError), RO},
- {"ProgrammingError", T_OBJECT, offsetof(Connection, ProgrammingError), RO},
- {"NotSupportedError", T_OBJECT, offsetof(Connection, NotSupportedError), RO},
- {"row_factory", T_OBJECT, offsetof(Connection, row_factory)},
- {"text_factory", T_OBJECT, offsetof(Connection, text_factory)},
+ {"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), RO},
+ {"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), RO},
+ {"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), RO},
+ {"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), RO},
+ {"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), RO},
+ {"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), RO},
+ {"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), RO},
+ {"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), RO},
+ {"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), RO},
+ {"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), RO},
+ {"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
+ {"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
{NULL}
};
-PyTypeObject ConnectionType = {
+PyTypeObject pysqlite_ConnectionType = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
MODULE_NAME ".Connection", /* tp_name */
- sizeof(Connection), /* tp_basicsize */
+ sizeof(pysqlite_Connection), /* tp_basicsize */
0, /* tp_itemsize */
- (destructor)connection_dealloc, /* tp_dealloc */
+ (destructor)pysqlite_connection_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
@@ -1221,7 +1221,7 @@
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
- (ternaryfunc)connection_call, /* tp_call */
+ (ternaryfunc)pysqlite_connection_call, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
@@ -1242,14 +1242,14 @@
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
- (initproc)connection_init, /* tp_init */
+ (initproc)pysqlite_connection_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0 /* tp_free */
};
-extern int connection_setup_types(void)
+extern int pysqlite_connection_setup_types(void)
{
- ConnectionType.tp_new = PyType_GenericNew;
- return PyType_Ready(&ConnectionType);
+ pysqlite_ConnectionType.tp_new = PyType_GenericNew;
+ return PyType_Ready(&pysqlite_ConnectionType);
}
Modified: python/branches/p3yk-noslice/Modules/_sqlite/connection.h
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/connection.h (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/connection.h Fri Feb 23 18:29:35 2007
@@ -66,7 +66,7 @@
/* thread identification of the thread the connection was created in */
long thread_ident;
- Cache* statement_cache;
+ pysqlite_Cache* statement_cache;
/* A list of weak references to statements used within this connection */
PyObject* statements;
@@ -106,24 +106,23 @@
PyObject* InternalError;
PyObject* ProgrammingError;
PyObject* NotSupportedError;
-} Connection;
+} pysqlite_Connection;
-extern PyTypeObject ConnectionType;
+extern PyTypeObject pysqlite_ConnectionType;
-PyObject* connection_alloc(PyTypeObject* type, int aware);
-void connection_dealloc(Connection* self);
-PyObject* connection_cursor(Connection* self, PyObject* args, PyObject* kwargs);
-PyObject* connection_close(Connection* self, PyObject* args);
-PyObject* _connection_begin(Connection* self);
-PyObject* connection_begin(Connection* self, PyObject* args);
-PyObject* connection_commit(Connection* self, PyObject* args);
-PyObject* connection_rollback(Connection* self, PyObject* args);
-PyObject* connection_new(PyTypeObject* type, PyObject* args, PyObject* kw);
-int connection_init(Connection* self, PyObject* args, PyObject* kwargs);
+PyObject* pysqlite_connection_alloc(PyTypeObject* type, int aware);
+void pysqlite_connection_dealloc(pysqlite_Connection* self);
+PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs);
+PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args);
+PyObject* _pysqlite_connection_begin(pysqlite_Connection* self);
+PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args);
+PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args);
+PyObject* pysqlite_connection_new(PyTypeObject* type, PyObject* args, PyObject* kw);
+int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs);
-int check_thread(Connection* self);
-int check_connection(Connection* con);
+int pysqlite_check_thread(pysqlite_Connection* self);
+int pysqlite_check_connection(pysqlite_Connection* con);
-int connection_setup_types(void);
+int pysqlite_connection_setup_types(void);
#endif
Modified: python/branches/p3yk-noslice/Modules/_sqlite/cursor.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/cursor.c (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/cursor.c Fri Feb 23 18:29:35 2007
@@ -34,9 +34,9 @@
#define INT32_MAX 2147483647
#endif
-PyObject* cursor_iternext(Cursor *self);
+PyObject* pysqlite_cursor_iternext(pysqlite_Cursor* self);
-static StatementKind detect_statement_type(char* statement)
+static pysqlite_StatementKind detect_statement_type(char* statement)
{
char buf[20];
char* src;
@@ -74,11 +74,11 @@
}
}
-int cursor_init(Cursor* self, PyObject* args, PyObject* kwargs)
+int pysqlite_cursor_init(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs)
{
- Connection* connection;
+ pysqlite_Connection* connection;
- if (!PyArg_ParseTuple(args, "O!", &ConnectionType, &connection))
+ if (!PyArg_ParseTuple(args, "O!", &pysqlite_ConnectionType, &connection))
{
return -1;
}
@@ -109,20 +109,20 @@
Py_INCREF(Py_None);
self->row_factory = Py_None;
- if (!check_thread(self->connection)) {
+ if (!pysqlite_check_thread(self->connection)) {
return -1;
}
return 0;
}
-void cursor_dealloc(Cursor* self)
+void pysqlite_cursor_dealloc(pysqlite_Cursor* self)
{
int rc;
/* Reset the statement if the user has not closed the cursor */
if (self->statement) {
- rc = statement_reset(self->statement);
+ rc = pysqlite_statement_reset(self->statement);
Py_DECREF(self->statement);
}
@@ -137,7 +137,7 @@
self->ob_type->tp_free((PyObject*)self);
}
-PyObject* _get_converter(PyObject* key)
+PyObject* _pysqlite_get_converter(PyObject* key)
{
PyObject* upcase_key;
PyObject* retval;
@@ -153,7 +153,7 @@
return retval;
}
-int build_row_cast_map(Cursor* self)
+int pysqlite_build_row_cast_map(pysqlite_Cursor* self)
{
int i;
const char* type_start = (const char*)-1;
@@ -175,7 +175,7 @@
for (i = 0; i < sqlite3_column_count(self->statement->st); i++) {
converter = NULL;
- if (self->connection->detect_types | PARSE_COLNAMES) {
+ if (self->connection->detect_types & PARSE_COLNAMES) {
colname = sqlite3_column_name(self->statement->st, i);
if (colname) {
for (pos = colname; *pos != 0; pos++) {
@@ -190,7 +190,7 @@
break;
}
- converter = _get_converter(key);
+ converter = _pysqlite_get_converter(key);
Py_DECREF(key);
break;
}
@@ -198,7 +198,7 @@
}
}
- if (!converter && self->connection->detect_types | PARSE_DECLTYPES) {
+ if (!converter && self->connection->detect_types & PARSE_DECLTYPES) {
decltype = sqlite3_column_decltype(self->statement->st, i);
if (decltype) {
for (pos = decltype;;pos++) {
@@ -211,7 +211,7 @@
}
}
- converter = _get_converter(py_decltype);
+ converter = _pysqlite_get_converter(py_decltype);
Py_DECREF(py_decltype);
}
}
@@ -234,7 +234,7 @@
return 0;
}
-PyObject* _build_column_name(const char* colname)
+PyObject* _pysqlite_build_column_name(const char* colname)
{
const char* pos;
@@ -253,7 +253,7 @@
}
}
-PyObject* unicode_from_string(const char* val_str, int optimize)
+PyObject* pysqlite_unicode_from_string(const char* val_str, int optimize)
{
const char* check;
int is_ascii = 0;
@@ -285,7 +285,7 @@
* Precondidition:
* - sqlite3_step() has been called before and it returned SQLITE_ROW.
*/
-PyObject* _fetch_one_row(Cursor* self)
+PyObject* _pysqlite_fetch_one_row(pysqlite_Cursor* self)
{
int i, numcols;
PyObject* row;
@@ -356,10 +356,10 @@
} else if (coltype == SQLITE_TEXT) {
val_str = (const char*)sqlite3_column_text(self->statement->st, i);
if ((self->connection->text_factory == (PyObject*)&PyUnicode_Type)
- || (self->connection->text_factory == OptimizedUnicode)) {
+ || (self->connection->text_factory == pysqlite_OptimizedUnicode)) {
- converted = unicode_from_string(val_str,
- self->connection->text_factory == OptimizedUnicode ? 1 : 0);
+ converted = pysqlite_unicode_from_string(val_str,
+ self->connection->text_factory == pysqlite_OptimizedUnicode ? 1 : 0);
if (!converted) {
colname = sqlite3_column_name(self->statement->st, i);
@@ -368,7 +368,7 @@
}
PyOS_snprintf(buf, sizeof(buf) - 1, "Could not decode to UTF-8 column '%s' with text '%s'",
colname , val_str);
- PyErr_SetString(OperationalError, buf);
+ PyErr_SetString(pysqlite_OperationalError, buf);
}
} else if (self->connection->text_factory == (PyObject*)&PyString_Type) {
converted = PyString_FromString(val_str);
@@ -406,7 +406,7 @@
return row;
}
-PyObject* _query_execute(Cursor* self, int multiple, PyObject* args)
+PyObject* _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* args)
{
PyObject* operation;
PyObject* operation_bytestr = NULL;
@@ -425,7 +425,7 @@
PyObject* second_argument = NULL;
long rowcount = 0;
- if (!check_thread(self->connection) || !check_connection(self->connection)) {
+ if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) {
return NULL;
}
@@ -492,7 +492,7 @@
if (self->statement != NULL) {
/* There is an active statement */
- rc = statement_reset(self->statement);
+ rc = pysqlite_statement_reset(self->statement);
}
if (PyString_Check(operation)) {
@@ -525,7 +525,7 @@
case STATEMENT_INSERT:
case STATEMENT_REPLACE:
if (!self->connection->inTransaction) {
- result = _connection_begin(self->connection);
+ result = _pysqlite_connection_begin(self->connection);
if (!result) {
goto error;
}
@@ -536,7 +536,7 @@
/* it's a DDL statement or something similar
- we better COMMIT first so it works for all cases */
if (self->connection->inTransaction) {
- result = connection_commit(self->connection, NULL);
+ result = pysqlite_connection_commit(self->connection, NULL);
if (!result) {
goto error;
}
@@ -545,7 +545,7 @@
break;
case STATEMENT_SELECT:
if (multiple) {
- PyErr_SetString(ProgrammingError,
+ PyErr_SetString(pysqlite_ProgrammingError,
"You cannot execute SELECT statements in executemany().");
goto error;
}
@@ -563,11 +563,11 @@
}
if (self->statement) {
- (void)statement_reset(self->statement);
+ (void)pysqlite_statement_reset(self->statement);
Py_DECREF(self->statement);
}
- self->statement = (Statement*)cache_get(self->connection->statement_cache, func_args);
+ self->statement = (pysqlite_Statement*)pysqlite_cache_get(self->connection->statement_cache, func_args);
Py_DECREF(func_args);
if (!self->statement) {
@@ -576,19 +576,19 @@
if (self->statement->in_use) {
Py_DECREF(self->statement);
- self->statement = PyObject_New(Statement, &StatementType);
+ self->statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
if (!self->statement) {
goto error;
}
- rc = statement_create(self->statement, self->connection, operation);
+ rc = pysqlite_statement_create(self->statement, self->connection, operation);
if (rc != SQLITE_OK) {
self->statement = 0;
goto error;
}
}
- statement_reset(self->statement);
- statement_mark_dirty(self->statement);
+ pysqlite_statement_reset(self->statement);
+ pysqlite_statement_mark_dirty(self->statement);
while (1) {
parameters = PyIter_Next(parameters_iter);
@@ -596,27 +596,37 @@
break;
}
- statement_mark_dirty(self->statement);
+ pysqlite_statement_mark_dirty(self->statement);
- statement_bind_parameters(self->statement, parameters);
+ pysqlite_statement_bind_parameters(self->statement, parameters);
if (PyErr_Occurred()) {
goto error;
}
- if (build_row_cast_map(self) != 0) {
- PyErr_SetString(OperationalError, "Error while building row_cast_map");
+ if (pysqlite_build_row_cast_map(self) != 0) {
+ PyErr_SetString(pysqlite_OperationalError, "Error while building row_cast_map");
goto error;
}
- rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection);
- if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
- rc = statement_reset(self->statement);
+ /* Keep trying the SQL statement until the schema stops changing. */
+ while (1) {
+ /* Actually execute the SQL statement. */
+ rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection);
+ if (rc == SQLITE_DONE || rc == SQLITE_ROW) {
+ /* If it worked, let's get out of the loop */
+ break;
+ }
+ /* Something went wrong. Re-set the statement and try again. */
+ rc = pysqlite_statement_reset(self->statement);
if (rc == SQLITE_SCHEMA) {
- rc = statement_recompile(self->statement, parameters);
+ /* If this was a result of the schema changing, let's try
+ again. */
+ rc = pysqlite_statement_recompile(self->statement, parameters);
if (rc == SQLITE_OK) {
- rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection);
+ continue;
} else {
- _seterror(self->connection->db);
+ /* If the database gave us an error, promote it to Python. */
+ _pysqlite_seterror(self->connection->db);
goto error;
}
} else {
@@ -628,7 +638,7 @@
PyErr_Clear();
}
}
- _seterror(self->connection->db);
+ _pysqlite_seterror(self->connection->db);
goto error;
}
}
@@ -649,7 +659,7 @@
if (!descriptor) {
goto error;
}
- PyTuple_SetItem(descriptor, 0, _build_column_name(sqlite3_column_name(self->statement->st, i)));
+ PyTuple_SetItem(descriptor, 0, _pysqlite_build_column_name(sqlite3_column_name(self->statement->st, i)));
Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 1, Py_None);
Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 2, Py_None);
Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 3, Py_None);
@@ -663,13 +673,13 @@
if (rc == SQLITE_ROW) {
if (multiple) {
- PyErr_SetString(ProgrammingError, "executemany() can only execute DML statements.");
+ PyErr_SetString(pysqlite_ProgrammingError, "executemany() can only execute DML statements.");
goto error;
}
- self->next_row = _fetch_one_row(self);
+ self->next_row = _pysqlite_fetch_one_row(self);
} else if (rc == SQLITE_DONE && !multiple) {
- statement_reset(self->statement);
+ pysqlite_statement_reset(self->statement);
Py_DECREF(self->statement);
self->statement = 0;
}
@@ -698,7 +708,7 @@
}
if (multiple) {
- rc = statement_reset(self->statement);
+ rc = pysqlite_statement_reset(self->statement);
}
Py_XDECREF(parameters);
}
@@ -717,17 +727,17 @@
}
}
-PyObject* cursor_execute(Cursor* self, PyObject* args)
+PyObject* pysqlite_cursor_execute(pysqlite_Cursor* self, PyObject* args)
{
- return _query_execute(self, 0, args);
+ return _pysqlite_query_execute(self, 0, args);
}
-PyObject* cursor_executemany(Cursor* self, PyObject* args)
+PyObject* pysqlite_cursor_executemany(pysqlite_Cursor* self, PyObject* args)
{
- return _query_execute(self, 1, args);
+ return _pysqlite_query_execute(self, 1, args);
}
-PyObject* cursor_executescript(Cursor* self, PyObject* args)
+PyObject* pysqlite_cursor_executescript(pysqlite_Cursor* self, PyObject* args)
{
PyObject* script_obj;
PyObject* script_str = NULL;
@@ -741,7 +751,7 @@
return NULL;
}
- if (!check_thread(self->connection) || !check_connection(self->connection)) {
+ if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) {
return NULL;
}
@@ -760,7 +770,7 @@
}
/* commit first */
- result = connection_commit(self->connection, NULL);
+ result = pysqlite_connection_commit(self->connection, NULL);
if (!result) {
goto error;
}
@@ -778,7 +788,7 @@
&statement,
&script_cstr);
if (rc != SQLITE_OK) {
- _seterror(self->connection->db);
+ _pysqlite_seterror(self->connection->db);
goto error;
}
@@ -790,13 +800,13 @@
if (rc != SQLITE_DONE) {
(void)sqlite3_finalize(statement);
- _seterror(self->connection->db);
+ _pysqlite_seterror(self->connection->db);
goto error;
}
rc = sqlite3_finalize(statement);
if (rc != SQLITE_OK) {
- _seterror(self->connection->db);
+ _pysqlite_seterror(self->connection->db);
goto error;
}
}
@@ -805,7 +815,7 @@
Py_XDECREF(script_str);
if (!statement_completed) {
- PyErr_SetString(ProgrammingError, "you did not provide a complete SQL statement");
+ PyErr_SetString(pysqlite_ProgrammingError, "you did not provide a complete SQL statement");
}
if (PyErr_Occurred()) {
@@ -816,25 +826,25 @@
}
}
-PyObject* cursor_getiter(Cursor *self)
+PyObject* pysqlite_cursor_getiter(pysqlite_Cursor *self)
{
Py_INCREF(self);
return (PyObject*)self;
}
-PyObject* cursor_iternext(Cursor *self)
+PyObject* pysqlite_cursor_iternext(pysqlite_Cursor *self)
{
PyObject* next_row_tuple;
PyObject* next_row;
int rc;
- if (!check_thread(self->connection) || !check_connection(self->connection)) {
+ if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) {
return NULL;
}
if (!self->next_row) {
if (self->statement) {
- (void)statement_reset(self->statement);
+ (void)pysqlite_statement_reset(self->statement);
Py_DECREF(self->statement);
self->statement = NULL;
}
@@ -851,25 +861,27 @@
next_row = next_row_tuple;
}
- rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection);
- if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
- Py_DECREF(next_row);
- _seterror(self->connection->db);
- return NULL;
- }
+ if (self->statement) {
+ rc = _sqlite_step_with_busyhandler(self->statement->st, self->connection);
+ if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
+ Py_DECREF(next_row);
+ _pysqlite_seterror(self->connection->db);
+ return NULL;
+ }
- if (rc == SQLITE_ROW) {
- self->next_row = _fetch_one_row(self);
+ if (rc == SQLITE_ROW) {
+ self->next_row = _pysqlite_fetch_one_row(self);
+ }
}
return next_row;
}
-PyObject* cursor_fetchone(Cursor* self, PyObject* args)
+PyObject* pysqlite_cursor_fetchone(pysqlite_Cursor* self, PyObject* args)
{
PyObject* row;
- row = cursor_iternext(self);
+ row = pysqlite_cursor_iternext(self);
if (!row && !PyErr_Occurred()) {
Py_INCREF(Py_None);
return Py_None;
@@ -878,7 +890,7 @@
return row;
}
-PyObject* cursor_fetchmany(Cursor* self, PyObject* args)
+PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args)
{
PyObject* row;
PyObject* list;
@@ -898,7 +910,7 @@
row = Py_None;
while (row) {
- row = cursor_iternext(self);
+ row = pysqlite_cursor_iternext(self);
if (row) {
PyList_Append(list, row);
Py_DECREF(row);
@@ -919,7 +931,7 @@
}
}
-PyObject* cursor_fetchall(Cursor* self, PyObject* args)
+PyObject* pysqlite_cursor_fetchall(pysqlite_Cursor* self, PyObject* args)
{
PyObject* row;
PyObject* list;
@@ -933,7 +945,7 @@
row = (PyObject*)Py_None;
while (row) {
- row = cursor_iternext(self);
+ row = pysqlite_cursor_iternext(self);
if (row) {
PyList_Append(list, row);
Py_DECREF(row);
@@ -948,21 +960,21 @@
}
}
-PyObject* pysqlite_noop(Connection* self, PyObject* args)
+PyObject* pysqlite_noop(pysqlite_Connection* self, PyObject* args)
{
/* don't care, return None */
Py_INCREF(Py_None);
return Py_None;
}
-PyObject* cursor_close(Cursor* self, PyObject* args)
+PyObject* pysqlite_cursor_close(pysqlite_Cursor* self, PyObject* args)
{
- if (!check_thread(self->connection) || !check_connection(self->connection)) {
+ if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) {
return NULL;
}
if (self->statement) {
- (void)statement_reset(self->statement);
+ (void)pysqlite_statement_reset(self->statement);
Py_DECREF(self->statement);
self->statement = 0;
}
@@ -972,19 +984,19 @@
}
static PyMethodDef cursor_methods[] = {
- {"execute", (PyCFunction)cursor_execute, METH_VARARGS,
+ {"execute", (PyCFunction)pysqlite_cursor_execute, METH_VARARGS,
PyDoc_STR("Executes a SQL statement.")},
- {"executemany", (PyCFunction)cursor_executemany, METH_VARARGS,
+ {"executemany", (PyCFunction)pysqlite_cursor_executemany, METH_VARARGS,
PyDoc_STR("Repeatedly executes a SQL statement.")},
- {"executescript", (PyCFunction)cursor_executescript, METH_VARARGS,
+ {"executescript", (PyCFunction)pysqlite_cursor_executescript, METH_VARARGS,
PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
- {"fetchone", (PyCFunction)cursor_fetchone, METH_NOARGS,
+ {"fetchone", (PyCFunction)pysqlite_cursor_fetchone, METH_NOARGS,
PyDoc_STR("Fetches several rows from the resultset.")},
- {"fetchmany", (PyCFunction)cursor_fetchmany, METH_VARARGS,
+ {"fetchmany", (PyCFunction)pysqlite_cursor_fetchmany, METH_VARARGS,
PyDoc_STR("Fetches all rows from the resultset.")},
- {"fetchall", (PyCFunction)cursor_fetchall, METH_NOARGS,
+ {"fetchall", (PyCFunction)pysqlite_cursor_fetchall, METH_NOARGS,
PyDoc_STR("Fetches one row from the resultset.")},
- {"close", (PyCFunction)cursor_close, METH_NOARGS,
+ {"close", (PyCFunction)pysqlite_cursor_close, METH_NOARGS,
PyDoc_STR("Closes the cursor.")},
{"setinputsizes", (PyCFunction)pysqlite_noop, METH_VARARGS,
PyDoc_STR("Required by DB-API. Does nothing in pysqlite.")},
@@ -995,25 +1007,25 @@
static struct PyMemberDef cursor_members[] =
{
- {"connection", T_OBJECT, offsetof(Cursor, connection), RO},
- {"description", T_OBJECT, offsetof(Cursor, description), RO},
- {"arraysize", T_INT, offsetof(Cursor, arraysize), 0},
- {"lastrowid", T_OBJECT, offsetof(Cursor, lastrowid), RO},
- {"rowcount", T_OBJECT, offsetof(Cursor, rowcount), RO},
- {"row_factory", T_OBJECT, offsetof(Cursor, row_factory), 0},
+ {"connection", T_OBJECT, offsetof(pysqlite_Cursor, connection), RO},
+ {"description", T_OBJECT, offsetof(pysqlite_Cursor, description), RO},
+ {"arraysize", T_INT, offsetof(pysqlite_Cursor, arraysize), 0},
+ {"lastrowid", T_OBJECT, offsetof(pysqlite_Cursor, lastrowid), RO},
+ {"rowcount", T_OBJECT, offsetof(pysqlite_Cursor, rowcount), RO},
+ {"row_factory", T_OBJECT, offsetof(pysqlite_Cursor, row_factory), 0},
{NULL}
};
static char cursor_doc[] =
PyDoc_STR("SQLite database cursor class.");
-PyTypeObject CursorType = {
+PyTypeObject pysqlite_CursorType = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
MODULE_NAME ".Cursor", /* tp_name */
- sizeof(Cursor), /* tp_basicsize */
+ sizeof(pysqlite_Cursor), /* tp_basicsize */
0, /* tp_itemsize */
- (destructor)cursor_dealloc, /* tp_dealloc */
+ (destructor)pysqlite_cursor_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
@@ -1034,8 +1046,8 @@
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
- (getiterfunc)cursor_getiter, /* tp_iter */
- (iternextfunc)cursor_iternext, /* tp_iternext */
+ (getiterfunc)pysqlite_cursor_getiter, /* tp_iter */
+ (iternextfunc)pysqlite_cursor_iternext, /* tp_iternext */
cursor_methods, /* tp_methods */
cursor_members, /* tp_members */
0, /* tp_getset */
@@ -1044,14 +1056,14 @@
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
- (initproc)cursor_init, /* tp_init */
+ (initproc)pysqlite_cursor_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0 /* tp_free */
};
-extern int cursor_setup_types(void)
+extern int pysqlite_cursor_setup_types(void)
{
- CursorType.tp_new = PyType_GenericNew;
- return PyType_Ready(&CursorType);
+ pysqlite_CursorType.tp_new = PyType_GenericNew;
+ return PyType_Ready(&pysqlite_CursorType);
}
Modified: python/branches/p3yk-noslice/Modules/_sqlite/cursor.h
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/cursor.h (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/cursor.h Fri Feb 23 18:29:35 2007
@@ -32,40 +32,40 @@
typedef struct
{
PyObject_HEAD
- Connection* connection;
+ pysqlite_Connection* connection;
PyObject* description;
PyObject* row_cast_map;
int arraysize;
PyObject* lastrowid;
PyObject* rowcount;
PyObject* row_factory;
- Statement* statement;
+ pysqlite_Statement* statement;
/* the next row to be returned, NULL if no next row available */
PyObject* next_row;
-} Cursor;
+} pysqlite_Cursor;
typedef enum {
STATEMENT_INVALID, STATEMENT_INSERT, STATEMENT_DELETE,
STATEMENT_UPDATE, STATEMENT_REPLACE, STATEMENT_SELECT,
STATEMENT_OTHER
-} StatementKind;
+} pysqlite_StatementKind;
-extern PyTypeObject CursorType;
+extern PyTypeObject pysqlite_CursorType;
-int cursor_init(Cursor* self, PyObject* args, PyObject* kwargs);
-void cursor_dealloc(Cursor* self);
-PyObject* cursor_execute(Cursor* self, PyObject* args);
-PyObject* cursor_executemany(Cursor* self, PyObject* args);
-PyObject* cursor_getiter(Cursor *self);
-PyObject* cursor_iternext(Cursor *self);
-PyObject* cursor_fetchone(Cursor* self, PyObject* args);
-PyObject* cursor_fetchmany(Cursor* self, PyObject* args);
-PyObject* cursor_fetchall(Cursor* self, PyObject* args);
-PyObject* pysqlite_noop(Connection* self, PyObject* args);
-PyObject* cursor_close(Cursor* self, PyObject* args);
+int pysqlite_cursor_init(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs);
+void pysqlite_cursor_dealloc(pysqlite_Cursor* self);
+PyObject* pysqlite_cursor_execute(pysqlite_Cursor* self, PyObject* args);
+PyObject* pysqlite_cursor_executemany(pysqlite_Cursor* self, PyObject* args);
+PyObject* pysqlite_cursor_getiter(pysqlite_Cursor *self);
+PyObject* pysqlite_cursor_iternext(pysqlite_Cursor *self);
+PyObject* pysqlite_cursor_fetchone(pysqlite_Cursor* self, PyObject* args);
+PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args);
+PyObject* pysqlite_cursor_fetchall(pysqlite_Cursor* self, PyObject* args);
+PyObject* pysqlite_noop(pysqlite_Connection* self, PyObject* args);
+PyObject* pysqlite_cursor_close(pysqlite_Cursor* self, PyObject* args);
-int cursor_setup_types(void);
+int pysqlite_cursor_setup_types(void);
#define UNKNOWN (-1)
#endif
Modified: python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.c (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.c Fri Feb 23 18:29:35 2007
@@ -57,7 +57,7 @@
PyObject* key;
int rc;
- if (proto == NULL) proto = (PyObject*)&SQLitePrepareProtocolType;
+ if (proto == NULL) proto = (PyObject*)&pysqlite_PrepareProtocolType;
key = Py_BuildValue("(OO)", (PyObject*)type, proto);
if (!key) {
@@ -78,7 +78,7 @@
PyObject *adapter, *key;
/* we don't check for exact type conformance as specified in PEP 246
- because the SQLitePrepareProtocolType type is abstract and there is no
+ because the pysqlite_PrepareProtocolType type is abstract and there is no
way to get a quotable object to be its instance */
/* look for an adapter in the registry */
@@ -125,17 +125,17 @@
}
/* else set the right exception and return NULL */
- PyErr_SetString(ProgrammingError, "can't adapt");
+ PyErr_SetString(pysqlite_ProgrammingError, "can't adapt");
return NULL;
}
/** module-level functions **/
PyObject *
-psyco_microprotocols_adapt(Cursor *self, PyObject *args)
+psyco_microprotocols_adapt(pysqlite_Cursor *self, PyObject *args)
{
PyObject *obj, *alt = NULL;
- PyObject *proto = (PyObject*)&SQLitePrepareProtocolType;
+ PyObject *proto = (PyObject*)&pysqlite_PrepareProtocolType;
if (!PyArg_ParseTuple(args, "O|OO", &obj, &proto, &alt)) return NULL;
return microprotocols_adapt(obj, proto, alt);
Modified: python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.h
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.h (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/microprotocols.h Fri Feb 23 18:29:35 2007
@@ -52,7 +52,7 @@
PyObject *obj, PyObject *proto, PyObject *alt);
extern PyObject *
- psyco_microprotocols_adapt(Cursor* self, PyObject *args);
+ psyco_microprotocols_adapt(pysqlite_Cursor* self, PyObject *args);
#define psyco_microprotocols_adapt_doc \
"adapt(obj, protocol, alternate) -> adapt obj to given protocol. Non-standard."
Modified: python/branches/p3yk-noslice/Modules/_sqlite/module.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/module.c (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/module.c Fri Feb 23 18:29:35 2007
@@ -35,9 +35,9 @@
/* static objects at module-level */
-PyObject* Error, *Warning, *InterfaceError, *DatabaseError, *InternalError,
- *OperationalError, *ProgrammingError, *IntegrityError, *DataError,
- *NotSupportedError, *OptimizedUnicode;
+PyObject* pysqlite_Error, *pysqlite_Warning, *pysqlite_InterfaceError, *pysqlite_DatabaseError,
+ *pysqlite_InternalError, *pysqlite_OperationalError, *pysqlite_ProgrammingError,
+ *pysqlite_IntegrityError, *pysqlite_DataError, *pysqlite_NotSupportedError, *pysqlite_OptimizedUnicode;
PyObject* converters;
int _enable_callback_tracebacks;
@@ -67,7 +67,7 @@
}
if (factory == NULL) {
- factory = (PyObject*)&ConnectionType;
+ factory = (PyObject*)&pysqlite_ConnectionType;
}
result = PyObject_Call(factory, args, kwargs);
@@ -115,7 +115,7 @@
rc = sqlite3_enable_shared_cache(do_enable);
if (rc != SQLITE_OK) {
- PyErr_SetString(OperationalError, "Changing the shared_cache flag failed");
+ PyErr_SetString(pysqlite_OperationalError, "Changing the shared_cache flag failed");
return NULL;
} else {
Py_INCREF(Py_None);
@@ -133,7 +133,7 @@
return NULL;
}
- microprotocols_add(type, (PyObject*)&SQLitePrepareProtocolType, caster);
+ microprotocols_add(type, (PyObject*)&pysqlite_PrepareProtocolType, caster);
Py_INCREF(Py_None);
return Py_None;
@@ -141,36 +141,29 @@
static PyObject* module_register_converter(PyObject* self, PyObject* args, PyObject* kwargs)
{
- char* orig_name;
- char* name = NULL;
- char* c;
+ PyObject* orig_name;
+ PyObject* name = NULL;
PyObject* callable;
PyObject* retval = NULL;
- if (!PyArg_ParseTuple(args, "sO", &orig_name, &callable)) {
+ if (!PyArg_ParseTuple(args, "SO", &orig_name, &callable)) {
return NULL;
}
- /* convert the name to lowercase */
- name = PyMem_Malloc(strlen(orig_name) + 2);
+ /* convert the name to upper case */
+ name = PyObject_CallMethod(orig_name, "upper", "");
if (!name) {
goto error;
}
- strcpy(name, orig_name);
- for (c = name; *c != (char)0; c++) {
- *c = (*c) & 0xDF;
- }
- if (PyDict_SetItemString(converters, name, callable) != 0) {
+ if (PyDict_SetItem(converters, name, callable) != 0) {
goto error;
}
Py_INCREF(Py_None);
retval = Py_None;
error:
- if (name) {
- PyMem_Free(name);
- }
+ Py_XDECREF(name);
return retval;
}
@@ -184,7 +177,7 @@
return Py_None;
}
-void converters_init(PyObject* dict)
+static void converters_init(PyObject* dict)
{
converters = PyDict_New();
if (!converters) {
@@ -265,28 +258,28 @@
module = Py_InitModule("_sqlite3", module_methods);
if (!module ||
- (row_setup_types() < 0) ||
- (cursor_setup_types() < 0) ||
- (connection_setup_types() < 0) ||
- (cache_setup_types() < 0) ||
- (statement_setup_types() < 0) ||
- (prepare_protocol_setup_types() < 0)
+ (pysqlite_row_setup_types() < 0) ||
+ (pysqlite_cursor_setup_types() < 0) ||
+ (pysqlite_connection_setup_types() < 0) ||
+ (pysqlite_cache_setup_types() < 0) ||
+ (pysqlite_statement_setup_types() < 0) ||
+ (pysqlite_prepare_protocol_setup_types() < 0)
) {
return;
}
- Py_INCREF(&ConnectionType);
- PyModule_AddObject(module, "Connection", (PyObject*) &ConnectionType);
- Py_INCREF(&CursorType);
- PyModule_AddObject(module, "Cursor", (PyObject*) &CursorType);
- Py_INCREF(&CacheType);
- PyModule_AddObject(module, "Statement", (PyObject*)&StatementType);
- Py_INCREF(&StatementType);
- PyModule_AddObject(module, "Cache", (PyObject*) &CacheType);
- Py_INCREF(&SQLitePrepareProtocolType);
- PyModule_AddObject(module, "PrepareProtocol", (PyObject*) &SQLitePrepareProtocolType);
- Py_INCREF(&RowType);
- PyModule_AddObject(module, "Row", (PyObject*) &RowType);
+ Py_INCREF(&pysqlite_ConnectionType);
+ PyModule_AddObject(module, "Connection", (PyObject*) &pysqlite_ConnectionType);
+ Py_INCREF(&pysqlite_CursorType);
+ PyModule_AddObject(module, "Cursor", (PyObject*) &pysqlite_CursorType);
+ Py_INCREF(&pysqlite_CacheType);
+ PyModule_AddObject(module, "Statement", (PyObject*)&pysqlite_StatementType);
+ Py_INCREF(&pysqlite_StatementType);
+ PyModule_AddObject(module, "Cache", (PyObject*) &pysqlite_CacheType);
+ Py_INCREF(&pysqlite_PrepareProtocolType);
+ PyModule_AddObject(module, "PrepareProtocol", (PyObject*) &pysqlite_PrepareProtocolType);
+ Py_INCREF(&pysqlite_RowType);
+ PyModule_AddObject(module, "Row", (PyObject*) &pysqlite_RowType);
if (!(dict = PyModule_GetDict(module))) {
goto error;
@@ -294,67 +287,67 @@
/*** Create DB-API Exception hierarchy */
- if (!(Error = PyErr_NewException(MODULE_NAME ".Error", PyExc_StandardError, NULL))) {
+ if (!(pysqlite_Error = PyErr_NewException(MODULE_NAME ".Error", PyExc_StandardError, NULL))) {
goto error;
}
- PyDict_SetItemString(dict, "Error", Error);
+ PyDict_SetItemString(dict, "Error", pysqlite_Error);
- if (!(Warning = PyErr_NewException(MODULE_NAME ".Warning", PyExc_StandardError, NULL))) {
+ if (!(pysqlite_Warning = PyErr_NewException(MODULE_NAME ".Warning", PyExc_StandardError, NULL))) {
goto error;
}
- PyDict_SetItemString(dict, "Warning", Warning);
+ PyDict_SetItemString(dict, "Warning", pysqlite_Warning);
/* Error subclasses */
- if (!(InterfaceError = PyErr_NewException(MODULE_NAME ".InterfaceError", Error, NULL))) {
+ if (!(pysqlite_InterfaceError = PyErr_NewException(MODULE_NAME ".InterfaceError", pysqlite_Error, NULL))) {
goto error;
}
- PyDict_SetItemString(dict, "InterfaceError", InterfaceError);
+ PyDict_SetItemString(dict, "InterfaceError", pysqlite_InterfaceError);
- if (!(DatabaseError = PyErr_NewException(MODULE_NAME ".DatabaseError", Error, NULL))) {
+ if (!(pysqlite_DatabaseError = PyErr_NewException(MODULE_NAME ".DatabaseError", pysqlite_Error, NULL))) {
goto error;
}
- PyDict_SetItemString(dict, "DatabaseError", DatabaseError);
+ PyDict_SetItemString(dict, "DatabaseError", pysqlite_DatabaseError);
- /* DatabaseError subclasses */
+ /* pysqlite_DatabaseError subclasses */
- if (!(InternalError = PyErr_NewException(MODULE_NAME ".InternalError", DatabaseError, NULL))) {
+ if (!(pysqlite_InternalError = PyErr_NewException(MODULE_NAME ".InternalError", pysqlite_DatabaseError, NULL))) {
goto error;
}
- PyDict_SetItemString(dict, "InternalError", InternalError);
+ PyDict_SetItemString(dict, "InternalError", pysqlite_InternalError);
- if (!(OperationalError = PyErr_NewException(MODULE_NAME ".OperationalError", DatabaseError, NULL))) {
+ if (!(pysqlite_OperationalError = PyErr_NewException(MODULE_NAME ".OperationalError", pysqlite_DatabaseError, NULL))) {
goto error;
}
- PyDict_SetItemString(dict, "OperationalError", OperationalError);
+ PyDict_SetItemString(dict, "OperationalError", pysqlite_OperationalError);
- if (!(ProgrammingError = PyErr_NewException(MODULE_NAME ".ProgrammingError", DatabaseError, NULL))) {
+ if (!(pysqlite_ProgrammingError = PyErr_NewException(MODULE_NAME ".ProgrammingError", pysqlite_DatabaseError, NULL))) {
goto error;
}
- PyDict_SetItemString(dict, "ProgrammingError", ProgrammingError);
+ PyDict_SetItemString(dict, "ProgrammingError", pysqlite_ProgrammingError);
- if (!(IntegrityError = PyErr_NewException(MODULE_NAME ".IntegrityError", DatabaseError,NULL))) {
+ if (!(pysqlite_IntegrityError = PyErr_NewException(MODULE_NAME ".IntegrityError", pysqlite_DatabaseError,NULL))) {
goto error;
}
- PyDict_SetItemString(dict, "IntegrityError", IntegrityError);
+ PyDict_SetItemString(dict, "IntegrityError", pysqlite_IntegrityError);
- if (!(DataError = PyErr_NewException(MODULE_NAME ".DataError", DatabaseError, NULL))) {
+ if (!(pysqlite_DataError = PyErr_NewException(MODULE_NAME ".DataError", pysqlite_DatabaseError, NULL))) {
goto error;
}
- PyDict_SetItemString(dict, "DataError", DataError);
+ PyDict_SetItemString(dict, "DataError", pysqlite_DataError);
- if (!(NotSupportedError = PyErr_NewException(MODULE_NAME ".NotSupportedError", DatabaseError, NULL))) {
+ if (!(pysqlite_NotSupportedError = PyErr_NewException(MODULE_NAME ".NotSupportedError", pysqlite_DatabaseError, NULL))) {
goto error;
}
- PyDict_SetItemString(dict, "NotSupportedError", NotSupportedError);
+ PyDict_SetItemString(dict, "NotSupportedError", pysqlite_NotSupportedError);
- /* We just need "something" unique for OptimizedUnicode. It does not really
+ /* We just need "something" unique for pysqlite_OptimizedUnicode. It does not really
* need to be a string subclass. Just anything that can act as a special
* marker for us. So I pulled PyCell_Type out of my magic hat.
*/
Py_INCREF((PyObject*)&PyCell_Type);
- OptimizedUnicode = (PyObject*)&PyCell_Type;
- PyDict_SetItemString(dict, "OptimizedUnicode", OptimizedUnicode);
+ pysqlite_OptimizedUnicode = (PyObject*)&PyCell_Type;
+ PyDict_SetItemString(dict, "OptimizedUnicode", pysqlite_OptimizedUnicode);
/* Set integer constants */
for (i = 0; _int_constants[i].constant_name != 0; i++) {
Modified: python/branches/p3yk-noslice/Modules/_sqlite/module.h
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/module.h (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/module.h Fri Feb 23 18:29:35 2007
@@ -25,20 +25,20 @@
#define PYSQLITE_MODULE_H
#include "Python.h"
-#define PYSQLITE_VERSION "2.3.2"
+#define PYSQLITE_VERSION "2.3.3"
-extern PyObject* Error;
-extern PyObject* Warning;
-extern PyObject* InterfaceError;
-extern PyObject* DatabaseError;
-extern PyObject* InternalError;
-extern PyObject* OperationalError;
-extern PyObject* ProgrammingError;
-extern PyObject* IntegrityError;
-extern PyObject* DataError;
-extern PyObject* NotSupportedError;
+extern PyObject* pysqlite_Error;
+extern PyObject* pysqlite_Warning;
+extern PyObject* pysqlite_InterfaceError;
+extern PyObject* pysqlite_DatabaseError;
+extern PyObject* pysqlite_InternalError;
+extern PyObject* pysqlite_OperationalError;
+extern PyObject* pysqlite_ProgrammingError;
+extern PyObject* pysqlite_IntegrityError;
+extern PyObject* pysqlite_DataError;
+extern PyObject* pysqlite_NotSupportedError;
-extern PyObject* OptimizedUnicode;
+extern PyObject* pysqlite_OptimizedUnicode;
/* the functions time.time() and time.sleep() */
extern PyObject* time_time;
Modified: python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.c (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.c Fri Feb 23 18:29:35 2007
@@ -23,23 +23,23 @@
#include "prepare_protocol.h"
-int prepare_protocol_init(SQLitePrepareProtocol* self, PyObject* args, PyObject* kwargs)
+int pysqlite_prepare_protocol_init(pysqlite_PrepareProtocol* self, PyObject* args, PyObject* kwargs)
{
return 0;
}
-void prepare_protocol_dealloc(SQLitePrepareProtocol* self)
+void pysqlite_prepare_protocol_dealloc(pysqlite_PrepareProtocol* self)
{
self->ob_type->tp_free((PyObject*)self);
}
-PyTypeObject SQLitePrepareProtocolType= {
+PyTypeObject pysqlite_PrepareProtocolType= {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
MODULE_NAME ".PrepareProtocol", /* tp_name */
- sizeof(SQLitePrepareProtocol), /* tp_basicsize */
+ sizeof(pysqlite_PrepareProtocol), /* tp_basicsize */
0, /* tp_itemsize */
- (destructor)prepare_protocol_dealloc, /* tp_dealloc */
+ (destructor)pysqlite_prepare_protocol_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
@@ -70,15 +70,15 @@
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
- (initproc)prepare_protocol_init, /* tp_init */
+ (initproc)pysqlite_prepare_protocol_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0 /* tp_free */
};
-extern int prepare_protocol_setup_types(void)
+extern int pysqlite_prepare_protocol_setup_types(void)
{
- SQLitePrepareProtocolType.tp_new = PyType_GenericNew;
- SQLitePrepareProtocolType.ob_type= &PyType_Type;
- return PyType_Ready(&SQLitePrepareProtocolType);
+ pysqlite_PrepareProtocolType.tp_new = PyType_GenericNew;
+ pysqlite_PrepareProtocolType.ob_type= &PyType_Type;
+ return PyType_Ready(&pysqlite_PrepareProtocolType);
}
Modified: python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.h
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.h (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/prepare_protocol.h Fri Feb 23 18:29:35 2007
@@ -28,14 +28,14 @@
typedef struct
{
PyObject_HEAD
-} SQLitePrepareProtocol;
+} pysqlite_PrepareProtocol;
-extern PyTypeObject SQLitePrepareProtocolType;
+extern PyTypeObject pysqlite_PrepareProtocolType;
-int prepare_protocol_init(SQLitePrepareProtocol* self, PyObject* args, PyObject* kwargs);
-void prepare_protocol_dealloc(SQLitePrepareProtocol* self);
+int pysqlite_prepare_protocol_init(pysqlite_PrepareProtocol* self, PyObject* args, PyObject* kwargs);
+void pysqlite_prepare_protocol_dealloc(pysqlite_PrepareProtocol* self);
-int prepare_protocol_setup_types(void);
+int pysqlite_prepare_protocol_setup_types(void);
#define UNKNOWN (-1)
#endif
Modified: python/branches/p3yk-noslice/Modules/_sqlite/row.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/row.c (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/row.c Fri Feb 23 18:29:35 2007
@@ -25,7 +25,7 @@
#include "cursor.h"
#include "sqlitecompat.h"
-void row_dealloc(Row* self)
+void pysqlite_row_dealloc(pysqlite_Row* self)
{
Py_XDECREF(self->data);
Py_XDECREF(self->description);
@@ -33,10 +33,10 @@
self->ob_type->tp_free((PyObject*)self);
}
-int row_init(Row* self, PyObject* args, PyObject* kwargs)
+int pysqlite_row_init(pysqlite_Row* self, PyObject* args, PyObject* kwargs)
{
PyObject* data;
- Cursor* cursor;
+ pysqlite_Cursor* cursor;
self->data = 0;
self->description = 0;
@@ -45,7 +45,7 @@
return -1;
}
- if (!PyObject_IsInstance((PyObject*)cursor, (PyObject*)&CursorType)) {
+ if (!PyObject_IsInstance((PyObject*)cursor, (PyObject*)&pysqlite_CursorType)) {
PyErr_SetString(PyExc_TypeError, "instance of cursor required for first argument");
return -1;
}
@@ -64,7 +64,7 @@
return 0;
}
-PyObject* row_subscript(Row* self, PyObject* idx)
+PyObject* pysqlite_row_subscript(pysqlite_Row* self, PyObject* idx)
{
long _idx;
char* key;
@@ -133,32 +133,63 @@
}
}
-Py_ssize_t row_length(Row* self, PyObject* args, PyObject* kwargs)
+Py_ssize_t pysqlite_row_length(pysqlite_Row* self, PyObject* args, PyObject* kwargs)
{
return PyTuple_GET_SIZE(self->data);
}
-static int row_print(Row* self, FILE *fp, int flags)
+PyObject* pysqlite_row_keys(pysqlite_Row* self, PyObject* args, PyObject* kwargs)
+{
+ PyObject* list;
+ int nitems, i;
+
+ list = PyList_New(0);
+ if (!list) {
+ return NULL;
+ }
+ nitems = PyTuple_Size(self->description);
+
+ for (i = 0; i < nitems; i++) {
+ if (PyList_Append(list, PyTuple_GET_ITEM(PyTuple_GET_ITEM(self->description, i), 0)) != 0) {
+ Py_DECREF(list);
+ return NULL;
+ }
+ }
+
+ return list;
+}
+
+static int pysqlite_row_print(pysqlite_Row* self, FILE *fp, int flags)
{
return (&PyTuple_Type)->tp_print(self->data, fp, flags);
}
+static PyObject* pysqlite_iter(pysqlite_Row* self)
+{
+ return PyObject_GetIter(self->data);
+}
-PyMappingMethods row_as_mapping = {
- /* mp_length */ (lenfunc)row_length,
- /* mp_subscript */ (binaryfunc)row_subscript,
+PyMappingMethods pysqlite_row_as_mapping = {
+ /* mp_length */ (lenfunc)pysqlite_row_length,
+ /* mp_subscript */ (binaryfunc)pysqlite_row_subscript,
/* mp_ass_subscript */ (objobjargproc)0,
};
+static PyMethodDef pysqlite_row_methods[] = {
+ {"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
+ PyDoc_STR("Returns the keys of the row.")},
+ {NULL, NULL}
+};
+
-PyTypeObject RowType = {
+PyTypeObject pysqlite_RowType = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
MODULE_NAME ".Row", /* tp_name */
- sizeof(Row), /* tp_basicsize */
+ sizeof(pysqlite_Row), /* tp_basicsize */
0, /* tp_itemsize */
- (destructor)row_dealloc, /* tp_dealloc */
- (printfunc)row_print, /* tp_print */
+ (destructor)pysqlite_row_dealloc, /* tp_dealloc */
+ (printfunc)pysqlite_row_print, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
@@ -174,13 +205,13 @@
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
0, /* tp_doc */
- 0, /* tp_traverse */
+ (traverseproc)0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
- 0, /* tp_iter */
+ (getiterfunc)pysqlite_iter, /* tp_iter */
0, /* tp_iternext */
- 0, /* tp_methods */
+ pysqlite_row_methods, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
@@ -188,15 +219,15 @@
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
- (initproc)row_init, /* tp_init */
+ (initproc)pysqlite_row_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0 /* tp_free */
};
-extern int row_setup_types(void)
+extern int pysqlite_row_setup_types(void)
{
- RowType.tp_new = PyType_GenericNew;
- RowType.tp_as_mapping = &row_as_mapping;
- return PyType_Ready(&RowType);
+ pysqlite_RowType.tp_new = PyType_GenericNew;
+ pysqlite_RowType.tp_as_mapping = &pysqlite_row_as_mapping;
+ return PyType_Ready(&pysqlite_RowType);
}
Modified: python/branches/p3yk-noslice/Modules/_sqlite/row.h
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/row.h (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/row.h Fri Feb 23 18:29:35 2007
@@ -30,10 +30,10 @@
PyObject_HEAD
PyObject* data;
PyObject* description;
-} Row;
+} pysqlite_Row;
-extern PyTypeObject RowType;
+extern PyTypeObject pysqlite_RowType;
-int row_setup_types(void);
+int pysqlite_row_setup_types(void);
#endif
Modified: python/branches/p3yk-noslice/Modules/_sqlite/statement.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/statement.c (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/statement.c Fri Feb 23 18:29:35 2007
@@ -29,7 +29,7 @@
#include "sqlitecompat.h"
/* prototypes */
-int check_remaining_sql(const char* tail);
+static int pysqlite_check_remaining_sql(const char* tail);
typedef enum {
LINECOMMENT_1,
@@ -40,7 +40,7 @@
NORMAL
} parse_remaining_sql_state;
-int statement_create(Statement* self, Connection* connection, PyObject* sql)
+int pysqlite_statement_create(pysqlite_Statement* self, pysqlite_Connection* connection, PyObject* sql)
{
const char* tail;
int rc;
@@ -77,7 +77,7 @@
self->db = connection->db;
- if (rc == SQLITE_OK && check_remaining_sql(tail)) {
+ if (rc == SQLITE_OK && pysqlite_check_remaining_sql(tail)) {
(void)sqlite3_finalize(self->st);
self->st = NULL;
rc = PYSQLITE_TOO_MUCH_SQL;
@@ -86,7 +86,7 @@
return rc;
}
-int statement_bind_parameter(Statement* self, int pos, PyObject* parameter)
+int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter)
{
int rc = SQLITE_OK;
long longval;
@@ -100,7 +100,7 @@
if (parameter == Py_None) {
rc = sqlite3_bind_null(self->st, pos);
- } else if (PyInt_Check(parameter)) {
+ } else if (PyInt_CheckExact(parameter)) {
longval = PyInt_AsLong(parameter);
rc = sqlite3_bind_int64(self->st, pos, (sqlite_int64)longval);
#ifdef HAVE_LONG_LONG
@@ -133,7 +133,7 @@
return rc;
}
-void statement_bind_parameters(Statement* self, PyObject* parameters)
+void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters)
{
PyObject* current_param;
PyObject* adapted;
@@ -154,19 +154,19 @@
binding_name = sqlite3_bind_parameter_name(self->st, i);
Py_END_ALLOW_THREADS
if (!binding_name) {
- PyErr_Format(ProgrammingError, "Binding %d has no name, but you supplied a dictionary (which has only names).", i);
+ PyErr_Format(pysqlite_ProgrammingError, "Binding %d has no name, but you supplied a dictionary (which has only names).", i);
return;
}
binding_name++; /* skip first char (the colon) */
current_param = PyDict_GetItemString(parameters, binding_name);
if (!current_param) {
- PyErr_Format(ProgrammingError, "You did not supply a value for binding %d.", i);
+ PyErr_Format(pysqlite_ProgrammingError, "You did not supply a value for binding %d.", i);
return;
}
Py_INCREF(current_param);
- adapted = microprotocols_adapt(current_param, (PyObject*)&SQLitePrepareProtocolType, NULL);
+ adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL);
if (adapted) {
Py_DECREF(current_param);
} else {
@@ -174,11 +174,11 @@
adapted = current_param;
}
- rc = statement_bind_parameter(self, i, adapted);
+ rc = pysqlite_statement_bind_parameter(self, i, adapted);
Py_DECREF(adapted);
if (rc != SQLITE_OK) {
- PyErr_Format(InterfaceError, "Error binding parameter :%s - probably unsupported type.", binding_name);
+ PyErr_Format(pysqlite_InterfaceError, "Error binding parameter :%s - probably unsupported type.", binding_name);
return;
}
}
@@ -186,7 +186,7 @@
/* parameters passed as sequence */
num_params = PySequence_Length(parameters);
if (num_params != num_params_needed) {
- PyErr_Format(ProgrammingError, "Incorrect number of bindings supplied. The current statement uses %d, and there are %d supplied.",
+ PyErr_Format(pysqlite_ProgrammingError, "Incorrect number of bindings supplied. The current statement uses %d, and there are %d supplied.",
num_params_needed, num_params);
return;
}
@@ -195,7 +195,7 @@
if (!current_param) {
return;
}
- adapted = microprotocols_adapt(current_param, (PyObject*)&SQLitePrepareProtocolType, NULL);
+ adapted = microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL);
if (adapted) {
Py_DECREF(current_param);
@@ -204,18 +204,18 @@
adapted = current_param;
}
- rc = statement_bind_parameter(self, i + 1, adapted);
+ rc = pysqlite_statement_bind_parameter(self, i + 1, adapted);
Py_DECREF(adapted);
if (rc != SQLITE_OK) {
- PyErr_Format(InterfaceError, "Error binding parameter %d - probably unsupported type.", i);
+ PyErr_Format(pysqlite_InterfaceError, "Error binding parameter %d - probably unsupported type.", i);
return;
}
}
}
}
-int statement_recompile(Statement* self, PyObject* params)
+int pysqlite_statement_recompile(pysqlite_Statement* self, PyObject* params)
{
const char* tail;
int rc;
@@ -250,7 +250,7 @@
return rc;
}
-int statement_finalize(Statement* self)
+int pysqlite_statement_finalize(pysqlite_Statement* self)
{
int rc;
@@ -267,7 +267,7 @@
return rc;
}
-int statement_reset(Statement* self)
+int pysqlite_statement_reset(pysqlite_Statement* self)
{
int rc;
@@ -286,12 +286,12 @@
return rc;
}
-void statement_mark_dirty(Statement* self)
+void pysqlite_statement_mark_dirty(pysqlite_Statement* self)
{
self->in_use = 1;
}
-void statement_dealloc(Statement* self)
+void pysqlite_statement_dealloc(pysqlite_Statement* self)
{
int rc;
@@ -320,7 +320,7 @@
*
* Returns 1 if there is more left than should be. 0 if ok.
*/
-int check_remaining_sql(const char* tail)
+static int pysqlite_check_remaining_sql(const char* tail)
{
const char* pos = tail;
@@ -382,13 +382,13 @@
return 0;
}
-PyTypeObject StatementType = {
+PyTypeObject pysqlite_StatementType = {
PyObject_HEAD_INIT(NULL)
0, /* ob_size */
MODULE_NAME ".Statement", /* tp_name */
- sizeof(Statement), /* tp_basicsize */
+ sizeof(pysqlite_Statement), /* tp_basicsize */
0, /* tp_itemsize */
- (destructor)statement_dealloc, /* tp_dealloc */
+ (destructor)pysqlite_statement_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
@@ -408,7 +408,7 @@
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
- offsetof(Statement, in_weakreflist), /* tp_weaklistoffset */
+ offsetof(pysqlite_Statement, in_weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
@@ -425,8 +425,8 @@
0 /* tp_free */
};
-extern int statement_setup_types(void)
+extern int pysqlite_statement_setup_types(void)
{
- StatementType.tp_new = PyType_GenericNew;
- return PyType_Ready(&StatementType);
+ pysqlite_StatementType.tp_new = PyType_GenericNew;
+ return PyType_Ready(&pysqlite_StatementType);
}
Modified: python/branches/p3yk-noslice/Modules/_sqlite/statement.h
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/statement.h (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/statement.h Fri Feb 23 18:29:35 2007
@@ -39,21 +39,21 @@
PyObject* sql;
int in_use;
PyObject* in_weakreflist; /* List of weak references */
-} Statement;
+} pysqlite_Statement;
-extern PyTypeObject StatementType;
+extern PyTypeObject pysqlite_StatementType;
-int statement_create(Statement* self, Connection* connection, PyObject* sql);
-void statement_dealloc(Statement* self);
+int pysqlite_statement_create(pysqlite_Statement* self, pysqlite_Connection* connection, PyObject* sql);
+void pysqlite_statement_dealloc(pysqlite_Statement* self);
-int statement_bind_parameter(Statement* self, int pos, PyObject* parameter);
-void statement_bind_parameters(Statement* self, PyObject* parameters);
+int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter);
+void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters);
-int statement_recompile(Statement* self, PyObject* parameters);
-int statement_finalize(Statement* self);
-int statement_reset(Statement* self);
-void statement_mark_dirty(Statement* self);
+int pysqlite_statement_recompile(pysqlite_Statement* self, PyObject* parameters);
+int pysqlite_statement_finalize(pysqlite_Statement* self);
+int pysqlite_statement_reset(pysqlite_Statement* self);
+void pysqlite_statement_mark_dirty(pysqlite_Statement* self);
-int statement_setup_types(void);
+int pysqlite_statement_setup_types(void);
#endif
Modified: python/branches/p3yk-noslice/Modules/_sqlite/util.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/util.c (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/util.c Fri Feb 23 18:29:35 2007
@@ -24,8 +24,7 @@
#include "module.h"
#include "connection.h"
-int _sqlite_step_with_busyhandler(sqlite3_stmt* statement, Connection* connection
-)
+int _sqlite_step_with_busyhandler(sqlite3_stmt* statement, pysqlite_Connection* connection)
{
int rc;
@@ -40,7 +39,7 @@
* Checks the SQLite error code and sets the appropriate DB-API exception.
* Returns the error code (0 means no error occurred).
*/
-int _seterror(sqlite3* db)
+int _pysqlite_seterror(sqlite3* db)
{
int errorcode;
@@ -53,7 +52,7 @@
break;
case SQLITE_INTERNAL:
case SQLITE_NOTFOUND:
- PyErr_SetString(InternalError, sqlite3_errmsg(db));
+ PyErr_SetString(pysqlite_InternalError, sqlite3_errmsg(db));
break;
case SQLITE_NOMEM:
(void)PyErr_NoMemory();
@@ -71,23 +70,23 @@
case SQLITE_PROTOCOL:
case SQLITE_EMPTY:
case SQLITE_SCHEMA:
- PyErr_SetString(OperationalError, sqlite3_errmsg(db));
+ PyErr_SetString(pysqlite_OperationalError, sqlite3_errmsg(db));
break;
case SQLITE_CORRUPT:
- PyErr_SetString(DatabaseError, sqlite3_errmsg(db));
+ PyErr_SetString(pysqlite_DatabaseError, sqlite3_errmsg(db));
break;
case SQLITE_TOOBIG:
- PyErr_SetString(DataError, sqlite3_errmsg(db));
+ PyErr_SetString(pysqlite_DataError, sqlite3_errmsg(db));
break;
case SQLITE_CONSTRAINT:
case SQLITE_MISMATCH:
- PyErr_SetString(IntegrityError, sqlite3_errmsg(db));
+ PyErr_SetString(pysqlite_IntegrityError, sqlite3_errmsg(db));
break;
case SQLITE_MISUSE:
- PyErr_SetString(ProgrammingError, sqlite3_errmsg(db));
+ PyErr_SetString(pysqlite_ProgrammingError, sqlite3_errmsg(db));
break;
default:
- PyErr_SetString(DatabaseError, sqlite3_errmsg(db));
+ PyErr_SetString(pysqlite_DatabaseError, sqlite3_errmsg(db));
break;
}
Modified: python/branches/p3yk-noslice/Modules/_sqlite/util.h
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sqlite/util.h (original)
+++ python/branches/p3yk-noslice/Modules/_sqlite/util.h Fri Feb 23 18:29:35 2007
@@ -28,11 +28,11 @@
#include "sqlite3.h"
#include "connection.h"
-int _sqlite_step_with_busyhandler(sqlite3_stmt* statement, Connection* connection);
+int _sqlite_step_with_busyhandler(sqlite3_stmt* statement, pysqlite_Connection* connection);
/**
* Checks the SQLite error code and sets the appropriate DB-API exception.
* Returns the error code (0 means no error occurred).
*/
-int _seterror(sqlite3* db);
+int _pysqlite_seterror(sqlite3* db);
#endif
Modified: python/branches/p3yk-noslice/Modules/_sre.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_sre.c (original)
+++ python/branches/p3yk-noslice/Modules/_sre.c Fri Feb 23 18:29:35 2007
@@ -2688,8 +2688,7 @@
for (i = 0; i < n; i++) {
PyObject *o = PyList_GET_ITEM(code, i);
- unsigned long value = PyInt_Check(o) ? (unsigned long)PyInt_AsLong(o)
- : PyLong_AsUnsignedLong(o);
+ unsigned long value = PyLong_AsUnsignedLong(o);
self->code[i] = (SRE_CODE) value;
if ((unsigned long) self->code[i] != value) {
PyErr_SetString(PyExc_OverflowError,
@@ -2763,6 +2762,10 @@
{
Py_ssize_t i;
+ if (index == NULL)
+ /* Default value */
+ return 0;
+
if (PyInt_Check(index))
return PyInt_AsSsize_t(index);
@@ -2913,7 +2916,7 @@
{
Py_ssize_t index;
- PyObject* index_ = Py_False; /* zero */
+ PyObject* index_ = NULL;
if (!PyArg_UnpackTuple(args, "start", 0, 1, &index_))
return NULL;
@@ -2936,7 +2939,7 @@
{
Py_ssize_t index;
- PyObject* index_ = Py_False; /* zero */
+ PyObject* index_ = NULL;
if (!PyArg_UnpackTuple(args, "end", 0, 1, &index_))
return NULL;
@@ -2986,7 +2989,7 @@
{
Py_ssize_t index;
- PyObject* index_ = Py_False; /* zero */
+ PyObject* index_ = NULL;
if (!PyArg_UnpackTuple(args, "span", 0, 1, &index_))
return NULL;
Modified: python/branches/p3yk-noslice/Modules/_struct.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_struct.c (original)
+++ python/branches/p3yk-noslice/Modules/_struct.c Fri Feb 23 18:29:35 2007
@@ -104,6 +104,15 @@
#define LONG_LONG_ALIGN (sizeof(s_long_long) - sizeof(PY_LONG_LONG))
#endif
+#ifdef HAVE_C99_BOOL
+#define BOOL_TYPE _Bool
+typedef struct { char c; _Bool x; } s_bool;
+#define BOOL_ALIGN (sizeof(s_bool) - sizeof(BOOL_TYPE))
+#else
+#define BOOL_TYPE char
+#define BOOL_ALIGN 0
+#endif
+
#define STRINGIFY(x) #x
#ifdef __powerc
@@ -118,8 +127,6 @@
PyNumberMethods *m;
assert(v != NULL);
- if (PyInt_Check(v))
- return PyLong_FromLong(PyInt_AS_LONG(v));
if (PyLong_Check(v)) {
Py_INCREF(v);
return v;
@@ -536,6 +543,15 @@
#endif
static PyObject *
+nu_bool(const char *p, const formatdef *f)
+{
+ BOOL_TYPE x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyBool_FromLong(x != 0);
+}
+
+
+static PyObject *
nu_float(const char *p, const formatdef *f)
{
float x;
@@ -711,6 +727,16 @@
}
#endif
+
+static int
+np_bool(char *p, PyObject *v, const formatdef *f)
+{
+ BOOL_TYPE y;
+ y = PyObject_IsTrue(v);
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
+}
+
static int
np_float(char *p, PyObject *v, const formatdef *f)
{
@@ -771,6 +797,7 @@
{'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
{'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
#endif
+ {'t', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
{'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
{'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
{'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
@@ -865,6 +892,14 @@
return unpack_double(p, 0);
}
+static PyObject *
+bu_bool(const char *p, const formatdef *f)
+{
+ char x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyBool_FromLong(x != 0);
+}
+
static int
bp_int(char *p, PyObject *v, const formatdef *f)
{
@@ -969,6 +1004,15 @@
return _PyFloat_Pack8(x, (unsigned char *)p, 0);
}
+static int
+bp_bool(char *p, PyObject *v, const formatdef *f)
+{
+ char y;
+ y = PyObject_IsTrue(v);
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
+}
+
static formatdef bigendian_table[] = {
{'x', 1, 0, NULL},
#ifdef PY_STRUCT_OVERFLOW_MASKING
@@ -990,6 +1034,7 @@
{'L', 4, 0, bu_uint, bp_uint},
{'q', 8, 0, bu_longlong, bp_longlong},
{'Q', 8, 0, bu_ulonglong, bp_ulonglong},
+ {'t', 1, 0, bu_bool, bp_bool},
{'f', 4, 0, bu_float, bp_float},
{'d', 8, 0, bu_double, bp_double},
{0}
@@ -1208,6 +1253,8 @@
{'L', 4, 0, lu_uint, lp_uint},
{'q', 8, 0, lu_longlong, lp_longlong},
{'Q', 8, 0, lu_ulonglong, lp_ulonglong},
+ {'t', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
+ but potentially different from native rep -- reuse bx_bool funcs. */
{'f', 4, 0, lu_float, lp_float},
{'d', 8, 0, lu_double, lp_double},
{0}
Modified: python/branches/p3yk-noslice/Modules/_testcapimodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_testcapimodule.c (original)
+++ python/branches/p3yk-noslice/Modules/_testcapimodule.c Fri Feb 23 18:29:35 2007
@@ -718,6 +718,119 @@
Py_RETURN_NONE;
}
+#ifdef HAVE_GETTIMEOFDAY
+/* Profiling of integer performance */
+void print_delta(int test, struct timeval *s, struct timeval *e)
+{
+ e->tv_sec -= s->tv_sec;
+ e->tv_usec -= s->tv_usec;
+ if (e->tv_usec < 0) {
+ e->tv_sec -=1;
+ e->tv_usec += 1000000;
+ }
+ printf("Test %d: %d.%06ds\n", test, (int)e->tv_sec, e->tv_usec);
+}
+
+static PyObject *
+profile_int(PyObject *self, PyObject* args)
+{
+ int i, k;
+ struct timeval start, stop;
+ PyObject *single, **multiple, *op1, *result;
+
+ /* Test 1: Allocate and immediately deallocate
+ many small integers */
+ gettimeofday(&start, NULL);
+ for(k=0; k < 20000; k++)
+ for(i=0; i < 1000; i++) {
+ single = PyInt_FromLong(i);
+ Py_DECREF(single);
+ }
+ gettimeofday(&stop, NULL);
+ print_delta(1, &start, &stop);
+
+ /* Test 2: Allocate and immediately deallocate
+ many large integers */
+ gettimeofday(&start, NULL);
+ for(k=0; k < 20000; k++)
+ for(i=0; i < 1000; i++) {
+ single = PyInt_FromLong(i+1000000);
+ Py_DECREF(single);
+ }
+ gettimeofday(&stop, NULL);
+ print_delta(2, &start, &stop);
+
+ /* Test 3: Allocate a few integers, then release
+ them all simultaneously. */
+ multiple = malloc(sizeof(PyObject*) * 1000);
+ gettimeofday(&start, NULL);
+ for(k=0; k < 20000; k++) {
+ for(i=0; i < 1000; i++) {
+ multiple[i] = PyInt_FromLong(i+1000000);
+ }
+ for(i=0; i < 1000; i++) {
+ Py_DECREF(multiple[i]);
+ }
+ }
+ gettimeofday(&stop, NULL);
+ print_delta(3, &start, &stop);
+
+ /* Test 4: Allocate many integers, then release
+ them all simultaneously. */
+ multiple = malloc(sizeof(PyObject*) * 1000000);
+ gettimeofday(&start, NULL);
+ for(k=0; k < 20; k++) {
+ for(i=0; i < 1000000; i++) {
+ multiple[i] = PyInt_FromLong(i+1000000);
+ }
+ for(i=0; i < 1000000; i++) {
+ Py_DECREF(multiple[i]);
+ }
+ }
+ gettimeofday(&stop, NULL);
+ print_delta(4, &start, &stop);
+
+ /* Test 5: Allocate many integers < 32000 */
+ multiple = malloc(sizeof(PyObject*) * 1000000);
+ gettimeofday(&start, NULL);
+ for(k=0; k < 10; k++) {
+ for(i=0; i < 1000000; i++) {
+ multiple[i] = PyInt_FromLong(i+1000);
+ }
+ for(i=0; i < 1000000; i++) {
+ Py_DECREF(multiple[i]);
+ }
+ }
+ gettimeofday(&stop, NULL);
+ print_delta(5, &start, &stop);
+
+ /* Test 6: Perform small int addition */
+ op1 = PyInt_FromLong(1);
+ gettimeofday(&start, NULL);
+ for(i=0; i < 10000000; i++) {
+ result = PyNumber_Add(op1, op1);
+ Py_DECREF(result);
+ }
+ gettimeofday(&stop, NULL);
+ Py_DECREF(op1);
+ print_delta(6, &start, &stop);
+
+ /* Test 7: Perform medium int addition */
+ op1 = PyInt_FromLong(1000);
+ gettimeofday(&start, NULL);
+ for(i=0; i < 10000000; i++) {
+ result = PyNumber_Add(op1, op1);
+ Py_DECREF(result);
+ }
+ gettimeofday(&stop, NULL);
+ Py_DECREF(op1);
+ print_delta(7, &start, &stop);
+
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+#endif
+
static PyMethodDef TestMethods[] = {
{"raise_exception", raise_exception, METH_VARARGS},
{"test_config", (PyCFunction)test_config, METH_NOARGS},
@@ -756,6 +869,9 @@
#ifdef WITH_THREAD
{"_test_thread_state", test_thread_state, METH_VARARGS},
#endif
+#ifdef HAVE_GETTIMEOFDAY
+ {"profile_int", profile_int, METH_NOARGS},
+#endif
{NULL, NULL} /* sentinel */
};
Modified: python/branches/p3yk-noslice/Modules/_tkinter.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/_tkinter.c (original)
+++ python/branches/p3yk-noslice/Modules/_tkinter.c Fri Feb 23 18:29:35 2007
@@ -913,7 +913,7 @@
PyString_GET_SIZE(value));
else if (PyBool_Check(value))
return Tcl_NewBooleanObj(PyObject_IsTrue(value));
- else if (PyInt_Check(value))
+ else if (PyInt_CheckExact(value))
return Tcl_NewLongObj(PyInt_AS_LONG(value));
else if (PyFloat_Check(value))
return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value));
Modified: python/branches/p3yk-noslice/Modules/arraymodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/arraymodule.c (original)
+++ python/branches/p3yk-noslice/Modules/arraymodule.c Fri Feb 23 18:29:35 2007
@@ -1846,7 +1846,7 @@
PyObject *initial = NULL, *it = NULL;
struct arraydescr *descr;
- if (!_PyArg_NoKeywords("array.array()", kwds))
+ if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
return NULL;
if (!PyArg_ParseTuple(args, "c|O:array", &c, &initial))
Modified: python/branches/p3yk-noslice/Modules/bz2module.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/bz2module.c (original)
+++ python/branches/p3yk-noslice/Modules/bz2module.c Fri Feb 23 18:29:35 2007
@@ -102,8 +102,6 @@
char* f_bufend; /* Points after last occupied position */
char* f_bufptr; /* Current buffer position */
- int f_softspace; /* Flag used by 'print' command */
-
int f_univ_newline; /* Handle any newline convention */
int f_newlinetypes; /* Types of newlines seen */
int f_skipnextlf; /* Skip next \n */
@@ -813,8 +811,6 @@
goto cleanup;
}
- self->f_softspace = 0;
-
Py_BEGIN_ALLOW_THREADS
BZ2_bzWrite (&bzerror, self->fp, buf, len);
self->pos += len;
@@ -934,8 +930,6 @@
}
}
- self->f_softspace = 0;
-
/* Since we are releasing the global lock, the
following code may *not* execute Python code. */
Py_BEGIN_ALLOW_THREADS
@@ -1265,18 +1259,6 @@
/* ===================================================================== */
-/* Members of BZ2File_Type. */
-
-#undef OFF
-#define OFF(x) offsetof(BZ2FileObject, x)
-
-static PyMemberDef BZ2File_members[] = {
- {"softspace", T_INT, OFF(f_softspace), 0,
- "flag indicating that a space needs to be printed; used by print"},
- {NULL} /* Sentinel */
-};
-
-/* ===================================================================== */
/* Slot definitions for BZ2File_Type. */
static int
@@ -1501,7 +1483,7 @@
(getiterfunc)BZ2File_getiter, /*tp_iter*/
(iternextfunc)BZ2File_iternext, /*tp_iternext*/
BZ2File_methods, /*tp_methods*/
- BZ2File_members, /*tp_members*/
+ 0, /*tp_members*/
BZ2File_getset, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
Modified: python/branches/p3yk-noslice/Modules/cPickle.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/cPickle.c (original)
+++ python/branches/p3yk-noslice/Modules/cPickle.c Fri Feb 23 18:29:35 2007
@@ -711,7 +711,9 @@
PyErr_SetString(PicklingError, "no int where int expected in memo");
return -1;
}
- c_value = PyInt_AS_LONG((PyIntObject*)value);
+ c_value = PyInt_AsLong(value);
+ if (c_value == -1 && PyErr_Occurred())
+ return -1;
if (!self->bin) {
s[0] = GET;
@@ -958,7 +960,7 @@
{
static const char *buf[2] = {FALSE, TRUE};
static char len[2] = {sizeof(FALSE)-1, sizeof(TRUE)-1};
- long l = PyInt_AS_LONG((PyIntObject *)args);
+ long l = args == Py_True;
if (self->proto >= 2) {
char opcode = l ? NEWTRUE : NEWFALSE;
@@ -971,10 +973,9 @@
}
static int
-save_int(Picklerobject *self, PyObject *args)
+save_int(Picklerobject *self, long l)
{
char c_str[32];
- long l = PyInt_AS_LONG((PyIntObject *)args);
int len = 0;
if (!self->bin
@@ -1027,9 +1028,16 @@
Py_ssize_t size;
int res = -1;
PyObject *repr = NULL;
-
+ int val = PyInt_AsLong(args);
static char l = LONG;
+ if (val == -1 && PyErr_Occurred()) {
+ /* out of range for int pickling */
+ PyErr_Clear();
+ }
+ else
+ return save_int(self, val);
+
if (self->proto >= 2) {
/* Linear-time pickling. */
size_t nbits;
@@ -1744,7 +1752,7 @@
int res = -1;
char s[3];
int len;
- PyObject *iter;
+ PyObject *items, *iter;
if (self->fast && !fast_save_enter(self, args))
goto finally;
@@ -1776,7 +1784,11 @@
goto finally;
/* Materialize the dict items. */
- iter = PyObject_CallMethod(args, "iteritems", "()");
+ items = PyObject_CallMethod(args, "items", "()");
+ if (items == NULL)
+ goto finally;
+ iter = PyObject_GetIter(items);
+ Py_DECREF(items);
if (iter == NULL)
goto finally;
res = batch_dict(self, iter);
@@ -2184,13 +2196,6 @@
}
break;
case 'i':
- if (type == &PyInt_Type) {
- res = save_int(self, args);
- goto finally;
- }
- break;
-
- case 'l':
if (type == &PyLong_Type) {
res = save_long(self, args);
goto finally;
@@ -2486,7 +2491,9 @@
rsize += PyString_GET_SIZE(k);
else if (PyInt_Check(k)) { /* put */
- ik = PyInt_AS_LONG((PyIntObject*)k);
+ ik = PyInt_AsLong(k);
+ if (ik == -1 && PyErr_Occurred())
+ goto err;
if (ik >= lm || ik == 0) {
PyErr_SetString(PicklingError,
"Invalid get data");
@@ -2506,7 +2513,9 @@
}
else { /* put */
- ik = PyInt_AS_LONG((PyIntObject *)k);
+ ik = PyInt_AsLong(k);
+ if (ik == -1 && PyErr_Occurred())
+ goto err;
if (ik >= lm || ik == 0) {
PyErr_SetString(PicklingError,
"Invalid get data");
@@ -2535,8 +2544,9 @@
}
else if (PyTuple_Check(k)) { /* get */
- ik = PyInt_AS_LONG((PyIntObject *)
- PyTuple_GET_ITEM(k, 0));
+ ik = PyLong_AsLong(PyTuple_GET_ITEM(k, 0));
+ if (ik == -1 && PyErr_Occurred())
+ goto err;
if (ik < 256) {
*s++ = BINGET;
*s++ = (int)(ik & 0xff);
@@ -2551,7 +2561,9 @@
}
else { /* put */
- ik = PyInt_AS_LONG((PyIntObject*)k);
+ ik = PyLong_AsLong(k);
+ if (ik == -1 && PyErr_Occurred())
+ goto err;
if (have_get[ik]) { /* with matching get */
if (ik < 256) {
Modified: python/branches/p3yk-noslice/Modules/cStringIO.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/cStringIO.c (original)
+++ python/branches/p3yk-noslice/Modules/cStringIO.c Fri Feb 23 18:29:35 2007
@@ -57,7 +57,6 @@
Py_ssize_t pos, string_size;
Py_ssize_t buf_size;
- int softspace;
} Oobject;
/* Declarations for objects of type StringI */
@@ -489,13 +488,6 @@
{NULL, NULL} /* sentinel */
};
-static PyMemberDef O_memberlist[] = {
- {"softspace", T_INT, offsetof(Oobject, softspace), 0,
- "flag indicating that a space needs to be printed; used by print"},
- /* getattr(f, "closed") is implemented without this table */
- {NULL} /* Sentinel */
-};
-
static void
O_dealloc(Oobject *self) {
if (self->buf != NULL)
@@ -536,7 +528,7 @@
PyObject_SelfIter, /*tp_iter */
(iternextfunc)IO_iternext, /*tp_iternext */
O_methods, /*tp_methods */
- O_memberlist, /*tp_members */
+ 0, /*tp_members */
file_getsetlist, /*tp_getset */
};
@@ -549,7 +541,6 @@
return NULL;
self->pos=0;
self->string_size = 0;
- self->softspace = 0;
self->buf = (char *)malloc(size);
if (!self->buf) {
Modified: python/branches/p3yk-noslice/Modules/cjkcodecs/multibytecodec.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/cjkcodecs/multibytecodec.c (original)
+++ python/branches/p3yk-noslice/Modules/cjkcodecs/multibytecodec.c Fri Feb 23 18:29:35 2007
@@ -1314,6 +1314,9 @@
return NULL;
}
+ if (size == -1 && PyErr_Occurred())
+ return NULL;
+
return mbstreamreader_iread(self, "read", size);
}
@@ -1335,6 +1338,9 @@
return NULL;
}
+ if (size == -1 && PyErr_Occurred())
+ return NULL;
+
return mbstreamreader_iread(self, "readline", size);
}
@@ -1356,6 +1362,9 @@
return NULL;
}
+ if (sizehint == -1 && PyErr_Occurred())
+ return NULL;
+
r = mbstreamreader_iread(self, "read", sizehint);
if (r == NULL)
return NULL;
Modified: python/branches/p3yk-noslice/Modules/collectionsmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/collectionsmodule.c (original)
+++ python/branches/p3yk-noslice/Modules/collectionsmodule.c Fri Feb 23 18:29:35 2007
@@ -95,7 +95,7 @@
dequeobject *deque;
block *b;
- if (!_PyArg_NoKeywords("deque()", kwds))
+ if (type == &deque_type && !_PyArg_NoKeywords("deque()", kwds))
return NULL;
/* create dequeobject structure */
@@ -1140,6 +1140,7 @@
*/
PyObject *args;
PyObject *items;
+ PyObject *iteritems;
PyObject *result;
if (dd->default_factory == NULL || dd->default_factory == Py_None)
args = PyTuple_New(0);
@@ -1147,14 +1148,20 @@
args = PyTuple_Pack(1, dd->default_factory);
if (args == NULL)
return NULL;
- items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
+ items = PyObject_CallMethod((PyObject *)dd, "items", "()");
if (items == NULL) {
Py_DECREF(args);
return NULL;
}
- result = PyTuple_Pack(5, dd->dict.ob_type, args,
- Py_None, Py_None, items);
+ iteritems = PyObject_GetIter(items);
Py_DECREF(items);
+ if (iteritems == NULL) {
+ Py_DECREF(args);
+ return NULL;
+ }
+ result = PyTuple_Pack(5, dd->dict.ob_type, args,
+ Py_None, Py_None, iteritems);
+ Py_DECREF(iteritems);
Py_DECREF(args);
return result;
}
@@ -1252,8 +1259,14 @@
newargs = PyTuple_New(0);
else {
Py_ssize_t n = PyTuple_GET_SIZE(args);
- if (n > 0)
+ if (n > 0) {
newdefault = PyTuple_GET_ITEM(args, 0);
+ if (!PyCallable_Check(newdefault)) {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be callable");
+ return -1;
+ }
+ }
newargs = PySequence_GetSlice(args, 1, n);
}
if (newargs == NULL)
Modified: python/branches/p3yk-noslice/Modules/datetimemodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/datetimemodule.c (original)
+++ python/branches/p3yk-noslice/Modules/datetimemodule.c Fri Feb 23 18:29:35 2007
@@ -1844,10 +1844,7 @@
* lose a little info.
*/
assert(PyInt_Check(factor) || PyLong_Check(factor));
- if (PyInt_Check(factor))
- dnum = (double)PyInt_AsLong(factor);
- else
- dnum = PyLong_AsDouble(factor);
+ dnum = PyLong_AsDouble(factor);
dnum *= fracpart;
fracpart = modf(dnum, &intpart);
@@ -3141,7 +3138,7 @@
}
static PyObject *
-time_isoformat(PyDateTime_Time *self)
+time_isoformat(PyDateTime_Time *self, PyObject *unused)
{
char buf[100];
PyObject *result;
@@ -3377,7 +3374,7 @@
static PyMethodDef time_methods[] = {
- {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS,
+ {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
"[+HH:MM].")},
@@ -3800,7 +3797,7 @@
Py_DECREF(obj);
return NULL;
}
- if (PyInt_Check(p))
+ if (PyInt_CheckExact(p))
ia[i] = PyInt_AsLong(p);
else
good_timetuple = 0;
Modified: python/branches/p3yk-noslice/Modules/dlmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/dlmodule.c (original)
+++ python/branches/p3yk-noslice/Modules/dlmodule.c Fri Feb 23 18:29:35 2007
@@ -107,9 +107,11 @@
}
for (i = 1; i < n; i++) {
PyObject *v = PyTuple_GetItem(args, i);
- if (PyInt_Check(v))
+ if (PyInt_Check(v)) {
alist[i-1] = PyInt_AsLong(v);
- else if (PyString_Check(v))
+ if (alist[i-1] == -1 && PyErr_Occurred())
+ return NULL;
+ } else if (PyString_Check(v))
alist[i-1] = (long)PyString_AsString(v);
else if (v == Py_None)
alist[i-1] = (long) ((char *)NULL);
Modified: python/branches/p3yk-noslice/Modules/itertoolsmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/itertoolsmodule.c (original)
+++ python/branches/p3yk-noslice/Modules/itertoolsmodule.c Fri Feb 23 18:29:35 2007
@@ -681,7 +681,7 @@
PyObject *saved;
cycleobject *lz;
- if (!_PyArg_NoKeywords("cycle()", kwds))
+ if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds))
return NULL;
if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable))
@@ -831,7 +831,7 @@
PyObject *it;
dropwhileobject *lz;
- if (!_PyArg_NoKeywords("dropwhile()", kwds))
+ if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds))
return NULL;
if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq))
@@ -975,7 +975,7 @@
PyObject *it;
takewhileobject *lz;
- if (!_PyArg_NoKeywords("takewhile()", kwds))
+ if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds))
return NULL;
if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq))
@@ -1120,7 +1120,7 @@
Py_ssize_t numargs;
isliceobject *lz;
- if (!_PyArg_NoKeywords("islice()", kwds))
+ if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds))
return NULL;
if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3))
@@ -1311,7 +1311,7 @@
PyObject *it;
starmapobject *lz;
- if (!_PyArg_NoKeywords("starmap()", kwds))
+ if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds))
return NULL;
if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq))
@@ -1443,7 +1443,7 @@
imapobject *lz;
Py_ssize_t numargs, i;
- if (!_PyArg_NoKeywords("imap()", kwds))
+ if (type == &imap_type && !_PyArg_NoKeywords("imap()", kwds))
return NULL;
numargs = PyTuple_Size(args);
@@ -1625,7 +1625,7 @@
Py_ssize_t i;
PyObject *ittuple;
- if (!_PyArg_NoKeywords("chain()", kwds))
+ if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds))
return NULL;
/* obtain iterators */
@@ -1768,7 +1768,7 @@
PyObject *it;
ifilterobject *lz;
- if (!_PyArg_NoKeywords("ifilter()", kwds))
+ if (type == &ifilter_type && !_PyArg_NoKeywords("ifilter()", kwds))
return NULL;
if (!PyArg_UnpackTuple(args, "ifilter", 2, 2, &func, &seq))
@@ -1912,7 +1912,8 @@
PyObject *it;
ifilterfalseobject *lz;
- if (!_PyArg_NoKeywords("ifilterfalse()", kwds))
+ if (type == &ifilterfalse_type &&
+ !_PyArg_NoKeywords("ifilterfalse()", kwds))
return NULL;
if (!PyArg_UnpackTuple(args, "ifilterfalse", 2, 2, &func, &seq))
@@ -2054,7 +2055,7 @@
countobject *lz;
Py_ssize_t cnt = 0;
- if (!_PyArg_NoKeywords("count()", kwds))
+ if (type == &count_type && !_PyArg_NoKeywords("count()", kwds))
return NULL;
if (!PyArg_ParseTuple(args, "|n:count", &cnt))
@@ -2072,6 +2073,11 @@
static PyObject *
count_next(countobject *lz)
{
+ if (lz->cnt == LONG_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "cannot count beyond LONG_MAX");
+ return NULL;
+ }
return PyInt_FromSsize_t(lz->cnt++);
}
@@ -2153,7 +2159,7 @@
PyObject *result;
Py_ssize_t tuplesize = PySequence_Length(args);
- if (!_PyArg_NoKeywords("izip()", kwds))
+ if (type == &izip_type && !_PyArg_NoKeywords("izip()", kwds))
return NULL;
/* args must be a tuple */
@@ -2336,7 +2342,7 @@
PyObject *element;
Py_ssize_t cnt = -1;
- if (!_PyArg_NoKeywords("repeat()", kwds))
+ if (type == &repeat_type && !_PyArg_NoKeywords("repeat()", kwds))
return NULL;
if (!PyArg_ParseTuple(args, "O|n:repeat", &element, &cnt))
@@ -2466,6 +2472,234 @@
PyObject_GC_Del, /* tp_free */
};
+/* iziplongest object ************************************************************/
+
+#include "Python.h"
+
+typedef struct {
+ PyObject_HEAD
+ Py_ssize_t tuplesize;
+ Py_ssize_t numactive;
+ PyObject *ittuple; /* tuple of iterators */
+ PyObject *result;
+ PyObject *fillvalue;
+} iziplongestobject;
+
+static PyTypeObject iziplongest_type;
+
+static PyObject *
+izip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
+{
+ iziplongestobject *lz;
+ Py_ssize_t i;
+ PyObject *ittuple; /* tuple of iterators */
+ PyObject *result;
+ PyObject *fillvalue = Py_None;
+ Py_ssize_t tuplesize = PySequence_Length(args);
+
+ if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) {
+ fillvalue = PyDict_GetItemString(kwds, "fillvalue");
+ if (fillvalue == NULL || PyDict_Size(kwds) > 1) {
+ PyErr_SetString(PyExc_TypeError,
+ "izip_longest() got an unexpected keyword argument");
+ return NULL;
+ }
+ }
+
+ /* args must be a tuple */
+ assert(PyTuple_Check(args));
+
+ /* obtain iterators */
+ ittuple = PyTuple_New(tuplesize);
+ if (ittuple == NULL)
+ return NULL;
+ for (i=0; i < tuplesize; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(args, i);
+ PyObject *it = PyObject_GetIter(item);
+ if (it == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_TypeError))
+ PyErr_Format(PyExc_TypeError,
+ "izip_longest argument #%zd must support iteration",
+ i+1);
+ Py_DECREF(ittuple);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(ittuple, i, it);
+ }
+
+ /* create a result holder */
+ result = PyTuple_New(tuplesize);
+ if (result == NULL) {
+ Py_DECREF(ittuple);
+ return NULL;
+ }
+ for (i=0 ; i < tuplesize ; i++) {
+ Py_INCREF(Py_None);
+ PyTuple_SET_ITEM(result, i, Py_None);
+ }
+
+ /* create iziplongestobject structure */
+ lz = (iziplongestobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(ittuple);
+ Py_DECREF(result);
+ return NULL;
+ }
+ lz->ittuple = ittuple;
+ lz->tuplesize = tuplesize;
+ lz->numactive = tuplesize;
+ lz->result = result;
+ Py_INCREF(fillvalue);
+ lz->fillvalue = fillvalue;
+ return (PyObject *)lz;
+}
+
+static void
+izip_longest_dealloc(iziplongestobject *lz)
+{
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->ittuple);
+ Py_XDECREF(lz->result);
+ Py_XDECREF(lz->fillvalue);
+ lz->ob_type->tp_free(lz);
+}
+
+static int
+izip_longest_traverse(iziplongestobject *lz, visitproc visit, void *arg)
+{
+ Py_VISIT(lz->ittuple);
+ Py_VISIT(lz->result);
+ Py_VISIT(lz->fillvalue);
+ return 0;
+}
+
+static PyObject *
+izip_longest_next(iziplongestobject *lz)
+{
+ Py_ssize_t i;
+ Py_ssize_t tuplesize = lz->tuplesize;
+ PyObject *result = lz->result;
+ PyObject *it;
+ PyObject *item;
+ PyObject *olditem;
+
+ if (tuplesize == 0)
+ return NULL;
+ if (lz->numactive == 0)
+ return NULL;
+ if (result->ob_refcnt == 1) {
+ Py_INCREF(result);
+ for (i=0 ; i < tuplesize ; i++) {
+ it = PyTuple_GET_ITEM(lz->ittuple, i);
+ if (it == NULL) {
+ Py_INCREF(lz->fillvalue);
+ item = lz->fillvalue;
+ } else {
+ assert(PyIter_Check(it));
+ item = (*it->ob_type->tp_iternext)(it);
+ if (item == NULL) {
+ lz->numactive -= 1;
+ if (lz->numactive == 0) {
+ Py_DECREF(result);
+ return NULL;
+ } else {
+ Py_INCREF(lz->fillvalue);
+ item = lz->fillvalue;
+ PyTuple_SET_ITEM(lz->ittuple, i, NULL);
+ Py_DECREF(it);
+ }
+ }
+ }
+ olditem = PyTuple_GET_ITEM(result, i);
+ PyTuple_SET_ITEM(result, i, item);
+ Py_DECREF(olditem);
+ }
+ } else {
+ result = PyTuple_New(tuplesize);
+ if (result == NULL)
+ return NULL;
+ for (i=0 ; i < tuplesize ; i++) {
+ it = PyTuple_GET_ITEM(lz->ittuple, i);
+ if (it == NULL) {
+ Py_INCREF(lz->fillvalue);
+ item = lz->fillvalue;
+ } else {
+ assert(PyIter_Check(it));
+ item = (*it->ob_type->tp_iternext)(it);
+ if (item == NULL) {
+ lz->numactive -= 1;
+ if (lz->numactive == 0) {
+ Py_DECREF(result);
+ return NULL;
+ } else {
+ Py_INCREF(lz->fillvalue);
+ item = lz->fillvalue;
+ PyTuple_SET_ITEM(lz->ittuple, i, NULL);
+ Py_DECREF(it);
+ }
+ }
+ }
+ PyTuple_SET_ITEM(result, i, item);
+ }
+ }
+ return result;
+}
+
+PyDoc_STRVAR(izip_longest_doc,
+"izip_longest(iter1 [,iter2 [...]], [fillvalue=None]) --> izip_longest object\n\
+\n\
+Return an izip_longest object whose .next() method returns a tuple where\n\
+the i-th element comes from the i-th iterable argument. The .next()\n\
+method continues until the longest iterable in the argument sequence\n\
+is exhausted and then it raises StopIteration. When the shorter iterables\n\
+are exhausted, the fillvalue is substituted in their place. The fillvalue\n\
+defaults to None or can be specified by a keyword argument.\n\
+");
+
+static PyTypeObject iziplongest_type = {
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "itertools.izip_longest", /* tp_name */
+ sizeof(iziplongestobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)izip_longest_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 */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ izip_longest_doc, /* tp_doc */
+ (traverseproc)izip_longest_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)izip_longest_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ izip_longest_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
+};
/* module level code ********************************************************/
@@ -2479,6 +2713,7 @@
\n\
Iterators terminating on the shortest input sequence:\n\
izip(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\
+izip_longest(p, q, ...) --> (p[0], q[0]), (p[1], q[1]), ... \n\
ifilter(pred, seq) --> elements of seq where pred(elem) is True\n\
ifilterfalse(pred, seq) --> elements of seq where pred(elem) is False\n\
islice(seq, [start,] stop [, step]) --> elements from\n\
@@ -2516,6 +2751,7 @@
&ifilterfalse_type,
&count_type,
&izip_type,
+ &iziplongest_type,
&repeat_type,
&groupby_type,
NULL
Modified: python/branches/p3yk-noslice/Modules/parsermodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/parsermodule.c (original)
+++ python/branches/p3yk-noslice/Modules/parsermodule.c Fri Feb 23 18:29:35 2007
@@ -857,7 +857,7 @@
VALIDATER(vfpdef); VALIDATER(vfplist);
VALIDATER(stmt); VALIDATER(simple_stmt);
VALIDATER(expr_stmt); VALIDATER(power);
-VALIDATER(print_stmt); VALIDATER(del_stmt);
+VALIDATER(del_stmt);
VALIDATER(return_stmt); VALIDATER(list_iter);
VALIDATER(raise_stmt); VALIDATER(import_stmt);
VALIDATER(import_name); VALIDATER(import_from);
@@ -1545,7 +1545,6 @@
int ntype = TYPE(CHILD(tree, 0));
if ( (ntype == expr_stmt)
- || (ntype == print_stmt)
|| (ntype == del_stmt)
|| (ntype == pass_stmt)
|| (ntype == flow_stmt)
@@ -1650,54 +1649,6 @@
}
-/* print_stmt:
- *
- * 'print' ( [ test (',' test)* [','] ]
- * | '>>' test [ (',' test)+ [','] ] )
- */
-static int
-validate_print_stmt(node *tree)
-{
- int nch = NCH(tree);
- int res = (validate_ntype(tree, print_stmt)
- && (nch > 0)
- && validate_name(CHILD(tree, 0), "print"));
-
- if (res && nch > 1) {
- int sym = TYPE(CHILD(tree, 1));
- int i = 1;
- int allow_trailing_comma = 1;
-
- if (sym == test)
- res = validate_test(CHILD(tree, i++));
- else {
- if (nch < 3)
- res = validate_numnodes(tree, 3, "print_stmt");
- else {
- res = (validate_ntype(CHILD(tree, i), RIGHTSHIFT)
- && validate_test(CHILD(tree, i+1)));
- i += 2;
- allow_trailing_comma = 0;
- }
- }
- if (res) {
- /* ... (',' test)* [','] */
- while (res && i+2 <= nch) {
- res = (validate_comma(CHILD(tree, i))
- && validate_test(CHILD(tree, i+1)));
- allow_trailing_comma = 1;
- i += 2;
- }
- if (res && !allow_trailing_comma)
- res = validate_numnodes(tree, i, "print_stmt");
- else if (res && i < nch)
- res = validate_comma(CHILD(tree, i));
- }
- }
- return (res);
-}
-
-
static int
validate_del_stmt(node *tree)
{
@@ -2977,7 +2928,7 @@
break;
case small_stmt:
/*
- * expr_stmt | print_stmt | del_stmt | pass_stmt | flow_stmt
+ * expr_stmt | del_stmt | pass_stmt | flow_stmt
* | import_stmt | global_stmt | assert_stmt
*/
res = validate_small_stmt(tree);
@@ -3012,9 +2963,6 @@
case expr_stmt:
res = validate_expr_stmt(tree);
break;
- case print_stmt:
- res = validate_print_stmt(tree);
- break;
case del_stmt:
res = validate_del_stmt(tree);
break;
Modified: python/branches/p3yk-noslice/Modules/posixmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/posixmodule.c (original)
+++ python/branches/p3yk-noslice/Modules/posixmodule.c Fri Feb 23 18:29:35 2007
@@ -1462,7 +1462,7 @@
/* POSIX methods */
PyDoc_STRVAR(posix_access__doc__,
-"access(path, mode) -> 1 if granted, 0 otherwise\n\n\
+"access(path, mode) -> True if granted, False otherwise\n\n\
Use the real uid/gid to test for access to a path. Note that most\n\
operations will use the effective uid/gid, therefore this routine can\n\
be used in a suid/sgid environment to test if the invoking user has the\n\
@@ -1692,6 +1692,57 @@
}
+#ifdef HAVE_CHFLAGS
+PyDoc_STRVAR(posix_chflags__doc__,
+"chflags(path, flags)\n\n\
+Set file flags.");
+
+static PyObject *
+posix_chflags(PyObject *self, PyObject *args)
+{
+ char *path;
+ unsigned long flags;
+ int res;
+ if (!PyArg_ParseTuple(args, "etk:chflags",
+ Py_FileSystemDefaultEncoding, &path, &flags))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ res = chflags(path, flags);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return posix_error_with_allocated_filename(path);
+ PyMem_Free(path);
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+#endif /* HAVE_CHFLAGS */
+
+#ifdef HAVE_LCHFLAGS
+PyDoc_STRVAR(posix_lchflags__doc__,
+"lchflags(path, flags)\n\n\
+Set file flags.\n\
+This function will not follow symbolic links.");
+
+static PyObject *
+posix_lchflags(PyObject *self, PyObject *args)
+{
+ char *path;
+ unsigned long flags;
+ int res;
+ if (!PyArg_ParseTuple(args, "etk:lchflags",
+ Py_FileSystemDefaultEncoding, &path, &flags))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ res = lchflags(path, flags);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return posix_error_with_allocated_filename(path);
+ PyMem_Free(path);
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+#endif /* HAVE_LCHFLAGS */
+
#ifdef HAVE_CHROOT
PyDoc_STRVAR(posix_chroot__doc__,
"chroot(path)\n\n\
@@ -5437,32 +5488,21 @@
elem = PySequence_GetItem(groups, i);
if (!elem)
return NULL;
- if (!PyInt_Check(elem)) {
- if (!PyLong_Check(elem)) {
- PyErr_SetString(PyExc_TypeError,
- "groups must be integers");
+ if (!PyLong_Check(elem)) {
+ PyErr_SetString(PyExc_TypeError,
+ "groups must be integers");
+ Py_DECREF(elem);
+ return NULL;
+ } else {
+ unsigned long x = PyLong_AsUnsignedLong(elem);
+ if (PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError,
+ "group id too big");
Py_DECREF(elem);
return NULL;
- } else {
- unsigned long x = PyLong_AsUnsignedLong(elem);
- if (PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError,
- "group id too big");
- Py_DECREF(elem);
- return NULL;
- }
- grouplist[i] = x;
- /* read back the value to see if it fitted in gid_t */
- if (grouplist[i] != x) {
- PyErr_SetString(PyExc_TypeError,
- "group id too big");
- Py_DECREF(elem);
- return NULL;
- }
}
- } else {
- long x = PyInt_AsLong(elem);
grouplist[i] = x;
+ /* read back the value to see if it fitted in gid_t */
if (grouplist[i] != x) {
PyErr_SetString(PyExc_TypeError,
"group id too big");
@@ -8081,10 +8121,16 @@
{"ttyname", posix_ttyname, METH_VARARGS, posix_ttyname__doc__},
#endif
{"chdir", posix_chdir, METH_VARARGS, posix_chdir__doc__},
+#ifdef HAVE_CHFLAGS
+ {"chflags", posix_chflags, METH_VARARGS, posix_chflags__doc__},
+#endif /* HAVE_CHFLAGS */
{"chmod", posix_chmod, METH_VARARGS, posix_chmod__doc__},
#ifdef HAVE_CHOWN
{"chown", posix_chown, METH_VARARGS, posix_chown__doc__},
#endif /* HAVE_CHOWN */
+#ifdef HAVE_LCHFLAGS
+ {"lchflags", posix_lchflags, METH_VARARGS, posix_lchflags__doc__},
+#endif /* HAVE_LCHFLAGS */
#ifdef HAVE_LCHOWN
{"lchown", posix_lchown, METH_VARARGS, posix_lchown__doc__},
#endif /* HAVE_LCHOWN */
Modified: python/branches/p3yk-noslice/Modules/socketmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/socketmodule.c (original)
+++ python/branches/p3yk-noslice/Modules/socketmodule.c Fri Feb 23 18:29:35 2007
@@ -362,20 +362,25 @@
#if defined(__FreeBSD__)
#define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
#define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
+#define BTPROTO_HCI BLUETOOTH_PROTO_HCI
#define sockaddr_l2 sockaddr_l2cap
#define sockaddr_rc sockaddr_rfcomm
#define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
#define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
+#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
#elif defined(__NetBSD__)
#define sockaddr_l2 sockaddr_bt
#define sockaddr_rc sockaddr_bt
+#define sockaddr_hci sockaddr_bt
#define sockaddr_sco sockaddr_bt
#define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
#define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
+#define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
#define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
#else
#define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
#define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
+#define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
#define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
#endif
#endif
@@ -1119,6 +1124,14 @@
return ret;
}
+ case BTPROTO_HCI:
+ {
+ struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
+ PyObject *ret = NULL;
+ ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
+ return ret;
+ }
+
#if !defined(__FreeBSD__)
case BTPROTO_SCO:
{
@@ -1347,6 +1360,18 @@
*len_ret = sizeof *addr;
return 1;
}
+ case BTPROTO_HCI:
+ {
+ struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
+ _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
+ if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
+ PyErr_SetString(socket_error, "getsockaddrarg: "
+ "wrong format");
+ return 0;
+ }
+ *len_ret = sizeof *addr;
+ return 1;
+ }
#if !defined(__FreeBSD__)
case BTPROTO_SCO:
{
@@ -1485,6 +1510,9 @@
case BTPROTO_RFCOMM:
*len_ret = sizeof (struct sockaddr_rc);
return 1;
+ case BTPROTO_HCI:
+ *len_ret = sizeof (struct sockaddr_hci);
+ return 1;
#if !defined(__FreeBSD__)
case BTPROTO_SCO:
*len_ret = sizeof (struct sockaddr_sco);
@@ -3468,7 +3496,12 @@
if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
return NULL;
}
- x2 = (int)ntohs((short)x1);
+ if (x1 < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative number to unsigned long");
+ return NULL;
+ }
+ x2 = (unsigned int)ntohs((unsigned short)x1);
return PyInt_FromLong(x2);
}
@@ -3483,12 +3516,7 @@
{
unsigned long x;
- if (PyInt_Check(arg)) {
- x = PyInt_AS_LONG(arg);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
- }
- else if (PyLong_Check(arg)) {
+ if (PyLong_Check(arg)) {
x = PyLong_AsUnsignedLong(arg);
if (x == (unsigned long) -1 && PyErr_Occurred())
return NULL;
@@ -3510,7 +3538,7 @@
arg->ob_type->tp_name);
if (x == (unsigned long) -1 && PyErr_Occurred())
return NULL;
- return PyInt_FromLong(ntohl(x));
+ return PyLong_FromUnsignedLong(ntohl(x));
}
PyDoc_STRVAR(ntohl_doc,
@@ -3527,7 +3555,12 @@
if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
return NULL;
}
- x2 = (int)htons((short)x1);
+ if (x1 < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative number to unsigned long");
+ return NULL;
+ }
+ x2 = (unsigned int)htons((unsigned short)x1);
return PyInt_FromLong(x2);
}
@@ -3542,12 +3575,7 @@
{
unsigned long x;
- if (PyInt_Check(arg)) {
- x = PyInt_AS_LONG(arg);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
- }
- else if (PyLong_Check(arg)) {
+ if (PyLong_Check(arg)) {
x = PyLong_AsUnsignedLong(arg);
if (x == (unsigned long) -1 && PyErr_Occurred())
return NULL;
@@ -3567,7 +3595,7 @@
return PyErr_Format(PyExc_TypeError,
"expected int/long, %s found",
arg->ob_type->tp_name);
- return PyInt_FromLong(htonl(x));
+ return PyLong_FromUnsignedLong(htonl((unsigned long)x));
}
PyDoc_STRVAR(htonl_doc,
@@ -3827,7 +3855,7 @@
"getaddrinfo() argument 1 must be string or None");
return NULL;
}
- if (PyInt_Check(pobj)) {
+ if (PyInt_CheckExact(pobj)) {
PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
pptr = pbuf;
} else if (PyString_Check(pobj)) {
@@ -4363,7 +4391,9 @@
PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
#endif
PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
+#ifdef NETLINK_DNRTMSG
PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
+#endif
#ifdef NETLINK_TAPBASE
PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
#endif
@@ -4408,6 +4438,11 @@
#ifdef USE_BLUETOOTH
PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
+ PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
+ PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
+ PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
+ PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
+ PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
#if !defined(__FreeBSD__)
PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
#endif
Modified: python/branches/p3yk-noslice/Modules/socketmodule.h
==============================================================================
--- python/branches/p3yk-noslice/Modules/socketmodule.h (original)
+++ python/branches/p3yk-noslice/Modules/socketmodule.h Fri Feb 23 18:29:35 2007
@@ -46,6 +46,7 @@
#include <bluetooth/rfcomm.h>
#include <bluetooth/l2cap.h>
#include <bluetooth/sco.h>
+#include <bluetooth/hci.h>
#endif
#ifdef HAVE_BLUETOOTH_H
@@ -98,6 +99,7 @@
struct sockaddr_l2 bt_l2;
struct sockaddr_rc bt_rc;
struct sockaddr_sco bt_sco;
+ struct sockaddr_hci bt_hci;
#endif
#ifdef HAVE_NETPACKET_PACKET_H
struct sockaddr_ll ll;
Modified: python/branches/p3yk-noslice/Modules/timemodule.c
==============================================================================
--- python/branches/p3yk-noslice/Modules/timemodule.c (original)
+++ python/branches/p3yk-noslice/Modules/timemodule.c Fri Feb 23 18:29:35 2007
@@ -357,7 +357,7 @@
if (y < 1900) {
PyObject *accept = PyDict_GetItemString(moddict,
"accept2dyear");
- if (accept == NULL || !PyInt_Check(accept) ||
+ if (accept == NULL || !PyInt_CheckExact(accept) ||
PyInt_AsLong(accept) == 0) {
PyErr_SetString(PyExc_ValueError,
"year >= 1900 required");
Modified: python/branches/p3yk-noslice/Objects/abstract.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/abstract.c (original)
+++ python/branches/p3yk-noslice/Objects/abstract.c Fri Feb 23 18:29:35 2007
@@ -790,25 +790,6 @@
return type_error("bad operand type for abs(): '%.200s'", o);
}
-/* Add a check for embedded NULL-bytes in the argument. */
-static PyObject *
-int_from_string(const char *s, Py_ssize_t len)
-{
- char *end;
- PyObject *x;
-
- x = PyInt_FromString((char*)s, &end, 10);
- if (x == NULL)
- return NULL;
- if (end != s + len) {
- PyErr_SetString(PyExc_ValueError,
- "null byte in argument for int()");
- Py_DECREF(x);
- return NULL;
- }
- return x;
-}
-
/* Return a Python Int or Long from the object item
Raise TypeError if the result is not an int-or-long
or if the object cannot be interpreted as an index.
@@ -828,7 +809,7 @@
if (result &&
!PyInt_Check(result) && !PyLong_Check(result)) {
PyErr_Format(PyExc_TypeError,
- "__index__ returned non-(int,long) " \
+ "__index__ returned non-int " \
"(type %.200s)",
result->ob_type->tp_name);
Py_DECREF(result);
@@ -890,51 +871,6 @@
}
-PyObject *
-PyNumber_Int(PyObject *o)
-{
- PyNumberMethods *m;
- const char *buffer;
- Py_ssize_t buffer_len;
-
- if (o == NULL)
- return null_error();
- if (PyInt_CheckExact(o)) {
- Py_INCREF(o);
- return o;
- }
- m = o->ob_type->tp_as_number;
- if (m && m->nb_int) { /* This should include subclasses of int */
- PyObject *res = m->nb_int(o);
- if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
- PyErr_Format(PyExc_TypeError,
- "__int__ returned non-int (type %.200s)",
- res->ob_type->tp_name);
- Py_DECREF(res);
- return NULL;
- }
- return res;
- }
- if (PyInt_Check(o)) { /* A int subclass without nb_int */
- PyIntObject *io = (PyIntObject*)o;
- return PyInt_FromLong(io->ob_ival);
- }
- if (PyString_Check(o))
- return int_from_string(PyString_AS_STRING(o),
- PyString_GET_SIZE(o));
-#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(o))
- return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
- PyUnicode_GET_SIZE(o),
- 10);
-#endif
- if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
- return int_from_string((char*)buffer, buffer_len);
-
- return type_error("int() argument must be a string or a "
- "number, not '%.200s'", o);
-}
-
/* Add a check for embedded NULL-bytes in the argument. */
static PyObject *
long_from_string(const char *s, Py_ssize_t len)
@@ -947,7 +883,7 @@
return NULL;
if (end != s + len) {
PyErr_SetString(PyExc_ValueError,
- "null byte in argument for long()");
+ "null byte in argument for int()");
Py_DECREF(x);
return NULL;
}
@@ -963,7 +899,22 @@
if (o == NULL)
return null_error();
+ if (PyLong_CheckExact(o)) {
+ Py_INCREF(o);
+ return o;
+ }
m = o->ob_type->tp_as_number;
+ if (m && m->nb_int) { /* This should include subclasses of int */
+ PyObject *res = m->nb_int(o);
+ if (res && !PyLong_Check(res)) {
+ PyErr_Format(PyExc_TypeError,
+ "__int__ returned non-int (type %.200s)",
+ res->ob_type->tp_name);
+ Py_DECREF(res);
+ return NULL;
+ }
+ return res;
+ }
if (m && m->nb_long) { /* This should include subclasses of long */
PyObject *res = m->nb_long(o);
if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
@@ -994,7 +945,7 @@
if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
return long_from_string(buffer, buffer_len);
- return type_error("long() argument must be a string or a "
+ return type_error("int() argument must be a string or a "
"number, not '%.200s'", o);
}
@@ -1029,6 +980,8 @@
int
PySequence_Check(PyObject *s)
{
+ if (PyObject_IsInstance(s, (PyObject *)&PyDict_Type))
+ return 0;
return s != NULL && s->ob_type->tp_as_sequence &&
s->ob_type->tp_as_sequence->sq_item != NULL;
}
@@ -1671,6 +1624,54 @@
return 0;
}
+PyObject *
+PyMapping_Keys(PyObject *o)
+{
+ PyObject *keys;
+ PyObject *fast;
+
+ if (PyDict_CheckExact(o))
+ return PyDict_Keys(o);
+ keys = PyObject_CallMethod(o, "keys", NULL);
+ if (keys == NULL)
+ return NULL;
+ fast = PySequence_Fast(keys, "o.keys() are not iterable");
+ Py_DECREF(keys);
+ return fast;
+}
+
+PyObject *
+PyMapping_Items(PyObject *o)
+{
+ PyObject *items;
+ PyObject *fast;
+
+ if (PyDict_CheckExact(o))
+ return PyDict_Items(o);
+ items = PyObject_CallMethod(o, "items", NULL);
+ if (items == NULL)
+ return NULL;
+ fast = PySequence_Fast(items, "o.items() are not iterable");
+ Py_DECREF(items);
+ return fast;
+}
+
+PyObject *
+PyMapping_Values(PyObject *o)
+{
+ PyObject *values;
+ PyObject *fast;
+
+ if (PyDict_CheckExact(o))
+ return PyDict_Values(o);
+ values = PyObject_CallMethod(o, "values", NULL);
+ if (values == NULL)
+ return NULL;
+ fast = PySequence_Fast(values, "o.values() are not iterable");
+ Py_DECREF(values);
+ return fast;
+}
+
/* Operations on callable objects */
/* XXX PyCallable_Check() is in object.c */
Modified: python/branches/p3yk-noslice/Objects/boolobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/boolobject.c (original)
+++ python/branches/p3yk-noslice/Objects/boolobject.c Fri Feb 23 18:29:35 2007
@@ -1,13 +1,14 @@
/* Boolean type, a subtype of int */
#include "Python.h"
+#include "longintrepr.h"
/* We need to define bool_print to override int_print */
static int
-bool_print(PyBoolObject *self, FILE *fp, int flags)
+bool_print(PyObject *self, FILE *fp, int flags)
{
- fputs(self->ob_ival == 0 ? "False" : "True", fp);
+ fputs(self == Py_False ? "False" : "True", fp);
return 0;
}
@@ -17,11 +18,11 @@
static PyObject *true_str = NULL;
static PyObject *
-bool_repr(PyBoolObject *self)
+bool_repr(PyObject *self)
{
PyObject *s;
- if (self->ob_ival)
+ if (self == Py_True)
s = true_str ? true_str :
(true_str = PyString_InternFromString("True"));
else
@@ -68,27 +69,24 @@
bool_and(PyObject *a, PyObject *b)
{
if (!PyBool_Check(a) || !PyBool_Check(b))
- return PyInt_Type.tp_as_number->nb_and(a, b);
- return PyBool_FromLong(
- ((PyBoolObject *)a)->ob_ival & ((PyBoolObject *)b)->ob_ival);
+ return PyLong_Type.tp_as_number->nb_and(a, b);
+ return PyBool_FromLong((a == Py_True) & (b == Py_True));
}
static PyObject *
bool_or(PyObject *a, PyObject *b)
{
if (!PyBool_Check(a) || !PyBool_Check(b))
- return PyInt_Type.tp_as_number->nb_or(a, b);
- return PyBool_FromLong(
- ((PyBoolObject *)a)->ob_ival | ((PyBoolObject *)b)->ob_ival);
+ return PyLong_Type.tp_as_number->nb_or(a, b);
+ return PyBool_FromLong((a == Py_True) | (b == Py_True));
}
static PyObject *
bool_xor(PyObject *a, PyObject *b)
{
if (!PyBool_Check(a) || !PyBool_Check(b))
- return PyInt_Type.tp_as_number->nb_xor(a, b);
- return PyBool_FromLong(
- ((PyBoolObject *)a)->ob_ival ^ ((PyBoolObject *)b)->ob_ival);
+ return PyLong_Type.tp_as_number->nb_xor(a, b);
+ return PyBool_FromLong((a == Py_True) ^ (b == Py_True));
}
/* Doc string */
@@ -139,6 +137,7 @@
0, /* nb_true_divide */
0, /* nb_inplace_floor_divide */
0, /* nb_inplace_true_divide */
+ 0, /* nb_index */
};
/* The type object for bool. Note that this cannot be subclassed! */
@@ -147,20 +146,20 @@
PyObject_HEAD_INIT(&PyType_Type)
0,
"bool",
- sizeof(PyIntObject),
+ sizeof(struct _longobject),
0,
0, /* tp_dealloc */
- (printfunc)bool_print, /* tp_print */
+ bool_print, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
- (reprfunc)bool_repr, /* tp_repr */
+ bool_repr, /* tp_repr */
&bool_as_number, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
- (reprfunc)bool_repr, /* tp_str */
+ bool_repr, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
@@ -175,7 +174,7 @@
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
- &PyInt_Type, /* tp_base */
+ &PyLong_Type, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
@@ -188,12 +187,12 @@
/* The objects representing bool values False and True */
/* Named Zero for link-level compatibility */
-PyIntObject _Py_ZeroStruct = {
+struct _longobject _Py_FalseStruct = {
PyObject_HEAD_INIT(&PyBool_Type)
- 0
+ 0, { 0 }
};
-PyIntObject _Py_TrueStruct = {
+struct _longobject _Py_TrueStruct = {
PyObject_HEAD_INIT(&PyBool_Type)
- 1
+ 1, { 1 }
};
Modified: python/branches/p3yk-noslice/Objects/complexobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/complexobject.c (original)
+++ python/branches/p3yk-noslice/Objects/complexobject.c Fri Feb 23 18:29:35 2007
@@ -349,10 +349,6 @@
PyObject *obj = *pobj;
pc->real = pc->imag = 0.0;
- if (PyInt_Check(obj)) {
- pc->real = PyInt_AS_LONG(obj);
- return 0;
- }
if (PyLong_Check(obj)) {
pc->real = PyLong_AsDouble(obj);
if (pc->real == -1.0 && PyErr_Occurred()) {
Modified: python/branches/p3yk-noslice/Objects/dictnotes.txt
==============================================================================
--- python/branches/p3yk-noslice/Objects/dictnotes.txt (original)
+++ python/branches/p3yk-noslice/Objects/dictnotes.txt Fri Feb 23 18:29:35 2007
@@ -98,6 +98,17 @@
depending on the size of the dictionary. Setting to *4
eliminates every other resize step.
+* Maximum sparseness (minimum dictionary load). What percentage
+ of entries can be unused before the dictionary shrinks to
+ free up memory and speed up iteration? (The current CPython
+ code does not represent this parameter directly.)
+
+* Shrinkage rate upon exceeding maximum sparseness. The current
+ CPython code never even checks sparseness when deleting a
+ key. When a new key is added, it resizes based on the number
+ of active keys, so that the addition may trigger shrinkage
+ rather than growth.
+
Tune-ups should be measured across a broad range of applications and
use cases. A change to any parameter will help in some situations and
hurt in others. The key is to find settings that help the most common
@@ -115,6 +126,15 @@
Also, every dictionary iterates at least twice, once for the memset()
when it is created and once by dealloc().
+Dictionary operations involving only a single key can be O(1) unless
+resizing is possible. By checking for a resize only when the
+dictionary can grow (and may *require* resizing), other operations
+remain O(1), and the odds of resize thrashing or memory fragmentation
+are reduced. In particular, an algorithm that empties a dictionary
+by repeatedly invoking .pop will see no resizing, which might
+not be necessary at all because the dictionary is eventually
+discarded entirely.
+
Results of Cache Locality Experiments
-------------------------------------
Modified: python/branches/p3yk-noslice/Objects/dictobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/dictobject.c (original)
+++ python/branches/p3yk-noslice/Objects/dictobject.c Fri Feb 23 18:29:35 2007
@@ -833,6 +833,34 @@
return 1;
}
+/* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/
+int
+_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash)
+{
+ register Py_ssize_t i;
+ register Py_ssize_t mask;
+ register dictentry *ep;
+
+ if (!PyDict_Check(op))
+ return 0;
+ i = *ppos;
+ if (i < 0)
+ return 0;
+ ep = ((dictobject *)op)->ma_table;
+ mask = ((dictobject *)op)->ma_mask;
+ while (i <= mask && ep[i].me_value == NULL)
+ i++;
+ *ppos = i+1;
+ if (i > mask)
+ return 0;
+ *phash = (long)(ep[i].me_hash);
+ if (pkey)
+ *pkey = ep[i].me_key;
+ if (pvalue)
+ *pvalue = ep[i].me_value;
+ return 1;
+}
+
/* Methods */
static void
@@ -1336,7 +1364,7 @@
return -1;
}
mp = (dictobject*)a;
- if (PyDict_Check(b)) {
+ if (PyDict_CheckExact(b)) {
other = (dictobject*)b;
if (other == mp || other->ma_used == 0)
/* a.update(a) or a.update({}); nothing to do */
@@ -1760,6 +1788,7 @@
extern PyTypeObject PyDictIterItem_Type; /* Forward */
static PyObject *dictiter_new(dictobject *, PyTypeObject *);
+#if 0
static PyObject *
dict_iterkeys(dictobject *dict)
{
@@ -1777,6 +1806,7 @@
{
return dictiter_new(dict, &PyDictIterItem_Type);
}
+#endif
PyDoc_STRVAR(contains__doc__,
@@ -1798,6 +1828,7 @@
"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
2-tuple; but raise KeyError if D is empty");
+#if 0
PyDoc_STRVAR(keys__doc__,
"D.keys() -> list of D's keys");
@@ -1806,10 +1837,11 @@
PyDoc_STRVAR(values__doc__,
"D.values() -> list of D's values");
+#endif
PyDoc_STRVAR(update__doc__,
-"D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k]\n\
-(if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k]");
+"D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k]\
+\n(if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k]");
PyDoc_STRVAR(fromkeys__doc__,
"dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.\n\
@@ -1821,6 +1853,7 @@
PyDoc_STRVAR(copy__doc__,
"D.copy() -> a shallow copy of D");
+#if 0
PyDoc_STRVAR(iterkeys__doc__,
"D.iterkeys() -> an iterator over the keys of D");
@@ -1829,6 +1862,16 @@
PyDoc_STRVAR(iteritems__doc__,
"D.iteritems() -> an iterator over the (key, value) items of D");
+#endif
+
+/* Forward */
+static PyObject *dictkeys_new(PyObject *);
+static PyObject *dictitems_new(PyObject *);
+static PyObject *dictvalues_new(PyObject *);
+
+PyDoc_STRVAR(KEYS__doc__, "D.KEYS() -> a set-like object for D's keys");
+PyDoc_STRVAR(ITEMS__doc__, "D.ITEMS() -> a set-like object for D's items");
+PyDoc_STRVAR(VALUES__doc__, "D.VALUES() -> a set-like object for D's values");
static PyMethodDef mapp_methods[] = {
{"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST,
@@ -1843,12 +1886,20 @@
pop__doc__},
{"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
popitem__doc__},
+#if 0
{"keys", (PyCFunction)dict_keys, METH_NOARGS,
keys__doc__},
{"items", (PyCFunction)dict_items, METH_NOARGS,
items__doc__},
{"values", (PyCFunction)dict_values, METH_NOARGS,
values__doc__},
+#endif
+ {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
+ KEYS__doc__},
+ {"items", (PyCFunction)dictitems_new, METH_NOARGS,
+ ITEMS__doc__},
+ {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
+ VALUES__doc__},
{"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
update__doc__},
{"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS,
@@ -1857,12 +1908,14 @@
clear__doc__},
{"copy", (PyCFunction)dict_copy, METH_NOARGS,
copy__doc__},
+#if 0
{"iterkeys", (PyCFunction)dict_iterkeys, METH_NOARGS,
iterkeys__doc__},
{"itervalues", (PyCFunction)dict_itervalues, METH_NOARGS,
itervalues__doc__},
{"iteritems", (PyCFunction)dict_iteritems, METH_NOARGS,
iteritems__doc__},
+#endif
{NULL, NULL} /* sentinel */
};
@@ -1884,6 +1937,17 @@
return ep == NULL ? -1 : (ep->me_value != NULL);
}
+/* Internal version of PyDict_Contains used when the hash value is already known */
+int
+_PyDict_Contains(PyObject *op, PyObject *key, long hash)
+{
+ dictobject *mp = (dictobject *)op;
+ dictentry *ep;
+
+ ep = (mp->ma_lookup)(mp, key, hash);
+ return ep == NULL ? -1 : (ep->me_value != NULL);
+}
+
/* Hack to implement "key in dict" */
static PySequenceMethods dict_as_sequence = {
0, /* sq_length */
@@ -2078,10 +2142,12 @@
return PyInt_FromSize_t(len);
}
-PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
+PyDoc_STRVAR(length_hint_doc,
+ "Private method returning an estimate of len(list(it)).");
static PyMethodDef dictiter_methods[] = {
- {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, length_hint_doc},
+ {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS,
+ length_hint_doc},
{NULL, NULL} /* sentinel */
};
@@ -2317,3 +2383,359 @@
dictiter_methods, /* tp_methods */
0,
};
+
+
+/***********************************************/
+/* View objects for keys(), items(), values(). */
+/***********************************************/
+
+/* While this is incomplete, we use KEYS(), ITEMS(), VALUES(). */
+
+/* The instance lay-out is the same for all three; but the type differs. */
+
+typedef struct {
+ PyObject_HEAD
+ dictobject *dv_dict;
+} dictviewobject;
+
+
+static void
+dictview_dealloc(dictviewobject *dv)
+{
+ Py_XDECREF(dv->dv_dict);
+ PyObject_Del(dv);
+}
+
+static Py_ssize_t
+dictview_len(dictviewobject *dv)
+{
+ Py_ssize_t len = 0;
+ if (dv->dv_dict != NULL)
+ len = dv->dv_dict->ma_used;
+ return len;
+}
+
+static PyObject *
+dictview_new(PyObject *dict, PyTypeObject *type)
+{
+ dictviewobject *dv;
+ if (dict == NULL) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ if (!PyDict_Check(dict)) {
+ /* XXX Get rid of this restriction later */
+ PyErr_Format(PyExc_TypeError,
+ "%s() requires a dict argument, not '%s'",
+ type->tp_name, dict->ob_type->tp_name);
+ return NULL;
+ }
+ dv = PyObject_New(dictviewobject, type);
+ if (dv == NULL)
+ return NULL;
+ Py_INCREF(dict);
+ dv->dv_dict = (dictobject *)dict;
+ return (PyObject *)dv;
+}
+
+/* Forward */
+PyTypeObject PyDictKeys_Type;
+PyTypeObject PyDictItems_Type;
+PyTypeObject PyDictValues_Type;
+
+#define PyDictKeys_Check(obj) ((obj)->ob_type == &PyDictKeys_Type)
+#define PyDictItems_Check(obj) ((obj)->ob_type == &PyDictItems_Type)
+#define PyDictValues_Check(obj) ((obj)->ob_type == &PyDictValues_Type)
+
+/* This excludes Values, since they are not sets. */
+# define PyDictViewSet_Check(obj) \
+ (PyDictKeys_Check(obj) || PyDictItems_Check(obj))
+
+static int
+all_contained_in(PyObject *self, PyObject *other)
+{
+ PyObject *iter = PyObject_GetIter(self);
+ int ok = 1;
+
+ if (iter == NULL)
+ return -1;
+ for (;;) {
+ PyObject *next = PyIter_Next(iter);
+ if (next == NULL) {
+ if (PyErr_Occurred())
+ ok = -1;
+ break;
+ }
+ ok = PySequence_Contains(other, next);
+ Py_DECREF(next);
+ if (ok <= 0)
+ break;
+ }
+ Py_DECREF(iter);
+ return ok;
+}
+
+static PyObject *
+dictview_richcompare(PyObject *self, PyObject *other, int op)
+{
+ assert(self != NULL);
+ assert(PyDictViewSet_Check(self));
+ assert(other != NULL);
+ if ((op == Py_EQ || op == Py_NE) &&
+ (PyAnySet_Check(other) || PyDictViewSet_Check(other)))
+ {
+ Py_ssize_t len_self, len_other;
+ int ok;
+ PyObject *result;
+
+ len_self = PyObject_Size(self);
+ if (len_self < 0)
+ return NULL;
+ len_other = PyObject_Size(other);
+ if (len_other < 0)
+ return NULL;
+ if (len_self != len_other)
+ ok = 0;
+ else if (len_self == 0)
+ ok = 1;
+ else
+ ok = all_contained_in(self, other);
+ if (ok < 0)
+ return NULL;
+ if (ok == (op == Py_EQ))
+ result = Py_True;
+ else
+ result = Py_False;
+ Py_INCREF(result);
+ return result;
+ }
+ else {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+}
+
+/*** dict_keys ***/
+
+static PyObject *
+dictkeys_iter(dictviewobject *dv)
+{
+ if (dv->dv_dict == NULL) {
+ Py_RETURN_NONE;
+ }
+ return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
+}
+
+static int
+dictkeys_contains(dictviewobject *dv, PyObject *obj)
+{
+ if (dv->dv_dict == NULL)
+ return 0;
+ return PyDict_Contains((PyObject *)dv->dv_dict, obj);
+}
+
+static PySequenceMethods dictkeys_as_sequence = {
+ (lenfunc)dictview_len, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ (objobjproc)dictkeys_contains, /* sq_contains */
+};
+
+static PyMethodDef dictkeys_methods[] = {
+ {NULL, NULL} /* sentinel */
+};
+
+PyTypeObject PyDictKeys_Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /* ob_size */
+ "dict_keys", /* tp_name */
+ sizeof(dictviewobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dictview_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &dictkeys_as_sequence, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ dictview_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ (getiterfunc)dictkeys_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ dictkeys_methods, /* tp_methods */
+ 0,
+};
+
+static PyObject *
+dictkeys_new(PyObject *dict)
+{
+ return dictview_new(dict, &PyDictKeys_Type);
+}
+
+/*** dict_items ***/
+
+static PyObject *
+dictitems_iter(dictviewobject *dv)
+{
+ if (dv->dv_dict == NULL) {
+ Py_RETURN_NONE;
+ }
+ return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
+}
+
+static int
+dictitems_contains(dictviewobject *dv, PyObject *obj)
+{
+ PyObject *key, *value, *found;
+ if (dv->dv_dict == NULL)
+ return 0;
+ if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
+ return 0;
+ key = PyTuple_GET_ITEM(obj, 0);
+ value = PyTuple_GET_ITEM(obj, 1);
+ found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
+ if (found == NULL) {
+ if (PyErr_Occurred())
+ return -1;
+ return 0;
+ }
+ return PyObject_RichCompareBool(value, found, Py_EQ);
+}
+
+static PySequenceMethods dictitems_as_sequence = {
+ (lenfunc)dictview_len, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ (objobjproc)dictitems_contains, /* sq_contains */
+};
+
+static PyMethodDef dictitems_methods[] = {
+ {NULL, NULL} /* sentinel */
+};
+
+PyTypeObject PyDictItems_Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /* ob_size */
+ "dict_items", /* tp_name */
+ sizeof(dictviewobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dictview_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &dictitems_as_sequence, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ dictview_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ (getiterfunc)dictitems_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ dictitems_methods, /* tp_methods */
+ 0,
+};
+
+static PyObject *
+dictitems_new(PyObject *dict)
+{
+ return dictview_new(dict, &PyDictItems_Type);
+}
+
+/*** dict_values ***/
+
+static PyObject *
+dictvalues_iter(dictviewobject *dv)
+{
+ if (dv->dv_dict == NULL) {
+ Py_RETURN_NONE;
+ }
+ return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
+}
+
+static PySequenceMethods dictvalues_as_sequence = {
+ (lenfunc)dictview_len, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ (objobjproc)0, /* sq_contains */
+};
+
+static PyMethodDef dictvalues_methods[] = {
+ {NULL, NULL} /* sentinel */
+};
+
+PyTypeObject PyDictValues_Type = {
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /* ob_size */
+ "dict_values", /* tp_name */
+ sizeof(dictviewobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dictview_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &dictvalues_as_sequence, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* 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 */
+ (getiterfunc)dictvalues_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ dictvalues_methods, /* tp_methods */
+ 0,
+};
+
+static PyObject *
+dictvalues_new(PyObject *dict)
+{
+ return dictview_new(dict, &PyDictValues_Type);
+}
Modified: python/branches/p3yk-noslice/Objects/enumobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/enumobject.c (original)
+++ python/branches/p3yk-noslice/Objects/enumobject.c Fri Feb 23 18:29:35 2007
@@ -62,6 +62,12 @@
PyObject *result = en->en_result;
PyObject *it = en->en_sit;
+ if (en->en_index == LONG_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "enumerate() is limited to LONG_MAX items");
+ return NULL;
+ }
+
next_item = (*it->ob_type->tp_iternext)(it);
if (next_item == NULL)
return NULL;
Modified: python/branches/p3yk-noslice/Objects/exceptions.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/exceptions.c (original)
+++ python/branches/p3yk-noslice/Objects/exceptions.c Fri Feb 23 18:29:35 2007
@@ -1089,7 +1089,7 @@
have_filename = (self->filename != NULL) &&
PyString_Check(self->filename);
- have_lineno = (self->lineno != NULL) && PyInt_Check(self->lineno);
+ have_lineno = (self->lineno != NULL) && PyInt_CheckExact(self->lineno);
if (!have_filename && !have_lineno)
return str;
@@ -1225,10 +1225,8 @@
return -1;
}
- if (PyInt_Check(attr)) {
- *value = PyInt_AS_LONG(attr);
- } else if (PyLong_Check(attr)) {
- *value = _PyLong_AsSsize_t(attr);
+ if (PyLong_Check(attr)) {
+ *value = PyLong_AsSsize_t(attr);
if (*value == -1 && PyErr_Occurred())
return -1;
} else {
@@ -1515,8 +1513,8 @@
if (!PyArg_ParseTuple(args, "O!O!O!O!O!",
&PyString_Type, &self->encoding,
objecttype, &self->object,
- &PyInt_Type, &self->start,
- &PyInt_Type, &self->end,
+ &PyLong_Type, &self->start,
+ &PyLong_Type, &self->end,
&PyString_Type, &self->reason)) {
self->encoding = self->object = self->start = self->end =
self->reason = NULL;
@@ -1748,8 +1746,8 @@
if (!PyArg_ParseTuple(args, "O!O!O!O!",
&PyUnicode_Type, &self->object,
- &PyInt_Type, &self->start,
- &PyInt_Type, &self->end,
+ &PyLong_Type, &self->start,
+ &PyLong_Type, &self->end,
&PyString_Type, &self->reason)) {
self->object = self->start = self->end = self->reason = NULL;
return -1;
Modified: python/branches/p3yk-noslice/Objects/fileobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/fileobject.c (original)
+++ python/branches/p3yk-noslice/Objects/fileobject.c Fri Feb 23 18:29:35 2007
@@ -118,7 +118,6 @@
f->f_mode = PyString_FromString(mode);
f->f_close = close;
- f->f_softspace = 0;
f->f_binary = strchr(mode,'b') != NULL;
f->f_buf = NULL;
f->f_univ_newline = (strchr(mode, 'U') != NULL);
@@ -354,6 +353,8 @@
{
PyFileObject *file = (PyFileObject*)f;
PyObject *str = PyString_FromString(enc);
+
+ assert(PyFile_Check(f));
if (!str)
return 0;
Py_DECREF(file->f_encoding);
@@ -1521,7 +1522,6 @@
return err_closed();
if (!PyArg_ParseTuple(args, f->f_binary ? "s#" : "t#", &s, &n))
return NULL;
- f->f_softspace = 0;
Py_BEGIN_ALLOW_THREADS
errno = 0;
n2 = fwrite(s, 1, n, f->f_fp);
@@ -1624,7 +1624,6 @@
/* Since we are releasing the global lock, the
following code may *not* execute Python code. */
Py_BEGIN_ALLOW_THREADS
- f->f_softspace = 0;
errno = 0;
for (i = 0; i < j; i++) {
line = PyList_GET_ITEM(list, i);
@@ -1784,8 +1783,6 @@
#define OFF(x) offsetof(PyFileObject, x)
static PyMemberDef file_memberlist[] = {
- {"softspace", T_INT, OFF(f_softspace), 0,
- "flag indicating that a space needs to be printed; used by print"},
{"mode", T_OBJECT, OFF(f_mode), RO,
"file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
{"name", T_OBJECT, OFF(f_name), RO,
@@ -2092,8 +2089,7 @@
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
- /* softspace is writable: we must supply tp_setattro */
- PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
file_doc, /* tp_doc */
@@ -2117,42 +2113,6 @@
PyObject_Del, /* tp_free */
};
-/* Interface for the 'soft space' between print items. */
-
-int
-PyFile_SoftSpace(PyObject *f, int newflag)
-{
- long oldflag = 0;
- if (f == NULL) {
- /* Do nothing */
- }
- else if (PyFile_Check(f)) {
- oldflag = ((PyFileObject *)f)->f_softspace;
- ((PyFileObject *)f)->f_softspace = newflag;
- }
- else {
- PyObject *v;
- v = PyObject_GetAttrString(f, "softspace");
- if (v == NULL)
- PyErr_Clear();
- else {
- if (PyInt_Check(v))
- oldflag = PyInt_AsLong(v);
- assert(oldflag < INT_MAX);
- Py_DECREF(v);
- }
- v = PyInt_FromLong((long)newflag);
- if (v == NULL)
- PyErr_Clear();
- else {
- if (PyObject_SetAttrString(f, "softspace", v) != 0)
- PyErr_Clear();
- Py_DECREF(v);
- }
- }
- return (int)oldflag;
-}
-
/* Interfaces to write objects/strings to file-like objects */
int
@@ -2301,6 +2261,8 @@
return -1;
}
+ if (fd == -1 && PyErr_Occurred())
+ return -1;
if (fd < 0) {
PyErr_Format(PyExc_ValueError,
"file descriptor cannot be a negative integer (%i)",
Modified: python/branches/p3yk-noslice/Objects/floatobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/floatobject.c (original)
+++ python/branches/p3yk-noslice/Objects/floatobject.c Fri Feb 23 18:29:35 2007
@@ -273,10 +273,7 @@
{
register PyObject *obj = *v;
- if (PyInt_Check(obj)) {
- *dbl = (double)PyInt_AS_LONG(obj);
- }
- else if (PyLong_Check(obj)) {
+ if (PyLong_Check(obj)) {
*dbl = PyLong_AsDouble(obj);
if (*dbl == -1.0 && PyErr_Occurred()) {
*v = NULL;
@@ -376,32 +373,6 @@
goto Unimplemented;
}
- else if (PyInt_Check(w)) {
- long jj = PyInt_AS_LONG(w);
- /* In the worst realistic case I can imagine, C double is a
- * Cray single with 48 bits of precision, and long has 64
- * bits.
- */
-#if SIZEOF_LONG > 6
- unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
- if (abs >> 48) {
- /* Needs more than 48 bits. Make it take the
- * PyLong path.
- */
- PyObject *result;
- PyObject *ww = PyLong_FromLong(jj);
-
- if (ww == NULL)
- return NULL;
- result = float_richcompare(v, ww, op);
- Py_DECREF(ww);
- return result;
- }
-#endif
- j = (double)jj;
- assert((long)j == jj);
- }
-
else if (PyLong_Check(w)) {
int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
int wsign = _PyLong_Sign(w);
Modified: python/branches/p3yk-noslice/Objects/frameobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/frameobject.c (original)
+++ python/branches/p3yk-noslice/Objects/frameobject.c Fri Feb 23 18:29:35 2007
@@ -88,7 +88,7 @@
int setup_op = 0; /* (ditto) */
/* f_lineno must be an integer. */
- if (!PyInt_Check(p_new_lineno)) {
+ if (!PyInt_CheckExact(p_new_lineno)) {
PyErr_SetString(PyExc_ValueError,
"lineno must be an integer");
return -1;
Modified: python/branches/p3yk-noslice/Objects/intobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/intobject.c (original)
+++ python/branches/p3yk-noslice/Objects/intobject.c Fri Feb 23 18:29:35 2007
@@ -10,6 +10,7 @@
return LONG_MAX; /* To initialize sys.maxint */
}
+#if 0
/* Integers are quite normal objects, to make object handling uniform.
(Using odd pointers to represent integers would save much space
but require extra checks for this special case throughout the code.)
@@ -1049,8 +1050,9 @@
argument will be truncated towards zero (this does not include a string\n\
representation of a floating point number!) When converting a string, use\n\
the optional base. It is an error to supply a base when converting a\n\
-non-string. If the argument is outside the integer range a long object\n\
-will be returned instead.");
+non-string. If base is zero, the proper base is guessed based on the\n\
+string content. If the argument is outside the integer range a\n\
+long object will be returned instead.");
static PyNumberMethods int_as_number = {
(binaryfunc)int_add, /*nb_add*/
@@ -1254,3 +1256,4 @@
}
}
}
+#endif /* if 0 */
Modified: python/branches/p3yk-noslice/Objects/iterobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/iterobject.c (original)
+++ python/branches/p3yk-noslice/Objects/iterobject.c Fri Feb 23 18:29:35 2007
@@ -302,7 +302,6 @@
zipiter->result = (PyTupleObject*) result;
zipiter->resultsize = tuplesize;
- Py_INCREF(ziptuple);
zipiter->it_tuple = (PyTupleObject *) ziptuple;
_PyObject_GC_TRACK(zipiter);
return (PyObject *)zipiter;
Modified: python/branches/p3yk-noslice/Objects/listobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/listobject.c (original)
+++ python/branches/p3yk-noslice/Objects/listobject.c Fri Feb 23 18:29:35 2007
@@ -945,7 +945,7 @@
Py_DECREF(args);
if (res == NULL)
return -1;
- if (!PyInt_Check(res)) {
+ if (!PyInt_CheckExact(res)) {
PyErr_Format(PyExc_TypeError,
"comparison function must return int, not %.200s",
res->ob_type->tp_name);
Modified: python/branches/p3yk-noslice/Objects/longobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/longobject.c (original)
+++ python/branches/p3yk-noslice/Objects/longobject.c Fri Feb 23 18:29:35 2007
@@ -7,6 +7,53 @@
#include <ctype.h>
+#ifndef NSMALLPOSINTS
+#define NSMALLPOSINTS 257
+#endif
+#ifndef NSMALLNEGINTS
+#define NSMALLNEGINTS 5
+#endif
+#if NSMALLNEGINTS + NSMALLPOSINTS > 0
+/* Small integers are preallocated in this array so that they
+ can be shared.
+ The integers that are preallocated are those in the range
+ -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
+*/
+static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
+#ifdef COUNT_ALLOCS
+int quick_int_allocs, quick_neg_int_allocs;
+#endif
+
+static inline PyObject *
+get_small_int(int ival)
+{
+ PyObject *v = (PyObject*)(small_ints + ival + NSMALLNEGINTS);
+ Py_INCREF(v);
+#ifdef COUNT_ALLOCS
+ if (ival >= 0)
+ quick_int_allocs++;
+ else
+ quick_neg_int_allocs++;
+#endif
+ return v;
+}
+#define CHECK_SMALL_INT(ival) \
+ do if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) { \
+ return get_small_int(ival); \
+ } while(0)
+
+#else
+#define CHECK_SMALL_INT(ival)
+#endif
+
+#define MEDIUM_VALUE(x) ((x)->ob_size < 0 ? -(x)->ob_digit[0] : ((x)->ob_size == 0 ? 0 : (x)->ob_digit[0]))
+/* If a freshly-allocated long is already shared, it must
+ be a small integer, so negating it must go to PyLong_FromLong */
+#define NEGATE(x) \
+ do if ((x)->ob_refcnt == 1) (x)->ob_size = -(x)->ob_size; \
+ else { PyObject* tmp=PyInt_FromLong(-MEDIUM_VALUE(x)); \
+ Py_DECREF(x); (x) = (PyLongObject*)tmp; } \
+ while(0)
/* For long multiplication, use the O(N**2) school algorithm unless
* both operands contain more than KARATSUBA_CUTOFF digits (this
* being an internal Python long digit, in base BASE).
@@ -64,11 +111,21 @@
PyLongObject *
_PyLong_New(Py_ssize_t size)
{
- if (size > PY_SSIZE_T_MAX) {
+ PyLongObject *result;
+ /* Can't use sizeof(PyLongObject) here, since the
+ compiler takes padding at the end into account.
+ As the consequence, this would waste 2 bytes on
+ a 32-bit system, and 6 bytes on a 64-bit system.
+ This computation would be incorrect on systems
+ which have padding before the digits; with 16-bit
+ digits this should not happen. */
+ result = PyObject_MALLOC(sizeof(PyVarObject) +
+ size*sizeof(digit));
+ if (!result) {
PyErr_NoMemory();
return NULL;
}
- return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
+ return (PyLongObject*)PyObject_INIT_VAR(result, &PyLong_Type, size);
}
PyObject *
@@ -81,6 +138,12 @@
i = src->ob_size;
if (i < 0)
i = -(i);
+ if (i < 2) {
+ int ival = src->ob_digit[0];
+ if (src->ob_size < 0)
+ ival = -ival;
+ CHECK_SMALL_INT(ival);
+ }
result = _PyLong_New(i);
if (result != NULL) {
result->ob_size = src->ob_size;
@@ -98,17 +161,37 @@
PyLongObject *v;
unsigned long t; /* unsigned so >> doesn't propagate sign bit */
int ndigits = 0;
- int negative = 0;
+ int sign = 1;
+
+ CHECK_SMALL_INT(ival);
if (ival < 0) {
ival = -ival;
- negative = 1;
+ sign = -1;
}
- /* Count the number of Python digits.
- We used to pick 5 ("big enough for anything"), but that's a
- waste of time and space given that 5*15 = 75 bits are rarely
- needed. */
+ /* Fast path for single-digits ints */
+ if (!(ival>>SHIFT)) {
+ v = _PyLong_New(1);
+ if (v) {
+ v->ob_size = sign;
+ v->ob_digit[0] = ival;
+ }
+ return (PyObject*)v;
+ }
+
+ /* 2 digits */
+ if (!(ival >> 2*SHIFT)) {
+ v = _PyLong_New(2);
+ if (v) {
+ v->ob_size = 2*sign;
+ v->ob_digit[0] = (digit)ival & MASK;
+ v->ob_digit[1] = ival >> SHIFT;
+ }
+ return (PyObject*)v;
+ }
+
+ /* Larger numbers: loop to determine number of digits */
t = (unsigned long)ival;
while (t) {
++ndigits;
@@ -117,7 +200,7 @@
v = _PyLong_New(ndigits);
if (v != NULL) {
digit *p = v->ob_digit;
- v->ob_size = negative ? -ndigits : ndigits;
+ v->ob_size = ndigits*sign;
t = (unsigned long)ival;
while (t) {
*p++ = (digit)(t & MASK);
@@ -136,6 +219,8 @@
unsigned long t;
int ndigits = 0;
+ if (ival < BASE)
+ return PyLong_FromLong(ival);
/* Count the number of Python digits. */
t = (unsigned long)ival;
while (t) {
@@ -165,9 +250,10 @@
neg = 0;
if (Py_IS_INFINITY(dval)) {
PyErr_SetString(PyExc_OverflowError,
- "cannot convert float infinity to long");
+ "cannot convert float infinity to int");
return NULL;
}
+ CHECK_SMALL_INT((int)dval);
if (dval < 0.0) {
neg = 1;
dval = -dval;
@@ -214,15 +300,39 @@
unsigned long x, prev;
Py_ssize_t i;
int sign;
+ int do_decref = 0; /* if nb_int was called */
- if (vv == NULL || !PyLong_Check(vv)) {
- if (vv != NULL && PyInt_Check(vv))
- return PyInt_AsLong(vv);
+ if (vv == NULL) {
PyErr_BadInternalCall();
return -1;
}
+
+ if (!PyLong_Check(vv)) {
+ PyNumberMethods *nb;
+ if ((nb = vv->ob_type->tp_as_number) == NULL ||
+ nb->nb_int == NULL) {
+ PyErr_SetString(PyExc_TypeError, "an integer is required");
+ return -1;
+ }
+ vv = (*nb->nb_int) (vv);
+ if (vv == NULL)
+ return -1;
+ do_decref = 1;
+ if (!PyLong_Check(vv)) {
+ Py_DECREF(vv);
+ PyErr_SetString(PyExc_TypeError,
+ "nb_int should return int object");
+ return -1;
+ }
+ }
+
v = (PyLongObject *)vv;
i = v->ob_size;
+ switch (i) {
+ case -1: return -v->ob_digit[0];
+ case 0: return 0;
+ case 1: return v->ob_digit[0];
+ }
sign = 1;
x = 0;
if (i < 0) {
@@ -235,6 +345,9 @@
if ((x >> SHIFT) != prev)
goto overflow;
}
+ if (do_decref) {
+ Py_DECREF(vv);
+ }
/* Haven't lost any bits, but casting to long requires extra care
* (see comment above).
*/
@@ -247,16 +360,32 @@
/* else overflow */
overflow:
+ if (do_decref) {
+ Py_DECREF(vv);
+ }
PyErr_SetString(PyExc_OverflowError,
- "long int too large to convert to int");
+ "Python int too large to convert to C long");
return -1;
}
+int
+_PyLong_FitsInLong(PyObject *vv)
+{
+ int size;
+ if (!PyLong_CheckExact(vv)) {
+ PyErr_BadInternalCall();
+ return 0;
+ }
+ /* conservative estimate */
+ size = ((PyLongObject*)vv)->ob_size;
+ return -2 <= size && size <= 2;
+}
+
/* Get a Py_ssize_t from a long int object.
Returns -1 and sets an error condition if overflow occurs. */
Py_ssize_t
-_PyLong_AsSsize_t(PyObject *vv) {
+PyLong_AsSsize_t(PyObject *vv) {
register PyLongObject *v;
size_t x, prev;
Py_ssize_t i;
@@ -268,6 +397,11 @@
}
v = (PyLongObject *)vv;
i = v->ob_size;
+ switch (i) {
+ case -1: return -v->ob_digit[0];
+ case 0: return 0;
+ case 1: return v->ob_digit[0];
+ }
sign = 1;
x = 0;
if (i < 0) {
@@ -293,7 +427,7 @@
overflow:
PyErr_SetString(PyExc_OverflowError,
- "long int too large to convert to int");
+ "Python int too large to convert to C ssize_t");
return -1;
}
@@ -308,15 +442,6 @@
Py_ssize_t i;
if (vv == NULL || !PyLong_Check(vv)) {
- if (vv != NULL && PyInt_Check(vv)) {
- long val = PyInt_AsLong(vv);
- if (val < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "can't convert negative value to unsigned long");
- return (unsigned long) -1;
- }
- return val;
- }
PyErr_BadInternalCall();
return (unsigned long) -1;
}
@@ -325,15 +450,57 @@
x = 0;
if (i < 0) {
PyErr_SetString(PyExc_OverflowError,
- "can't convert negative value to unsigned long");
+ "can't convert negative value to unsigned int");
return (unsigned long) -1;
}
+ switch (i) {
+ case 0: return 0;
+ case 1: return v->ob_digit[0];
+ }
+ while (--i >= 0) {
+ prev = x;
+ x = (x << SHIFT) + v->ob_digit[i];
+ if ((x >> SHIFT) != prev) {
+ PyErr_SetString(PyExc_OverflowError,
+ "python int too large to convert to C unsigned long");
+ return (unsigned long) -1;
+ }
+ }
+ return x;
+}
+
+/* Get a C unsigned long int from a long int object.
+ Returns -1 and sets an error condition if overflow occurs. */
+
+size_t
+PyLong_AsSize_t(PyObject *vv)
+{
+ register PyLongObject *v;
+ size_t x, prev;
+ Py_ssize_t i;
+
+ if (vv == NULL || !PyLong_Check(vv)) {
+ PyErr_BadInternalCall();
+ return (unsigned long) -1;
+ }
+ v = (PyLongObject *)vv;
+ i = v->ob_size;
+ x = 0;
+ if (i < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative value to size_t");
+ return (size_t) -1;
+ }
+ switch (i) {
+ case 0: return 0;
+ case 1: return v->ob_digit[0];
+ }
while (--i >= 0) {
prev = x;
x = (x << SHIFT) + v->ob_digit[i];
if ((x >> SHIFT) != prev) {
PyErr_SetString(PyExc_OverflowError,
- "long int too large to convert");
+ "Python int too large to convert to C size_t");
return (unsigned long) -1;
}
}
@@ -343,8 +510,8 @@
/* Get a C unsigned long int from a long int object, ignoring the high bits.
Returns -1 and sets an error condition if an error occurs. */
-unsigned long
-PyLong_AsUnsignedLongMask(PyObject *vv)
+static unsigned long
+_PyLong_AsUnsignedLongMask(PyObject *vv)
{
register PyLongObject *v;
unsigned long x;
@@ -352,13 +519,15 @@
int sign;
if (vv == NULL || !PyLong_Check(vv)) {
- if (vv != NULL && PyInt_Check(vv))
- return PyInt_AsUnsignedLongMask(vv);
PyErr_BadInternalCall();
return (unsigned long) -1;
}
v = (PyLongObject *)vv;
i = v->ob_size;
+ switch (i) {
+ case 0: return 0;
+ case 1: return v->ob_digit[0];
+ }
sign = 1;
x = 0;
if (i < 0) {
@@ -371,6 +540,41 @@
return x * sign;
}
+unsigned long
+PyLong_AsUnsignedLongMask(register PyObject *op)
+{
+ PyNumberMethods *nb;
+ PyLongObject *lo;
+ unsigned long val;
+
+ if (op && PyLong_Check(op))
+ return _PyLong_AsUnsignedLongMask(op);
+
+ if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
+ nb->nb_int == NULL) {
+ PyErr_SetString(PyExc_TypeError, "an integer is required");
+ return (unsigned long)-1;
+ }
+
+ lo = (PyLongObject*) (*nb->nb_int) (op);
+ if (lo == NULL)
+ return (unsigned long)-1;
+ if (PyLong_Check(lo)) {
+ val = _PyLong_AsUnsignedLongMask((PyObject *)lo);
+ Py_DECREF(lo);
+ if (PyErr_Occurred())
+ return (unsigned long)-1;
+ return val;
+ }
+ else
+ {
+ Py_DECREF(lo);
+ PyErr_SetString(PyExc_TypeError,
+ "nb_int should return int object");
+ return (unsigned long)-1;
+ }
+}
+
int
_PyLong_Sign(PyObject *vv)
{
@@ -409,7 +613,7 @@
return result;
Overflow:
- PyErr_SetString(PyExc_OverflowError, "long has too many bits "
+ PyErr_SetString(PyExc_OverflowError, "int has too many bits "
"to express in a platform size_t");
return (size_t)-1;
}
@@ -542,7 +746,7 @@
ndigits = -(v->ob_size);
if (!is_signed) {
PyErr_SetString(PyExc_TypeError,
- "can't convert negative long to unsigned");
+ "can't convert negative int to unsigned");
return -1;
}
do_twos_comp = 1;
@@ -653,7 +857,7 @@
return 0;
Overflow:
- PyErr_SetString(PyExc_OverflowError, "long too big to convert");
+ PyErr_SetString(PyExc_OverflowError, "int too big to convert");
return -1;
}
@@ -739,7 +943,7 @@
overflow:
PyErr_SetString(PyExc_OverflowError,
- "long int too large to convert to float");
+ "Python int too large to convert to C double");
return -1.0;
}
@@ -748,24 +952,17 @@
PyObject *
PyLong_FromVoidPtr(void *p)
{
-#if SIZEOF_VOID_P <= SIZEOF_LONG
- if ((long)p < 0)
- return PyLong_FromUnsignedLong((unsigned long)p);
- return PyInt_FromLong((long)p);
-#else
-
#ifndef HAVE_LONG_LONG
# error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
#endif
#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
#endif
- /* optimize null pointers */
- if (p == NULL)
+ /* special-case null pointer */
+ if (!p)
return PyInt_FromLong(0);
- return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
+ return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)(Py_uintptr_t)p);
-#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
}
/* Get a C pointer from a long object (or an int object in some cases) */
@@ -780,9 +977,7 @@
#if SIZEOF_VOID_P <= SIZEOF_LONG
long x;
- if (PyInt_Check(vv))
- x = PyInt_AS_LONG(vv);
- else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
+ if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
x = PyLong_AsLong(vv);
else
x = PyLong_AsUnsignedLong(vv);
@@ -796,9 +991,7 @@
#endif
PY_LONG_LONG x;
- if (PyInt_Check(vv))
- x = PyInt_AS_LONG(vv);
- else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
+ if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
x = PyLong_AsLongLong(vv);
else
x = PyLong_AsUnsignedLongLong(vv);
@@ -828,6 +1021,7 @@
int ndigits = 0;
int negative = 0;
+ CHECK_SMALL_INT(ival);
if (ival < 0) {
ival = -ival;
negative = 1;
@@ -864,6 +1058,8 @@
unsigned PY_LONG_LONG t;
int ndigits = 0;
+ if (ival < BASE)
+ return PyLong_FromLong(ival);
/* Count the number of Python digits. */
t = (unsigned PY_LONG_LONG)ival;
while (t) {
@@ -885,22 +1081,26 @@
/* Create a new long int object from a C Py_ssize_t. */
PyObject *
-_PyLong_FromSsize_t(Py_ssize_t ival)
+PyLong_FromSsize_t(Py_ssize_t ival)
{
Py_ssize_t bytes = ival;
int one = 1;
+ if (ival < BASE)
+ return PyLong_FromLong(ival);
return _PyLong_FromByteArray(
(unsigned char *)&bytes,
- SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
+ SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
}
/* Create a new long int object from a C size_t. */
PyObject *
-_PyLong_FromSize_t(size_t ival)
+PyLong_FromSize_t(size_t ival)
{
size_t bytes = ival;
int one = 1;
+ if (ival < BASE)
+ return PyLong_FromLong(ival);
return _PyLong_FromByteArray(
(unsigned char *)&bytes,
SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
@@ -912,6 +1112,7 @@
PY_LONG_LONG
PyLong_AsLongLong(PyObject *vv)
{
+ PyLongObject *v;
PY_LONG_LONG bytes;
int one = 1;
int res;
@@ -923,8 +1124,6 @@
if (!PyLong_Check(vv)) {
PyNumberMethods *nb;
PyObject *io;
- if (PyInt_Check(vv))
- return (PY_LONG_LONG)PyInt_AsLong(vv);
if ((nb = vv->ob_type->tp_as_number) == NULL ||
nb->nb_int == NULL) {
PyErr_SetString(PyExc_TypeError, "an integer is required");
@@ -933,11 +1132,6 @@
io = (*nb->nb_int) (vv);
if (io == NULL)
return -1;
- if (PyInt_Check(io)) {
- bytes = PyInt_AsLong(io);
- Py_DECREF(io);
- return bytes;
- }
if (PyLong_Check(io)) {
bytes = PyLong_AsLongLong(io);
Py_DECREF(io);
@@ -948,6 +1142,12 @@
return -1;
}
+ v = (PyLongObject*)vv;
+ switch(v->ob_size) {
+ case -1: return -v->ob_digit[0];
+ case 0: return 0;
+ case 1: return v->ob_digit[0];
+ }
res = _PyLong_AsByteArray(
(PyLongObject *)vv, (unsigned char *)&bytes,
SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
@@ -965,6 +1165,7 @@
unsigned PY_LONG_LONG
PyLong_AsUnsignedLongLong(PyObject *vv)
{
+ PyLongObject *v;
unsigned PY_LONG_LONG bytes;
int one = 1;
int res;
@@ -974,6 +1175,12 @@
return (unsigned PY_LONG_LONG)-1;
}
+ v = (PyLongObject*)vv;
+ switch(v->ob_size) {
+ case 0: return 0;
+ case 1: return v->ob_digit[0];
+ }
+
res = _PyLong_AsByteArray(
(PyLongObject *)vv, (unsigned char *)&bytes,
SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
@@ -988,8 +1195,8 @@
/* Get a C unsigned long int from a long int object, ignoring the high bits.
Returns -1 and sets an error condition if an error occurs. */
-unsigned PY_LONG_LONG
-PyLong_AsUnsignedLongLongMask(PyObject *vv)
+static unsigned PY_LONG_LONG
+_PyLong_AsUnsignedLongLongMask(PyObject *vv)
{
register PyLongObject *v;
unsigned PY_LONG_LONG x;
@@ -1001,6 +1208,10 @@
return (unsigned long) -1;
}
v = (PyLongObject *)vv;
+ switch(v->ob_size) {
+ case 0: return 0;
+ case 1: return v->ob_digit[0];
+ }
i = v->ob_size;
sign = 1;
x = 0;
@@ -1013,6 +1224,41 @@
}
return x * sign;
}
+
+unsigned PY_LONG_LONG
+PyLong_AsUnsignedLongLongMask(register PyObject *op)
+{
+ PyNumberMethods *nb;
+ PyLongObject *lo;
+ unsigned PY_LONG_LONG val;
+
+ if (op && PyLong_Check(op))
+ return _PyLong_AsUnsignedLongLongMask(op);
+
+ if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
+ nb->nb_int == NULL) {
+ PyErr_SetString(PyExc_TypeError, "an integer is required");
+ return (unsigned PY_LONG_LONG)-1;
+ }
+
+ lo = (PyLongObject*) (*nb->nb_int) (op);
+ if (lo == NULL)
+ return (unsigned PY_LONG_LONG)-1;
+ if (PyLong_Check(lo)) {
+ val = _PyLong_AsUnsignedLongLongMask((PyObject *)lo);
+ Py_DECREF(lo);
+ if (PyErr_Occurred())
+ return (unsigned PY_LONG_LONG)-1;
+ return val;
+ }
+ else
+ {
+ Py_DECREF(lo);
+ PyErr_SetString(PyExc_TypeError,
+ "nb_int should return int object");
+ return (unsigned PY_LONG_LONG)-1;
+ }
+}
#undef IS_LITTLE_ENDIAN
#endif /* HAVE_LONG_LONG */
@@ -1024,9 +1270,6 @@
*a = (PyLongObject *) v;
Py_INCREF(v);
}
- else if (PyInt_Check(v)) {
- *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
- }
else {
return 0;
}
@@ -1034,9 +1277,6 @@
*b = (PyLongObject *) w;
Py_INCREF(w);
}
- else if (PyInt_Check(w)) {
- *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
- }
else {
Py_DECREF(*a);
return 0;
@@ -1206,7 +1446,7 @@
sz = i + j / bits;
if (j / SHIFT < size_a || sz < i) {
PyErr_SetString(PyExc_OverflowError,
- "long is too large to format");
+ "int is too large to format");
return NULL;
}
str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
@@ -1386,7 +1626,7 @@
n = (p - start) * bits_per_char + SHIFT - 1;
if (n / bits_per_char < p - start) {
PyErr_SetString(PyExc_ValueError,
- "long string too large to convert");
+ "int string too large to convert");
return NULL;
}
n = n / SHIFT;
@@ -1433,7 +1673,7 @@
if ((base != 0 && base < 2) || base > 36) {
PyErr_SetString(PyExc_ValueError,
- "long() arg 2 must be >= 2 and <= 36");
+ "int() arg 2 must be >= 2 and <= 36");
return NULL;
}
while (*str != '\0' && isspace(Py_CHARMASK(*str)))
@@ -1683,7 +1923,7 @@
if (strrepr == NULL)
return NULL;
PyErr_Format(PyExc_ValueError,
- "invalid literal for long() with base %d: %s",
+ "invalid literal for int() with base %d: %s",
base, PyString_AS_STRING(strrepr));
Py_DECREF(strrepr);
return NULL;
@@ -1727,14 +1967,14 @@
if (size_b == 0) {
PyErr_SetString(PyExc_ZeroDivisionError,
- "long division or modulo by zero");
+ "integer division or modulo by zero");
return -1;
}
if (size_a < size_b ||
(size_a == size_b &&
a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
/* |a| < |b|. */
- *pdiv = _PyLong_New(0);
+ *pdiv = (PyLongObject*)PyLong_FromLong(0);
Py_INCREF(a);
*prem = (PyLongObject *) a;
return 0;
@@ -1756,9 +1996,9 @@
the remainder r has the sign of a,
so a = b*z + r. */
if ((a->ob_size < 0) != (b->ob_size < 0))
- z->ob_size = -(z->ob_size);
+ NEGATE(z);
if (a->ob_size < 0 && (*prem)->ob_size != 0)
- (*prem)->ob_size = -((*prem)->ob_size);
+ NEGATE(*prem);
*pdiv = z;
return 0;
}
@@ -1907,8 +2147,12 @@
long_richcompare(PyObject *self, PyObject *other, int op)
{
PyLongObject *a, *b;
+ PyObject *result;
CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b);
- return Py_CmpToRich(op, long_compare(a, b));
+ result = Py_CmpToRich(op, long_compare(a, b));
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return result;
}
static long
@@ -1922,6 +2166,11 @@
same value hash to the same value, otherwise comparisons
of mapping keys will turn out weird */
i = v->ob_size;
+ switch(i) {
+ case -1: return v->ob_digit[0]==1 ? -2 : -v->ob_digit[0];
+ case 0: return 0;
+ case 1: return v->ob_digit[0];
+ }
sign = 1;
x = 0;
if (i < 0) {
@@ -2027,7 +2276,7 @@
}
assert(borrow == 0);
if (sign < 0)
- z->ob_size = -(z->ob_size);
+ NEGATE(z);
return long_normalize(z);
}
@@ -2038,6 +2287,13 @@
CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
+ if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) {
+ PyObject *result = PyInt_FromLong(MEDIUM_VALUE(a) +
+ MEDIUM_VALUE(b));
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return result;
+ }
if (a->ob_size < 0) {
if (b->ob_size < 0) {
z = x_add(a, b);
@@ -2065,6 +2321,13 @@
CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
+ if (ABS(a->ob_size) <= 1 && ABS(b->ob_size) <= 1) {
+ PyObject* r;
+ r = PyLong_FromLong(MEDIUM_VALUE(a)-MEDIUM_VALUE(b));
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return r;
+ }
if (a->ob_size < 0) {
if (b->ob_size < 0)
z = x_sub(a, b);
@@ -2494,10 +2757,18 @@
return Py_NotImplemented;
}
+ if (ABS(v->ob_size) <= 1 && ABS(w->ob_size) <= 1) {
+ PyObject *r;
+ r = PyLong_FromLong(MEDIUM_VALUE(v)*MEDIUM_VALUE(w));
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return r;
+ }
+
z = k_mul(a, b);
/* Negate if exactly one of the inputs is negative. */
if (((a->ob_size ^ b->ob_size) < 0) && z)
- z->ob_size = -(z->ob_size);
+ NEGATE(z);
Py_DECREF(a);
Py_DECREF(b);
return (PyObject *)z;
@@ -2603,7 +2874,7 @@
if (bd == 0.0) {
PyErr_SetString(PyExc_ZeroDivisionError,
- "long division or modulo by zero");
+ "int division or modulo by zero");
return NULL;
}
@@ -2622,7 +2893,7 @@
overflow:
PyErr_SetString(PyExc_OverflowError,
- "long/long too large for a float");
+ "int/int too large for a float");
return NULL;
}
@@ -2691,11 +2962,6 @@
c = (PyLongObject *)x;
Py_INCREF(x);
}
- else if (PyInt_Check(x)) {
- c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
- if (c == NULL)
- goto Error;
- }
else if (x == Py_None)
c = NULL;
else {
@@ -2741,7 +3007,7 @@
Py_DECREF(c);
c = temp;
temp = NULL;
- c->ob_size = - c->ob_size;
+ NEGATE(c);
}
/* if modulus == 1:
@@ -2862,6 +3128,8 @@
/* Implement ~x as -(x+1) */
PyLongObject *x;
PyLongObject *w;
+ if (ABS(v->ob_size) <=1)
+ return PyLong_FromLong(-(MEDIUM_VALUE(v)+1));
w = (PyLongObject *)PyLong_FromLong(1L);
if (w == NULL)
return NULL;
@@ -2888,11 +3156,8 @@
long_neg(PyLongObject *v)
{
PyLongObject *z;
- if (v->ob_size == 0 && PyLong_CheckExact(v)) {
- /* -0 == 0 */
- Py_INCREF(v);
- return (PyObject *) v;
- }
+ if (ABS(v->ob_size) <= 1)
+ return PyLong_FromLong(-MEDIUM_VALUE(v));
z = (PyLongObject *)_PyLong_Copy(v);
if (z != NULL)
z->ob_size = -(v->ob_size);
@@ -3016,7 +3281,7 @@
if (z == NULL)
goto lshift_error;
if (a->ob_size < 0)
- z->ob_size = -(z->ob_size);
+ NEGATE(z);
for (i = 0; i < wordshift; i++)
z->ob_digit[i] = 0;
accum = 0;
@@ -3194,22 +3459,7 @@
static PyObject *
long_int(PyObject *v)
{
- long x;
- x = PyLong_AsLong(v);
- if (PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
- PyErr_Clear();
- if (PyLong_CheckExact(v)) {
- Py_INCREF(v);
- return v;
- }
- else
- return _PyLong_Copy((PyLongObject *)v);
- }
- else
- return NULL;
- }
- return PyInt_FromLong(x);
+ return long_long(v);
}
static PyObject *
@@ -3246,15 +3496,25 @@
if (type != &PyLong_Type)
return long_subtype_new(type, args, kwds); /* Wimp out */
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
&x, &base))
return NULL;
if (x == NULL)
return PyLong_FromLong(0L);
if (base == -909)
return PyNumber_Long(x);
- else if (PyString_Check(x))
- return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
+ else if (PyString_Check(x)) {
+ char *s = PyString_AS_STRING(x);
+ char *end;
+ PyObject *r = PyLong_FromString(s, &end, base);
+ if (r != NULL && end != s + PyString_GET_SIZE(x)) {
+ PyErr_SetString(PyExc_ValueError,
+ "null byte in argument for int()");
+ Py_DECREF(r);
+ r = NULL;
+ }
+ return r;
+ }
#ifdef Py_USING_UNICODE
else if (PyUnicode_Check(x))
return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
@@ -3263,7 +3523,7 @@
#endif
else {
PyErr_SetString(PyExc_TypeError,
- "long() can't convert non-string with explicit base");
+ "int() can't convert non-string with explicit base");
return NULL;
}
}
@@ -3312,9 +3572,9 @@
};
PyDoc_STRVAR(long_doc,
-"long(x[, base]) -> integer\n\
+"int(x[, base]) -> integer\n\
\n\
-Convert a string or number to a long integer, if possible. A floating\n\
+Convert a string or number to an integer, if possible. A floating\n\
point argument will be truncated towards zero (this does not include a\n\
string representation of a floating point number!) When converting a\n\
string, use the optional base. It is an error to supply a base when\n\
@@ -3363,8 +3623,10 @@
PyTypeObject PyLong_Type = {
PyObject_HEAD_INIT(&PyType_Type)
0, /* ob_size */
- "long", /* tp_name */
- sizeof(PyLongObject) - sizeof(digit), /* tp_basicsize */
+ "int", /* tp_name */
+ /* See _PyLong_New for why this isn't
+ sizeof(PyLongObject) - sizeof(digit) */
+ sizeof(PyVarObject), /* tp_basicsize */
sizeof(digit), /* tp_itemsize */
long_dealloc, /* tp_dealloc */
0, /* tp_print */
@@ -3377,7 +3639,7 @@
0, /* tp_as_mapping */
(hashfunc)long_hash, /* tp_hash */
0, /* tp_call */
- 0, /* tp_str */
+ long_repr, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
@@ -3402,3 +3664,43 @@
long_new, /* tp_new */
PyObject_Del, /* tp_free */
};
+
+int
+_PyLong_Init(void)
+{
+#if NSMALLNEGINTS + NSMALLPOSINTS > 0
+ int ival;
+ PyLongObject *v = small_ints;
+ for (ival = -NSMALLNEGINTS; ival < 0; ival++, v++) {
+ PyObject_INIT(v, &PyLong_Type);
+ v->ob_size = -1;
+ v->ob_digit[0] = -ival;
+ }
+ for (; ival < NSMALLPOSINTS; ival++, v++) {
+ PyObject_INIT(v, &PyLong_Type);
+ v->ob_size = ival ? 1 : 0;
+ v->ob_digit[0] = ival;
+ }
+#endif
+ return 1;
+}
+
+void
+PyLong_Fini(void)
+{
+#if 0
+ int i;
+ /* This is currently not needed; the small integers
+ are statically allocated */
+#if NSMALLNEGINTS + NSMALLPOSINTS > 0
+ PyIntObject **q;
+
+ i = NSMALLNEGINTS + NSMALLPOSINTS;
+ q = small_ints;
+ while (--i >= 0) {
+ Py_XDECREF(*q);
+ *q++ = NULL;
+ }
+#endif
+#endif
+}
Modified: python/branches/p3yk-noslice/Objects/object.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/object.c (original)
+++ python/branches/p3yk-noslice/Objects/object.c Fri Feb 23 18:29:35 2007
@@ -314,7 +314,7 @@
/* For debugging convenience. Set a breakpoint here and call it from your DLL */
void
-_Py_Break(void)
+_Py_BreakPoint(void)
{
}
Modified: python/branches/p3yk-noslice/Objects/setobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/setobject.c (original)
+++ python/branches/p3yk-noslice/Objects/setobject.c Fri Feb 23 18:29:35 2007
@@ -932,14 +932,31 @@
{
PyObject *key, *it;
- if (PyAnySet_Check(other))
+ if (PyAnySet_CheckExact(other))
return set_merge(so, other);
- if (PyDict_Check(other)) {
+ if (PyDict_CheckExact(other)) {
PyObject *value;
Py_ssize_t pos = 0;
- while (PyDict_Next(other, &pos, &key, &value)) {
- if (set_add_key(so, key) == -1)
+ long hash;
+ Py_ssize_t dictsize = PyDict_Size(other);
+
+ /* Do one big resize at the start, rather than
+ * incrementally resizing as we insert new keys. Expect
+ * that there will be no (or few) overlapping keys.
+ */
+ if (dictsize == -1)
+ return -1;
+ if ((so->fill + dictsize)*3 >= (so->mask+1)*2) {
+ if (set_table_resize(so, (so->used + dictsize)*2) != 0)
+ return -1;
+ }
+ while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
+ setentry an_entry;
+
+ an_entry.hash = hash;
+ an_entry.key = key;
+ if (set_add_entry(so, &an_entry) == -1)
return -1;
}
return 0;
@@ -1024,7 +1041,7 @@
{
PyObject *iterable = NULL, *result;
- if (!_PyArg_NoKeywords("frozenset()", kwds))
+ if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds))
return NULL;
if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable))
@@ -1068,7 +1085,7 @@
static PyObject *
set_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- if (!_PyArg_NoKeywords("set()", kwds))
+ if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds))
return NULL;
return make_new_set(type, NULL);
@@ -1210,7 +1227,7 @@
if (result == NULL)
return NULL;
- if (PyAnySet_Check(other)) {
+ if (PyAnySet_CheckExact(other)) {
Py_ssize_t pos = 0;
setentry *entry;
@@ -1334,7 +1351,7 @@
if ((PyObject *)so == other)
return set_clear_internal(so);
- if (PyAnySet_Check(other)) {
+ if (PyAnySet_CheckExact(other)) {
setentry *entry;
Py_ssize_t pos = 0;
@@ -1383,7 +1400,7 @@
setentry *entry;
Py_ssize_t pos = 0;
- if (!PyAnySet_Check(other) && !PyDict_Check(other)) {
+ if (!PyAnySet_CheckExact(other) && !PyDict_CheckExact(other)) {
result = set_copy(so);
if (result == NULL)
return NULL;
@@ -1397,12 +1414,12 @@
if (result == NULL)
return NULL;
- if (PyDict_Check(other)) {
+ if (PyDict_CheckExact(other)) {
while (set_next(so, &pos, &entry)) {
setentry entrycopy;
entrycopy.hash = entry->hash;
entrycopy.key = entry->key;
- if (!PyDict_Contains(other, entry->key)) {
+ if (!_PyDict_Contains(other, entry->key, entry->hash)) {
if (set_add_entry((PySetObject *)result, &entrycopy) == -1) {
Py_DECREF(result);
return NULL;
@@ -1470,15 +1487,13 @@
if ((PyObject *)so == other)
return set_clear(so);
- if (PyDict_Check(other)) {
+ if (PyDict_CheckExact(other)) {
PyObject *value;
int rv;
- while (PyDict_Next(other, &pos, &key, &value)) {
+ long hash;
+ while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
setentry an_entry;
- long hash = PyObject_Hash(key);
- if (hash == -1)
- return NULL;
an_entry.hash = hash;
an_entry.key = key;
rv = set_discard_entry(so, &an_entry);
@@ -1492,7 +1507,7 @@
Py_RETURN_NONE;
}
- if (PyAnySet_Check(other)) {
+ if (PyAnySet_CheckExact(other)) {
Py_INCREF(other);
otherset = (PySetObject *)other;
} else {
@@ -1575,7 +1590,7 @@
setentry *entry;
Py_ssize_t pos = 0;
- if (!PyAnySet_Check(other)) {
+ if (!PyAnySet_CheckExact(other)) {
PyObject *tmp, *result;
tmp = make_new_set(&PySet_Type, other);
if (tmp == NULL)
@@ -1604,7 +1619,7 @@
{
PyObject *tmp, *result;
- if (!PyAnySet_Check(other)) {
+ if (!PyAnySet_CheckExact(other)) {
tmp = make_new_set(&PySet_Type, other);
if (tmp == NULL)
return NULL;
Modified: python/branches/p3yk-noslice/Objects/stringobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/stringobject.c (original)
+++ python/branches/p3yk-noslice/Objects/stringobject.c Fri Feb 23 18:29:35 2007
@@ -4209,6 +4209,14 @@
int numdigits; /* len == numnondigits + numdigits */
int numnondigits = 0;
+ /* Avoid exceeding SSIZE_T_MAX */
+ if (prec > PY_SSIZE_T_MAX-3) {
+ PyErr_SetString(PyExc_OverflowError,
+ "precision too large");
+ return NULL;
+ }
+
+
switch (type) {
case 'd':
case 'u':
@@ -4553,6 +4561,8 @@
goto error;
}
width = PyInt_AsLong(v);
+ if (width == -1 && PyErr_Occurred())
+ goto error;
if (width < 0) {
flags |= F_LJUST;
width = -width;
@@ -4590,6 +4600,8 @@
goto error;
}
prec = PyInt_AsLong(v);
+ if (prec == -1 && PyErr_Occurred())
+ goto error;
if (prec < 0)
prec = 0;
if (--fmtcnt >= 0)
Modified: python/branches/p3yk-noslice/Objects/typeobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/typeobject.c (original)
+++ python/branches/p3yk-noslice/Objects/typeobject.c Fri Feb 23 18:29:35 2007
@@ -655,6 +655,17 @@
goto endlabel; /* resurrected */
else
_PyObject_GC_UNTRACK(self);
+ /* New weakrefs could be created during the finalizer call.
+ If this occurs, clear them out without calling their
+ finalizers since they might rely on part of the object
+ being finalized that has already been destroyed. */
+ if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
+ /* Modeled after GET_WEAKREFS_LISTPTR() */
+ PyWeakReference **list = (PyWeakReference **) \
+ PyObject_GET_WEAKREFS_LISTPTR(self);
+ while (*list)
+ _PyWeakref_ClearRef(*list);
+ }
}
/* Clear slots up to the nearest base with a different tp_dealloc */
@@ -2589,7 +2600,11 @@
Py_INCREF(dictitems);
}
else {
- dictitems = PyObject_CallMethod(obj, "iteritems", "");
+ PyObject *items = PyObject_CallMethod(obj, "items", "");
+ if (items == NULL)
+ goto end;
+ dictitems = PyObject_GetIter(items);
+ Py_DECREF(items);
if (dictitems == NULL)
goto end;
}
@@ -4197,7 +4212,13 @@
SLOT1(slot_nb_inplace_subtract, "__isub__", PyObject *, "O")
SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
-SLOT1(slot_nb_inplace_power, "__ipow__", PyObject *, "O")
+/* Can't use SLOT1 here, because nb_inplace_power is ternary */
+static PyObject *
+slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
+{
+ static PyObject *cache_str;
+ return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
+}
SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
Modified: python/branches/p3yk-noslice/Objects/unicodeobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/unicodeobject.c (original)
+++ python/branches/p3yk-noslice/Objects/unicodeobject.c Fri Feb 23 18:29:35 2007
@@ -7569,6 +7569,8 @@
goto onError;
}
width = PyInt_AsLong(v);
+ if (width == -1 && PyErr_Occurred())
+ goto onError;
if (width < 0) {
flags |= F_LJUST;
width = -width;
@@ -7604,6 +7606,8 @@
goto onError;
}
prec = PyInt_AsLong(v);
+ if (prec == -1 && PyErr_Occurred())
+ goto onError;
if (prec < 0)
prec = 0;
if (--fmtcnt >= 0)
Modified: python/branches/p3yk-noslice/Objects/weakrefobject.c
==============================================================================
--- python/branches/p3yk-noslice/Objects/weakrefobject.c (original)
+++ python/branches/p3yk-noslice/Objects/weakrefobject.c Fri Feb 23 18:29:35 2007
@@ -57,6 +57,9 @@
PyWeakref_GET_OBJECT(self));
if (*list == self)
+ /* If 'self' is the end of the list (and thus self->wr_next == NULL)
+ then the weakref list itself (and thus the value of *list) will
+ end up being set to NULL. */
*list = self->wr_next;
self->wr_object = Py_None;
if (self->wr_prev != NULL)
Modified: python/branches/p3yk-noslice/PC/_msi.c
==============================================================================
--- python/branches/p3yk-noslice/PC/_msi.c (original)
+++ python/branches/p3yk-noslice/PC/_msi.c Fri Feb 23 18:29:35 2007
@@ -543,7 +543,7 @@
if (PyString_Check(data)) {
status = MsiSummaryInfoSetProperty(si->h, field, VT_LPSTR,
0, NULL, PyString_AsString(data));
- } else if (PyInt_Check(data)) {
+ } else if (PyInt_CheckExact(data)) {
status = MsiSummaryInfoSetProperty(si->h, field, VT_I4,
PyInt_AsLong(data), NULL, NULL);
} else {
Modified: python/branches/p3yk-noslice/PCbuild/_bsddb.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/_bsddb.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/_bsddb.vcproj Fri Feb 23 18:29:35 2007
@@ -130,7 +130,7 @@
ATLMinimizesCRunTimeLibraryUsage="FALSE">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include;..\PC;"..\..\db-4.4.20\build_win32""
Modified: python/branches/p3yk-noslice/PCbuild/_elementtree.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/_elementtree.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/_elementtree.vcproj Fri Feb 23 18:29:35 2007
@@ -129,7 +129,7 @@
ATLMinimizesCRunTimeLibraryUsage="FALSE">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\expat"
Modified: python/branches/p3yk-noslice/PCbuild/_msi.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/_msi.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/_msi.vcproj Fri Feb 23 18:29:35 2007
@@ -129,7 +129,7 @@
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC"
@@ -150,7 +150,7 @@
<Tool
Name="VCLinkerTool"
AdditionalOptions=" /MACHINE:IA64 /USELINK:MS_SDK"
- AdditionalDependencies="fci.lib msi.lib rpcrt4.lib"
+ AdditionalDependencies="fci.lib msi.lib rpcrt4.lib bufferoverflowU.lib"
OutputFile="./_msi.pyd"
LinkIncremental="1"
SuppressStartupBanner="TRUE"
Modified: python/branches/p3yk-noslice/PCbuild/_socket.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/_socket.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/_socket.vcproj Fri Feb 23 18:29:35 2007
@@ -128,7 +128,7 @@
ATLMinimizesCRunTimeLibraryUsage="FALSE">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC"
Modified: python/branches/p3yk-noslice/PCbuild/_sqlite3.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/_sqlite3.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/_sqlite3.vcproj Fri Feb 23 18:29:35 2007
@@ -131,7 +131,7 @@
ATLMinimizesCRunTimeLibraryUsage="FALSE">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include;..\PC;..\..\sqlite-source-3.3.4"
@@ -193,7 +193,7 @@
ATLMinimizesCRunTimeLibraryUsage="FALSE">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_OPTERON"
+ AdditionalOptions=" /USECL:MS_OPTERON /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include;..\PC;..\..\sqlite-source-3.3.4"
Modified: python/branches/p3yk-noslice/PCbuild/_ssl.mak
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/_ssl.mak (original)
+++ python/branches/p3yk-noslice/PCbuild/_ssl.mak Fri Feb 23 18:29:35 2007
@@ -31,7 +31,7 @@
_hashlib$(SUFFIX): $(HASH_SOURCE) $(SSL_LIB_DIR)/libeay32.lib ../PC/*.h ../Include/*.h
@if not exist "$(TEMP)/_hashlib/." mkdir "$(TEMP)/_hashlib"
- cl /nologo /c $(HASH_SOURCE) $(CFLAGS) /Fo$(TEMP)\_hashlib\$*.obj $(INCLUDES)
+ cl /nologo /c $(HASH_SOURCE) $(CFLAGS) $(EXTRA_CFLAGS) /Fo$(TEMP)\_hashlib\$*.obj $(INCLUDES)
link /nologo @<<
/dll /out:_hashlib$(SUFFIX) $(HASH_LIBS) $(TEMP)\_hashlib\$*.obj
<<
Modified: python/branches/p3yk-noslice/PCbuild/_testcapi.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/_testcapi.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/_testcapi.vcproj Fri Feb 23 18:29:35 2007
@@ -126,7 +126,7 @@
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC"
Modified: python/branches/p3yk-noslice/PCbuild/_tkinter.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/_tkinter.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/_tkinter.vcproj Fri Feb 23 18:29:35 2007
@@ -130,7 +130,7 @@
ATLMinimizesCRunTimeLibraryUsage="FALSE">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\..\tcltk\include,..\Include,..\PC"
Modified: python/branches/p3yk-noslice/PCbuild/build_ssl.py
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/build_ssl.py (original)
+++ python/branches/p3yk-noslice/PCbuild/build_ssl.py Fri Feb 23 18:29:35 2007
@@ -169,6 +169,8 @@
defs = "SSL_DIR=\"%s\"" % (ssl_dir,)
if debug:
defs = defs + " " + "DEBUG=1"
+ if arch in ('amd64', 'ia64'):
+ defs = defs + " EXTRA_CFLAGS=/GS-"
makeCommand = 'nmake /nologo -f _ssl.mak ' + defs + " " + make_flags
print "Executing:", makeCommand
sys.stdout.flush()
Modified: python/branches/p3yk-noslice/PCbuild/bz2.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/bz2.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/bz2.vcproj Fri Feb 23 18:29:35 2007
@@ -137,7 +137,7 @@
ATLMinimizesCRunTimeLibraryUsage="FALSE">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC,..\..\bzip2-1.0.3"
Modified: python/branches/p3yk-noslice/PCbuild/pyexpat.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/pyexpat.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/pyexpat.vcproj Fri Feb 23 18:29:35 2007
@@ -128,7 +128,7 @@
ATLMinimizesCRunTimeLibraryUsage="FALSE">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\expat"
@@ -189,7 +189,7 @@
ATLMinimizesCRunTimeLibraryUsage="FALSE">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_OPTERON"
+ AdditionalOptions=" /USECL:MS_OPTERON /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC,..\Modules\expat"
Modified: python/branches/p3yk-noslice/PCbuild/python.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/python.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/python.vcproj Fri Feb 23 18:29:35 2007
@@ -137,7 +137,7 @@
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM /VSEXTCOMP_VERBOSE"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC"
Modified: python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/pythoncore.vcproj Fri Feb 23 18:29:35 2007
@@ -144,7 +144,7 @@
ATLMinimizesCRunTimeLibraryUsage="FALSE">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC"
Modified: python/branches/p3yk-noslice/PCbuild/pythonw.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/pythonw.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/pythonw.vcproj Fri Feb 23 18:29:35 2007
@@ -130,7 +130,7 @@
ATLMinimizesCRunTimeLibraryUsage="FALSE">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC"
Modified: python/branches/p3yk-noslice/PCbuild/select.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/select.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/select.vcproj Fri Feb 23 18:29:35 2007
@@ -130,7 +130,7 @@
ATLMinimizesCRunTimeLibraryUsage="FALSE">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC"
Modified: python/branches/p3yk-noslice/PCbuild/unicodedata.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/unicodedata.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/unicodedata.vcproj Fri Feb 23 18:29:35 2007
@@ -126,7 +126,7 @@
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC"
Modified: python/branches/p3yk-noslice/PCbuild/winsound.vcproj
==============================================================================
--- python/branches/p3yk-noslice/PCbuild/winsound.vcproj (original)
+++ python/branches/p3yk-noslice/PCbuild/winsound.vcproj Fri Feb 23 18:29:35 2007
@@ -128,7 +128,7 @@
CharacterSet="2">
<Tool
Name="VCCLCompilerTool"
- AdditionalOptions=" /USECL:MS_ITANIUM"
+ AdditionalOptions=" /USECL:MS_ITANIUM /GS-"
Optimization="2"
InlineFunctionExpansion="1"
AdditionalIncludeDirectories="..\Include,..\PC"
Modified: python/branches/p3yk-noslice/Parser/Python.asdl
==============================================================================
--- python/branches/p3yk-noslice/Parser/Python.asdl (original)
+++ python/branches/p3yk-noslice/Parser/Python.asdl Fri Feb 23 18:29:35 2007
@@ -18,9 +18,6 @@
| Assign(expr* targets, expr value)
| AugAssign(expr target, operator op, expr value)
- -- not sure if bool is allowed, can always use int
- | Print(expr? dest, expr* values, bool nl)
-
-- use 'orelse' because else is a keyword in target languages
| For(expr target, expr iter, stmt* body, stmt* orelse)
| While(expr test, stmt* body, stmt* orelse)
@@ -71,7 +68,7 @@
| Subscript(expr value, slice slice, expr_context ctx)
| Name(identifier id, expr_context ctx)
| List(expr* elts, expr_context ctx)
- | Tuple(expr *elts, expr_context ctx)
+ | Tuple(expr* elts, expr_context ctx)
-- col_offset is the byte offset in the utf8 string the parser uses
attributes (int lineno, int col_offset)
Modified: python/branches/p3yk-noslice/Parser/asdl_c.py
==============================================================================
--- python/branches/p3yk-noslice/Parser/asdl_c.py (original)
+++ python/branches/p3yk-noslice/Parser/asdl_c.py Fri Feb 23 18:29:35 2007
@@ -260,7 +260,12 @@
argstr += ", PyArena *arena"
else:
argstr = "PyArena *arena"
- self.emit("%s %s(%s);" % (ctype, name, argstr), 0)
+ margs = "a0"
+ for i in range(1, len(args)+1):
+ margs += ", a%d" % i
+ self.emit("#define %s(%s) _Py_%s(%s)" % (name, margs, name, margs), 0,
+ reflow = 0)
+ self.emit("%s _Py_%s(%s);" % (ctype, name, argstr), 0)
def visitProduct(self, prod, name):
self.emit_function(name, get_c_type(name),
@@ -520,6 +525,9 @@
(cons.name, cons.name), 1)
self.emit("if (!%s_singleton) return 0;" % cons.name, 1)
+def parse_version(mod):
+ return mod.version.value[12:-3]
+
class ASTModuleVisitor(PickleVisitor):
def visitModule(self, mod):
@@ -535,7 +543,8 @@
self.emit('if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)', 1)
self.emit("return;", 2)
# Value of version: "$Revision$"
- self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)' % mod.version.value[12:-3], 1)
+ self.emit('if (PyModule_AddStringConstant(m, "__version__", "%s") < 0)'
+ % parse_version(mod), 1)
self.emit("return;", 2)
for dfn in mod.dfns:
self.visit(dfn)
@@ -716,11 +725,23 @@
v.visit(object)
v.emit("", 0)
+common_msg = "/* File automatically generated by %s. */\n"
+
+c_file_msg = """
+/*
+ __version__ %s.
+
+ This module must be committed separately after each AST grammar change;
+ The __version__ number is set to the revision number of the commit
+ containing the grammar change.
+*/
+"""
+
def main(srcfile):
argv0 = sys.argv[0]
components = argv0.split(os.sep)
argv0 = os.sep.join(components[-2:])
- auto_gen_msg = '/* File automatically generated by %s */\n' % argv0
+ auto_gen_msg = common_msg % argv0
mod = asdl.parse(srcfile)
if not asdl.check(mod):
sys.exit(1)
@@ -741,6 +762,7 @@
p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c")
f = open(p, "wb")
print >> f, auto_gen_msg
+ print >> f, c_file_msg % parse_version(mod)
print >> f, '#include "Python.h"'
print >> f, '#include "%s-ast.h"' % mod.name
print >> f
Modified: python/branches/p3yk-noslice/Parser/tokenizer.c
==============================================================================
--- python/branches/p3yk-noslice/Parser/tokenizer.c (original)
+++ python/branches/p3yk-noslice/Parser/tokenizer.c Fri Feb 23 18:29:35 2007
@@ -1323,17 +1323,13 @@
return ERRORTOKEN;
}
}
- if (c == 'l' || c == 'L')
- c = tok_nextc(tok);
}
else {
/* Decimal */
do {
c = tok_nextc(tok);
} while (isdigit(c));
- if (c == 'l' || c == 'L')
- c = tok_nextc(tok);
- else {
+ {
/* Accept floating point numbers. */
if (c == '.') {
fraction:
Modified: python/branches/p3yk-noslice/Python/Python-ast.c
==============================================================================
--- python/branches/p3yk-noslice/Python/Python-ast.c (original)
+++ python/branches/p3yk-noslice/Python/Python-ast.c Fri Feb 23 18:29:35 2007
@@ -1,4 +1,13 @@
-/* File automatically generated by Parser/asdl_c.py */
+/* File automatically generated by Parser/asdl_c.py. */
+
+
+/*
+ __version__ 53731.
+
+ This module must be committed separately after each AST grammar change;
+ The __version__ number is set to the revision number of the commit
+ containing the grammar change.
+*/
#include "Python.h"
#include "Python-ast.h"
@@ -61,12 +70,6 @@
"op",
"value",
};
-static PyTypeObject *Print_type;
-static char *Print_fields[]={
- "dest",
- "values",
- "nl",
-};
static PyTypeObject *For_type;
static char *For_fields[]={
"target",
@@ -480,8 +483,6 @@
if (!Assign_type) return 0;
AugAssign_type = make_type("AugAssign", stmt_type, AugAssign_fields, 3);
if (!AugAssign_type) return 0;
- Print_type = make_type("Print", stmt_type, Print_fields, 3);
- if (!Print_type) return 0;
For_type = make_type("For", stmt_type, For_fields, 4);
if (!For_type) return 0;
While_type = make_type("While", stmt_type, While_fields, 3);
@@ -949,25 +950,6 @@
}
stmt_ty
-Print(expr_ty dest, asdl_seq * values, bool nl, int lineno, int col_offset,
- PyArena *arena)
-{
- stmt_ty p;
- p = (stmt_ty)PyArena_Malloc(arena, sizeof(*p));
- if (!p) {
- PyErr_NoMemory();
- return NULL;
- }
- p->kind = Print_kind;
- p->v.Print.dest = dest;
- p->v.Print.values = values;
- p->v.Print.nl = nl;
- p->lineno = lineno;
- p->col_offset = col_offset;
- return p;
-}
-
-stmt_ty
For(expr_ty target, expr_ty iter, asdl_seq * body, asdl_seq * orelse, int
lineno, int col_offset, PyArena *arena)
{
@@ -2118,25 +2100,6 @@
goto failed;
Py_DECREF(value);
break;
- case Print_kind:
- result = PyType_GenericNew(Print_type, NULL, NULL);
- if (!result) goto failed;
- value = ast2obj_expr(o->v.Print.dest);
- if (!value) goto failed;
- if (PyObject_SetAttrString(result, "dest", value) == -1)
- goto failed;
- Py_DECREF(value);
- value = ast2obj_list(o->v.Print.values, ast2obj_expr);
- if (!value) goto failed;
- if (PyObject_SetAttrString(result, "values", value) == -1)
- goto failed;
- Py_DECREF(value);
- value = ast2obj_bool(o->v.Print.nl);
- if (!value) goto failed;
- if (PyObject_SetAttrString(result, "nl", value) == -1)
- goto failed;
- Py_DECREF(value);
- break;
case For_kind:
result = PyType_GenericNew(For_type, NULL, NULL);
if (!result) goto failed;
@@ -3126,7 +3089,7 @@
if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return;
if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)
return;
- if (PyModule_AddStringConstant(m, "__version__", "53363") < 0)
+ if (PyModule_AddStringConstant(m, "__version__", "53731") < 0)
return;
if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return;
if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0)
@@ -3149,7 +3112,6 @@
return;
if (PyDict_SetItemString(d, "AugAssign", (PyObject*)AugAssign_type) <
0) return;
- if (PyDict_SetItemString(d, "Print", (PyObject*)Print_type) < 0) return;
if (PyDict_SetItemString(d, "For", (PyObject*)For_type) < 0) return;
if (PyDict_SetItemString(d, "While", (PyObject*)While_type) < 0) return;
if (PyDict_SetItemString(d, "If", (PyObject*)If_type) < 0) return;
Modified: python/branches/p3yk-noslice/Python/ast.c
==============================================================================
--- python/branches/p3yk-noslice/Python/ast.c (original)
+++ python/branches/p3yk-noslice/Python/ast.c Fri Feb 23 18:29:35 2007
@@ -2218,37 +2218,6 @@
}
}
-static stmt_ty
-ast_for_print_stmt(struct compiling *c, const node *n)
-{
- /* print_stmt: 'print' ( [ test (',' test)* [','] ]
- | '>>' test [ (',' test)+ [','] ] )
- */
- expr_ty dest = NULL, expression;
- asdl_seq *seq;
- bool nl;
- int i, j, start = 1;
-
- REQ(n, print_stmt);
- if (NCH(n) >= 2 && TYPE(CHILD(n, 1)) == RIGHTSHIFT) {
- dest = ast_for_expr(c, CHILD(n, 2));
- if (!dest)
- return NULL;
- start = 4;
- }
- seq = asdl_seq_new((NCH(n) + 1 - start) / 2, c->c_arena);
- if (!seq)
- return NULL;
- for (i = start, j = 0; i < NCH(n); i += 2, ++j) {
- expression = ast_for_expr(c, CHILD(n, i));
- if (!expression)
- return NULL;
- asdl_seq_SET(seq, j, expression);
- }
- nl = (TYPE(CHILD(n, NCH(n) - 1)) == COMMA) ? false : true;
- return Print(dest, seq, nl, LINENO(n), n->n_col_offset, c->c_arena);
-}
-
static asdl_seq *
ast_for_exprlist(struct compiling *c, const node *n, expr_context_ty context)
{
@@ -3089,14 +3058,12 @@
if (TYPE(n) == small_stmt) {
REQ(n, small_stmt);
n = CHILD(n, 0);
- /* small_stmt: expr_stmt | print_stmt | del_stmt | pass_stmt
+ /* small_stmt: expr_stmt | del_stmt | pass_stmt
| flow_stmt | import_stmt | global_stmt | assert_stmt
*/
switch (TYPE(n)) {
case expr_stmt:
return ast_for_expr_stmt(c, n);
- case print_stmt:
- return ast_for_print_stmt(c, n);
case del_stmt:
return ast_for_del_stmt(c, n);
case pass_stmt:
Modified: python/branches/p3yk-noslice/Python/bltinmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Python/bltinmodule.c (original)
+++ python/branches/p3yk-noslice/Python/bltinmodule.c Fri Feb 23 18:29:35 2007
@@ -1398,7 +1398,7 @@
if (dummy_args == NULL)
return NULL;
- if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:Print",
+ if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
kwlist, &sep, &end, &file))
return NULL;
if (file == NULL || file == Py_None)
@@ -1446,7 +1446,7 @@
}
PyDoc_STRVAR(print_doc,
-"Print(value, ..., file=None, sep=' ', end='\\n')\n\
+"print(value, ..., file=None, sep=' ', end='\\n')\n\
\n\
Prints the values to a stream, or to sys.stdout by default.\n\
Optional keyword arguments:\n\
@@ -2056,7 +2056,7 @@
{"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
{"ord", builtin_ord, METH_O, ord_doc},
{"pow", builtin_pow, METH_VARARGS, pow_doc},
- {"Print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
+ {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
{"range", builtin_range, METH_VARARGS, range_doc},
{"reload", builtin_reload, METH_O, reload_doc},
{"repr", builtin_repr, METH_O, repr_doc},
@@ -2124,9 +2124,8 @@
SETBUILTIN("float", &PyFloat_Type);
SETBUILTIN("frozenset", &PyFrozenSet_Type);
SETBUILTIN("property", &PyProperty_Type);
- SETBUILTIN("int", &PyInt_Type);
+ SETBUILTIN("int", &PyLong_Type);
SETBUILTIN("list", &PyList_Type);
- SETBUILTIN("long", &PyLong_Type);
SETBUILTIN("object", &PyBaseObject_Type);
SETBUILTIN("reversed", &PyReversed_Type);
SETBUILTIN("set", &PySet_Type);
Modified: python/branches/p3yk-noslice/Python/ceval.c
==============================================================================
--- python/branches/p3yk-noslice/Python/ceval.c (original)
+++ python/branches/p3yk-noslice/Python/ceval.c Fri Feb 23 18:29:35 2007
@@ -520,7 +520,6 @@
register PyObject *v; /* Temporary objects popped off stack */
register PyObject *w;
register PyObject *u;
- register PyObject *stream = NULL; /* for PRINT opcodes */
register PyObject **fastlocals, **freevars;
PyObject *retval = NULL; /* Return value */
PyThreadState *tstate = PyThreadState_GET();
@@ -1440,81 +1439,6 @@
Py_XDECREF(x);
break;
- case PRINT_ITEM_TO:
- w = stream = POP();
- /* fall through to PRINT_ITEM */
-
- case PRINT_ITEM:
- v = POP();
- if (stream == NULL || stream == Py_None) {
- w = PySys_GetObject("stdout");
- if (w == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "lost sys.stdout");
- err = -1;
- }
- }
- /* PyFile_SoftSpace() can exececute arbitrary code
- if sys.stdout is an instance with a __getattr__.
- If __getattr__ raises an exception, w will
- be freed, so we need to prevent that temporarily. */
- Py_XINCREF(w);
- if (w != NULL && PyFile_SoftSpace(w, 0))
- err = PyFile_WriteString(" ", w);
- if (err == 0)
- err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
- if (err == 0) {
- /* XXX move into writeobject() ? */
- if (PyString_Check(v)) {
- char *s = PyString_AS_STRING(v);
- Py_ssize_t len = PyString_GET_SIZE(v);
- if (len == 0 ||
- !isspace(Py_CHARMASK(s[len-1])) ||
- s[len-1] == ' ')
- PyFile_SoftSpace(w, 1);
- }
-#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(v)) {
- Py_UNICODE *s = PyUnicode_AS_UNICODE(v);
- Py_ssize_t len = PyUnicode_GET_SIZE(v);
- if (len == 0 ||
- !Py_UNICODE_ISSPACE(s[len-1]) ||
- s[len-1] == ' ')
- PyFile_SoftSpace(w, 1);
- }
-#endif
- else
- PyFile_SoftSpace(w, 1);
- }
- Py_XDECREF(w);
- Py_DECREF(v);
- Py_XDECREF(stream);
- stream = NULL;
- if (err == 0)
- continue;
- break;
-
- case PRINT_NEWLINE_TO:
- w = stream = POP();
- /* fall through to PRINT_NEWLINE */
-
- case PRINT_NEWLINE:
- if (stream == NULL || stream == Py_None) {
- w = PySys_GetObject("stdout");
- if (w == NULL)
- PyErr_SetString(PyExc_RuntimeError,
- "lost sys.stdout");
- }
- if (w != NULL) {
- err = PyFile_WriteString("\n", w);
- if (err == 0)
- PyFile_SoftSpace(w, 0);
- }
- Py_XDECREF(stream);
- stream = NULL;
- break;
-
-
#ifdef CASE_TOO_BIG
default: switch (opcode) {
#endif
@@ -2106,8 +2030,9 @@
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());
@@ -2705,7 +2630,7 @@
}
PyErr_Format(PyExc_TypeError,
"%.200s() needs "
- "keyword only argument %s",
+ "keyword-only argument %s",
PyString_AsString(co->co_name),
PyString_AsString(name));
goto fail;
@@ -3357,17 +3282,6 @@
return result;
}
-int
-Py_FlushLine(void)
-{
- PyObject *f = PySys_GetObject("stdout");
- if (f == NULL)
- return 0;
- if (!PyFile_SoftSpace(f, 0))
- return 0;
- return PyFile_WriteString("\n", f);
-}
-
/* External interface to call any callable object.
The arg must be a tuple or NULL. */
@@ -3833,7 +3747,7 @@
{
if (v != NULL) {
Py_ssize_t x;
- if (PyInt_Check(v)) {
+ if (PyInt_CheckExact(v)) {
/* XXX(nnorwitz): I think PyInt_AS_LONG is correct,
however, it looks like it should be AsSsize_t.
There should be a comment here explaining why.
@@ -3879,6 +3793,35 @@
res = !res;
break;
case PyCmp_EXC_MATCH:
+ if (PyTuple_Check(w)) {
+ Py_ssize_t i, length;
+ length = PyTuple_Size(w);
+ for (i = 0; i < length; i += 1) {
+ PyObject *exc = PyTuple_GET_ITEM(w, i);
+ if (PyString_Check(exc)) {
+ int ret_val;
+ ret_val = PyErr_WarnEx(
+ PyExc_DeprecationWarning,
+ "catching of string "
+ "exceptions is "
+ "deprecated", 1);
+ if (ret_val == -1)
+ return NULL;
+ }
+ }
+ }
+ else {
+ if (PyString_Check(w)) {
+ int ret_val;
+ ret_val = PyErr_WarnEx(
+ PyExc_DeprecationWarning,
+ "catching of string "
+ "exceptions is deprecated",
+ 1);
+ if (ret_val == -1)
+ return NULL;
+ }
+ }
res = PyErr_GivenExceptionMatches(v, w);
break;
default:
Modified: python/branches/p3yk-noslice/Python/compile.c
==============================================================================
--- python/branches/p3yk-noslice/Python/compile.c (original)
+++ python/branches/p3yk-noslice/Python/compile.c Fri Feb 23 18:29:35 2007
@@ -707,14 +707,6 @@
case PRINT_EXPR:
return -1;
- case PRINT_ITEM:
- return -1;
- case PRINT_NEWLINE:
- return 0;
- case PRINT_ITEM_TO:
- return -2;
- case PRINT_NEWLINE_TO:
- return -1;
case INPLACE_LSHIFT:
case INPLACE_RSHIFT:
case INPLACE_AND:
@@ -1599,43 +1591,6 @@
}
static int
-compiler_print(struct compiler *c, stmt_ty s)
-{
- int i, n;
- bool dest;
-
- assert(s->kind == Print_kind);
- n = asdl_seq_LEN(s->v.Print.values);
- dest = false;
- if (s->v.Print.dest) {
- VISIT(c, expr, s->v.Print.dest);
- dest = true;
- }
- for (i = 0; i < n; i++) {
- expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
- if (dest) {
- ADDOP(c, DUP_TOP);
- VISIT(c, expr, e);
- ADDOP(c, ROT_TWO);
- ADDOP(c, PRINT_ITEM_TO);
- }
- else {
- VISIT(c, expr, e);
- ADDOP(c, PRINT_ITEM);
- }
- }
- if (s->v.Print.nl) {
- if (dest)
- ADDOP(c, PRINT_NEWLINE_TO)
- else
- ADDOP(c, PRINT_NEWLINE)
- }
- else if (dest)
- ADDOP(c, POP_TOP);
- return 1;
-}
-
-static int
compiler_if(struct compiler *c, stmt_ty s)
{
basicblock *end, *next;
@@ -2209,8 +2164,6 @@
break;
case AugAssign_kind:
return compiler_augassign(c, s);
- case Print_kind:
- return compiler_print(c, s);
case For_kind:
return compiler_for(c, s);
case While_kind:
Modified: python/branches/p3yk-noslice/Python/frozen.c
==============================================================================
--- python/branches/p3yk-noslice/Python/frozen.c (original)
+++ python/branches/p3yk-noslice/Python/frozen.c Fri Feb 23 18:29:35 2007
@@ -12,14 +12,15 @@
the appropriate bytes from M___main__.c. */
static unsigned char M___hello__[] = {
- 99,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,
- 0,64,0,0,0,115,9,0,0,0,100,0,0,71,72,100,
- 1,0,83,40,2,0,0,0,115,14,0,0,0,72,101,108,
- 108,111,32,119,111,114,108,100,46,46,46,78,40,0,0,0,
- 0,40,0,0,0,0,40,0,0,0,0,40,0,0,0,0,
- 115,8,0,0,0,104,101,108,108,111,46,112,121,115,8,0,
- 0,0,60,109,111,100,117,108,101,62,1,0,0,0,115,0,
- 0,0,0,
+ 99,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,
+ 0,64,0,0,0,115,14,0,0,0,101,0,0,100,0,0,
+ 131,1,0,1,100,1,0,83,40,2,0,0,0,115,14,0,
+ 0,0,72,101,108,108,111,32,119,111,114,108,100,46,46,46,
+ 78,40,1,0,0,0,116,5,0,0,0,112,114,105,110,116,
+ 40,0,0,0,0,40,0,0,0,0,40,0,0,0,0,115,
+ 8,0,0,0,104,101,108,108,111,46,112,121,115,8,0,0,
+ 0,60,109,111,100,117,108,101,62,1,0,0,0,115,0,0,
+ 0,0,
};
#define SIZE (int)sizeof(M___hello__)
Modified: python/branches/p3yk-noslice/Python/getargs.c
==============================================================================
--- python/branches/p3yk-noslice/Python/getargs.c (original)
+++ python/branches/p3yk-noslice/Python/getargs.c Fri Feb 23 18:29:35 2007
@@ -720,9 +720,7 @@
case 'K': { /* long long sized bitfield */
unsigned PY_LONG_LONG *p = va_arg(*p_va, unsigned PY_LONG_LONG *);
unsigned PY_LONG_LONG ival;
- if (PyInt_Check(arg))
- ival = PyInt_AsUnsignedLongMask(arg);
- else if (PyLong_Check(arg))
+ if (PyLong_Check(arg))
ival = PyLong_AsUnsignedLongLongMask(arg);
else
return converterr("integer<K>", arg, msgbuf, bufsize);
Modified: python/branches/p3yk-noslice/Python/graminit.c
==============================================================================
--- python/branches/p3yk-noslice/Python/graminit.c (original)
+++ python/branches/p3yk-noslice/Python/graminit.c Fri Feb 23 18:29:35 2007
@@ -403,7 +403,7 @@
{2, arcs_16_2},
{1, arcs_16_3},
};
-static arc arcs_17_0[8] = {
+static arc arcs_17_0[7] = {
{39, 1},
{40, 1},
{41, 1},
@@ -411,29 +411,28 @@
{43, 1},
{44, 1},
{45, 1},
- {46, 1},
};
static arc arcs_17_1[1] = {
{0, 1},
};
static state states_17[2] = {
- {8, arcs_17_0},
+ {7, arcs_17_0},
{1, arcs_17_1},
};
static arc arcs_18_0[1] = {
{9, 1},
};
static arc arcs_18_1[3] = {
- {47, 2},
+ {46, 2},
{27, 3},
{0, 1},
};
static arc arcs_18_2[2] = {
- {48, 4},
+ {47, 4},
{9, 4},
};
static arc arcs_18_3[2] = {
- {48, 5},
+ {47, 5},
{9, 5},
};
static arc arcs_18_4[1] = {
@@ -452,6 +451,7 @@
{2, arcs_18_5},
};
static arc arcs_19_0[12] = {
+ {48, 1},
{49, 1},
{50, 1},
{51, 1},
@@ -463,7 +463,6 @@
{57, 1},
{58, 1},
{59, 1},
- {60, 1},
};
static arc arcs_19_1[1] = {
{0, 1},
@@ -473,90 +472,55 @@
{1, arcs_19_1},
};
static arc arcs_20_0[1] = {
- {61, 1},
+ {60, 1},
};
-static arc arcs_20_1[3] = {
- {22, 2},
- {62, 3},
- {0, 1},
+static arc arcs_20_1[1] = {
+ {61, 2},
};
-static arc arcs_20_2[2] = {
- {28, 4},
+static arc arcs_20_2[1] = {
{0, 2},
};
-static arc arcs_20_3[1] = {
- {22, 5},
-};
-static arc arcs_20_4[2] = {
- {22, 2},
- {0, 4},
-};
-static arc arcs_20_5[2] = {
- {28, 6},
- {0, 5},
-};
-static arc arcs_20_6[1] = {
- {22, 7},
-};
-static arc arcs_20_7[2] = {
- {28, 8},
- {0, 7},
-};
-static arc arcs_20_8[2] = {
- {22, 7},
- {0, 8},
-};
-static state states_20[9] = {
+static state states_20[3] = {
{1, arcs_20_0},
- {3, arcs_20_1},
- {2, arcs_20_2},
- {1, arcs_20_3},
- {2, arcs_20_4},
- {2, arcs_20_5},
- {1, arcs_20_6},
- {2, arcs_20_7},
- {2, arcs_20_8},
+ {1, arcs_20_1},
+ {1, arcs_20_2},
};
static arc arcs_21_0[1] = {
- {63, 1},
+ {62, 1},
};
static arc arcs_21_1[1] = {
- {64, 2},
-};
-static arc arcs_21_2[1] = {
- {0, 2},
+ {0, 1},
};
-static state states_21[3] = {
+static state states_21[2] = {
{1, arcs_21_0},
{1, arcs_21_1},
- {1, arcs_21_2},
};
-static arc arcs_22_0[1] = {
+static arc arcs_22_0[5] = {
+ {63, 1},
+ {64, 1},
{65, 1},
+ {66, 1},
+ {67, 1},
};
static arc arcs_22_1[1] = {
{0, 1},
};
static state states_22[2] = {
- {1, arcs_22_0},
+ {5, arcs_22_0},
{1, arcs_22_1},
};
-static arc arcs_23_0[5] = {
- {66, 1},
- {67, 1},
+static arc arcs_23_0[1] = {
{68, 1},
- {69, 1},
- {70, 1},
};
static arc arcs_23_1[1] = {
{0, 1},
};
static state states_23[2] = {
- {5, arcs_23_0},
+ {1, arcs_23_0},
{1, arcs_23_1},
};
static arc arcs_24_0[1] = {
- {71, 1},
+ {69, 1},
};
static arc arcs_24_1[1] = {
{0, 1},
@@ -566,142 +530,151 @@
{1, arcs_24_1},
};
static arc arcs_25_0[1] = {
- {72, 1},
+ {70, 1},
};
-static arc arcs_25_1[1] = {
+static arc arcs_25_1[2] = {
+ {9, 2},
{0, 1},
};
-static state states_25[2] = {
+static arc arcs_25_2[1] = {
+ {0, 2},
+};
+static state states_25[3] = {
{1, arcs_25_0},
- {1, arcs_25_1},
+ {2, arcs_25_1},
+ {1, arcs_25_2},
};
static arc arcs_26_0[1] = {
- {73, 1},
+ {47, 1},
};
-static arc arcs_26_1[2] = {
- {9, 2},
+static arc arcs_26_1[1] = {
{0, 1},
};
-static arc arcs_26_2[1] = {
- {0, 2},
-};
-static state states_26[3] = {
+static state states_26[2] = {
{1, arcs_26_0},
- {2, arcs_26_1},
- {1, arcs_26_2},
+ {1, arcs_26_1},
};
static arc arcs_27_0[1] = {
- {48, 1},
-};
-static arc arcs_27_1[1] = {
- {0, 1},
-};
-static state states_27[2] = {
- {1, arcs_27_0},
- {1, arcs_27_1},
-};
-static arc arcs_28_0[1] = {
- {74, 1},
+ {71, 1},
};
-static arc arcs_28_1[2] = {
+static arc arcs_27_1[2] = {
{22, 2},
{0, 1},
};
-static arc arcs_28_2[2] = {
+static arc arcs_27_2[2] = {
{28, 3},
{0, 2},
};
-static arc arcs_28_3[1] = {
+static arc arcs_27_3[1] = {
{22, 4},
};
-static arc arcs_28_4[2] = {
+static arc arcs_27_4[2] = {
{28, 5},
{0, 4},
};
-static arc arcs_28_5[1] = {
+static arc arcs_27_5[1] = {
{22, 6},
};
-static arc arcs_28_6[1] = {
+static arc arcs_27_6[1] = {
{0, 6},
};
-static state states_28[7] = {
- {1, arcs_28_0},
- {2, arcs_28_1},
- {2, arcs_28_2},
- {1, arcs_28_3},
- {2, arcs_28_4},
- {1, arcs_28_5},
- {1, arcs_28_6},
+static state states_27[7] = {
+ {1, arcs_27_0},
+ {2, arcs_27_1},
+ {2, arcs_27_2},
+ {1, arcs_27_3},
+ {2, arcs_27_4},
+ {1, arcs_27_5},
+ {1, arcs_27_6},
};
-static arc arcs_29_0[2] = {
- {75, 1},
- {76, 1},
+static arc arcs_28_0[2] = {
+ {72, 1},
+ {73, 1},
};
-static arc arcs_29_1[1] = {
+static arc arcs_28_1[1] = {
{0, 1},
};
-static state states_29[2] = {
- {2, arcs_29_0},
- {1, arcs_29_1},
+static state states_28[2] = {
+ {2, arcs_28_0},
+ {1, arcs_28_1},
};
-static arc arcs_30_0[1] = {
- {77, 1},
+static arc arcs_29_0[1] = {
+ {74, 1},
};
-static arc arcs_30_1[1] = {
- {78, 2},
+static arc arcs_29_1[1] = {
+ {75, 2},
};
-static arc arcs_30_2[1] = {
+static arc arcs_29_2[1] = {
{0, 2},
};
-static state states_30[3] = {
- {1, arcs_30_0},
- {1, arcs_30_1},
- {1, arcs_30_2},
+static state states_29[3] = {
+ {1, arcs_29_0},
+ {1, arcs_29_1},
+ {1, arcs_29_2},
};
-static arc arcs_31_0[1] = {
- {79, 1},
+static arc arcs_30_0[1] = {
+ {76, 1},
};
-static arc arcs_31_1[2] = {
- {80, 2},
+static arc arcs_30_1[2] = {
+ {77, 2},
{12, 3},
};
-static arc arcs_31_2[3] = {
- {80, 2},
+static arc arcs_30_2[3] = {
+ {77, 2},
{12, 3},
- {77, 4},
+ {74, 4},
};
-static arc arcs_31_3[1] = {
- {77, 4},
+static arc arcs_30_3[1] = {
+ {74, 4},
};
-static arc arcs_31_4[3] = {
+static arc arcs_30_4[3] = {
{29, 5},
{13, 6},
- {81, 5},
+ {78, 5},
};
-static arc arcs_31_5[1] = {
+static arc arcs_30_5[1] = {
{0, 5},
};
-static arc arcs_31_6[1] = {
- {81, 7},
+static arc arcs_30_6[1] = {
+ {78, 7},
};
-static arc arcs_31_7[1] = {
+static arc arcs_30_7[1] = {
{15, 5},
};
-static state states_31[8] = {
+static state states_30[8] = {
+ {1, arcs_30_0},
+ {2, arcs_30_1},
+ {3, arcs_30_2},
+ {1, arcs_30_3},
+ {3, arcs_30_4},
+ {1, arcs_30_5},
+ {1, arcs_30_6},
+ {1, arcs_30_7},
+};
+static arc arcs_31_0[1] = {
+ {19, 1},
+};
+static arc arcs_31_1[2] = {
+ {80, 2},
+ {0, 1},
+};
+static arc arcs_31_2[1] = {
+ {19, 3},
+};
+static arc arcs_31_3[1] = {
+ {0, 3},
+};
+static state states_31[4] = {
{1, arcs_31_0},
{2, arcs_31_1},
- {3, arcs_31_2},
+ {1, arcs_31_2},
{1, arcs_31_3},
- {3, arcs_31_4},
- {1, arcs_31_5},
- {1, arcs_31_6},
- {1, arcs_31_7},
};
static arc arcs_32_0[1] = {
- {19, 1},
+ {12, 1},
};
static arc arcs_32_1[2] = {
- {83, 2},
+ {80, 2},
{0, 1},
};
static arc arcs_32_2[1] = {
@@ -717,45 +690,37 @@
{1, arcs_32_3},
};
static arc arcs_33_0[1] = {
- {12, 1},
+ {79, 1},
};
static arc arcs_33_1[2] = {
- {83, 2},
+ {28, 2},
{0, 1},
};
-static arc arcs_33_2[1] = {
- {19, 3},
-};
-static arc arcs_33_3[1] = {
- {0, 3},
+static arc arcs_33_2[2] = {
+ {79, 1},
+ {0, 2},
};
-static state states_33[4] = {
+static state states_33[3] = {
{1, arcs_33_0},
{2, arcs_33_1},
- {1, arcs_33_2},
- {1, arcs_33_3},
+ {2, arcs_33_2},
};
static arc arcs_34_0[1] = {
- {82, 1},
+ {81, 1},
};
static arc arcs_34_1[2] = {
- {28, 2},
+ {28, 0},
{0, 1},
};
-static arc arcs_34_2[2] = {
- {82, 1},
- {0, 2},
-};
-static state states_34[3] = {
+static state states_34[2] = {
{1, arcs_34_0},
{2, arcs_34_1},
- {2, arcs_34_2},
};
static arc arcs_35_0[1] = {
- {84, 1},
+ {19, 1},
};
static arc arcs_35_1[2] = {
- {28, 0},
+ {77, 0},
{0, 1},
};
static state states_35[2] = {
@@ -763,69 +728,94 @@
{2, arcs_35_1},
};
static arc arcs_36_0[1] = {
- {19, 1},
+ {82, 1},
};
-static arc arcs_36_1[2] = {
- {80, 0},
- {0, 1},
+static arc arcs_36_1[1] = {
+ {19, 2},
};
-static state states_36[2] = {
+static arc arcs_36_2[2] = {
+ {28, 1},
+ {0, 2},
+};
+static state states_36[3] = {
{1, arcs_36_0},
- {2, arcs_36_1},
+ {1, arcs_36_1},
+ {2, arcs_36_2},
};
static arc arcs_37_0[1] = {
- {85, 1},
+ {83, 1},
};
static arc arcs_37_1[1] = {
- {19, 2},
+ {22, 2},
};
static arc arcs_37_2[2] = {
- {28, 1},
+ {28, 3},
{0, 2},
};
-static state states_37[3] = {
+static arc arcs_37_3[1] = {
+ {22, 4},
+};
+static arc arcs_37_4[1] = {
+ {0, 4},
+};
+static state states_37[5] = {
{1, arcs_37_0},
{1, arcs_37_1},
{2, arcs_37_2},
+ {1, arcs_37_3},
+ {1, arcs_37_4},
};
-static arc arcs_38_0[1] = {
+static arc arcs_38_0[7] = {
+ {84, 1},
+ {85, 1},
{86, 1},
+ {87, 1},
+ {88, 1},
+ {17, 1},
+ {89, 1},
};
static arc arcs_38_1[1] = {
+ {0, 1},
+};
+static state states_38[2] = {
+ {7, arcs_38_0},
+ {1, arcs_38_1},
+};
+static arc arcs_39_0[1] = {
+ {90, 1},
+};
+static arc arcs_39_1[1] = {
{22, 2},
};
-static arc arcs_38_2[2] = {
- {28, 3},
- {0, 2},
+static arc arcs_39_2[1] = {
+ {23, 3},
};
-static arc arcs_38_3[1] = {
- {22, 4},
+static arc arcs_39_3[1] = {
+ {24, 4},
};
-static arc arcs_38_4[1] = {
+static arc arcs_39_4[3] = {
+ {91, 1},
+ {92, 5},
{0, 4},
};
-static state states_38[5] = {
- {1, arcs_38_0},
- {1, arcs_38_1},
- {2, arcs_38_2},
- {1, arcs_38_3},
- {1, arcs_38_4},
+static arc arcs_39_5[1] = {
+ {23, 6},
};
-static arc arcs_39_0[7] = {
- {87, 1},
- {88, 1},
- {89, 1},
- {90, 1},
- {91, 1},
- {17, 1},
- {92, 1},
+static arc arcs_39_6[1] = {
+ {24, 7},
};
-static arc arcs_39_1[1] = {
- {0, 1},
+static arc arcs_39_7[1] = {
+ {0, 7},
};
-static state states_39[2] = {
- {7, arcs_39_0},
+static state states_39[8] = {
+ {1, arcs_39_0},
{1, arcs_39_1},
+ {1, arcs_39_2},
+ {1, arcs_39_3},
+ {3, arcs_39_4},
+ {1, arcs_39_5},
+ {1, arcs_39_6},
+ {1, arcs_39_7},
};
static arc arcs_40_0[1] = {
{93, 1},
@@ -839,9 +829,8 @@
static arc arcs_40_3[1] = {
{24, 4},
};
-static arc arcs_40_4[3] = {
- {94, 1},
- {95, 5},
+static arc arcs_40_4[2] = {
+ {92, 5},
{0, 4},
};
static arc arcs_40_5[1] = {
@@ -858,404 +847,380 @@
{1, arcs_40_1},
{1, arcs_40_2},
{1, arcs_40_3},
- {3, arcs_40_4},
+ {2, arcs_40_4},
{1, arcs_40_5},
{1, arcs_40_6},
{1, arcs_40_7},
};
static arc arcs_41_0[1] = {
- {96, 1},
+ {94, 1},
};
static arc arcs_41_1[1] = {
- {22, 2},
+ {61, 2},
};
static arc arcs_41_2[1] = {
- {23, 3},
+ {95, 3},
};
static arc arcs_41_3[1] = {
- {24, 4},
+ {9, 4},
};
-static arc arcs_41_4[2] = {
- {95, 5},
- {0, 4},
+static arc arcs_41_4[1] = {
+ {23, 5},
};
static arc arcs_41_5[1] = {
- {23, 6},
+ {24, 6},
};
-static arc arcs_41_6[1] = {
- {24, 7},
+static arc arcs_41_6[2] = {
+ {92, 7},
+ {0, 6},
};
static arc arcs_41_7[1] = {
- {0, 7},
+ {23, 8},
+};
+static arc arcs_41_8[1] = {
+ {24, 9},
+};
+static arc arcs_41_9[1] = {
+ {0, 9},
};
-static state states_41[8] = {
+static state states_41[10] = {
{1, arcs_41_0},
{1, arcs_41_1},
{1, arcs_41_2},
{1, arcs_41_3},
- {2, arcs_41_4},
+ {1, arcs_41_4},
{1, arcs_41_5},
- {1, arcs_41_6},
+ {2, arcs_41_6},
{1, arcs_41_7},
+ {1, arcs_41_8},
+ {1, arcs_41_9},
};
static arc arcs_42_0[1] = {
- {97, 1},
+ {96, 1},
};
static arc arcs_42_1[1] = {
- {64, 2},
+ {23, 2},
};
static arc arcs_42_2[1] = {
- {98, 3},
+ {24, 3},
};
-static arc arcs_42_3[1] = {
- {9, 4},
+static arc arcs_42_3[2] = {
+ {97, 4},
+ {98, 5},
};
static arc arcs_42_4[1] = {
- {23, 5},
+ {23, 6},
};
static arc arcs_42_5[1] = {
- {24, 6},
+ {23, 7},
};
-static arc arcs_42_6[2] = {
- {95, 7},
- {0, 6},
+static arc arcs_42_6[1] = {
+ {24, 8},
};
static arc arcs_42_7[1] = {
- {23, 8},
-};
-static arc arcs_42_8[1] = {
{24, 9},
};
+static arc arcs_42_8[4] = {
+ {97, 4},
+ {92, 10},
+ {98, 5},
+ {0, 8},
+};
static arc arcs_42_9[1] = {
{0, 9},
};
-static state states_42[10] = {
+static arc arcs_42_10[1] = {
+ {23, 11},
+};
+static arc arcs_42_11[1] = {
+ {24, 12},
+};
+static arc arcs_42_12[2] = {
+ {98, 5},
+ {0, 12},
+};
+static state states_42[13] = {
{1, arcs_42_0},
{1, arcs_42_1},
{1, arcs_42_2},
- {1, arcs_42_3},
+ {2, arcs_42_3},
{1, arcs_42_4},
{1, arcs_42_5},
- {2, arcs_42_6},
+ {1, arcs_42_6},
{1, arcs_42_7},
- {1, arcs_42_8},
+ {4, arcs_42_8},
{1, arcs_42_9},
+ {1, arcs_42_10},
+ {1, arcs_42_11},
+ {2, arcs_42_12},
};
static arc arcs_43_0[1] = {
{99, 1},
};
static arc arcs_43_1[1] = {
- {23, 2},
+ {22, 2},
};
-static arc arcs_43_2[1] = {
- {24, 3},
+static arc arcs_43_2[2] = {
+ {100, 3},
+ {23, 4},
};
-static arc arcs_43_3[2] = {
- {100, 4},
- {101, 5},
+static arc arcs_43_3[1] = {
+ {23, 4},
};
static arc arcs_43_4[1] = {
- {23, 6},
+ {24, 5},
};
static arc arcs_43_5[1] = {
- {23, 7},
-};
-static arc arcs_43_6[1] = {
- {24, 8},
-};
-static arc arcs_43_7[1] = {
- {24, 9},
-};
-static arc arcs_43_8[4] = {
- {100, 4},
- {95, 10},
- {101, 5},
- {0, 8},
-};
-static arc arcs_43_9[1] = {
- {0, 9},
-};
-static arc arcs_43_10[1] = {
- {23, 11},
-};
-static arc arcs_43_11[1] = {
- {24, 12},
-};
-static arc arcs_43_12[2] = {
- {101, 5},
- {0, 12},
+ {0, 5},
};
-static state states_43[13] = {
+static state states_43[6] = {
{1, arcs_43_0},
{1, arcs_43_1},
- {1, arcs_43_2},
- {2, arcs_43_3},
+ {2, arcs_43_2},
+ {1, arcs_43_3},
{1, arcs_43_4},
{1, arcs_43_5},
- {1, arcs_43_6},
- {1, arcs_43_7},
- {4, arcs_43_8},
- {1, arcs_43_9},
- {1, arcs_43_10},
- {1, arcs_43_11},
- {2, arcs_43_12},
};
static arc arcs_44_0[1] = {
- {102, 1},
+ {80, 1},
};
static arc arcs_44_1[1] = {
- {22, 2},
-};
-static arc arcs_44_2[2] = {
- {103, 3},
- {23, 4},
+ {101, 2},
};
-static arc arcs_44_3[1] = {
- {23, 4},
-};
-static arc arcs_44_4[1] = {
- {24, 5},
-};
-static arc arcs_44_5[1] = {
- {0, 5},
+static arc arcs_44_2[1] = {
+ {0, 2},
};
-static state states_44[6] = {
+static state states_44[3] = {
{1, arcs_44_0},
{1, arcs_44_1},
- {2, arcs_44_2},
- {1, arcs_44_3},
- {1, arcs_44_4},
- {1, arcs_44_5},
+ {1, arcs_44_2},
};
static arc arcs_45_0[1] = {
- {83, 1},
+ {102, 1},
};
-static arc arcs_45_1[1] = {
- {104, 2},
+static arc arcs_45_1[2] = {
+ {22, 2},
+ {0, 1},
};
-static arc arcs_45_2[1] = {
+static arc arcs_45_2[2] = {
+ {80, 3},
{0, 2},
};
-static state states_45[3] = {
+static arc arcs_45_3[1] = {
+ {19, 4},
+};
+static arc arcs_45_4[1] = {
+ {0, 4},
+};
+static state states_45[5] = {
{1, arcs_45_0},
- {1, arcs_45_1},
- {1, arcs_45_2},
+ {2, arcs_45_1},
+ {2, arcs_45_2},
+ {1, arcs_45_3},
+ {1, arcs_45_4},
};
-static arc arcs_46_0[1] = {
- {105, 1},
+static arc arcs_46_0[2] = {
+ {3, 1},
+ {2, 2},
};
-static arc arcs_46_1[2] = {
- {22, 2},
+static arc arcs_46_1[1] = {
{0, 1},
};
-static arc arcs_46_2[2] = {
- {83, 3},
- {0, 2},
+static arc arcs_46_2[1] = {
+ {103, 3},
};
static arc arcs_46_3[1] = {
- {19, 4},
+ {6, 4},
};
-static arc arcs_46_4[1] = {
- {0, 4},
+static arc arcs_46_4[2] = {
+ {6, 4},
+ {104, 1},
};
static state states_46[5] = {
- {1, arcs_46_0},
- {2, arcs_46_1},
- {2, arcs_46_2},
+ {2, arcs_46_0},
+ {1, arcs_46_1},
+ {1, arcs_46_2},
{1, arcs_46_3},
- {1, arcs_46_4},
+ {2, arcs_46_4},
};
-static arc arcs_47_0[2] = {
- {3, 1},
- {2, 2},
+static arc arcs_47_0[1] = {
+ {106, 1},
};
-static arc arcs_47_1[1] = {
+static arc arcs_47_1[2] = {
+ {28, 2},
{0, 1},
};
static arc arcs_47_2[1] = {
{106, 3},
};
-static arc arcs_47_3[1] = {
- {6, 4},
+static arc arcs_47_3[2] = {
+ {28, 4},
+ {0, 3},
};
static arc arcs_47_4[2] = {
- {6, 4},
- {107, 1},
+ {106, 3},
+ {0, 4},
};
static state states_47[5] = {
- {2, arcs_47_0},
- {1, arcs_47_1},
+ {1, arcs_47_0},
+ {2, arcs_47_1},
{1, arcs_47_2},
- {1, arcs_47_3},
+ {2, arcs_47_3},
{2, arcs_47_4},
};
-static arc arcs_48_0[1] = {
- {109, 1},
+static arc arcs_48_0[2] = {
+ {107, 1},
+ {108, 1},
};
-static arc arcs_48_1[2] = {
- {28, 2},
+static arc arcs_48_1[1] = {
{0, 1},
};
-static arc arcs_48_2[1] = {
- {109, 3},
+static state states_48[2] = {
+ {2, arcs_48_0},
+ {1, arcs_48_1},
};
-static arc arcs_48_3[2] = {
- {28, 4},
- {0, 3},
+static arc arcs_49_0[1] = {
+ {109, 1},
};
-static arc arcs_48_4[2] = {
- {109, 3},
- {0, 4},
+static arc arcs_49_1[2] = {
+ {33, 2},
+ {23, 3},
};
-static state states_48[5] = {
- {1, arcs_48_0},
- {2, arcs_48_1},
- {1, arcs_48_2},
- {2, arcs_48_3},
- {2, arcs_48_4},
+static arc arcs_49_2[1] = {
+ {23, 3},
};
-static arc arcs_49_0[2] = {
- {110, 1},
- {111, 1},
+static arc arcs_49_3[1] = {
+ {106, 4},
};
-static arc arcs_49_1[1] = {
- {0, 1},
+static arc arcs_49_4[1] = {
+ {0, 4},
};
-static state states_49[2] = {
- {2, arcs_49_0},
- {1, arcs_49_1},
+static state states_49[5] = {
+ {1, arcs_49_0},
+ {2, arcs_49_1},
+ {1, arcs_49_2},
+ {1, arcs_49_3},
+ {1, arcs_49_4},
};
-static arc arcs_50_0[1] = {
- {112, 1},
+static arc arcs_50_0[2] = {
+ {107, 1},
+ {110, 2},
};
static arc arcs_50_1[2] = {
- {33, 2},
- {23, 3},
+ {90, 3},
+ {0, 1},
};
static arc arcs_50_2[1] = {
- {23, 3},
+ {0, 2},
};
static arc arcs_50_3[1] = {
- {109, 4},
+ {107, 4},
};
static arc arcs_50_4[1] = {
- {0, 4},
+ {92, 5},
+};
+static arc arcs_50_5[1] = {
+ {22, 2},
};
-static state states_50[5] = {
- {1, arcs_50_0},
+static state states_50[6] = {
+ {2, arcs_50_0},
{2, arcs_50_1},
{1, arcs_50_2},
{1, arcs_50_3},
{1, arcs_50_4},
+ {1, arcs_50_5},
};
-static arc arcs_51_0[2] = {
- {110, 1},
- {113, 2},
+static arc arcs_51_0[1] = {
+ {111, 1},
};
static arc arcs_51_1[2] = {
- {93, 3},
+ {112, 0},
{0, 1},
};
-static arc arcs_51_2[1] = {
- {0, 2},
-};
-static arc arcs_51_3[1] = {
- {110, 4},
-};
-static arc arcs_51_4[1] = {
- {95, 5},
-};
-static arc arcs_51_5[1] = {
- {22, 2},
-};
-static state states_51[6] = {
- {2, arcs_51_0},
+static state states_51[2] = {
+ {1, arcs_51_0},
{2, arcs_51_1},
- {1, arcs_51_2},
- {1, arcs_51_3},
- {1, arcs_51_4},
- {1, arcs_51_5},
};
static arc arcs_52_0[1] = {
- {114, 1},
+ {113, 1},
};
static arc arcs_52_1[2] = {
- {115, 0},
+ {114, 0},
{0, 1},
};
static state states_52[2] = {
{1, arcs_52_0},
{2, arcs_52_1},
};
-static arc arcs_53_0[1] = {
- {116, 1},
-};
-static arc arcs_53_1[2] = {
- {117, 0},
- {0, 1},
-};
-static state states_53[2] = {
- {1, arcs_53_0},
- {2, arcs_53_1},
-};
-static arc arcs_54_0[2] = {
- {118, 1},
- {119, 2},
-};
-static arc arcs_54_1[1] = {
+static arc arcs_53_0[2] = {
+ {115, 1},
{116, 2},
};
-static arc arcs_54_2[1] = {
+static arc arcs_53_1[1] = {
+ {113, 2},
+};
+static arc arcs_53_2[1] = {
{0, 2},
};
-static state states_54[3] = {
- {2, arcs_54_0},
- {1, arcs_54_1},
- {1, arcs_54_2},
+static state states_53[3] = {
+ {2, arcs_53_0},
+ {1, arcs_53_1},
+ {1, arcs_53_2},
};
-static arc arcs_55_0[1] = {
- {104, 1},
+static arc arcs_54_0[1] = {
+ {101, 1},
};
-static arc arcs_55_1[2] = {
- {120, 0},
+static arc arcs_54_1[2] = {
+ {117, 0},
{0, 1},
};
-static state states_55[2] = {
- {1, arcs_55_0},
- {2, arcs_55_1},
+static state states_54[2] = {
+ {1, arcs_54_0},
+ {2, arcs_54_1},
};
-static arc arcs_56_0[9] = {
+static arc arcs_55_0[9] = {
+ {118, 1},
+ {119, 1},
+ {120, 1},
{121, 1},
{122, 1},
{123, 1},
- {124, 1},
- {125, 1},
- {126, 1},
- {98, 1},
- {118, 2},
- {127, 3},
+ {95, 1},
+ {115, 2},
+ {124, 3},
};
-static arc arcs_56_1[1] = {
+static arc arcs_55_1[1] = {
{0, 1},
};
-static arc arcs_56_2[1] = {
- {98, 1},
+static arc arcs_55_2[1] = {
+ {95, 1},
};
-static arc arcs_56_3[2] = {
- {118, 1},
+static arc arcs_55_3[2] = {
+ {115, 1},
{0, 3},
};
-static state states_56[4] = {
- {9, arcs_56_0},
- {1, arcs_56_1},
- {1, arcs_56_2},
- {2, arcs_56_3},
+static state states_55[4] = {
+ {9, arcs_55_0},
+ {1, arcs_55_1},
+ {1, arcs_55_2},
+ {2, arcs_55_3},
+};
+static arc arcs_56_0[1] = {
+ {125, 1},
+};
+static arc arcs_56_1[2] = {
+ {126, 0},
+ {0, 1},
+};
+static state states_56[2] = {
+ {1, arcs_56_0},
+ {2, arcs_56_1},
};
static arc arcs_57_0[1] = {
- {128, 1},
+ {127, 1},
};
static arc arcs_57_1[2] = {
- {129, 0},
+ {128, 0},
{0, 1},
};
static state states_57[2] = {
@@ -1263,10 +1228,10 @@
{2, arcs_57_1},
};
static arc arcs_58_0[1] = {
- {130, 1},
+ {129, 1},
};
static arc arcs_58_1[2] = {
- {131, 0},
+ {130, 0},
{0, 1},
};
static state states_58[2] = {
@@ -1274,22 +1239,23 @@
{2, arcs_58_1},
};
static arc arcs_59_0[1] = {
- {132, 1},
+ {131, 1},
};
-static arc arcs_59_1[2] = {
+static arc arcs_59_1[3] = {
+ {132, 0},
{133, 0},
{0, 1},
};
static state states_59[2] = {
{1, arcs_59_0},
- {2, arcs_59_1},
+ {3, arcs_59_1},
};
static arc arcs_60_0[1] = {
{134, 1},
};
static arc arcs_60_1[3] = {
{135, 0},
- {62, 0},
+ {136, 0},
{0, 1},
};
static state states_60[2] = {
@@ -1297,300 +1263,304 @@
{3, arcs_60_1},
};
static arc arcs_61_0[1] = {
- {136, 1},
+ {137, 1},
};
-static arc arcs_61_1[3] = {
- {137, 0},
+static arc arcs_61_1[5] = {
+ {29, 0},
{138, 0},
+ {139, 0},
+ {140, 0},
{0, 1},
};
static state states_61[2] = {
{1, arcs_61_0},
- {3, arcs_61_1},
+ {5, arcs_61_1},
};
-static arc arcs_62_0[1] = {
- {139, 1},
-};
-static arc arcs_62_1[5] = {
- {29, 0},
- {140, 0},
- {141, 0},
- {142, 0},
- {0, 1},
-};
-static state states_62[2] = {
- {1, arcs_62_0},
- {5, arcs_62_1},
-};
-static arc arcs_63_0[4] = {
- {137, 1},
- {138, 1},
- {143, 1},
- {144, 2},
+static arc arcs_62_0[4] = {
+ {135, 1},
+ {136, 1},
+ {141, 1},
+ {142, 2},
};
-static arc arcs_63_1[1] = {
- {139, 2},
+static arc arcs_62_1[1] = {
+ {137, 2},
};
-static arc arcs_63_2[1] = {
+static arc arcs_62_2[1] = {
{0, 2},
};
-static state states_63[3] = {
- {4, arcs_63_0},
- {1, arcs_63_1},
- {1, arcs_63_2},
+static state states_62[3] = {
+ {4, arcs_62_0},
+ {1, arcs_62_1},
+ {1, arcs_62_2},
};
-static arc arcs_64_0[1] = {
- {145, 1},
+static arc arcs_63_0[1] = {
+ {143, 1},
};
-static arc arcs_64_1[3] = {
- {146, 1},
+static arc arcs_63_1[3] = {
+ {144, 1},
{31, 2},
{0, 1},
};
-static arc arcs_64_2[1] = {
- {139, 3},
+static arc arcs_63_2[1] = {
+ {137, 3},
};
-static arc arcs_64_3[1] = {
+static arc arcs_63_3[1] = {
{0, 3},
};
-static state states_64[4] = {
- {1, arcs_64_0},
- {3, arcs_64_1},
- {1, arcs_64_2},
- {1, arcs_64_3},
+static state states_63[4] = {
+ {1, arcs_63_0},
+ {3, arcs_63_1},
+ {1, arcs_63_2},
+ {1, arcs_63_3},
};
-static arc arcs_65_0[7] = {
+static arc arcs_64_0[7] = {
{13, 1},
- {148, 2},
- {151, 3},
+ {146, 2},
+ {149, 3},
{19, 4},
- {154, 4},
- {155, 5},
- {80, 6},
+ {152, 4},
+ {153, 5},
+ {77, 6},
};
-static arc arcs_65_1[3] = {
- {48, 7},
- {147, 7},
+static arc arcs_64_1[3] = {
+ {47, 7},
+ {145, 7},
{15, 4},
};
-static arc arcs_65_2[2] = {
- {149, 8},
- {150, 4},
-};
-static arc arcs_65_3[2] = {
- {152, 9},
- {153, 4},
+static arc arcs_64_2[2] = {
+ {147, 8},
+ {148, 4},
+};
+static arc arcs_64_3[2] = {
+ {150, 9},
+ {151, 4},
};
-static arc arcs_65_4[1] = {
+static arc arcs_64_4[1] = {
{0, 4},
};
-static arc arcs_65_5[2] = {
- {155, 5},
+static arc arcs_64_5[2] = {
+ {153, 5},
{0, 5},
};
-static arc arcs_65_6[1] = {
- {80, 10},
+static arc arcs_64_6[1] = {
+ {77, 10},
};
-static arc arcs_65_7[1] = {
+static arc arcs_64_7[1] = {
{15, 4},
};
-static arc arcs_65_8[1] = {
- {150, 4},
+static arc arcs_64_8[1] = {
+ {148, 4},
};
-static arc arcs_65_9[1] = {
- {153, 4},
+static arc arcs_64_9[1] = {
+ {151, 4},
};
-static arc arcs_65_10[1] = {
- {80, 4},
+static arc arcs_64_10[1] = {
+ {77, 4},
};
-static state states_65[11] = {
- {7, arcs_65_0},
- {3, arcs_65_1},
- {2, arcs_65_2},
- {2, arcs_65_3},
- {1, arcs_65_4},
- {2, arcs_65_5},
- {1, arcs_65_6},
- {1, arcs_65_7},
- {1, arcs_65_8},
- {1, arcs_65_9},
- {1, arcs_65_10},
+static state states_64[11] = {
+ {7, arcs_64_0},
+ {3, arcs_64_1},
+ {2, arcs_64_2},
+ {2, arcs_64_3},
+ {1, arcs_64_4},
+ {2, arcs_64_5},
+ {1, arcs_64_6},
+ {1, arcs_64_7},
+ {1, arcs_64_8},
+ {1, arcs_64_9},
+ {1, arcs_64_10},
};
-static arc arcs_66_0[1] = {
+static arc arcs_65_0[1] = {
{22, 1},
};
-static arc arcs_66_1[3] = {
- {156, 2},
+static arc arcs_65_1[3] = {
+ {154, 2},
{28, 3},
{0, 1},
};
-static arc arcs_66_2[1] = {
+static arc arcs_65_2[1] = {
{0, 2},
};
-static arc arcs_66_3[2] = {
+static arc arcs_65_3[2] = {
{22, 4},
{0, 3},
};
-static arc arcs_66_4[2] = {
+static arc arcs_65_4[2] = {
{28, 3},
{0, 4},
};
-static state states_66[5] = {
- {1, arcs_66_0},
- {3, arcs_66_1},
- {1, arcs_66_2},
- {2, arcs_66_3},
- {2, arcs_66_4},
+static state states_65[5] = {
+ {1, arcs_65_0},
+ {3, arcs_65_1},
+ {1, arcs_65_2},
+ {2, arcs_65_3},
+ {2, arcs_65_4},
};
-static arc arcs_67_0[1] = {
+static arc arcs_66_0[1] = {
{22, 1},
};
-static arc arcs_67_1[3] = {
- {157, 2},
+static arc arcs_66_1[3] = {
+ {155, 2},
{28, 3},
{0, 1},
};
-static arc arcs_67_2[1] = {
+static arc arcs_66_2[1] = {
{0, 2},
};
-static arc arcs_67_3[2] = {
+static arc arcs_66_3[2] = {
{22, 4},
{0, 3},
};
-static arc arcs_67_4[2] = {
+static arc arcs_66_4[2] = {
{28, 3},
{0, 4},
};
-static state states_67[5] = {
- {1, arcs_67_0},
- {3, arcs_67_1},
- {1, arcs_67_2},
- {2, arcs_67_3},
- {2, arcs_67_4},
+static state states_66[5] = {
+ {1, arcs_66_0},
+ {3, arcs_66_1},
+ {1, arcs_66_2},
+ {2, arcs_66_3},
+ {2, arcs_66_4},
};
-static arc arcs_68_0[1] = {
- {112, 1},
+static arc arcs_67_0[1] = {
+ {109, 1},
};
-static arc arcs_68_1[2] = {
+static arc arcs_67_1[2] = {
{33, 2},
{23, 3},
};
-static arc arcs_68_2[1] = {
+static arc arcs_67_2[1] = {
{23, 3},
};
-static arc arcs_68_3[1] = {
+static arc arcs_67_3[1] = {
{22, 4},
};
-static arc arcs_68_4[1] = {
+static arc arcs_67_4[1] = {
{0, 4},
};
-static state states_68[5] = {
- {1, arcs_68_0},
- {2, arcs_68_1},
- {1, arcs_68_2},
- {1, arcs_68_3},
- {1, arcs_68_4},
+static state states_67[5] = {
+ {1, arcs_67_0},
+ {2, arcs_67_1},
+ {1, arcs_67_2},
+ {1, arcs_67_3},
+ {1, arcs_67_4},
};
-static arc arcs_69_0[3] = {
+static arc arcs_68_0[3] = {
{13, 1},
- {148, 2},
- {80, 3},
+ {146, 2},
+ {77, 3},
};
-static arc arcs_69_1[2] = {
+static arc arcs_68_1[2] = {
{14, 4},
{15, 5},
};
-static arc arcs_69_2[1] = {
- {158, 6},
+static arc arcs_68_2[1] = {
+ {156, 6},
};
-static arc arcs_69_3[1] = {
+static arc arcs_68_3[1] = {
{19, 5},
};
-static arc arcs_69_4[1] = {
+static arc arcs_68_4[1] = {
{15, 5},
};
-static arc arcs_69_5[1] = {
+static arc arcs_68_5[1] = {
{0, 5},
};
-static arc arcs_69_6[1] = {
- {150, 5},
+static arc arcs_68_6[1] = {
+ {148, 5},
};
-static state states_69[7] = {
- {3, arcs_69_0},
- {2, arcs_69_1},
- {1, arcs_69_2},
- {1, arcs_69_3},
- {1, arcs_69_4},
- {1, arcs_69_5},
- {1, arcs_69_6},
+static state states_68[7] = {
+ {3, arcs_68_0},
+ {2, arcs_68_1},
+ {1, arcs_68_2},
+ {1, arcs_68_3},
+ {1, arcs_68_4},
+ {1, arcs_68_5},
+ {1, arcs_68_6},
};
-static arc arcs_70_0[1] = {
- {159, 1},
+static arc arcs_69_0[1] = {
+ {157, 1},
};
-static arc arcs_70_1[2] = {
+static arc arcs_69_1[2] = {
{28, 2},
{0, 1},
};
-static arc arcs_70_2[2] = {
- {159, 1},
+static arc arcs_69_2[2] = {
+ {157, 1},
{0, 2},
};
-static state states_70[3] = {
- {1, arcs_70_0},
- {2, arcs_70_1},
- {2, arcs_70_2},
+static state states_69[3] = {
+ {1, arcs_69_0},
+ {2, arcs_69_1},
+ {2, arcs_69_2},
};
-static arc arcs_71_0[2] = {
+static arc arcs_70_0[2] = {
{22, 1},
{23, 2},
};
-static arc arcs_71_1[2] = {
+static arc arcs_70_1[2] = {
{23, 2},
{0, 1},
};
-static arc arcs_71_2[3] = {
+static arc arcs_70_2[3] = {
{22, 3},
- {160, 4},
+ {158, 4},
{0, 2},
};
-static arc arcs_71_3[2] = {
- {160, 4},
+static arc arcs_70_3[2] = {
+ {158, 4},
{0, 3},
};
-static arc arcs_71_4[1] = {
+static arc arcs_70_4[1] = {
{0, 4},
};
-static state states_71[5] = {
- {2, arcs_71_0},
+static state states_70[5] = {
+ {2, arcs_70_0},
+ {2, arcs_70_1},
+ {3, arcs_70_2},
+ {2, arcs_70_3},
+ {1, arcs_70_4},
+};
+static arc arcs_71_0[1] = {
+ {23, 1},
+};
+static arc arcs_71_1[2] = {
+ {22, 2},
+ {0, 1},
+};
+static arc arcs_71_2[1] = {
+ {0, 2},
+};
+static state states_71[3] = {
+ {1, arcs_71_0},
{2, arcs_71_1},
- {3, arcs_71_2},
- {2, arcs_71_3},
- {1, arcs_71_4},
+ {1, arcs_71_2},
};
static arc arcs_72_0[1] = {
- {23, 1},
+ {101, 1},
};
static arc arcs_72_1[2] = {
- {22, 2},
+ {28, 2},
{0, 1},
};
-static arc arcs_72_2[1] = {
+static arc arcs_72_2[2] = {
+ {101, 1},
{0, 2},
};
static state states_72[3] = {
{1, arcs_72_0},
{2, arcs_72_1},
- {1, arcs_72_2},
+ {2, arcs_72_2},
};
static arc arcs_73_0[1] = {
- {104, 1},
+ {22, 1},
};
static arc arcs_73_1[2] = {
{28, 2},
{0, 1},
};
static arc arcs_73_2[2] = {
- {104, 1},
+ {22, 1},
{0, 2},
};
static state states_73[3] = {
@@ -1601,500 +1571,482 @@
static arc arcs_74_0[1] = {
{22, 1},
};
-static arc arcs_74_1[2] = {
- {28, 2},
- {0, 1},
-};
-static arc arcs_74_2[2] = {
- {22, 1},
- {0, 2},
-};
-static state states_74[3] = {
- {1, arcs_74_0},
- {2, arcs_74_1},
- {2, arcs_74_2},
-};
-static arc arcs_75_0[1] = {
- {22, 1},
-};
-static arc arcs_75_1[3] = {
+static arc arcs_74_1[3] = {
{23, 2},
{28, 3},
{0, 1},
};
-static arc arcs_75_2[1] = {
+static arc arcs_74_2[1] = {
{22, 4},
};
-static arc arcs_75_3[2] = {
+static arc arcs_74_3[2] = {
{22, 5},
{0, 3},
};
-static arc arcs_75_4[2] = {
+static arc arcs_74_4[2] = {
{28, 6},
{0, 4},
};
-static arc arcs_75_5[2] = {
+static arc arcs_74_5[2] = {
{28, 3},
{0, 5},
};
-static arc arcs_75_6[2] = {
+static arc arcs_74_6[2] = {
{22, 7},
{0, 6},
};
-static arc arcs_75_7[1] = {
+static arc arcs_74_7[1] = {
{23, 2},
};
-static state states_75[8] = {
- {1, arcs_75_0},
- {3, arcs_75_1},
- {1, arcs_75_2},
- {2, arcs_75_3},
- {2, arcs_75_4},
- {2, arcs_75_5},
- {2, arcs_75_6},
- {1, arcs_75_7},
+static state states_74[8] = {
+ {1, arcs_74_0},
+ {3, arcs_74_1},
+ {1, arcs_74_2},
+ {2, arcs_74_3},
+ {2, arcs_74_4},
+ {2, arcs_74_5},
+ {2, arcs_74_6},
+ {1, arcs_74_7},
};
-static arc arcs_76_0[1] = {
- {161, 1},
+static arc arcs_75_0[1] = {
+ {159, 1},
};
-static arc arcs_76_1[1] = {
+static arc arcs_75_1[1] = {
{19, 2},
};
-static arc arcs_76_2[2] = {
+static arc arcs_75_2[2] = {
{13, 3},
{23, 4},
};
-static arc arcs_76_3[2] = {
+static arc arcs_75_3[2] = {
{9, 5},
{15, 6},
};
-static arc arcs_76_4[1] = {
+static arc arcs_75_4[1] = {
{24, 7},
};
-static arc arcs_76_5[1] = {
+static arc arcs_75_5[1] = {
{15, 6},
};
-static arc arcs_76_6[1] = {
+static arc arcs_75_6[1] = {
{23, 4},
};
-static arc arcs_76_7[1] = {
+static arc arcs_75_7[1] = {
{0, 7},
};
-static state states_76[8] = {
- {1, arcs_76_0},
- {1, arcs_76_1},
- {2, arcs_76_2},
- {2, arcs_76_3},
- {1, arcs_76_4},
- {1, arcs_76_5},
- {1, arcs_76_6},
- {1, arcs_76_7},
+static state states_75[8] = {
+ {1, arcs_75_0},
+ {1, arcs_75_1},
+ {2, arcs_75_2},
+ {2, arcs_75_3},
+ {1, arcs_75_4},
+ {1, arcs_75_5},
+ {1, arcs_75_6},
+ {1, arcs_75_7},
};
-static arc arcs_77_0[3] = {
- {162, 1},
+static arc arcs_76_0[3] = {
+ {160, 1},
{29, 2},
{31, 3},
};
-static arc arcs_77_1[2] = {
+static arc arcs_76_1[2] = {
{28, 4},
{0, 1},
};
-static arc arcs_77_2[1] = {
+static arc arcs_76_2[1] = {
{22, 5},
};
-static arc arcs_77_3[1] = {
+static arc arcs_76_3[1] = {
{22, 6},
};
-static arc arcs_77_4[4] = {
- {162, 1},
+static arc arcs_76_4[4] = {
+ {160, 1},
{29, 2},
{31, 3},
{0, 4},
};
-static arc arcs_77_5[2] = {
+static arc arcs_76_5[2] = {
{28, 7},
{0, 5},
};
-static arc arcs_77_6[1] = {
+static arc arcs_76_6[1] = {
{0, 6},
};
-static arc arcs_77_7[1] = {
+static arc arcs_76_7[1] = {
{31, 3},
};
-static state states_77[8] = {
- {3, arcs_77_0},
- {2, arcs_77_1},
- {1, arcs_77_2},
- {1, arcs_77_3},
- {4, arcs_77_4},
- {2, arcs_77_5},
- {1, arcs_77_6},
- {1, arcs_77_7},
+static state states_76[8] = {
+ {3, arcs_76_0},
+ {2, arcs_76_1},
+ {1, arcs_76_2},
+ {1, arcs_76_3},
+ {4, arcs_76_4},
+ {2, arcs_76_5},
+ {1, arcs_76_6},
+ {1, arcs_76_7},
};
-static arc arcs_78_0[1] = {
+static arc arcs_77_0[1] = {
{22, 1},
};
-static arc arcs_78_1[3] = {
- {157, 2},
+static arc arcs_77_1[3] = {
+ {155, 2},
{27, 3},
{0, 1},
};
-static arc arcs_78_2[1] = {
+static arc arcs_77_2[1] = {
{0, 2},
};
-static arc arcs_78_3[1] = {
+static arc arcs_77_3[1] = {
{22, 2},
};
-static state states_78[4] = {
- {1, arcs_78_0},
- {3, arcs_78_1},
- {1, arcs_78_2},
- {1, arcs_78_3},
+static state states_77[4] = {
+ {1, arcs_77_0},
+ {3, arcs_77_1},
+ {1, arcs_77_2},
+ {1, arcs_77_3},
};
-static arc arcs_79_0[2] = {
- {156, 1},
- {164, 1},
+static arc arcs_78_0[2] = {
+ {154, 1},
+ {162, 1},
};
-static arc arcs_79_1[1] = {
+static arc arcs_78_1[1] = {
{0, 1},
};
-static state states_79[2] = {
- {2, arcs_79_0},
- {1, arcs_79_1},
+static state states_78[2] = {
+ {2, arcs_78_0},
+ {1, arcs_78_1},
};
-static arc arcs_80_0[1] = {
- {97, 1},
+static arc arcs_79_0[1] = {
+ {94, 1},
};
-static arc arcs_80_1[1] = {
- {64, 2},
+static arc arcs_79_1[1] = {
+ {61, 2},
};
-static arc arcs_80_2[1] = {
- {98, 3},
+static arc arcs_79_2[1] = {
+ {95, 3},
};
-static arc arcs_80_3[1] = {
- {108, 4},
+static arc arcs_79_3[1] = {
+ {105, 4},
};
-static arc arcs_80_4[2] = {
- {163, 5},
+static arc arcs_79_4[2] = {
+ {161, 5},
{0, 4},
};
-static arc arcs_80_5[1] = {
+static arc arcs_79_5[1] = {
{0, 5},
};
-static state states_80[6] = {
- {1, arcs_80_0},
- {1, arcs_80_1},
- {1, arcs_80_2},
- {1, arcs_80_3},
- {2, arcs_80_4},
- {1, arcs_80_5},
+static state states_79[6] = {
+ {1, arcs_79_0},
+ {1, arcs_79_1},
+ {1, arcs_79_2},
+ {1, arcs_79_3},
+ {2, arcs_79_4},
+ {1, arcs_79_5},
};
-static arc arcs_81_0[1] = {
- {93, 1},
+static arc arcs_80_0[1] = {
+ {90, 1},
};
-static arc arcs_81_1[1] = {
- {109, 2},
+static arc arcs_80_1[1] = {
+ {106, 2},
};
-static arc arcs_81_2[2] = {
- {163, 3},
+static arc arcs_80_2[2] = {
+ {161, 3},
{0, 2},
};
-static arc arcs_81_3[1] = {
+static arc arcs_80_3[1] = {
{0, 3},
};
-static state states_81[4] = {
- {1, arcs_81_0},
- {1, arcs_81_1},
- {2, arcs_81_2},
- {1, arcs_81_3},
+static state states_80[4] = {
+ {1, arcs_80_0},
+ {1, arcs_80_1},
+ {2, arcs_80_2},
+ {1, arcs_80_3},
};
-static arc arcs_82_0[2] = {
- {157, 1},
- {166, 1},
+static arc arcs_81_0[2] = {
+ {155, 1},
+ {164, 1},
};
-static arc arcs_82_1[1] = {
+static arc arcs_81_1[1] = {
{0, 1},
};
-static state states_82[2] = {
- {2, arcs_82_0},
- {1, arcs_82_1},
+static state states_81[2] = {
+ {2, arcs_81_0},
+ {1, arcs_81_1},
};
-static arc arcs_83_0[1] = {
- {97, 1},
+static arc arcs_82_0[1] = {
+ {94, 1},
};
-static arc arcs_83_1[1] = {
- {64, 2},
+static arc arcs_82_1[1] = {
+ {61, 2},
};
-static arc arcs_83_2[1] = {
- {98, 3},
+static arc arcs_82_2[1] = {
+ {95, 3},
};
-static arc arcs_83_3[1] = {
- {110, 4},
+static arc arcs_82_3[1] = {
+ {107, 4},
};
-static arc arcs_83_4[2] = {
- {165, 5},
+static arc arcs_82_4[2] = {
+ {163, 5},
{0, 4},
};
-static arc arcs_83_5[1] = {
+static arc arcs_82_5[1] = {
{0, 5},
};
-static state states_83[6] = {
- {1, arcs_83_0},
- {1, arcs_83_1},
- {1, arcs_83_2},
- {1, arcs_83_3},
- {2, arcs_83_4},
- {1, arcs_83_5},
+static state states_82[6] = {
+ {1, arcs_82_0},
+ {1, arcs_82_1},
+ {1, arcs_82_2},
+ {1, arcs_82_3},
+ {2, arcs_82_4},
+ {1, arcs_82_5},
};
-static arc arcs_84_0[1] = {
- {93, 1},
+static arc arcs_83_0[1] = {
+ {90, 1},
};
-static arc arcs_84_1[1] = {
- {109, 2},
+static arc arcs_83_1[1] = {
+ {106, 2},
};
-static arc arcs_84_2[2] = {
- {165, 3},
+static arc arcs_83_2[2] = {
+ {163, 3},
{0, 2},
};
-static arc arcs_84_3[1] = {
+static arc arcs_83_3[1] = {
{0, 3},
};
-static state states_84[4] = {
- {1, arcs_84_0},
- {1, arcs_84_1},
- {2, arcs_84_2},
- {1, arcs_84_3},
+static state states_83[4] = {
+ {1, arcs_83_0},
+ {1, arcs_83_1},
+ {2, arcs_83_2},
+ {1, arcs_83_3},
};
-static arc arcs_85_0[1] = {
+static arc arcs_84_0[1] = {
{22, 1},
};
-static arc arcs_85_1[2] = {
+static arc arcs_84_1[2] = {
{28, 0},
{0, 1},
};
-static state states_85[2] = {
- {1, arcs_85_0},
- {2, arcs_85_1},
+static state states_84[2] = {
+ {1, arcs_84_0},
+ {2, arcs_84_1},
};
-static arc arcs_86_0[1] = {
+static arc arcs_85_0[1] = {
{19, 1},
};
-static arc arcs_86_1[1] = {
+static arc arcs_85_1[1] = {
{0, 1},
};
-static state states_86[2] = {
- {1, arcs_86_0},
- {1, arcs_86_1},
+static state states_85[2] = {
+ {1, arcs_85_0},
+ {1, arcs_85_1},
};
-static arc arcs_87_0[1] = {
- {169, 1},
+static arc arcs_86_0[1] = {
+ {167, 1},
};
-static arc arcs_87_1[2] = {
+static arc arcs_86_1[2] = {
{9, 2},
{0, 1},
};
-static arc arcs_87_2[1] = {
+static arc arcs_86_2[1] = {
{0, 2},
};
-static state states_87[3] = {
- {1, arcs_87_0},
- {2, arcs_87_1},
- {1, arcs_87_2},
+static state states_86[3] = {
+ {1, arcs_86_0},
+ {2, arcs_86_1},
+ {1, arcs_86_2},
};
-static dfa dfas[88] = {
+static dfa dfas[87] = {
{256, "single_input", 0, 3, states_0,
- "\004\050\014\000\000\000\000\240\202\247\141\040\113\000\101\000\000\206\220\014\002\002"},
+ "\004\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"},
{257, "file_input", 0, 2, states_1,
- "\204\050\014\000\000\000\000\240\202\247\141\040\113\000\101\000\000\206\220\014\002\002"},
+ "\204\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"},
{258, "eval_input", 0, 3, states_2,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
{259, "decorator", 0, 7, states_3,
- "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
{260, "decorators", 0, 2, states_4,
- "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
{261, "funcdef", 0, 9, states_5,
- "\000\010\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ "\000\010\004\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
{262, "parameters", 0, 4, states_6,
- "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ "\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
{263, "typedargslist", 0, 12, states_7,
- "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
{264, "tname", 0, 4, states_8,
- "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
{265, "tfpdef", 0, 4, states_9,
- "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
{266, "tfplist", 0, 3, states_10,
- "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
{267, "varargslist", 0, 12, states_11,
- "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ "\000\040\010\240\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
{268, "vname", 0, 2, states_12,
- "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
{269, "vfpdef", 0, 4, states_13,
- "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
{270, "vfplist", 0, 3, states_14,
- "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
{271, "stmt", 0, 2, states_15,
- "\000\050\014\000\000\000\000\240\202\247\141\040\113\000\101\000\000\206\220\014\002\002"},
+ "\000\050\014\000\000\000\000\120\360\064\014\144\011\040\010\000\200\041\044\203\200"},
{272, "simple_stmt", 0, 4, states_16,
- "\000\040\010\000\000\000\000\240\202\247\141\000\000\000\101\000\000\206\220\014\000\002"},
+ "\000\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"},
{273, "small_stmt", 0, 2, states_17,
- "\000\040\010\000\000\000\000\240\202\247\141\000\000\000\101\000\000\206\220\014\000\002"},
+ "\000\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"},
{274, "expr_stmt", 0, 6, states_18,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
{275, "augassign", 0, 2, states_19,
- "\000\000\000\000\000\000\376\037\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
- {276, "print_stmt", 0, 9, states_20,
- "\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
- {277, "del_stmt", 0, 3, states_21,
- "\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
- {278, "pass_stmt", 0, 2, states_22,
- "\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000\000"},
- {279, "flow_stmt", 0, 2, states_23,
- "\000\000\000\000\000\000\000\000\200\007\000\000\000\000\000\000\000\000\000\000\000\002"},
- {280, "break_stmt", 0, 2, states_24,
- "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000"},
- {281, "continue_stmt", 0, 2, states_25,
- "\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000\000"},
- {282, "return_stmt", 0, 3, states_26,
- "\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000\000\000\000"},
- {283, "yield_stmt", 0, 2, states_27,
- "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"},
- {284, "raise_stmt", 0, 7, states_28,
- "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000"},
- {285, "import_stmt", 0, 2, states_29,
- "\000\000\000\000\000\000\000\000\000\240\000\000\000\000\000\000\000\000\000\000\000\000"},
- {286, "import_name", 0, 3, states_30,
- "\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"},
- {287, "import_from", 0, 8, states_31,
- "\000\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"},
- {288, "import_as_name", 0, 4, states_32,
- "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
- {289, "dotted_as_name", 0, 4, states_33,
- "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
- {290, "import_as_names", 0, 3, states_34,
- "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
- {291, "dotted_as_names", 0, 2, states_35,
- "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
- {292, "dotted_name", 0, 2, states_36,
- "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
- {293, "global_stmt", 0, 3, states_37,
- "\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000"},
- {294, "assert_stmt", 0, 5, states_38,
- "\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000"},
- {295, "compound_stmt", 0, 2, states_39,
- "\000\010\004\000\000\000\000\000\000\000\000\040\113\000\000\000\000\000\000\000\002\000"},
- {296, "if_stmt", 0, 8, states_40,
- "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"},
- {297, "while_stmt", 0, 8, states_41,
- "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000"},
- {298, "for_stmt", 0, 10, states_42,
- "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"},
- {299, "try_stmt", 0, 13, states_43,
- "\000\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000"},
- {300, "with_stmt", 0, 6, states_44,
- "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"},
- {301, "with_var", 0, 3, states_45,
- "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000\000"},
- {302, "except_clause", 0, 5, states_46,
- "\000\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000"},
- {303, "suite", 0, 5, states_47,
- "\004\040\010\000\000\000\000\240\202\247\141\000\000\000\101\000\000\206\220\014\000\002"},
- {304, "testlist_safe", 0, 5, states_48,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
- {305, "old_test", 0, 2, states_49,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
- {306, "old_lambdef", 0, 5, states_50,
- "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"},
- {307, "test", 0, 6, states_51,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
- {308, "or_test", 0, 2, states_52,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\100\000\000\206\220\014\000\000"},
- {309, "and_test", 0, 2, states_53,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\100\000\000\206\220\014\000\000"},
- {310, "not_test", 0, 3, states_54,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\100\000\000\206\220\014\000\000"},
- {311, "comparison", 0, 2, states_55,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"},
- {312, "comp_op", 0, 4, states_56,
- "\000\000\000\000\000\000\000\000\000\000\000\000\004\000\100\376\000\000\000\000\000\000"},
- {313, "expr", 0, 2, states_57,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"},
- {314, "xor_expr", 0, 2, states_58,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"},
- {315, "and_expr", 0, 2, states_59,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"},
- {316, "shift_expr", 0, 2, states_60,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"},
- {317, "arith_expr", 0, 2, states_61,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"},
- {318, "term", 0, 2, states_62,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"},
- {319, "factor", 0, 3, states_63,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"},
- {320, "power", 0, 4, states_64,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\220\014\000\000"},
- {321, "atom", 0, 11, states_65,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\220\014\000\000"},
- {322, "listmaker", 0, 5, states_66,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
- {323, "testlist_gexp", 0, 5, states_67,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
- {324, "lambdef", 0, 5, states_68,
- "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000"},
- {325, "trailer", 0, 7, states_69,
- "\000\040\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\020\000\000\000"},
- {326, "subscriptlist", 0, 3, states_70,
- "\000\040\210\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
- {327, "subscript", 0, 5, states_71,
- "\000\040\210\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
- {328, "sliceop", 0, 3, states_72,
- "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
- {329, "exprlist", 0, 3, states_73,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\000\000\000\206\220\014\000\000"},
- {330, "testlist", 0, 3, states_74,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
- {331, "dictsetmaker", 0, 8, states_75,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
- {332, "classdef", 0, 8, states_76,
- "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002\000"},
- {333, "arglist", 0, 8, states_77,
- "\000\040\010\240\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
- {334, "argument", 0, 4, states_78,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
- {335, "list_iter", 0, 2, states_79,
- "\000\000\000\000\000\000\000\000\000\000\000\040\002\000\000\000\000\000\000\000\000\000"},
- {336, "list_for", 0, 6, states_80,
- "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"},
- {337, "list_if", 0, 4, states_81,
- "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"},
- {338, "gen_iter", 0, 2, states_82,
- "\000\000\000\000\000\000\000\000\000\000\000\040\002\000\000\000\000\000\000\000\000\000"},
- {339, "gen_for", 0, 6, states_83,
- "\000\000\000\000\000\000\000\000\000\000\000\000\002\000\000\000\000\000\000\000\000\000"},
- {340, "gen_if", 0, 4, states_84,
- "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000"},
- {341, "testlist1", 0, 2, states_85,
- "\000\040\010\000\000\000\000\000\000\000\001\000\000\000\101\000\000\206\220\014\000\000"},
- {342, "encoding_decl", 0, 2, states_86,
- "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
- {343, "yield_expr", 0, 3, states_87,
- "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002"},
+ "\000\000\000\000\000\000\377\017\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {276, "del_stmt", 0, 3, states_20,
+ "\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {277, "pass_stmt", 0, 2, states_21,
+ "\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {278, "flow_stmt", 0, 2, states_22,
+ "\000\000\000\000\000\000\000\000\360\000\000\000\000\000\000\000\000\000\000\000\200"},
+ {279, "break_stmt", 0, 2, states_23,
+ "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {280, "continue_stmt", 0, 2, states_24,
+ "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {281, "return_stmt", 0, 3, states_25,
+ "\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {282, "yield_stmt", 0, 2, states_26,
+ "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"},
+ {283, "raise_stmt", 0, 7, states_27,
+ "\000\000\000\000\000\000\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {284, "import_stmt", 0, 2, states_28,
+ "\000\000\000\000\000\000\000\000\000\024\000\000\000\000\000\000\000\000\000\000\000"},
+ {285, "import_name", 0, 3, states_29,
+ "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000"},
+ {286, "import_from", 0, 8, states_30,
+ "\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000"},
+ {287, "import_as_name", 0, 4, states_31,
+ "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {288, "dotted_as_name", 0, 4, states_32,
+ "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {289, "import_as_names", 0, 3, states_33,
+ "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {290, "dotted_as_names", 0, 2, states_34,
+ "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {291, "dotted_name", 0, 2, states_35,
+ "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {292, "global_stmt", 0, 3, states_36,
+ "\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000"},
+ {293, "assert_stmt", 0, 5, states_37,
+ "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000\000"},
+ {294, "compound_stmt", 0, 2, states_38,
+ "\000\010\004\000\000\000\000\000\000\000\000\144\011\000\000\000\000\000\000\200\000"},
+ {295, "if_stmt", 0, 8, states_39,
+ "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"},
+ {296, "while_stmt", 0, 8, states_40,
+ "\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000"},
+ {297, "for_stmt", 0, 10, states_41,
+ "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"},
+ {298, "try_stmt", 0, 13, states_42,
+ "\000\000\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000"},
+ {299, "with_stmt", 0, 6, states_43,
+ "\000\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000"},
+ {300, "with_var", 0, 3, states_44,
+ "\000\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000"},
+ {301, "except_clause", 0, 5, states_45,
+ "\000\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000"},
+ {302, "suite", 0, 5, states_46,
+ "\004\040\010\000\000\000\000\120\360\064\014\000\000\040\010\000\200\041\044\003\200"},
+ {303, "testlist_safe", 0, 5, states_47,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+ {304, "old_test", 0, 2, states_48,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+ {305, "old_lambdef", 0, 5, states_49,
+ "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"},
+ {306, "test", 0, 6, states_50,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+ {307, "or_test", 0, 2, states_51,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"},
+ {308, "and_test", 0, 2, states_52,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"},
+ {309, "not_test", 0, 3, states_53,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\010\000\200\041\044\003\000"},
+ {310, "comparison", 0, 2, states_54,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
+ {311, "comp_op", 0, 4, states_55,
+ "\000\000\000\000\000\000\000\000\000\000\000\200\000\000\310\037\000\000\000\000\000"},
+ {312, "expr", 0, 2, states_56,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
+ {313, "xor_expr", 0, 2, states_57,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
+ {314, "and_expr", 0, 2, states_58,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
+ {315, "shift_expr", 0, 2, states_59,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
+ {316, "arith_expr", 0, 2, states_60,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
+ {317, "term", 0, 2, states_61,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
+ {318, "factor", 0, 3, states_62,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
+ {319, "power", 0, 4, states_63,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\044\003\000"},
+ {320, "atom", 0, 11, states_64,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\044\003\000"},
+ {321, "listmaker", 0, 5, states_65,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+ {322, "testlist_gexp", 0, 5, states_66,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+ {323, "lambdef", 0, 5, states_67,
+ "\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000"},
+ {324, "trailer", 0, 7, states_68,
+ "\000\040\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\004\000\000"},
+ {325, "subscriptlist", 0, 3, states_69,
+ "\000\040\210\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+ {326, "subscript", 0, 5, states_70,
+ "\000\040\210\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+ {327, "sliceop", 0, 3, states_71,
+ "\000\000\200\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {328, "exprlist", 0, 3, states_72,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\000\000\000\200\041\044\003\000"},
+ {329, "testlist", 0, 3, states_73,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+ {330, "dictsetmaker", 0, 8, states_74,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+ {331, "classdef", 0, 8, states_75,
+ "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000"},
+ {332, "arglist", 0, 8, states_76,
+ "\000\040\010\240\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+ {333, "argument", 0, 4, states_77,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+ {334, "list_iter", 0, 2, states_78,
+ "\000\000\000\000\000\000\000\000\000\000\000\104\000\000\000\000\000\000\000\000\000"},
+ {335, "list_for", 0, 6, states_79,
+ "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"},
+ {336, "list_if", 0, 4, states_80,
+ "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"},
+ {337, "gen_iter", 0, 2, states_81,
+ "\000\000\000\000\000\000\000\000\000\000\000\104\000\000\000\000\000\000\000\000\000"},
+ {338, "gen_for", 0, 6, states_82,
+ "\000\000\000\000\000\000\000\000\000\000\000\100\000\000\000\000\000\000\000\000\000"},
+ {339, "gen_if", 0, 4, states_83,
+ "\000\000\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000"},
+ {340, "testlist1", 0, 2, states_84,
+ "\000\040\010\000\000\000\000\000\000\040\000\000\000\040\010\000\200\041\044\003\000"},
+ {341, "encoding_decl", 0, 2, states_85,
+ "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"},
+ {342, "yield_expr", 0, 3, states_86,
+ "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"},
};
-static label labels[170] = {
+static label labels[168] = {
{0, "EMPTY"},
{256, 0},
{4, 0},
{272, 0},
- {295, 0},
+ {294, 0},
{257, 0},
{271, 0},
{0, 0},
{258, 0},
- {330, 0},
+ {329, 0},
{259, 0},
{50, 0},
- {292, 0},
+ {291, 0},
{7, 0},
- {333, 0},
+ {332, 0},
{8, 0},
{260, 0},
{261, 0},
@@ -2102,9 +2054,9 @@
{1, 0},
{262, 0},
{51, 0},
- {307, 0},
+ {306, 0},
{11, 0},
- {303, 0},
+ {302, 0},
{263, 0},
{265, 0},
{22, 0},
@@ -2123,12 +2075,11 @@
{276, 0},
{277, 0},
{278, 0},
- {279, 0},
- {285, 0},
+ {284, 0},
+ {292, 0},
{293, 0},
- {294, 0},
{275, 0},
- {343, 0},
+ {342, 0},
{37, 0},
{38, 0},
{39, 0},
@@ -2141,38 +2092,36 @@
{46, 0},
{47, 0},
{49, 0},
- {1, "print"},
- {35, 0},
{1, "del"},
- {329, 0},
+ {328, 0},
{1, "pass"},
+ {279, 0},
{280, 0},
{281, 0},
- {282, 0},
- {284, 0},
{283, 0},
+ {282, 0},
{1, "break"},
{1, "continue"},
{1, "return"},
{1, "raise"},
+ {285, 0},
{286, 0},
- {287, 0},
{1, "import"},
- {291, 0},
+ {290, 0},
{1, "from"},
{23, 0},
- {290, 0},
- {288, 0},
- {1, "as"},
{289, 0},
+ {287, 0},
+ {1, "as"},
+ {288, 0},
{1, "global"},
{1, "assert"},
+ {295, 0},
{296, 0},
{297, 0},
{298, 0},
{299, 0},
- {300, 0},
- {332, 0},
+ {331, 0},
{1, "if"},
{1, "elif"},
{1, "else"},
@@ -2180,27 +2129,27 @@
{1, "for"},
{1, "in"},
{1, "try"},
- {302, 0},
+ {301, 0},
{1, "finally"},
{1, "with"},
- {301, 0},
- {313, 0},
+ {300, 0},
+ {312, 0},
{1, "except"},
{5, 0},
{6, 0},
+ {303, 0},
{304, 0},
+ {307, 0},
{305, 0},
- {308, 0},
- {306, 0},
{1, "lambda"},
- {324, 0},
- {309, 0},
+ {323, 0},
+ {308, 0},
{1, "or"},
- {310, 0},
+ {309, 0},
{1, "and"},
{1, "not"},
+ {310, 0},
{311, 0},
- {312, 0},
{20, 0},
{21, 0},
{28, 0},
@@ -2208,52 +2157,53 @@
{30, 0},
{29, 0},
{1, "is"},
- {314, 0},
+ {313, 0},
{18, 0},
- {315, 0},
+ {314, 0},
{33, 0},
- {316, 0},
+ {315, 0},
{19, 0},
- {317, 0},
+ {316, 0},
{34, 0},
- {318, 0},
+ {35, 0},
+ {317, 0},
{14, 0},
{15, 0},
- {319, 0},
+ {318, 0},
{17, 0},
{24, 0},
{48, 0},
{32, 0},
+ {319, 0},
{320, 0},
- {321, 0},
- {325, 0},
- {323, 0},
- {9, 0},
+ {324, 0},
{322, 0},
+ {9, 0},
+ {321, 0},
{10, 0},
{26, 0},
- {331, 0},
+ {330, 0},
{27, 0},
{2, 0},
{3, 0},
- {336, 0},
- {339, 0},
+ {335, 0},
+ {338, 0},
+ {325, 0},
{326, 0},
{327, 0},
- {328, 0},
{1, "class"},
+ {333, 0},
{334, 0},
- {335, 0},
+ {336, 0},
{337, 0},
- {338, 0},
+ {339, 0},
{340, 0},
{341, 0},
- {342, 0},
{1, "yield"},
};
grammar _PyParser_Grammar = {
- 88,
+ 87,
dfas,
- {170, labels},
+ {168, labels},
256
};
Modified: python/branches/p3yk-noslice/Python/import.c
==============================================================================
--- python/branches/p3yk-noslice/Python/import.c (original)
+++ python/branches/p3yk-noslice/Python/import.c Fri Feb 23 18:29:35 2007
@@ -71,9 +71,10 @@
3020 (added BUILD_SET)
3030 (added keyword-only parameters)
3040 (added signature annotations)
+ 3050 (print becomes a function)
.
*/
-#define MAGIC (3040 | ((long)'\r'<<16) | ((long)'\n'<<24))
+#define MAGIC (3050 | ((long)'\r'<<16) | ((long)'\n'<<24))
/* Magic word as global; note that _PyImport_Init() can change the
value of this global to accommodate for alterations of how the
Modified: python/branches/p3yk-noslice/Python/marshal.c
==============================================================================
--- python/branches/p3yk-noslice/Python/marshal.c (original)
+++ python/branches/p3yk-noslice/Python/marshal.c Fri Feb 23 18:29:35 2007
@@ -144,31 +144,34 @@
else if (v == Py_True) {
w_byte(TYPE_TRUE, p);
}
- else if (PyInt_Check(v)) {
- long x = PyInt_AS_LONG((PyIntObject *)v);
+ else if (PyLong_Check(v)) {
+ long x = PyLong_AsLong(v);
+ if ((x == -1) && PyErr_Occurred()) {
+ PyLongObject *ob = (PyLongObject *)v;
+ PyErr_Clear();
+ w_byte(TYPE_LONG, p);
+ n = ob->ob_size;
+ w_long((long)n, p);
+ if (n < 0)
+ n = -n;
+ for (i = 0; i < n; i++)
+ w_short(ob->ob_digit[i], p);
+ }
+ else {
#if SIZEOF_LONG > 4
- long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31);
- if (y && y != -1) {
- w_byte(TYPE_INT64, p);
- w_long64(x, p);
- }
- else
+ long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31);
+ if (y && y != -1) {
+ w_byte(TYPE_INT64, p);
+ w_long64(x, p);
+ }
+ else
#endif
{
- w_byte(TYPE_INT, p);
- w_long(x, p);
+ w_byte(TYPE_INT, p);
+ w_long(x, p);
+ }
}
}
- else if (PyLong_Check(v)) {
- PyLongObject *ob = (PyLongObject *)v;
- w_byte(TYPE_LONG, p);
- n = ob->ob_size;
- w_long((long)n, p);
- if (n < 0)
- n = -n;
- for (i = 0; i < n; i++)
- w_short(ob->ob_digit[i], p);
- }
else if (PyFloat_Check(v)) {
if (p->version > 1) {
unsigned char buf[8];
Modified: python/branches/p3yk-noslice/Python/pythonrun.c
==============================================================================
--- python/branches/p3yk-noslice/Python/pythonrun.c (original)
+++ python/branches/p3yk-noslice/Python/pythonrun.c Fri Feb 23 18:29:35 2007
@@ -60,6 +60,8 @@
static void call_ll_exitfuncs(void);
extern void _PyUnicode_Init(void);
extern void _PyUnicode_Fini(void);
+extern int _PyLong_Init(void);
+extern void PyLong_Fini(void);
#ifdef WITH_THREAD
extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
@@ -181,8 +183,8 @@
if (!_PyFrame_Init())
Py_FatalError("Py_Initialize: can't init frames");
- if (!_PyInt_Init())
- Py_FatalError("Py_Initialize: can't init ints");
+ if (!_PyLong_Init())
+ Py_FatalError("Py_Initialize: can't init longs");
_PyFloat_Init();
@@ -271,7 +273,8 @@
sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
if (!sys_isatty)
PyErr_Clear();
- if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
+ if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
+ PyFile_Check(sys_stream)) {
if (!PyFile_SetEncoding(sys_stream, codeset))
Py_FatalError("Cannot set codeset of stdin");
}
@@ -281,7 +284,8 @@
sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
if (!sys_isatty)
PyErr_Clear();
- if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
+ if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
+ PyFile_Check(sys_stream)) {
if (!PyFile_SetEncoding(sys_stream, codeset))
Py_FatalError("Cannot set codeset of stdout");
}
@@ -291,7 +295,8 @@
sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
if (!sys_isatty)
PyErr_Clear();
- if(sys_isatty && PyObject_IsTrue(sys_isatty)) {
+ if(sys_isatty && PyObject_IsTrue(sys_isatty) &&
+ PyFile_Check(sys_stream)) {
if (!PyFile_SetEncoding(sys_stream, codeset))
Py_FatalError("Cannot set codeset of stderr");
}
@@ -453,7 +458,7 @@
PyList_Fini();
PySet_Fini();
PyString_Fini();
- PyInt_Fini();
+ PyLong_Fini();
PyFloat_Fini();
#ifdef Py_USING_UNICODE
@@ -790,8 +795,6 @@
return -1;
}
Py_DECREF(v);
- if (Py_FlushLine())
- PyErr_Clear();
return 0;
}
@@ -878,8 +881,6 @@
return -1;
}
Py_DECREF(v);
- if (Py_FlushLine())
- PyErr_Clear();
return 0;
}
@@ -897,8 +898,6 @@
return -1;
}
Py_DECREF(v);
- if (Py_FlushLine())
- PyErr_Clear();
return 0;
}
@@ -1013,8 +1012,6 @@
int exitcode = 0;
PyErr_Fetch(&exception, &value, &tb);
- if (Py_FlushLine())
- PyErr_Clear();
fflush(stdout);
if (value == NULL || value == Py_None)
goto done;
@@ -1092,8 +1089,6 @@
v2 = Py_None;
Py_INCREF(v2);
}
- if (Py_FlushLine())
- PyErr_Clear();
fflush(stdout);
PySys_WriteStderr("Error in sys.excepthook:\n");
PyErr_Display(exception2, v2, tb2);
@@ -1123,8 +1118,6 @@
if (f == NULL)
fprintf(stderr, "lost sys.stderr\n");
else {
- if (Py_FlushLine())
- PyErr_Clear();
fflush(stdout);
if (tb && tb != Py_None)
err = PyTraceBack_Print(tb, f);
@@ -1592,8 +1585,6 @@
Py_DECREF(exitfunc);
}
- if (Py_FlushLine())
- PyErr_Clear();
}
static void
@@ -1850,4 +1841,3 @@
#ifdef __cplusplus
}
#endif
-
Modified: python/branches/p3yk-noslice/Python/symtable.c
==============================================================================
--- python/branches/p3yk-noslice/Python/symtable.c (original)
+++ python/branches/p3yk-noslice/Python/symtable.c Fri Feb 23 18:29:35 2007
@@ -990,11 +990,6 @@
VISIT(st, expr, s->v.AugAssign.target);
VISIT(st, expr, s->v.AugAssign.value);
break;
- case Print_kind:
- if (s->v.Print.dest)
- VISIT(st, expr, s->v.Print.dest);
- VISIT_SEQ(st, expr, s->v.Print.values);
- break;
case For_kind:
VISIT(st, expr, s->v.For.target);
VISIT(st, expr, s->v.For.iter);
Modified: python/branches/p3yk-noslice/Python/sysmodule.c
==============================================================================
--- python/branches/p3yk-noslice/Python/sysmodule.c (original)
+++ python/branches/p3yk-noslice/Python/sysmodule.c Fri Feb 23 18:29:35 2007
@@ -104,8 +104,6 @@
}
if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
return NULL;
- if (Py_FlushLine() != 0)
- return NULL;
outf = PySys_GetObject("stdout");
if (outf == NULL) {
PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
@@ -113,8 +111,7 @@
}
if (PyFile_WriteObject(o, outf, 0) != 0)
return NULL;
- PyFile_SoftSpace(outf, 1);
- if (Py_FlushLine() != 0)
+ if (PyFile_WriteString("\n", outf) != 0)
return NULL;
if (PyObject_SetAttrString(builtins, "_", o) != 0)
return NULL;
@@ -904,7 +901,7 @@
Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\
\n\
stdin -- standard input file object; used by raw_input() and input()\n\
-stdout -- standard output file object; used by the print statement\n\
+stdout -- standard output file object; used by print()\n\
stderr -- standard error object; used for error messages\n\
By assigning other file objects (or objects that behave like files)\n\
to these, it is possible to redirect all of the interpreter's I/O.\n\
@@ -1110,17 +1107,17 @@
if (PyErr_Occurred())
return NULL;
#ifdef MS_WINDOWS
- if(isatty(_fileno(stdin))){
+ if(isatty(_fileno(stdin)) && PyFile_Check(sysin)) {
sprintf(buf, "cp%d", GetConsoleCP());
if (!PyFile_SetEncoding(sysin, buf))
return NULL;
}
- if(isatty(_fileno(stdout))) {
+ if(isatty(_fileno(stdout)) && PyFile_Check(sysout)) {
sprintf(buf, "cp%d", GetConsoleOutputCP());
if (!PyFile_SetEncoding(sysout, buf))
return NULL;
}
- if(isatty(_fileno(stderr))) {
+ if(isatty(_fileno(stderr)) && PyFile_Check(syserr)) {
sprintf(buf, "cp%d", GetConsoleOutputCP());
if (!PyFile_SetEncoding(syserr, buf))
return NULL;
Modified: python/branches/p3yk-noslice/Python/traceback.c
==============================================================================
--- python/branches/p3yk-noslice/Python/traceback.c (original)
+++ python/branches/p3yk-noslice/Python/traceback.c Fri Feb 23 18:29:35 2007
@@ -113,7 +113,7 @@
int
PyTraceBack_Here(PyFrameObject *frame)
{
- PyThreadState *tstate = frame->f_tstate;
+ PyThreadState *tstate = PyThreadState_GET();
PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback;
PyTracebackObject *tb = newtracebackobject(oldtb, frame);
if (tb == NULL)
@@ -250,7 +250,7 @@
return -1;
}
limitv = PySys_GetObject("tracebacklimit");
- if (limitv && PyInt_Check(limitv)) {
+ if (limitv && PyInt_CheckExact(limitv)) {
limit = PyInt_AsLong(limitv);
if (limit <= 0)
return 0;
Modified: python/branches/p3yk-noslice/Tools/compiler/ast.txt
==============================================================================
--- python/branches/p3yk-noslice/Tools/compiler/ast.txt (original)
+++ python/branches/p3yk-noslice/Tools/compiler/ast.txt Fri Feb 23 18:29:35 2007
@@ -34,8 +34,6 @@
Return: value
Yield: value
Const: value*
-Print: nodes!, dest&
-Printnl: nodes!, dest&
Discard: expr
AugAssign: node, op*, expr
Assign: nodes!, expr
Modified: python/branches/p3yk-noslice/Tools/freeze/bkfile.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/freeze/bkfile.py (original)
+++ python/branches/p3yk-noslice/Tools/freeze/bkfile.py Fri Feb 23 18:29:35 2007
@@ -25,7 +25,6 @@
self.readline = self.__file.readline
self.readlines = self.__file.readlines
self.seek = self.__file.seek
- self.softspace = self.__file.softspace
self.tell = self.__file.tell
self.truncate = self.__file.truncate
self.write = self.__file.write
Modified: python/branches/p3yk-noslice/Tools/freeze/freeze.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/freeze/freeze.py (original)
+++ python/branches/p3yk-noslice/Tools/freeze/freeze.py Fri Feb 23 18:29:35 2007
@@ -162,7 +162,7 @@
# proces option arguments
for o, a in opts:
if o == '-h':
- print __doc__
+ print(__doc__)
return
if o == '-d':
debug = debug + 1
@@ -222,7 +222,7 @@
if win:
extensions_c = 'frozen_extensions.c'
if ishome:
- print "(Using Python source directory)"
+ print("(Using Python source directory)")
binlib = exec_prefix
incldir = os.path.join(prefix, 'Include')
config_h_dir = exec_prefix
@@ -310,7 +310,7 @@
if odir and not os.path.isdir(odir):
try:
os.mkdir(odir)
- print "Created output directory", odir
+ print("Created output directory", odir)
except os.error as msg:
usage('%s: mkdir failed (%s)' % (odir, str(msg)))
base = ''
@@ -371,7 +371,7 @@
if debug > 0:
mf.report()
- print
+ print()
dict = mf.modules
if error_if_any_missing:
@@ -479,18 +479,18 @@
# Done!
if odir:
- print 'Now run "make" in', odir,
- print 'to build the target:', base_target
+ print('Now run "make" in', odir, end=' ')
+ print('to build the target:', base_target)
else:
- print 'Now run "make" to build the target:', base_target
+ print('Now run "make" to build the target:', base_target)
# Print usage message and exit
def usage(msg):
sys.stdout = sys.stderr
- print "Error:", msg
- print "Use ``%s -h'' for help" % sys.argv[0]
+ print("Error:", msg)
+ print("Use ``%s -h'' for help" % sys.argv[0])
sys.exit(2)
Modified: python/branches/p3yk-noslice/Tools/freeze/hello.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/freeze/hello.py (original)
+++ python/branches/p3yk-noslice/Tools/freeze/hello.py Fri Feb 23 18:29:35 2007
@@ -1 +1 @@
-print 'Hello world...'
+print('Hello world...')
Modified: python/branches/p3yk-noslice/Tools/freeze/makeconfig.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/freeze/makeconfig.py (original)
+++ python/branches/p3yk-noslice/Tools/freeze/makeconfig.py Fri Feb 23 18:29:35 2007
@@ -40,8 +40,8 @@
def test():
import sys
if not sys.argv[3:]:
- print 'usage: python makeconfig.py config.c.in outputfile',
- print 'modulename ...'
+ print('usage: python makeconfig.py config.c.in outputfile', end=' ')
+ print('modulename ...')
sys.exit(2)
if sys.argv[1] == '-':
infp = sys.stdin
Modified: python/branches/p3yk-noslice/Tools/freeze/makefreeze.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/freeze/makefreeze.py (original)
+++ python/branches/p3yk-noslice/Tools/freeze/makefreeze.py Fri Feb 23 18:29:35 2007
@@ -43,7 +43,7 @@
outfp = bkfile.open(base + file, 'w')
files.append(file)
if debug:
- print "freezing", mod, "..."
+ print("freezing", mod, "...")
str = marshal.dumps(m.__code__)
size = len(str)
if m.__path__:
@@ -53,7 +53,7 @@
writecode(outfp, mangled, str)
outfp.close()
if debug:
- print "generating table of frozen modules"
+ print("generating table of frozen modules")
outfp = bkfile.open(base + 'frozen.c', 'w')
for mod, mangled, size in done:
outfp.write('extern unsigned char M_%s[];\n' % mangled)
Modified: python/branches/p3yk-noslice/Tools/freeze/parsesetup.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/freeze/parsesetup.py (original)
+++ python/branches/p3yk-noslice/Tools/freeze/parsesetup.py Fri Feb 23 18:29:35 2007
@@ -84,29 +84,29 @@
import sys
import os
if not sys.argv[1:]:
- print 'usage: python parsesetup.py Makefile*|Setup* ...'
+ print('usage: python parsesetup.py Makefile*|Setup* ...')
sys.exit(2)
for arg in sys.argv[1:]:
base = os.path.basename(arg)
if base[:8] == 'Makefile':
- print 'Make style parsing:', arg
+ print('Make style parsing:', arg)
v = getmakevars(arg)
prdict(v)
elif base[:5] == 'Setup':
- print 'Setup style parsing:', arg
+ print('Setup style parsing:', arg)
m, v = getsetupinfo(arg)
prdict(m)
prdict(v)
else:
- print arg, 'is neither a Makefile nor a Setup file'
- print '(name must begin with "Makefile" or "Setup")'
+ print(arg, 'is neither a Makefile nor a Setup file')
+ print('(name must begin with "Makefile" or "Setup")')
def prdict(d):
keys = d.keys()
keys.sort()
for key in keys:
value = d[key]
- print "%-15s" % key, str(value)
+ print("%-15s" % key, str(value))
if __name__ == '__main__':
test()
Modified: python/branches/p3yk-noslice/Tools/freeze/winmakemakefile.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/freeze/winmakemakefile.py (original)
+++ python/branches/p3yk-noslice/Tools/freeze/winmakemakefile.py Fri Feb 23 18:29:35 2007
@@ -52,29 +52,29 @@
def realwork(vars, moddefns, target):
version_suffix = "%r%r" % sys.version_info[:2]
- print "# Makefile for Microsoft Visual C++ generated by freeze.py script"
- print
- print 'target = %s' % target
- print 'pythonhome = %s' % vars['prefix']
- print
- print 'DEBUG=0 # Set to 1 to use the _d versions of Python.'
- print '!IF $(DEBUG)'
- print 'debug_suffix=_d'
- print 'c_debug=/Zi /Od /DDEBUG /D_DEBUG'
- print 'l_debug=/DEBUG'
- print 'temp_dir=Build\\Debug'
- print '!ELSE'
- print 'debug_suffix='
- print 'c_debug=/Ox'
- print 'l_debug='
- print 'temp_dir=Build\\Release'
- print '!ENDIF'
- print
-
- print '# The following line assumes you have built Python using the standard instructions'
- print '# Otherwise fix the following line to point to the library.'
- print 'pythonlib = "$(pythonhome)/pcbuild/python%s$(debug_suffix).lib"' % version_suffix
- print
+ print("# Makefile for Microsoft Visual C++ generated by freeze.py script")
+ print()
+ print('target = %s' % target)
+ print('pythonhome = %s' % vars['prefix'])
+ print()
+ print('DEBUG=0 # Set to 1 to use the _d versions of Python.')
+ print('!IF $(DEBUG)')
+ print('debug_suffix=_d')
+ print('c_debug=/Zi /Od /DDEBUG /D_DEBUG')
+ print('l_debug=/DEBUG')
+ print('temp_dir=Build\\Debug')
+ print('!ELSE')
+ print('debug_suffix=')
+ print('c_debug=/Ox')
+ print('l_debug=')
+ print('temp_dir=Build\\Release')
+ print('!ENDIF')
+ print()
+
+ print('# The following line assumes you have built Python using the standard instructions')
+ print('# Otherwise fix the following line to point to the library.')
+ print('pythonlib = "$(pythonhome)/pcbuild/python%s$(debug_suffix).lib"' % version_suffix)
+ print()
# We only ever write one "entry point" symbol - either
# "main" or "WinMain". Therefore, there is no need to
@@ -88,59 +88,59 @@
target_ext = ".dll"
- print "# As the target uses Python%s.dll, we must use this compiler option!" % version_suffix
- print "cdl = /MD"
- print
- print "all: $(target)$(debug_suffix)%s" % (target_ext)
- print
-
- print '$(temp_dir):'
- print ' if not exist $(temp_dir)\. mkdir $(temp_dir)'
- print
+ print("# As the target uses Python%s.dll, we must use this compiler option!" % version_suffix)
+ print("cdl = /MD")
+ print()
+ print("all: $(target)$(debug_suffix)%s" % (target_ext))
+ print()
+
+ print('$(temp_dir):')
+ print(' if not exist $(temp_dir)\. mkdir $(temp_dir)')
+ print()
objects = []
libs = ["shell32.lib", "comdlg32.lib", "wsock32.lib", "user32.lib", "oleaut32.lib"]
for moddefn in moddefns:
- print "# Module", moddefn.name
+ print("# Module", moddefn.name)
for file in moddefn.sourceFiles:
base = os.path.basename(file)
base, ext = os.path.splitext(base)
objects.append(base + ".obj")
- print '$(temp_dir)\%s.obj: "%s"' % (base, file)
- print "\t@$(CC) -c -nologo /Fo$* $(cdl) $(c_debug) /D BUILD_FREEZE",
- print '"-I$(pythonhome)/Include" "-I$(pythonhome)/PC" \\'
- print "\t\t$(cflags) $(cdebug) $(cinclude) \\"
+ print('$(temp_dir)\%s.obj: "%s"' % (base, file))
+ print("\t@$(CC) -c -nologo /Fo$* $(cdl) $(c_debug) /D BUILD_FREEZE", end=' ')
+ print('"-I$(pythonhome)/Include" "-I$(pythonhome)/PC" \\')
+ print("\t\t$(cflags) $(cdebug) $(cinclude) \\")
extra = moddefn.GetCompilerOptions()
if extra:
- print "\t\t%s \\" % (' '.join(extra),)
- print '\t\t"%s"' % file
- print
+ print("\t\t%s \\" % (' '.join(extra),))
+ print('\t\t"%s"' % file)
+ print()
# Add .lib files this module needs
for modlib in moddefn.GetLinkerLibs():
if modlib not in libs:
libs.append(modlib)
- print "ADDN_LINK_FILES=",
- for addn in vars['addn_link']: print '"%s"' % (addn),
- print ; print
-
- print "OBJS=",
- for obj in objects: print '"$(temp_dir)\%s"' % (obj),
- print ; print
-
- print "LIBS=",
- for lib in libs: print '"%s"' % (lib),
- print ; print
-
- print "$(target)$(debug_suffix)%s: $(temp_dir) $(OBJS)" % (target_ext)
- print "\tlink -out:$(target)$(debug_suffix)%s %s" % (target_ext, target_link_flags),
- print "\t$(OBJS) \\"
- print "\t$(LIBS) \\"
- print "\t$(ADDN_LINK_FILES) \\"
- print "\t$(pythonlib) $(lcustom) $(l_debug)\\"
- print "\t$(resources)"
- print
- print "clean:"
- print "\t-rm -f *.obj"
- print "\t-rm -f $(target).exe"
+ print("ADDN_LINK_FILES=", end=' ')
+ for addn in vars['addn_link']: print('"%s"' % (addn), end=' ')
+ print() ; print()
+
+ print("OBJS=", end=' ')
+ for obj in objects: print('"$(temp_dir)\%s"' % (obj), end=' ')
+ print() ; print()
+
+ print("LIBS=", end=' ')
+ for lib in libs: print('"%s"' % (lib), end=' ')
+ print() ; print()
+
+ print("$(target)$(debug_suffix)%s: $(temp_dir) $(OBJS)" % (target_ext))
+ print("\tlink -out:$(target)$(debug_suffix)%s %s" % (target_ext, target_link_flags), end=' ')
+ print("\t$(OBJS) \\")
+ print("\t$(LIBS) \\")
+ print("\t$(ADDN_LINK_FILES) \\")
+ print("\t$(pythonlib) $(lcustom) $(l_debug)\\")
+ print("\t$(resources)")
+ print()
+ print("clean:")
+ print("\t-rm -f *.obj")
+ print("\t-rm -f $(target).exe")
Modified: python/branches/p3yk-noslice/Tools/msi/uuids.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/msi/uuids.py (original)
+++ python/branches/p3yk-noslice/Tools/msi/uuids.py Fri Feb 23 18:29:35 2007
@@ -33,4 +33,8 @@
'2.5.121': '{8e9321bc-6b24-48a3-8fd4-c95f8e531e5f}', # 2.5c1
'2.5.122': '{a6cd508d-9599-45da-a441-cbffa9f7e070}', # 2.5c2
'2.5.150': '{0a2c5854-557e-48c8-835a-3b9f074bdcaa}', # 2.5.0
+ '2.5.1121':'{0378b43e-6184-4c2f-be1a-4a367781cd54}', # 2.5.1c1
+ '2.5.1150':'{31800004-6386-4999-a519-518f2d78d8f0}', # 2.5.1
+ '2.5.2150':'{6304a7da-1132-4e91-a343-a296269eab8a}', # 2.5.2c1
+ '2.5.2150':'{6b976adf-8ae8-434e-b282-a06c7f624d2f}', # 2.5.2
}
Modified: python/branches/p3yk-noslice/Tools/pybench/CommandLine.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/CommandLine.py (original)
+++ python/branches/p3yk-noslice/Tools/pybench/CommandLine.py Fri Feb 23 18:29:35 2007
@@ -165,7 +165,7 @@
def __init__(self,name,help=None):
if not name[:1] == '-':
- raise TypeError,'option names must start with "-"'
+ raise TypeError('option names must start with "-"')
if name[1:2] == '-':
self.prefix = '--'
self.name = name[2:]
@@ -324,30 +324,32 @@
# Append preset options
for option in self.preset_options:
- if not self.option_map.has_key(option.name):
+ if not option.name in self.option_map:
self.add_option(option)
# Init .files list
self.files = []
# Start Application
+ rc = 0
try:
# Process startup
rc = self.startup()
if rc is not None:
- raise SystemExit,rc
+ raise SystemExit(rc)
# Parse command line
rc = self.parse()
if rc is not None:
- raise SystemExit,rc
+ raise SystemExit(rc)
# Start application
rc = self.main()
if rc is None:
rc = 0
- except SystemExit as rc:
+ except SystemExit as rcException:
+ rc = rcException
pass
except KeyboardInterrupt:
@@ -367,7 +369,7 @@
print
rc = 1
- raise SystemExit,rc
+ raise SystemExit(rc)
def add_option(self, option):
@@ -398,7 +400,7 @@
program. It defaults to 0 which usually means: OK.
"""
- raise SystemExit, rc
+ raise SystemExit(rc)
def parse(self):
@@ -459,7 +461,7 @@
except AttributeError:
if value == '':
# count the number of occurances
- if values.has_key(optionname):
+ if optionname in values:
values[optionname] = values[optionname] + 1
else:
values[optionname] = 1
@@ -468,7 +470,7 @@
else:
rc = handler(value)
if rc is not None:
- raise SystemExit, rc
+ raise SystemExit(rc)
# Apply final file check (for backward compatibility)
rc = self.check_files(self.files)
Modified: python/branches/p3yk-noslice/Tools/pybench/Dict.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Dict.py (original)
+++ python/branches/p3yk-noslice/Tools/pybench/Dict.py Fri Feb 23 18:29:35 2007
@@ -351,7 +351,7 @@
def test(self):
d = {}
- has_key = d.has_key
+ has_key = lambda key: key in d
for i in xrange(self.rounds):
@@ -498,7 +498,7 @@
def calibrate(self):
d = {}
- has_key = d.has_key
+ has_key = lambda key: key in d
for i in xrange(self.rounds):
pass
Modified: python/branches/p3yk-noslice/Tools/pybench/Exceptions.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Exceptions.py (original)
+++ python/branches/p3yk-noslice/Tools/pybench/Exceptions.py Fri Feb 23 18:29:35 2007
@@ -20,15 +20,15 @@
except:
pass
try:
- raise error,"something"
+ raise error("something")
except:
pass
try:
- raise error,"something"
+ raise error("something")
except:
pass
try:
- raise error,"something"
+ raise error("something")
except:
pass
try:
Modified: python/branches/p3yk-noslice/Tools/pybench/Lookups.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/Lookups.py (original)
+++ python/branches/p3yk-noslice/Tools/pybench/Lookups.py Fri Feb 23 18:29:35 2007
@@ -774,11 +774,11 @@
l.sort
l.sort
- d.has_key
- d.has_key
- d.has_key
- d.has_key
- d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
d.items
d.items
@@ -810,11 +810,11 @@
l.sort
l.sort
- d.has_key
- d.has_key
- d.has_key
- d.has_key
- d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
d.items
d.items
@@ -846,11 +846,11 @@
l.sort
l.sort
- d.has_key
- d.has_key
- d.has_key
- d.has_key
- d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
d.items
d.items
@@ -882,11 +882,11 @@
l.sort
l.sort
- d.has_key
- d.has_key
- d.has_key
- d.has_key
- d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
d.items
d.items
@@ -918,11 +918,11 @@
l.sort
l.sort
- d.has_key
- d.has_key
- d.has_key
- d.has_key
- d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
+ # d.has_key
d.items
d.items
Modified: python/branches/p3yk-noslice/Tools/pybench/pybench.py
==============================================================================
--- python/branches/p3yk-noslice/Tools/pybench/pybench.py (original)
+++ python/branches/p3yk-noslice/Tools/pybench/pybench.py Fri Feb 23 18:29:35 2007
@@ -34,7 +34,7 @@
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
"""
-import sys, time, operator, string
+import sys, time, operator, string, platform
from CommandLine import *
try:
@@ -102,27 +102,26 @@
def get_machine_details():
- import platform
if _debug:
print 'Getting machine details...'
buildno, builddate = platform.python_build()
python = platform.python_version()
- if python > '2.0':
- try:
- unichr(100000)
- except ValueError:
- # UCS2 build (standard)
- unicode = 'UCS2'
- else:
- # UCS4 build (most recent Linux distros)
- unicode = 'UCS4'
- else:
+ try:
+ unichr(100000)
+ except ValueError:
+ # UCS2 build (standard)
+ unicode = 'UCS2'
+ except NameError:
unicode = None
+ else:
+ # UCS4 build (most recent Linux distros)
+ unicode = 'UCS4'
bits, linkage = platform.architecture()
return {
'platform': platform.platform(),
'processor': platform.processor(),
'executable': sys.executable,
+ 'implementation': platform.python_implementation(),
'python': platform.python_version(),
'compiler': platform.python_compiler(),
'buildno': buildno,
@@ -134,17 +133,18 @@
def print_machine_details(d, indent=''):
l = ['Machine Details:',
- ' Platform ID: %s' % d.get('platform', 'n/a'),
- ' Processor: %s' % d.get('processor', 'n/a'),
+ ' Platform ID: %s' % d.get('platform', 'n/a'),
+ ' Processor: %s' % d.get('processor', 'n/a'),
'',
'Python:',
- ' Executable: %s' % d.get('executable', 'n/a'),
- ' Version: %s' % d.get('python', 'n/a'),
- ' Compiler: %s' % d.get('compiler', 'n/a'),
- ' Bits: %s' % d.get('bits', 'n/a'),
- ' Build: %s (#%s)' % (d.get('builddate', 'n/a'),
- d.get('buildno', 'n/a')),
- ' Unicode: %s' % d.get('unicode', 'n/a'),
+ ' Implementation: %s' % d.get('implementation', 'n/a'),
+ ' Executable: %s' % d.get('executable', 'n/a'),
+ ' Version: %s' % d.get('python', 'n/a'),
+ ' Compiler: %s' % d.get('compiler', 'n/a'),
+ ' Bits: %s' % d.get('bits', 'n/a'),
+ ' Build: %s (#%s)' % (d.get('builddate', 'n/a'),
+ d.get('buildno', 'n/a')),
+ ' Unicode: %s' % d.get('unicode', 'n/a'),
]
print indent + string.join(l, '\n' + indent) + '\n'
@@ -499,9 +499,10 @@
def calibrate(self):
- print 'Calibrating tests. Please wait...'
+ print 'Calibrating tests. Please wait...',
if self.verbose:
print
+ print
print 'Test min max'
print '-' * LINE
tests = self.tests.items()
@@ -514,6 +515,11 @@
(name,
min(test.overhead_times) * MILLI_SECONDS,
max(test.overhead_times) * MILLI_SECONDS)
+ if self.verbose:
+ print
+ print 'Done with the calibration.'
+ else:
+ print 'done.'
print
def run(self):
@@ -830,7 +836,9 @@
print '-' * LINE
print 'PYBENCH %s' % __version__
print '-' * LINE
- print '* using Python %s' % (string.split(sys.version)[0])
+ print '* using %s %s' % (
+ platform.python_implementation(),
+ string.join(string.split(sys.version), ' '))
# Switch off garbage collection
if not withgc:
@@ -839,15 +847,23 @@
except ImportError:
print '* Python version doesn\'t support garbage collection'
else:
- gc.disable()
- print '* disabled garbage collection'
+ try:
+ gc.disable()
+ except NotImplementedError:
+ print '* Python version doesn\'t support gc.disable'
+ else:
+ print '* disabled garbage collection'
# "Disable" sys check interval
if not withsyscheck:
# Too bad the check interval uses an int instead of a long...
value = 2147483647
- sys.setcheckinterval(value)
- print '* system check interval set to maximum: %s' % value
+ try:
+ sys.setcheckinterval(value)
+ except (AttributeError, NotImplementedError):
+ print '* Python version doesn\'t support sys.setcheckinterval'
+ else:
+ print '* system check interval set to maximum: %s' % value
if timer == TIMER_SYSTIMES_PROCESSTIME:
import systimes
Modified: python/branches/p3yk-noslice/configure
==============================================================================
--- python/branches/p3yk-noslice/configure (original)
+++ python/branches/p3yk-noslice/configure Fri Feb 23 18:29:35 2007
@@ -1,5 +1,5 @@
#! /bin/sh
-# From configure.in Revision: 51211 .
+# From configure.in Revision: 53610 .
# Guess values for system-dependent variables and create Makefiles.
# Generated by GNU Autoconf 2.61 for python 3.0.
#
@@ -10608,6 +10608,467 @@
fi
+{ echo "$as_me:$LINENO: checking for _Bool support" >&5
+echo $ECHO_N "checking for _Bool support... $ECHO_C" >&6; }
+have_c99_bool=no
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+
+int
+main ()
+{
+_Bool x; x = (_Bool)0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+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_compile") 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_objext; then
+
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_C99_BOOL 1
+_ACEOF
+
+ have_c99_bool=yes
+
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $have_c99_bool" >&5
+echo "${ECHO_T}$have_c99_bool" >&6; }
+if test "$have_c99_bool" = yes ; then
+{ echo "$as_me:$LINENO: checking for _Bool" >&5
+echo $ECHO_N "checking for _Bool... $ECHO_C" >&6; }
+if test "${ac_cv_type__Bool+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+typedef _Bool ac__type_new_;
+int
+main ()
+{
+if ((ac__type_new_ *) 0)
+ return 0;
+if (sizeof (ac__type_new_))
+ return 0;
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+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_compile") 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_objext; then
+ ac_cv_type__Bool=yes
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_cv_type__Bool=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5
+echo "${ECHO_T}$ac_cv_type__Bool" >&6; }
+
+# The cast to long int works around a bug in the HP C Compiler
+# version HP92453-01 B.11.11.23709.GP, which incorrectly rejects
+# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'.
+# This bug is HP SR number 8606223364.
+{ echo "$as_me:$LINENO: checking size of _Bool" >&5
+echo $ECHO_N "checking size of _Bool... $ECHO_C" >&6; }
+if test "${ac_cv_sizeof__Bool+set}" = set; then
+ echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+ if test "$cross_compiling" = yes; then
+ # Depending upon the size, compute the lo and hi bounds.
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+ typedef _Bool ac__type_sizeof_;
+int
+main ()
+{
+static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= 0)];
+test_array [0] = 0
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+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_compile") 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_objext; then
+ ac_lo=0 ac_mid=0
+ while :; do
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+ typedef _Bool ac__type_sizeof_;
+int
+main ()
+{
+static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)];
+test_array [0] = 0
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+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_compile") 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_objext; then
+ ac_hi=$ac_mid; break
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_lo=`expr $ac_mid + 1`
+ if test $ac_lo -le $ac_mid; then
+ ac_lo= ac_hi=
+ break
+ fi
+ ac_mid=`expr 2 '*' $ac_mid + 1`
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ done
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+ typedef _Bool ac__type_sizeof_;
+int
+main ()
+{
+static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) < 0)];
+test_array [0] = 0
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+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_compile") 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_objext; then
+ ac_hi=-1 ac_mid=-1
+ while :; do
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+ typedef _Bool ac__type_sizeof_;
+int
+main ()
+{
+static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) >= $ac_mid)];
+test_array [0] = 0
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+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_compile") 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_objext; then
+ ac_lo=$ac_mid; break
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_hi=`expr '(' $ac_mid ')' - 1`
+ if test $ac_mid -le $ac_hi; then
+ ac_lo= ac_hi=
+ break
+ fi
+ ac_mid=`expr 2 '*' $ac_mid`
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+ done
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_lo= ac_hi=
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+# Binary search between lo and hi bounds.
+while test "x$ac_lo" != "x$ac_hi"; do
+ ac_mid=`expr '(' $ac_hi - $ac_lo ')' / 2 + $ac_lo`
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+ typedef _Bool ac__type_sizeof_;
+int
+main ()
+{
+static int test_array [1 - 2 * !(((long int) (sizeof (ac__type_sizeof_))) <= $ac_mid)];
+test_array [0] = 0
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+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_compile") 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_objext; then
+ ac_hi=$ac_mid
+else
+ echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+ ac_lo=`expr '(' $ac_mid ')' + 1`
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+done
+case $ac_lo in
+?*) ac_cv_sizeof__Bool=$ac_lo;;
+'') if test "$ac_cv_type__Bool" = yes; then
+ { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool)
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot compute sizeof (_Bool)
+See \`config.log' for more details." >&2;}
+ { (exit 77); exit 77; }; }
+ else
+ ac_cv_sizeof__Bool=0
+ fi ;;
+esac
+else
+ cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h. */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h. */
+$ac_includes_default
+ typedef _Bool ac__type_sizeof_;
+static long int longval () { return (long int) (sizeof (ac__type_sizeof_)); }
+static unsigned long int ulongval () { return (long int) (sizeof (ac__type_sizeof_)); }
+#include <stdio.h>
+#include <stdlib.h>
+int
+main ()
+{
+
+ FILE *f = fopen ("conftest.val", "w");
+ if (! f)
+ return 1;
+ if (((long int) (sizeof (ac__type_sizeof_))) < 0)
+ {
+ long int i = longval ();
+ if (i != ((long int) (sizeof (ac__type_sizeof_))))
+ return 1;
+ fprintf (f, "%ld\n", i);
+ }
+ else
+ {
+ unsigned long int i = ulongval ();
+ if (i != ((long int) (sizeof (ac__type_sizeof_))))
+ return 1;
+ fprintf (f, "%lu\n", i);
+ }
+ return ferror (f) || fclose (f) != 0;
+
+ ;
+ return 0;
+}
+_ACEOF
+rm -f 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>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
+ { (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_try") 2>&5
+ ac_status=$?
+ echo "$as_me:$LINENO: \$? = $ac_status" >&5
+ (exit $ac_status); }; }; then
+ ac_cv_sizeof__Bool=`cat conftest.val`
+else
+ echo "$as_me: program exited with status $ac_status" >&5
+echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+( exit $ac_status )
+if test "$ac_cv_type__Bool" = yes; then
+ { { echo "$as_me:$LINENO: error: cannot compute sizeof (_Bool)
+See \`config.log' for more details." >&5
+echo "$as_me: error: cannot compute sizeof (_Bool)
+See \`config.log' for more details." >&2;}
+ { (exit 77); exit 77; }; }
+ else
+ ac_cv_sizeof__Bool=0
+ fi
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+fi
+rm -f conftest.val
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_sizeof__Bool" >&5
+echo "${ECHO_T}$ac_cv_sizeof__Bool" >&6; }
+
+
+
+cat >>confdefs.h <<_ACEOF
+#define SIZEOF__BOOL $ac_cv_sizeof__Bool
+_ACEOF
+
+
+fi
+
{ echo "$as_me:$LINENO: checking for uintptr_t" >&5
echo $ECHO_N "checking for uintptr_t... $ECHO_C" >&6; }
if test "${ac_cv_type_uintptr_t+set}" = set; then
@@ -14607,11 +15068,13 @@
-for ac_func in alarm bind_textdomain_codeset chown clock confstr ctermid \
- execv fork fpathconf ftime ftruncate \
+
+
+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 \
getpriority getpwent getspnam getspent getsid getwd \
- kill killpg lchown lstat mkfifo mknod mktime \
+ kill killpg lchflags lchown lstat mkfifo mknod mktime \
mremap nice pathconf pause plock poll pthread_init \
putenv readlink realpath \
select setegid seteuid setgid \
Modified: python/branches/p3yk-noslice/configure.in
==============================================================================
--- python/branches/p3yk-noslice/configure.in (original)
+++ python/branches/p3yk-noslice/configure.in Fri Feb 23 18:29:35 2007
@@ -1218,6 +1218,17 @@
AC_CHECK_SIZEOF(long long, 8)
fi
+AC_MSG_CHECKING(for _Bool support)
+have_c99_bool=no
+AC_TRY_COMPILE([], [_Bool x; x = (_Bool)0;], [
+ AC_DEFINE(HAVE_C99_BOOL, 1, [Define this if you have the type _Bool.])
+ have_c99_bool=yes
+])
+AC_MSG_RESULT($have_c99_bool)
+if test "$have_c99_bool" = yes ; then
+AC_CHECK_SIZEOF(_Bool, 1)
+fi
+
AC_CHECK_TYPES(uintptr_t,
[AC_CHECK_SIZEOF(uintptr_t, 4)],
[], [#ifdef HAVE_STDINT_H
@@ -2271,11 +2282,11 @@
AC_MSG_RESULT(MACHDEP_OBJS)
# checks for library functions
-AC_CHECK_FUNCS(alarm bind_textdomain_codeset chown clock confstr ctermid \
- execv fork fpathconf ftime ftruncate \
+AC_CHECK_FUNCS(alarm bind_textdomain_codeset chflags chown clock confstr \
+ ctermid execv fork fpathconf ftime ftruncate \
gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \
getpriority getpwent getspnam getspent getsid getwd \
- kill killpg lchown lstat mkfifo mknod mktime \
+ kill killpg lchflags lchown lstat mkfifo mknod mktime \
mremap nice pathconf pause plock poll pthread_init \
putenv readlink realpath \
select setegid seteuid setgid \
Modified: python/branches/p3yk-noslice/pyconfig.h.in
==============================================================================
--- python/branches/p3yk-noslice/pyconfig.h.in (original)
+++ python/branches/p3yk-noslice/pyconfig.h.in Fri Feb 23 18:29:35 2007
@@ -64,6 +64,12 @@
/* Define if pthread_sigmask() does not work on your system. */
#undef HAVE_BROKEN_PTHREAD_SIGMASK
+/* Define this if you have the type _Bool. */
+#undef HAVE_C99_BOOL
+
+/* Define to 1 if you have the `chflags' function. */
+#undef HAVE_CHFLAGS
+
/* Define to 1 if you have the `chown' function. */
#undef HAVE_CHOWN
@@ -287,6 +293,9 @@
Solaris and Linux, the necessary defines are already defined.) */
#undef HAVE_LARGEFILE_SUPPORT
+/* Define to 1 if you have the `lchflags' function. */
+#undef HAVE_LCHFLAGS
+
/* Define to 1 if you have the `lchown' function. */
#undef HAVE_LCHOWN
@@ -835,6 +844,9 @@
/* The size of a `wchar_t', as computed by sizeof. */
#undef SIZEOF_WCHAR_T
+/* The size of a `_Bool', as computed by sizeof. */
+#undef SIZEOF__BOOL
+
/* Define to 1 if you have the ANSI C header files. */
#undef STDC_HEADERS
Modified: python/branches/p3yk-noslice/setup.py
==============================================================================
--- python/branches/p3yk-noslice/setup.py (original)
+++ python/branches/p3yk-noslice/setup.py Fri Feb 23 18:29:35 2007
@@ -461,7 +461,7 @@
exts.append( Extension('audioop', ['audioop.c']) )
# Disabled on 64-bit platforms
- if sys.maxint != 9223372036854775807L:
+ if sys.maxint != 9223372036854775807:
# Operations on images
exts.append( Extension('imageop', ['imageop.c']) )
# Read SGI RGB image files (but coded portably)
@@ -664,7 +664,7 @@
# search path.
for d in inc_dirs + db_inc_paths:
f = os.path.join(d, "db.h")
- if db_setup_debug: print "db: looking for db.h in", f
+ if db_setup_debug: print("db: looking for db.h in", f)
if os.path.exists(f):
f = open(f).read()
m = re.search(r"#define\WDB_VERSION_MAJOR\W(\d+)", f)
@@ -680,16 +680,15 @@
# (first occurrance only)
db_ver_inc_map[db_ver] = d
if db_setup_debug:
- print "db.h: found", db_ver, "in", d
+ print("db.h: found", db_ver, "in", d)
else:
# we already found a header for this library version
- if db_setup_debug: print "db.h: ignoring", d
+ if db_setup_debug: print("db.h: ignoring", d)
else:
# ignore this header, it didn't contain a version number
- if db_setup_debug: print "db.h: unsupported version", db_ver, "in", d
+ if db_setup_debug: print("db.h: unsupported version", db_ver, "in", d)
- db_found_vers = db_ver_inc_map.keys()
- db_found_vers.sort()
+ db_found_vers = sorted(db_ver_inc_map.keys())
while db_found_vers:
db_ver = db_found_vers.pop()
@@ -717,12 +716,12 @@
dblib_dir = [ os.path.abspath(os.path.dirname(dblib_file)) ]
raise db_found
else:
- if db_setup_debug: print "db lib: ", dblib, "not found"
+ if db_setup_debug: print("db lib: ", dblib, "not found")
except db_found:
if db_setup_debug:
- print "db lib: using", db_ver, dblib
- print "db: lib dir", dblib_dir, "inc dir", db_incdir
+ print("db lib: using", db_ver, dblib)
+ print("db: lib dir", dblib_dir, "inc dir", db_incdir)
db_incs = [db_incdir]
dblibs = [dblib]
# We add the runtime_library_dirs argument because the
@@ -737,7 +736,7 @@
include_dirs=db_incs,
libraries=dblibs))
else:
- if db_setup_debug: print "db: no appropriate library found"
+ if db_setup_debug: print("db: no appropriate library found")
db_incs = None
dblibs = []
dblib_dir = None
@@ -765,7 +764,7 @@
for d in inc_dirs + sqlite_inc_paths:
f = os.path.join(d, "sqlite3.h")
if os.path.exists(f):
- if sqlite_setup_debug: print "sqlite: found %s"%f
+ if sqlite_setup_debug: print("sqlite: found %s"%f)
incf = open(f).read()
m = re.search(
r'\s*.*#\s*.*define\s.*SQLITE_VERSION\W*"(.*)"', incf)
@@ -776,15 +775,15 @@
if sqlite_version_tuple >= MIN_SQLITE_VERSION_NUMBER:
# we win!
if sqlite_setup_debug:
- print "%s/sqlite3.h: version %s"%(d, sqlite_version)
+ print("%s/sqlite3.h: version %s"%(d, sqlite_version))
sqlite_incdir = d
break
else:
if sqlite_setup_debug:
- print "%s: version %d is too old, need >= %s"%(d,
- sqlite_version, MIN_SQLITE_VERSION)
+ print("%s: version %d is too old, need >= %s"%(d,
+ sqlite_version, MIN_SQLITE_VERSION))
elif sqlite_setup_debug:
- print "sqlite: %s had no SQLITE_VERSION"%(f,)
+ print("sqlite: %s had no SQLITE_VERSION"%(f,))
if sqlite_incdir:
sqlite_dirs_to_check = [
@@ -1319,7 +1318,8 @@
from distutils.dep_util import newer_group
config_sources = [os.path.join(ffi_srcdir, fname)
- for fname in os.listdir(ffi_srcdir)]
+ for fname in os.listdir(ffi_srcdir)
+ if os.path.isfile(os.path.join(ffi_srcdir, fname))]
if self.force or newer_group(config_sources,
ffi_configfile):
from distutils.dir_util import mkpath
@@ -1333,7 +1333,7 @@
res = os.system(cmd)
if res or not os.path.exists(ffi_configfile):
- print "Failed to configure _ctypes module"
+ print("Failed to configure _ctypes module")
return False
fficonfig = {}
More information about the Python-checkins
mailing list