+++++++++++ Python News +++++++++++ (editors: check NEWS.help for information about editing NEWS using ReST.) What's New in Python 2.3.5? ============================== *Release date: 08-FEB-2005* Core and builtins ----------------- - Partially revert the fix for #1074011; don't try to fflush stdin anymore. Library ------- - Applied a security fix to SimpleXMLRPCserver (PSF-2005-001). This disables recursive traversal through instance attributes, which can be exploited in various ways. - Bug #1114776. Applied a fix to the copy.py fix in 2.3.5rc1 to deal with types that don't have an __mro__. What's New in Python 2.3.5rc1? ============================== *Release date: 26-JAN-2005* Core and builtins ----------------- - Bug #1074011: closing sys.std{in,out,err} now causes a flush() and an ferror() call. - Bug #1055820 Cyclic garbage collection was not protecting against that calling a live weakref to a piece of cyclic trash could resurrect an insane mutation of the trash if any Python code ran during gc (via running a dead object's __del__ method, running another callback on a weakref to a dead object, or via any Python code run in any other thread that managed to obtain the GIL while a __del__ or callback was running in the thread doing gc). The most likely symptom was "impossible" ``AttributeEror`` exceptions, appearing seemingly at random, on weakly referenced objects. The cure was to clear all weakrefs to unreachable objects before allowing any callbacks to run. - Bug #951851: Python crashed when reading import table of certain Windows DLLs - Bug #966623. classes created with type() in an exec(, {}) don't have a __module__, but code in typeobject assumed it would always be there. - Bug #952807: Unpickling pickled instances of subclasses of datetime.date, datetime.datetime and datetime.time could yield insane objects. Thanks to Jiwon Seo for a fix. - Bug #845802: Python crashed when __init__.py is a directory. - Bug #875692: Improve signal handling, especially when using threads, by forcing an early re-execution of PyEval_EvalFrame() "periodic" code when things_to_do is not cleared by Py_MakePendingCalls(). Extension modules ----------------- - Patch #1012280: Fix term.h compilation problems on Solaris. - Patch #914291: Set locale while getting a line from readline. - Bug #1005308: Define _BSD_TYPES. - Patch #1005568: Use _SC_PAGESIZE on Irix in resourcemoudle. - Patch #924294: Do no check for AF_INET6 if it is not defined. - Patch #954115: Properly handle UNC roots in nt.stat. - Bug #841757: xmlrpclib failed on structs with Unicode keys. - Bug #954364: inspect.getframeinfo() sometimes produces incorrect traceback line numbers - Patch #909007: Enable a bunch of safe bug workarounds in OpenSSL, for the sake of compatibility with various broken SSL implementations. - Patch #945642: Fix non-blocking SSL sockets, which blocked on reads/writes. - Bug #1083110: ``zlib.decompress.flush()`` would segfault if called immediately after creating the object, without any intervening ``.decompress()`` calls. Library ------- - copy.py fixed to first lookup __copy__ from the instance being copied, rather than only looking at the type - this was broken in 2.3. - Bug #1103844: fix distutils.install.dump_dirs() with negated options. - Bug #1067732: wininst --install-script doesn't leave residual files anymore. - Bug #1045381: strptime() now uses %U and %W for date calculations if the year and day of the week are also specified. - Bug #1039270: Locale data is now escaped for regex metacharacters. - Bug #807871: Fix tkMessageBox.askyesno result. - Patch #1014992: In tarfile.readline, never return more than a line. - Bug #1013882: Flush bz2 data even if nothing had been written so far. - Patch #997284: Allow pydoc to work with XP Themes (.manifest file) - Patch #808719: Ignore locale's encoding in IDLE if it is an empty string. - Patch #946153: Add wait_visibility before grab_set. - Patch #994595: urllib2 now recognizes Basic authentication even if other authentication schemes are offered. - Bug #993394. A KeyError was being raised by Thread.__delete() for dummy_threading when called by atexit if an instance of Thread was created in an interpreter running in -O. The exception was of no importance and thus is now thrown away if raised. - Bug #930024: posixpath.realpath() now detects loops from symlinks and returns the longest path before the loop begins. - Bug #980327/Patch #988607: ntpath now compresses extra slashes between the drive letter and the rest of the path properly. Also removed ambiguity from UNC paths. Thanks Paul Moore. - Bug #679953: zipfile can now handle file sizes over 2 GB. Previously the compressed and uncompressed file sizes were being stored as signed longs instead of unsigned as the ZIP spec specifies. - Bug #981530: Fix UnboundLocalError in shutil.rmtree(). This affects the documented behavior: the function passed to the onerror() handler can now also be os.listdir. - Bug #754449: threading.Thread will no longer mask exceptions raised during interpreter shutdown with another exception caused by attempting to output the initial exception. This fix also includes a backport of rev. 1.41 from HEAD. - Bug #982215: The Back and Next buttons in bdist_wininst installers are now disabled during file copy operations. - Bug #981299: rsync is now a recognized protocol in urlparse that uses a "netloc" portion of a URL. - Patch #975885: Print file name in err msg in quiet mode of compileall.py. - Bug #919012: shutil.move() raises an exception when you try to move a directory into itself. - Bug #934282: make pydoc.stripid() be case-insensitive. - Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)). - The distutils sdist command now ignores all .svn directories, in addition to CVS and RCS directories. .svn directories hold administrative files for the Subversion source control system. - Bug #902501: fix unicode value of CYRILLIC CAPITAL LETTER UKRAINIAN IE in KOI8-U to unicode convertion table. - Bug #1048816: fix bug in Ctrl-K at start of line in curses.textpad.Textbox - Bug #1017553: fix bug in tarfile.filemode() Tools/Demos ----------- - pygettext.py: Generate POT-Creation-Date header in ISO format. Macintosh --------- - Bug #1091468: make frameworkinstall now works with DESTROOT builds - Bug #1076490 (MacOS9 only): fixed a BuildApplication crash when it tried to actually save the application Build ----- - Patch #850977: Detect Tk on FreeBSD and OpenBSD. - Bug #1034496: Use -h instead of -soname for Solaris compatibility. - Patch #973204: Use -rpath instead of -R for runtime_library_dirs on Irix and True64. - Bug #978645: Modules/getpath.c now builds properly under --disable-framework build under OS X. What's New in Python 2.3.4 (final)? =================================== *Release date: 27-May-2004* What's New in Python 2.3.4rc1? ============================== *Release date: 13-May-2004* Core and builtins ----------------- - Bug #858016: isinstance() and issubclass() can have their second argument be a tuple whose nested depth is capped at the interpreter's recursion limit. Raises RuntimeError if the limit reached. - Made omitted callback and None equivalent for weakref.ref() and weakref.proxy(); the None case wasn't handled correctly in all cases. - Fixed problem where PyWeakref_NewRef() and PyWeakref_NewProxy() assumed that initial existing entries in an object's weakref list would not be removed while allocating a new weakref object. Since GC could be invoked at that time, however, that assumption was invalid. In a truly obscure case of GC being triggered during creation for a new weakref object for an referent which already has a weakref without a callback which is only referenced from cyclic trash, a memory error can occur. This consistently created a segfault in a debug build, but provided less predictable behavior in a release build. - Fixed a bug in object.__reduce_ex__ when using protocol 2. Failure to clear the error when attempts to get the __getstate__ attribute fail caused intermittent errors and odd behavior. - fixed: if a file is opened with an explicit buffer size >= 1, repeated close() calls would attempt to free() the buffer already free()ed on the first call. Library ------- - Bug #876278: Unbounded recursion in modulefinder - Brought platform.py in line with the 2.4 version, fixing support for newer Windows versions and a cache issue. - Bug #950057: itertools.chain() and itertools.cycle() now handle exceptions immediately instead of waiting until the input source is updated. - Bug #931848: Fix _sre.CODESIZE on 64-bit machines in UCS-4 mode. - Bug #938076: Consider output encoding in XMLGenerator. - Bug #936637: Properly delegate startElementNS in saxutils.XMLFilterBase. - Bug #944082: Empty passwords in urllib2 are now supported. - Bug #926075: Fixed a bug that returns a wrong pattern object for a string or unicode object in sre.compile() when a different type pattern with the same value exists. - Bug #924361: Properly support normalization of empty unicode strings. - Fixed a caching bug in platform.platform() where the argument of 'terse' was not taken into consideration when caching value. - Bug #920575: A problem that _locale module segfaults on nl_langinfo(ERA) caused by GNU libc's illegal NULL return is fixed. - Bug #883604: Fix Lib/test/test_strftime.py to escape characters from locale time values that might be mistaken as regex syntax. - Bug #700055: .pth files can now have any type of line endings. - Patch 817379: Allow absolute ftp paths in urllib2. - Patch 711838: Support non-anonymous ftp URLs in urllib2. Windows ------- - The Windows installer now includes tix, the Tk Interface eXtension, a powerful set of user interface components that expands the capabilities of your Tcl/Tk and Python applications. Build ----- - Bug #929689: Don't define _XOPEN_SOURCE on UnixWare 7.1.4. What's New in Python 2.3.3 (final)? =================================== *Release date: 19-Dec-2003* Core and builtins ----------------- - Removed PendingDeprecationWarning from apply(). apply() remains deprecated, but the nuisance warning will not be issued. Library ------- - A couple of bugs were squished in trace.py What's New in Python 2.3.3c1? ============================= *Release date: 05-Dec-2003* Core and builtins ----------------- - Critical bugfix, for SF bug 839548: if a weakref with a callback, its callback, and its weakly referenced object, all became part of cyclic garbage during a single run of garbage collection, the order in which they were torn down was unpredictable. It was possible for the callback to see partially-torn-down objects, leading to immediate segfaults, or, if the callback resurrected garbage objects, to resurrect insane objects that caused segfaults (or other surprises) later. In one sense this wasn't surprising, because Python's cyclic gc had no knowledge of Python's weakref objects. It does now. When weakrefs with callbacks become part of cyclic garbage now, those weakrefs are cleared first. The callbacks don't trigger then, preventing the problems. If you need callbacks to trigger, then just as when cyclic gc is not involved, you need to write your code so that weakref objects outlive the objects they weakly reference. - Critical bugfix, for SF bug 840829: if cyclic garbage collection happened to occur during a weakref callback for a new-style class instance, subtle memory corruption could result (in a release build; in a debug build, a segfault occurred reliably very soon after). This has been repaired. - At Python shutdown time (Py_Finalize()), 2.3 called cyclic garbage collection twice, both before and after tearing down modules. The call after tearing down modules has been disabled, because too much of Python has been torn down then for __del__ methods and weakref callbacks to execute sanely. The most common symptom was a sequence of uninformative messages on stderr when Python shut down, produced by threads trying to raise exceptions, but unable to report the nature of their problems because too much of the sys module had already been destroyed. - Patch #820195: object.__contains__() now returns True or False instead of 1 or 0. Extension modules ----------------- - Bug #852314: Fix return type of tkFileDialog.askdirectory on Unix. - Bug #834676: Fix crashes when normalizing Hangul syllables. - Bug #703198: Ignore "b" and "t" in os.popen on Unix. - Patch #803998: Deal with errors in SSL_write correctly. - The xml.parsers.expat module now provides Expat 1.95.7. - Patch #813445: Add missing socket.IPPROTO_IPV6. - Bug #807314: Properly raise an exception if non-existent Tcl variable is accessed. - Bug #811028: ncurses.h breakage on FreeBSD/MacOS X - Bug #814613: INET_ADDRSTRLEN fix needed for all compilers on SGI Library ------- - Bug #849662: UserDict.DictMixin had performance issues when an instance was tested for equality with None. - Bug #848614: distutils' msvccompiler fails to find the MSVC6 compiler because of incomplete registry entries. - Patch #841977: modulefinder didn't find extension modules in packages. - Bug #792101: Add missing file operations for httplib.SSLFile. - Bug #811082: test_tempfile fails if space in install directory. - Bug #780461: platform.mac_ver() raised MacOSError exception under OS X. - Bug #812202: random.randrange() returned only even numbers for range lengths above 2**53. - Bug #823328: urllib2's HTTP Digest Auth support works again. Build ----- - Bug #934635: Fixed a bug where the configure script couldn't detect getaddrinfo() properly if the KAME stack had SCTP support. What's New in Python 2.3.2 (final)? =================================== *Release date: 03-Oct-2003* Core and builtins ----------------- - A workaround for an OpenBSD compiler bug that meant python failed to detect floating point overflow in some cases. Tools/Demos ----------- - Tools/scripts/md5sum.py opens files in binary mode by default. Opening in text mode is almost certainly not what you want. Extension modules ----------------- - The documentation for bsddb now warns strongly about using the legacy API in multi-threaded applications. What's New in Python 2.3.2c1? ============================= *Release date: 30-Sep-2003* Build ----- - A bug in the autoconf machinery meant that os.fsync was never available. - A bug in autoconf meant a bunch of symbols were undefined on HP/UX. Mac --- - The Framework build now identifies itself as 2.3.2. What's New in Python 2.3.1? =========================== *Release date: 23-Sep-2003* Core and builtins ----------------- - Patch #805613: Fix usage of the PTH library. - Fixed a bug in the cache of length-one Unicode strings that could lead to a seg fault. The specific problem occurred when an earlier, non-fatal error left an uninitialized Unicode object in the freelist. - Fixed a leak in class objects defining a comparison but not a hash function. - Bug #789402, fixed memory leak when opening a file object. - Fixed a leak when new code objects are instantiated. - Bug #800796: slice(1).__hash__() now raises a TypeError, unhashable type. - Bug #603724: Pass an explicit buffer to setvbuf in PyFile_SetBufSize(). - Bug #795506: The % formatting operator did not support '%F' as had been documented. - Bug #775985: Only set stdout.encoding if a codec is available. Extension modules ----------------- - The _bsddb module now supports Berkeley DB 4.2. - Bug #698282: Add __file__ to dynamic modules in multiple interpreters. - Patch #798145: Return correct information from nl_langinfo(RADIXCHAR). - Bug #797447: Correct confusing error message for unsupported locales. - Patch #798534: fixed memory leak in os.popen(). - Bug #793826: re-ordered the reference counting code in itertools.izip() to prevent re-entrancy anomalies. Also, if given zero arguments, it now returns an empty iterator rather than raising a type error. - Bug #770485: cStringIO did not support the f.closed attribute. - Patch #781722: Gracefully reject AF_INET6 in socket.inet_pton if IPv6 is disabled. - Bug #783312: Release host name memory in socket calls. Library ------- - Bug #709491: Reset __starttext_tag in sgmllib. - The bsddb module and dbhash module now support the iterator and mapping protocols. - Bug #711632: Reset all state members in HTMLParser.reset. - Bug #792649: logging.ConfigStreamHandler had an uninitialized variable - The csv module's DictReader and DictWriter classes now accept keyword arguments. This was an omission in the initial implementation. - Bug #453515: filecmp.dircmp() can now make case insensitive filename comparisons. - Bug #798254: doctest.py can now handle unbound methods. - Bug #797650: textwrap.py now avoids an infinite loop when one of the indent arguments is set longer than the total width. - Bug #796149: time.strptime() now handles having parentheses in the format string properly. - The email package handles some RFC 2231 parameters with missing CHARSET fields better. It also includes a patch to parameter parsing when semicolons appear inside quotes. - sets.py now runs under Py2.2. In addition, the argument restrictions for most set methods (but not the operators) have been relaxed to allow any iterable. - Bug #801342: random.sample() now accepts a Set as a possible argument. Previously, it insisted that the population argument be indexable. - Bug #778964: random.seed() now uses fractional seconds so that rapid successive, seeding calls will produce different sequences. - Bug #777664: Add Tkconstants.HIDDEN. - Bug #781065: test_normalization is updated to the current URL of the Unicode 3.2 normalization file. - Bug #782369: fix memory leak in array module. - Caching in _strptime.py has been re-introduced. This leads to a large performance boost at the cost of not being thread-safe from locale changes while executing time.strptime() . - Bug #783952: time.strptime() now properly handles issue of time.tzname[0] == time.tzname[1] while time.daylight is set to be true. IDLE ---- - Bug #788378: Handle locale.error. - Bug #774680: IDLE now does not fail to save the file anymore if the Tk buffer is not a Unicode string, yet eol_convention is. - Bug #782510: The idna codec would fail to support names with a trailing full-stop. Tools/Demos ----------- - Patch #713645: Fix typo in checkextensions_win32. - Pynche was fixed to not crash when there is no ~/.pynche file and no -d option was given. - texcheck.py now checks for double word errors and erroneous spacing markup. Build ----- - patch #762934: improve detection of broken implementations of tzset(). - Patch #798202: detect redhat9 Tcl/Tk in configure script. Windows ------- - The _winreg module could segfault when reading very large registry values, due to unchecked alloca() calls (SF bug 851056). The fix is uses either PyMem_Malloc(n) or PyString_FromStringAndSize(NULL, n), as appropriate, followed by a size check. - The _ssl extension module was built using openssl-0.9.7b. - The Windows installer includes documentation in HTMLHelp format instead of single HTML pages. What's New in Python 2.3 final? =============================== *Release date: 29-Jul-2003* IDLE ---- - Bug 778400: IDLE hangs when selecting "Edit with IDLE" from explorer. This was unique to Windows, and was fixed by adding an -n switch to the command the Windows installer creates to execute "Edit with IDLE" context-menu actions. - IDLE displays a new message upon startup: some "personal firewall" kinds of programs (for example, ZoneAlarm) open a dialog of their own when any program opens a socket. IDLE does use sockets, talking on the computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. So, if you get such a dialog when opening IDLE, asking whether to let pythonw.exe talk to address 127.0.0.1, say yes, and rest assured no communication external to your machine is taking place. If you don't allow it, IDLE won't be able to start. What's New in Python 2.3 release candidate 2? ============================================= *Release date: 24-Jul-2003* Core and builtins ----------------- - It is now possible to import from zipfiles containing additional data bytes before the zip compatible archive. Zipfiles containing a comment at the end are still unsupported. Extension modules ----------------- - A longstanding bug in the parser module's initialization could cause fatal internal refcount confusion when the module got initialized more than once. This has been fixed. - Fixed memory leak in pyexpat; using the parser's ParseFile() method with open files that aren't instances of the standard file type caused an instance of the bound .read() method to be leaked on every call. - Fixed some leaks in the locale module. Library ------- - Lib/encodings/rot_13.py when used as a script, now more properly uses the first Python interpreter on your path. - Removed caching of TimeRE (and thus LocaleTime) in _strptime.py to fix a locale related bug in the test suite. Although another patch was needed to actually fix the problem, the cache code was not restored. IDLE ---- - Calltips patches. Build ----- - For MacOSX, added -mno-fused-madd to BASECFLAGS to fix test_coercion on Panther (OSX 10.3). Windows ------- - The tempfile module could do insane imports on Windows if PYTHONCASEOK was set, making temp file creation impossible. Repaired. - Add a patch to workaround pthread_sigmask() bugs in Cygwin. Mac --- - Various fixes to pimp. - Scripts runs with pythonw no longer had full window manager access. - Don't force boot-disk-only install, for reasons unknown it causes more problems than it solves. What's New in Python 2.3 release candidate 1? ============================================= *Release date: 18-Jul-2003* Core and builtins ----------------- - The new function sys.getcheckinterval() returns the last value set by sys.setcheckinterval(). - Several bugs in the symbol table phase of the compiler have been fixed. Errors could be lost and compilation could fail without reporting an error. SF patch 763201. - The interpreter is now more robust about importing the warnings module. In an executable generated by freeze or similar programs, earlier versions of 2.3 would fail if the warnings module could not be found on the file system. Fixes SF bug 771097. - A warning about assignments to module attributes that shadow builtins, present in earlier releases of 2.3, has been removed. - It is not possible to create subclasses of builtin types like str and tuple that define an itemsize. Earlier releases of Python 2.3 allowed this by mistake, leading to crashes and other problems. - The thread_id is now initialized to 0 in a non-thread build. SF bug 770247. - SF bug 762891: "del p[key]" on proxy object no longer raises SystemError. Extension modules ----------------- - weakref.proxy() can now handle "del obj[i]" for proxy objects defining __delitem__. Formerly, it generated a SystemError. - SSL no longer crashes the interpreter when the remote side disconnects. - On Unix the mmap module can again be used to map device files. - time.strptime now exclusively uses the Python implementation contained within the _strptime module. - The print slot of weakref proxy objects was removed, because it was not consistent with the object's repr slot. - The mmap module only checks file size for regular files, not character or block devices. SF patch 708374. - The cPickle Pickler garbage collection support was fixed to traverse the find_class attribute, if present. - There are several fixes for the bsddb3 wrapper module. bsddb3 no longer crashes if an environment is closed before a cursor (SF bug 763298). The DB and DBEnv set_get_returns_none function was extended to take a level instead of a boolean flag. The new level 2 means that in addition, cursor.set()/.get() methods return None instead of raising an exception. A typo was fixed in DBCursor.join_item(), preventing a crash. Library ------- - distutils now supports MSVC 7.1 - doctest now examines all docstrings by default. Previously, it would skip over functions with private names (as indicated by the underscore naming convention). The old default created too much of a risk that user tests were being skipped inadvertently. Note, this change could break code in the unlikely case that someone had intentionally put failing tests in the docstrings of private functions. The breakage is easily fixable by specifying the old behavior when calling testmod() or Tester(). - There were several fixes to the way dumbdbms are closed. It's vital that a dumbdbm database be closed properly, else the on-disk data and directory files can be left in mutually inconsistent states. dumbdbm.py's _Database.__del__() method attempted to close the database properly, but a shutdown race in _Database._commit() could prevent this from working, so that a program trusting __del__() to get the on-disk files in synch could be badly surprised. The race has been repaired. A sync() method was also added so that shelve can guarantee data is written to disk. The close() method can now be called more than once without complaint. - The classes in threading.py are now new-style classes. That they weren't before was an oversight. - The urllib2 digest authentication handlers now define the correct auth_header. The earlier versions would fail at runtime. - SF bug 763023: fix uncaught ZeroDivisionError in difflib ratio methods when there are no lines. - SF bug 763637: fix exception in Tkinter with after_cancel which could occur with Tk 8.4 - SF bug 770601: CGIHTTPServer.py now passes the entire environment to child processes. - SF bug 765238: add filter to fnmatch's __all__. - SF bug 748201: make time.strptime() error messages more helpful. - SF patch 764470: Do not dump the args attribute of a Fault object in xmlrpclib. - SF patch 549151: urllib and urllib2 now redirect POSTs on 301 responses. - SF patch 766650: The whichdb module was fixed to recognize dbm files generated by gdbm on OS/2 EMX. - SF bugs 763047 and 763052: fixes bug of timezone value being left as -1 when ``time.tzname[0] == time.tzname[1] and not time.daylight`` is true when it should only when time.daylight is true. - SF bug 764548: re now allows subclasses of str and unicode to be used as patterns. - SF bug 763637: In Tkinter, change after_cancel() to handle tuples of varying sizes. Tk 8.4 returns a different number of values than Tk 8.3. - SF bug 763023: difflib.ratio() did not catch zero division. - The Queue module now has an __all__ attribute. Tools/Demos ----------- - See Lib/idlelib/NEWS.txt for IDLE news. - SF bug 753592: webchecker/wsgui now handles user supplied directories. - The trace.py script has been removed. It is now in the standard library. Build ----- - Python now compiles with -fno-strict-aliasing if possible (SF bug 766696). - The socket module compiles on IRIX 6.5.10. - An irix64 system is treated the same way as an irix6 system (SF patch 764560). - Several definitions were missing on FreeBSD 5.x unless the __BSD_VISIBLE symbol was defined. configure now defines it as needed. C API ----- - Unicode objects now support mbcs as a built-in encoding, so the C API can use it without deferring to the encodings package. Windows ------- - The Windows implementation of PyThread_start_new_thread() never checked error returns from Windows functions correctly. As a result, it could claim to start a new thread even when the Microsoft _beginthread() function failed (due to "too many threads" -- this is on the order of thousands when it happens). In these cases, the Python exception :: thread.error: can't start new thread is raised now. - SF bug 766669: Prevent a GPF on interpreter exit when sockets are in use. The interpreter now calls WSACleanup() from Py_Finalize() instead of from DLL teardown. Mac --- - Bundlebuilder now inherits default values in the right way. It was previously possible for app bundles to get a type of "BNDL" instead of "APPL." Other improvements include, a --build-id option to specify the CFBundleIdentifier and using the --python option to set the executable in the bundle. - Fixed two bugs in MacOSX framework handling. - pythonw did not allow user interaction in 2.3rc1, this has been fixed. - Python is now compiled with -mno-fused-madd, making all tests pass on Panther. What's New in Python 2.3 beta 2? ================================ *Release date: 29-Jun-2003* Core and builtins ----------------- - A program can now set the environment variable PYTHONINSPECT to some string value in Python, and cause the interpreter to enter the interactive prompt at program exit, as if Python had been invoked with the -i option. - list.index() now accepts optional start and stop arguments. Similar changes were made to UserList.index(). SF feature request 754014. - SF patch 751998 fixes an unwanted side effect of the previous fix for SF bug 742860 (the next item). - SF bug 742860: "WeakKeyDictionary __delitem__ uses iterkeys". This wasn't threadsafe, was very inefficient (expected time O(len(dict)) instead of O(1)), and could raise a spurious RuntimeError if another thread mutated the dict during __delitem__, or if a comparison function mutated it. It also neglected to raise KeyError when the key wasn't present; didn't raise TypeError when the key wasn't of a weakly referencable type; and broke various more-or-less obscure dict invariants by using a sequence of equality comparisons over the whole set of dict keys instead of computing the key's hash code to narrow the search to those keys with the same hash code. All of these are considered to be bugs. A new implementation of __delitem__ repairs all that, but note that fixing these bugs may change visible behavior in code relying (whether intentionally or accidentally) on old behavior. - SF bug 734869: Fixed a compiler bug that caused a fatal error when compiling a list comprehension that contained another list comprehension embedded in a lambda expression. - SF bug 705231: builtin pow() no longer lets the platform C pow() raise -1.0 to integer powers, because (at least) glibc gets it wrong in some cases. The result should be -1.0 if the power is odd and 1.0 if the power is even, and any float with a sufficiently large exponent is (mathematically) an exact even integer. - SF bug 759227: A new-style class that implements __nonzero__() must return a bool or int (but not an int subclass) from that method. This matches the restriction on classic classes. - The encoding attribute has been added for file objects, and set to the terminal encoding on Unix and Windows. - The softspace attribute of file objects became read-only by oversight. It's writable again. - Reverted a 2.3 beta 1 change to iterators for subclasses of list and tuple. By default, the iterators now access data elements directly instead of going through __getitem__. If __getitem__ access is preferred, then __iter__ can be overridden. - SF bug 735247: The staticmethod and super types participate in garbage collection. Before this change, it was possible for leaks to occur in functions with non-global free variables that used these types. Extension modules ----------------- - the socket module has a new exception, socket.timeout, to allow timeouts to be handled separately from other socket errors. - SF bug 751276: cPickle has fixed to propagate exceptions raised in user code. In earlier versions, cPickle caught and ignored any exception when it performed operations that it expected to raise specific exceptions like AttributeError. - cPickle Pickler and Unpickler objects now participate in garbage collection. - mimetools.choose_boundary() could return duplicate strings at times, especially likely on Windows. The strings returned are now guaranteed unique within a single program run. - thread.interrupt_main() raises KeyboardInterrupt in the main thread. dummy_thread has also been modified to try to simulate the behavior. - array.array.insert() now treats negative indices as being relative to the end of the array, just like list.insert() does. (SF bug #739313) - The datetime module classes datetime, time, and timedelta are now properly subclassable. - _tkinter.{get|set}busywaitinterval was added. - itertools.islice() now accepts stop=None as documented. Fixes SF bug #730685. - the bsddb185 module is built in one restricted instance - /usr/include/db.h exists and defines HASHVERSION to be 2. This is true for many BSD-derived systems. Library ------- - Some happy doctest extensions from Jim Fulton have been added to doctest.py. These are already being used in Zope3. The two primary ones: doctest.debug(module, name) extracts the doctests from the named object in the given module, puts them in a temp file, and starts pdb running on that file. This is great when a doctest fails. doctest.DocTestSuite(module=None) returns a synthesized unittest TestSuite instance, to be run by the unittest framework, which runs all the doctests in the module. This allows writing tests in doctest style (which can be clearer and shorter than writing tests in unittest style), without losing unittest's powerful testing framework features (which doctest lacks). - For compatibility with doctests created before 2.3, if an expected output block consists solely of "1" and the actual output block consists solely of "True", it's accepted as a match; similarly for "0" and "False". This is quite un-doctest-like, but is practical. The behavior can be disabled by passing the new doctest module constant DONT_ACCEPT_TRUE_FOR_1 to the new optionflags optional argument. - ZipFile.testzip() now only traps BadZipfile exceptions. Previously, a bare except caught to much and reported all errors as a problem in the archive. - The logging module now has a new function, makeLogRecord() making LogHandler easier to interact with DatagramHandler and SocketHandler. - The cgitb module has been extended to support plain text display (SF patch 569574). - A brand new version of IDLE (from the IDLEfork project at SourceForge) is now included as Lib/idlelib. The old Tools/idle is no more. - Added a new module: trace (documentation missing). This module used to be distributed in Tools/scripts. It uses sys.settrace() to trace code execution -- either function calls or individual lines. It can generate tracing output during execution or a post-mortem report of code coverage. - The threading module has new functions settrace() and setprofile() that cooperate with the functions of the same name in the sys module. A function registered with the threading module will be used for all threads it creates. The new trace module uses this to provide tracing for code running in threads. - copy.py: applied SF patch 707900, fixing bug 702858, by Steven Taschuk. Copying a new-style class that had a reference to itself didn't work. (The same thing worked fine for old-style classes.) Builtin functions are now treated as atomic, fixing bug #746304. - difflib.py has two new functions: context_diff() and unified_diff(). - More fixes to urllib (SF 549151): (a) When redirecting, always use GET. This is common practice and more-or-less sanctioned by the HTTP standard. (b) Add a handler for 307 redirection, which becomes an error for POST, but a regular redirect for GET and HEAD - Added optional 'onerror' argument to os.walk(), to control error handling. - inspect.is{method|data}descriptor was added, to allow pydoc display __doc__ of data descriptors. - Fixed socket speed loss caused by use of the _socketobject wrapper class in socket.py. - timeit.py now checks the current directory for imports. - urllib2.py now knows how to order proxy classes, so the user doesn't have to insert it in front of other classes, nor do dirty tricks like inserting a "dummy" HTTPHandler after a ProxyHandler when building an opener with proxy support. - Iterators have been added for dbm keys. - random.Random objects can now be pickled. Tools/Demos ----------- - pydoc now offers help on keywords and topics. - Tools/idle is gone; long live Lib/idlelib. - diff.py prints file diffs in context, unified, or ndiff formats, providing a command line interface to difflib.py. - texcheck.py is a new script for making a rough validation of Python LaTeX files. Build ----- - Setting DESTDIR during 'make install' now allows specifying a different root directory. C API ----- - PyType_Ready(): If a type declares that it participates in gc (Py_TPFLAGS_HAVE_GC), and its base class does not, and its base class's tp_free slot is the default _PyObject_Del, and type does not define a tp_free slot itself, _PyObject_GC_Del is assigned to type->tp_free. Previously _PyObject_Del was inherited, which could at best lead to a segfault. In addition, if even after this magic the type's tp_free slot is _PyObject_Del or NULL, and the type is a base type (Py_TPFLAGS_BASETYPE), TypeError is raised: since the type is a base type, its dealloc function must call type->tp_free, and since the type is gc'able, tp_free must not be NULL or _PyObject_Del. - PyThreadState_SetAsyncExc(): A new API (deliberately accessible only from C) to interrupt a thread by sending it an exception. It is intentional that you have to write your own C extension to call it from Python. New platforms ------------- None this time. Tests ----- - test_imp rewritten so that it doesn't raise RuntimeError if run as a side effect of being imported ("import test.autotest"). Windows ------- - The Windows installer ships with Tcl/Tk 8.4.3 (upgraded from 8.4.1). - The installer always suggested that Python be installed on the C: drive, due to a hardcoded "C:" generated by the Wise installation wizard. People with machines where C: is not the system drive usually want Python installed on whichever drive is their system drive instead. We removed the hardcoded "C:", and two testers on machines where C: is not the system drive report that the installer now suggests their system drive. Note that you can always select the directory you want in the "Select Destination Directory" dialog -- that's what it's for. Mac --- - There's a new module called "autoGIL", which offers a mechanism to automatically release the Global Interpreter Lock when an event loop goes to sleep, allowing other threads to run. It's currently only supported on OSX, in the Mach-O version. - The OSA modules now allow direct access to properties of the toplevel application class (in AppleScript terminology). - The Package Manager can now update itself. SourceForge Bugs and Patches Applied ------------------------------------ 430160, 471893, 501716, 542562, 549151, 569574, 595837, 596434, 598163, 604210, 604716, 610332, 612627, 614770, 620190, 621891, 622042, 639139, 640236, 644345, 649742, 649742, 658233, 660022, 661318, 661676, 662807, 662923, 666219, 672855, 678325, 682347, 683486, 684981, 685773, 686254, 692776, 692959, 693094, 696777, 697989, 700827, 703666, 708495, 708604, 708901, 710733, 711902, 713722, 715782, 718286, 719359, 719367, 723136, 723831, 723962, 724588, 724767, 724767, 725942, 726150, 726446, 726869, 727051, 727719, 727719, 727805, 728277, 728563, 728656, 729096, 729103, 729293, 729297, 729300, 729317, 729395, 729622, 729817, 730170, 730296, 730594, 730685, 730826, 730963, 731209, 731403, 731504, 731514, 731626, 731635, 731643, 731644, 731644, 731689, 732124, 732143, 732234, 732284, 732284, 732479, 732761, 732783, 732951, 733667, 733781, 734118, 734231, 734869, 735051, 735293, 735527, 735613, 735694, 736962, 736962, 737970, 738066, 739313, 740055, 740234, 740301, 741806, 742126, 742741, 742860, 742860, 742911, 744041, 744104, 744238, 744687, 744877, 745055, 745478, 745525, 745620, 746012, 746304, 746366, 746801, 746953, 747348, 747667, 747954, 748846, 748849, 748973, 748975, 749191, 749210, 749759, 749831, 749911, 750008, 750092, 750542, 750595, 751038, 751107, 751276, 751451, 751916, 751941, 751956, 751998, 752671, 753451, 753602, 753617, 753845, 753925, 754014, 754340, 754447, 755031, 755087, 755147, 755245, 755683, 755987, 756032, 756996, 757058, 757229, 757818, 757821, 757822, 758112, 758910, 759227, 759889, 760257, 760703, 760792, 761104, 761337, 761519, 761830, 762455 What's New in Python 2.3 beta 1? ================================ *Release date: 25-Apr-2003* Core and builtins ----------------- - New format codes B, H, I, k and K have been implemented for PyArg_ParseTuple and PyBuild_Value. - New builtin function sum(seq, start=0) returns the sum of all the items in iterable object seq, plus start (items are normally numbers, and cannot be strings). - bool() called without arguments now returns False rather than raising an exception. This is consistent with calling the constructors for the other builtin types -- called without argument they all return the false value of that type. (SF patch #724135) - In support of PEP 269 (making the pgen parser generator accessible from Python), some changes to the pgen code structure were made; a few files that used to be linked only with pgen are now linked with Python itself. - The repr() of a weakref object now shows the __name__ attribute of the referenced object, if it has one. - super() no longer ignores data descriptors, except __class__. See the thread started at http://mail.python.org/pipermail/python-dev/2003-April/034338.html - list.insert(i, x) now interprets negative i as it would be interpreted by slicing, so negative values count from the end of the list. This was the only place where such an interpretation was not placed on a list index. - range() now works even if the arguments are longs with magnitude larger than sys.maxint, as long as the total length of the sequence fits. E.g., range(2**100, 2**101, 2**100) is the following list: [1267650600228229401496703205376L]. (SF patch #707427.) - Some horridly obscure problems were fixed involving interaction between garbage collection and old-style classes with "ambitious" getattr hooks. If an old-style instance didn't have a __del__ method, but did have a __getattr__ hook, and the instance became reachable only from an unreachable cycle, and the hook resurrected or deleted unreachable objects when asked to resolve "__del__", anything up to a segfault could happen. That's been repaired. - dict.pop now takes an optional argument specifying a default value to return if the key is not in the dict. If a default is not given and the key is not found, a KeyError will still be raised. Parallel changes were made to UserDict.UserDict and UserDict.DictMixin. [SF patch #693753] (contributed by Michael Stone.) - sys.getfilesystemencoding() was added to expose Py_FileSystemDefaultEncoding. - New function sys.exc_clear() clears the current exception. This is rarely needed, but can sometimes be useful to release objects referenced by the traceback held in sys.exc_info()[2]. (SF patch #693195.) - On 64-bit systems, a dictionary could contain duplicate long/int keys if the key value was larger than 2**32. See SF bug #689659. - Fixed SF bug #663074. The codec system was using global static variables to store internal data. As a result, any attempts to use the unicode system with multiple active interpreters, or successive interpreter executions, would fail. - "%c" % u"a" now returns a unicode string instead of raising a TypeError. u"%c" % 0xffffffff now raises a OverflowError instead of a ValueError to be consistent with "%c" % 256. See SF patch #710127. Extension modules ----------------- - The socket module now provides the functions inet_pton and inet_ntop for converting between string and packed representation of IP addresses. There is also a new module variable, has_ipv6, which is True iff the current Python has IPv6 support. See SF patch #658327. - Tkinter wrappers around Tcl variables now pass objects directly to Tcl, instead of first converting them to strings. - The .*? pattern in the re module is now special-cased to avoid the recursion limit. (SF patch #720991 -- many thanks to Gary Herron and Greg Chapman.) - New function sys.call_tracing() allows pdb to debug code recursively. - New function gc.get_referents(obj) returns a list of objects directly referenced by obj. In effect, it exposes what the object's tp_traverse slot does, and can be helpful when debugging memory leaks. - The iconv module has been removed from this release. - The platform-independent routines for packing floats in IEEE formats (struct.pack's f, d codes; pickle and cPickle's protocol 1 pickling of floats) ignored that rounding can cause a carry to propagate. The worst consequence was that, in rare cases, f could produce strings that, when unpacked again, were a factor of 2 away from the original float. This has been fixed. See SF bug #705836. - New function time.tzset() provides access to the C library tzset() function, if supported. (SF patch #675422.) - Using createfilehandler, deletefilehandler, createtimerhandler functions on Tkinter.tkinter (_tkinter module) no longer crashes the interpreter. See SF bug #692416. - Modified the fcntl.ioctl() function to allow modification of a passed mutable buffer (for details see the reference documentation). - Made user requested changes to the itertools module. Subsumed the times() function into repeat(). Added chain() and cycle(). - The rotor module is now deprecated; the encryption algorithm it uses is not believed to be secure, and including crypto code with Python has implications for exporting and importing it in various countries. - The socket module now always uses the _socketobject wrapper class, even on platforms which have dup(2). The makefile() method is built directly on top of the socket without duplicating the file descriptor, allowing timeouts to work properly. Library ------- - New generator function os.walk() is an easy-to-use alternative to os.path.walk(). See os module docs for details. os.path.walk() isn't deprecated at this time, but may become deprecated in a future release. - Added new module "platform" which provides a wide range of tools for querying platform dependent features. - netrc now allows ASCII punctuation characters in passwords. - shelve now supports the optional writeback argument, and exposes pickle protocol versions. - Several methods of nntplib.NNTP have grown an optional file argument which specifies a file where to divert the command's output (already supported by the body() method). (SF patch #720468) - The self-documenting XML server library DocXMLRPCServer was added. - Support for internationalized domain names has been added through the 'idna' and 'punycode' encodings, the 'stringprep' module, the 'mkstringprep' tool, and enhancements to the socket and httplib modules. - htmlentitydefs has two new dictionaries: name2codepoint maps HTML entity names to Unicode codepoints (as integers). codepoint2name is the reverse mapping. See SF patch #722017. - pdb has a new command, "debug", which lets you step through arbitrary code from the debugger's (pdb) prompt. - unittest.failUnlessEqual and its equivalent unittest.assertEqual now return 'not a == b' rather than 'a != b'. This gives the desired result for classes that define __eq__ without defining __ne__. - sgmllib now supports SGML marked sections, in particular the MS Office extensions. - The urllib module now offers support for the iterator protocol. SF patch 698520 contributed by Brett Cannon. - New module timeit provides a simple framework for timing the execution speed of expressions and statements. - sets.Set objects now support mixed-type __eq__ and __ne__, instead of raising TypeError. If x is a Set object and y is a non-Set object, x == y is False, and x != y is True. This is akin to the change made for mixed-type comparisons of datetime objects in 2.3a2; more info about the rationale is in the NEWS entry for that. See also SF bug report . - On Unix platforms, if os.listdir() is called with a Unicode argument, it now returns Unicode strings. (This behavior was added earlier to the Windows NT/2k/XP version of os.listdir().) - Distutils: both 'py_modules' and 'packages' keywords can now be specified in core.setup(). Previously you could supply one or the other, but not both of them. (SF patch #695090 from Bernhard Herzog) - New csv package makes it easy to read/write CSV files. - Module shlex has been extended to allow posix-like shell parsings, including a split() function for easy spliting of quoted strings and commands. An iterator interface was also implemented. Tools/Demos ----------- - New script combinerefs.py helps analyze new PYTHONDUMPREFS output. See the module docstring for details. Build ----- - Fix problem building on OSF1 because the compiler only accepted preprocessor directives that start in column 1. (SF bug #691793.) C API ----- - Added PyGC_Collect(), equivalent to calling gc.collect(). - PyThreadState_GetDict() was changed not to raise an exception or issue a fatal error when no current thread state is available. This makes it possible to print dictionaries when no thread is active. - LONG_LONG was renamed to PY_LONG_LONG. Extensions that use this and need compatibility with previous versions can use this: #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif - Added PyObject_SelfIter() to fill the tp_iter slot for the typical case where the method returns its self argument. - The extended type structure used for heap types (new-style classes defined by Python code using a class statement) is now exported from object.h as PyHeapTypeObject. (SF patch #696193.) New platforms ------------- None this time. Tests ----- - test_timeout now requires -u network to be passed to regrtest to run. See SF bug #692988. Windows ------- - os.fsync() now exists on Windows, and calls the Microsoft _commit() function. - New function winsound.MessageBeep() wraps the Win32 API MessageBeep(). Mac --- - os.listdir() now returns Unicode strings on MacOS X when called with a Unicode argument. See the general news item under "Library". - A new method MacOS.WMAvailable() returns true if it is safe to access the window manager, false otherwise. - EasyDialogs dialogs are now movable-modal, and if the application is currently in the background they will ask to be moved to the foreground before displaying. - OSA Scripting support has improved a lot, and gensuitemodule.py can now be used by mere mortals. The documentation is now also more or less complete. - The IDE (in a framework build) now includes introductory documentation in Apple Help Viewer format. What's New in Python 2.3 alpha 2? ================================= *Release date: 19-Feb-2003* Core and builtins ----------------- - Negative positions returned from PEP 293 error callbacks are now treated as being relative to the end of the input string. Positions that are out of bounds raise an IndexError. - sys.path[0] (the directory from which the script is loaded) is now turned into an absolute pathname, unless it is the empty string. (SF patch #664376.) - Finally fixed the bug in compile() and exec where a string ending with an indented code block but no newline would raise SyntaxError. This would have been a four-line change in parsetok.c... Except codeop.py depends on this behavior, so a compilation flag had to be invented that causes the tokenizer to revert to the old behavior; this required extra changes to 2 .h files, 2 .c files, and 2 .py files. (Fixes SF bug #501622.) - If a new-style class defines neither __new__ nor __init__, its constructor would ignore all arguments. This is changed now: the constructor refuses arguments in this case. This might break code that worked under Python 2.2. The simplest fix is to add a no-op __init__: ``def __init__(self, *args, **kw): pass``. - Through a bytecode optimizer bug (and I bet you didn't even know Python *had* a bytecode optimizer :-), "unsigned" hex/oct constants with a leading minus sign would come out with the wrong sign. ("Unsigned" hex/oct constants are those with a face value in the range sys.maxint+1 through sys.maxint*2+1, inclusive; these have always been interpreted as negative numbers through sign folding.) E.g. 0xffffffff is -1, and -(0xffffffff) is 1, but -0xffffffff would come out as -4294967295. This was the case in Python 2.2 through 2.2.2 and 2.3a1, and in Python 2.4 it will once again have that value, but according to PEP 237 it really needs to be 1 now. This will be backported to Python 2.2.3 a well. (SF #660455) - int(s, base) sometimes sign-folds hex and oct constants; it only does this when base is 0 and s.strip() starts with a '0'. When the sign is actually folded, as in int("0xffffffff", 0) on a 32-bit machine, which returns -1, a FutureWarning is now issued; in Python 2.4, this will return 4294967295L, as do int("+0xffffffff", 0) and int("0xffffffff", 16) right now. (PEP 347) - super(X, x): x may now be a proxy for an X instance, i.e. issubclass(x.__class__, X) but not issubclass(type(x), X). - isinstance(x, X): if X is a new-style class, this is now equivalent to issubclass(type(x), X) or issubclass(x.__class__, X). Previously only type(x) was tested. (For classic classes this was already the case.) - compile(), eval() and the exec statement now fully support source code passed as unicode strings. - int subclasses can be initialized with longs if the value fits in an int. See SF bug #683467. - long(string, base) takes time linear in len(string) when base is a power of 2 now. It used to take time quadratic in len(string). - filter returns now Unicode results for Unicode arguments. - raw_input can now return Unicode objects. - List objects' sort() method now accepts None as the comparison function. Passing None is semantically identical to calling sort() with no arguments. - Fixed crash when printing a subclass of str and __str__ returned self. See SF bug #667147. - Fixed an invalid RuntimeWarning and an undetected error when trying to convert a long integer into a float which couldn't fit. See SF bug #676155. - Function objects now have a __module__ attribute that is bound to the name of the module in which the function was defined. This applies for C functions and methods as well as functions and methods defined in Python. This attribute is used by pickle.whichmodule(), which changes the behavior of whichmodule slightly. In Python 2.2 whichmodule() returns "__main__" for functions that are not defined at the top-level of a module (examples: methods, nested functions). Now whichmodule() will return the proper module name. Extension modules ----------------- - operator.isNumberType() now checks that the object has a nb_int or nb_float slot, rather than simply checking whether it has a non-NULL tp_as_number pointer. - The imp module now has ways to acquire and release the "import lock": imp.acquire_lock() and imp.release_lock(). Note: this is a reentrant lock, so releasing the lock only truly releases it when this is the last release_lock() call. You can check with imp.lock_held(). (SF bug #580952 and patch #683257.) - Change to cPickle to match pickle.py (see below and PEP 307). - Fix some bugs in the parser module. SF bug #678518. - Thanks to Scott David Daniels, a subtle bug in how the zlib extension implemented flush() was fixed. Scott also rewrote the zlib test suite using the unittest module. (SF bug #640230 and patch #678531.) - Added an itertools module containing high speed, memory efficient looping constructs inspired by tools from Haskell and SML. - The SSL module now handles sockets with a timeout set correctly (SF patch #675750, fixing SF bug #675552). - os/posixmodule has grown the sysexits.h constants (EX_OK and friends). - Fixed broken threadstate swap in readline that could cause fatal errors when a readline hook was being invoked while a background thread was active. (SF bugs #660476 and #513033.) - fcntl now exposes the strops.h I_* constants. - Fix a crash on Solaris that occurred when calling close() on an mmap'ed file which was already closed. (SF patch #665913) - Fixed several serious bugs in the zipimport implementation. - datetime changes: The date class is now properly subclassable. (SF bug #720908) The datetime and datetimetz classes have been collapsed into a single datetime class, and likewise the time and timetz classes into a single time class. Previously, a datetimetz object with tzinfo=None acted exactly like a datetime object, and similarly for timetz. This wasn't enough of a difference to justify distinct classes, and life is simpler now. today() and now() now round system timestamps to the closest microsecond . This repairs an irritation most likely seen on Windows systems. In dt.astimezone(tz), if tz.utcoffset(dt) returns a duration, ValueError is raised if tz.dst(dt) returns None (2.3a1 treated it as 0 instead, but a tzinfo subclass wishing to participate in time zone conversion has to take a stand on whether it supports DST; if you don't care about DST, then code dst() to return 0 minutes, meaning that DST is never in effect). The tzinfo methods utcoffset() and dst() must return a timedelta object (or None) now. In 2.3a1 they could also return an int or long, but that was an unhelpfully redundant leftover from an earlier version wherein they couldn't return a timedelta. TOOWTDI. The example tzinfo class for local time had a bug. It was replaced by a later example coded by Guido. datetime.astimezone(tz) no longer raises an exception when the input datetime has no UTC equivalent in tz. For typical "hybrid" time zones (a single tzinfo subclass modeling both standard and daylight time), this case can arise one hour per year, at the hour daylight time ends. See new docs for details. In short, the new behavior mimics the local wall clock's behavior of repeating an hour in local time. dt.astimezone() can no longer be used to convert between naive and aware datetime objects. If you merely want to attach, or remove, a tzinfo object, without any conversion of date and time members, use dt.replace(tzinfo=whatever) instead, where "whatever" is None or a tzinfo subclass instance. A new method tzinfo.fromutc(dt) can be overridden in tzinfo subclasses to give complete control over how a UTC time is to be converted to a local time. The default astimezone() implementation calls fromutc() as its last step, so a tzinfo subclass can affect that too by overriding fromutc(). It's expected that the default fromutc() implementation will be suitable as-is for "almost all" time zone subclasses, but the creativity of political time zone fiddling appears unbounded -- fromutc() allows the highly motivated to emulate any scheme expressible in Python. datetime.now(): The optional tzinfo argument was undocumented (that's repaired), and its name was changed to tz ("tzinfo" is overloaded enough already). With a tz argument, now(tz) used to return the local date and time, and attach tz to it, without any conversion of date and time members. This was less than useful. Now now(tz) returns the current date and time as local time in tz's time zone, akin to :: tz.fromutc(datetime.utcnow().replace(tzinfo=utc)) where "utc" is an instance of a tzinfo subclass modeling UTC. Without a tz argument, now() continues to return the current local date and time, as a naive datetime object. datetime.fromtimestamp(): Like datetime.now() above, this had less than useful behavior when the optional tinzo argument was specified. See also SF bug report . date and datetime comparison: In order to prevent comparison from falling back to the default compare-object-addresses strategy, these raised TypeError whenever they didn't understand the other object type. They still do, except when the other object has a "timetuple" attribute, in which case they return NotImplemented now. This gives other datetime objects (e.g., mxDateTime) a chance to intercept the comparison. date, time, datetime and timedelta comparison: When the exception for mixed-type comparisons in the last paragraph doesn't apply, if the comparison is == then False is returned, and if the comparison is != then True is returned. Because dict lookup and the "in" operator only invoke __eq__, this allows, for example, :: if some_datetime in some_sequence: and :: some_dict[some_timedelta] = whatever to work as expected, without raising TypeError just because the sequence is heterogeneous, or the dict has mixed-type keys. [This seems like a good idea to implement for all mixed-type comparisons that don't want to allow falling back to address comparison.] The constructors building a datetime from a timestamp could raise ValueError if the platform C localtime()/gmtime() inserted "leap seconds". Leap seconds are ignored now. On such platforms, it's possible to have timestamps that differ by a second, yet where datetimes constructed from them are equal. The pickle format of date, time and datetime objects has changed completely. The undocumented pickler and unpickler functions no longer exist. The undocumented __setstate__() and __getstate__() methods no longer exist either. Library ------- - The logging module was updated slightly; the WARN level was renamed to WARNING, and the matching function/method warn() to warning(). - The pickle and cPickle modules were updated with a new pickling protocol (documented by pickletools.py, see below) and several extensions to the pickle customization API (__reduce__, __setstate__ etc.). The copy module now uses more of the pickle customization API to copy objects that don't implement __copy__ or __deepcopy__. See PEP 307 for details. - The distutils "register" command now uses http://www.python.org/pypi as the default repository. (See PEP 301.) - the platform dependent path related variables sep, altsep, extsep, pathsep, curdir, pardir and defpath are now defined in the platform dependent path modules (e.g. ntpath.py) rather than os.py, so these variables are now available via os.path. They continue to be available from the os module. (see ). - array.array was added to the types repr.py knows about (see ). - The new pickletools.py contains lots of documentation about pickle internals, and supplies some helpers for working with pickles, such as a symbolic pickle disassembler. - Xmlrpclib.py now supports the builtin boolean type. - py_compile has a new 'doraise' flag and a new PyCompileError exception. - SimpleXMLRPCServer now supports CGI through the CGIXMLRPCRequestHandler class. - The sets module now raises TypeError in __cmp__, to clarify that sets are not intended to be three-way-compared; the comparison operators are overloaded as subset/superset tests. - Bastion.py and rexec.py are disabled. These modules are not safe in Python 2.2. or 2.3. - realpath is now exported when doing ``from poxixpath import *``. It is also exported for ntpath, macpath, and os2emxpath. See SF bug #659228. - New module tarfile from Lars Gustäbel provides a comprehensive interface to tar archive files with transparent gzip and bzip2 compression. See SF patch #651082. - urlparse can now parse imap:// URLs. See SF feature request #618024. - Tkinter.Canvas.scan_dragto() provides an optional parameter to support the gain value which is passed to Tk. SF bug# 602259. - Fix logging.handlers.SysLogHandler protocol when using UNIX domain sockets. See SF patch #642974. - The dospath module was deleted. Use the ntpath module when manipulating DOS paths from other platforms. Tools/Demos ----------- - Two new scripts (db2pickle.py and pickle2db.py) were added to the Tools/scripts directory to facilitate conversion from the old bsddb module to the new one. While the user-visible API of the new module is compatible with the old one, it's likely that the version of the underlying database library has changed. To convert from the old library, run the db2pickle.py script using the old version of Python to convert it to a pickle file. After upgrading Python, run the pickle2db.py script using the new version of Python to reconstitute your database. For example: % python2.2 db2pickle.py -h some.db > some.pickle % python2.3 pickle2db.py -h some.db.new < some.pickle Run the scripts without any args to get a usage message. Build ----- - The audio driver tests (test_ossaudiodev.py and test_linuxaudiodev.py) are no longer run by default. This is because they don't always work, depending on your hardware and software. To run these tests, you must use an invocation like :: ./python Lib/test/regrtest.py -u audio test_ossaudiodev - On systems which build using the configure script, compiler flags which used to be lumped together using the OPT flag have been split into two groups, OPT and BASECFLAGS. OPT is meant to carry just optimization- and debug-related flags like "-g" and "-O3". BASECFLAGS is meant to carry compiler flags that are required to get a clean compile. On some platforms (many Linux flavors in particular) BASECFLAGS will be empty by default. On others, such as Mac OS X and SCO, it will contain required flags. This change allows people building Python to override OPT without fear of clobbering compiler flags which are required to get a clean build. - On Darwin/Mac OS X platforms, /sw/lib and /sw/include are added to the relevant search lists in setup.py. This allows users building Python to take advantage of the many packages available from the fink project . - A new Makefile target, scriptsinstall, installs a number of useful scripts from the Tools/scripts directory. C API ----- - PyEval_GetFrame() is now declared to return a ``PyFrameObject *`` instead of a plain ``PyObject *``. (SF patch #686601.) - PyNumber_Check() now checks that the object has a nb_int or nb_float slot, rather than simply checking whether it has a non-NULL tp_as_number pointer. - A C type that inherits from a base type that defines tp_as_buffer will now inherit the tp_as_buffer pointer if it doesn't define one. (SF #681367) - The PyArg_Parse functions now issue a DeprecationWarning if a float argument is provided when an integer is specified (this affects the 'b', 'B', 'h', 'H', 'i', and 'l' codes). Future versions of Python will raise a TypeError. Tests ----- - Several tests weren't being run from regrtest.py (test_timeout.py, test_tarfile.py, test_netrc.py, test_multifile.py, test_importhooks.py and test_imp.py). Now they are. (Note to developers: please read Lib/test/README when creating a new test, to make sure to do it right! All tests need to use either unittest or pydoc.) - Added test_posix.py, a test suite for the posix module. - Added test_hexoct.py, a test suite for hex/oct constant folding. Windows ------- - The timeout code for socket connect() didn't work right; this has now been fixed. test_timeout.py should pass (at least most of the time). - distutils' msvccompiler class now passes the preprocessor options to the resource compiler. See SF patch #669198. - The bsddb module now ships with Sleepycat's 4.1.25.NC, the latest release without strong cryptography. - sys.path[0], if it contains a directory name, is now always an absolute pathname. (SF patch #664376.) - The new logging package is now installed by the Windows installer. It wasn't in 2.3a1 due to oversight. Mac --- - There are new dialogs EasyDialogs.AskFileForOpen, AskFileForSave and AskFolder. The old macfs.StandardGetFile and friends are deprecated. - Most of the standard library now uses pathnames or FSRefs in preference of FSSpecs, and use the underlying Carbon.File and Carbon.Folder modules in stead of macfs. macfs will probably be deprecated in the future. - Type Carbon.File.FSCatalogInfo and supporting methods have been implemented. This also makes macfs.FSSpec.SetDates() work again. - There is a new module pimp, the package install manager for Python, and accompanying applet PackageManager. These allow you to easily download and install pretested extension packages either in source or binary form. Only in MacPython-OSX. - Applets are now built with bundlebuilder in MacPython-OSX, which should make them more robust and also provides a path towards BuildApplication. The downside of this change is that applets can no longer be run from the Terminal window, this will hopefully be fixed in the 2.3b1. What's New in Python 2.3 alpha 1? ================================= *Release date: 31-Dec-2002* Type/class unification and new-style classes -------------------------------------------- - One can now assign to __bases__ and __name__ of new-style classes. - dict() now accepts keyword arguments so that dict(one=1, two=2) is the equivalent of {"one": 1, "two": 2}. Accordingly, the existing (but undocumented) 'items' keyword argument has been eliminated. This means that dict(items=someMapping) now has a different meaning than before. - int() now returns a long object if the argument is outside the integer range, so int("4" * 1000), int(1e200) and int(1L<<1000) will all return long objects instead of raising an OverflowError. - Assignment to __class__ is disallowed if either the old or the new class is a statically allocated type object (such as defined by an extension module). This prevents anomalies like 2.__class__ = bool. - New-style object creation and deallocation have been sped up significantly; they are now faster than classic instance creation and deallocation. - The __slots__ variable can now mention "private" names, and the right thing will happen (e.g. __slots__ = ["__foo"]). - The built-ins slice() and buffer() are now callable types. The types classobj (formerly class), code, function, instance, and instancemethod (formerly instance-method), which have no built-in names but are accessible through the types module, are now also callable. The type dict-proxy is renamed to dictproxy. - Cycles going through the __class__ link of a new-style instance are now detected by the garbage collector. - Classes using __slots__ are now properly garbage collected. [SF bug 519621] - Tightened the __slots__ rules: a slot name must be a valid Python identifier. - The constructor for the module type now requires a name argument and takes an optional docstring argument. Previously, this constructor ignored its arguments. As a consequence, deriving a class from a module (not from the module type) is now illegal; previously this created an unnamed module, just like invoking the module type did. [SF bug 563060] - A new type object, 'basestring', is added. This is a common base type for 'str' and 'unicode', and can be used instead of types.StringTypes, e.g. to test whether something is "a string": isinstance(x, basestring) is True for Unicode and 8-bit strings. This is an abstract base class and cannot be instantiated directly. - Changed new-style class instantiation so that when C's __new__ method returns something that's not a C instance, its __init__ is not called. [SF bug #537450] - Fixed super() to work correctly with class methods. [SF bug #535444] - If you try to pickle an instance of a class that has __slots__ but doesn't define or override __getstate__, a TypeError is now raised. This is done by adding a bozo __getstate__ to the class that always raises TypeError. (Before, this would appear to be pickled, but the state of the slots would be lost.) Core and builtins ----------------- - Import from zipfiles is now supported. The name of a zipfile placed on sys.path causes the import statement to look for importable Python modules (with .py, pyc and .pyo extensions) and packages inside the zipfile. The zipfile import follows the specification (though not the sample implementation) of PEP 273. The semantics of __path__ are compatible with those that have been implemented in Jython since Jython 2.1. - PEP 302 has been accepted. Although it was initially developed to support zipimport, it offers a new, general import hook mechanism. Several new variables have been added to the sys module: sys.meta_path, sys.path_hooks, and sys.path_importer_cache; these make extending the import statement much more convenient than overriding the __import__ built-in function. For a description of these, see PEP 302. - A frame object's f_lineno attribute can now be written to from a trace function to change which line will execute next. A command to exploit this from pdb has been added. [SF patch #643835] - The _codecs support module for codecs.py was turned into a builtin module to assure that at least the builtin codecs are available to the Python parser for source code decoding according to PEP 263. - issubclass now supports a tuple as the second argument, just like isinstance does. ``issubclass(X, (A, B))`` is equivalent to ``issubclass(X, A) or issubclass(X, B)``. - Thanks to Armin Rigo, the last known way to provoke a system crash by cleverly arranging for a comparison function to mutate a list during a list.sort() operation has been fixed. The effect of attempting to mutate a list, or even to inspect its contents or length, while a sort is in progress, is not defined by the language. The C implementation of Python 2.3 attempts to detect mutations, and raise ValueError if one occurs, but there's no guarantee that all mutations will be caught, or that any will be caught across releases or implementations. - Unicode file name processing for Windows (PEP 277) is implemented. All platforms now have an os.path.supports_unicode_filenames attribute, which is set to True on Windows NT/2000/XP, and False elsewhere. - Codec error handling callbacks (PEP 293) are implemented. Error handling in unicode.encode or str.decode can now be customized. - A subtle change to the semantics of the built-in function intern(): interned strings are no longer immortal. You must keep a reference to the return value intern() around to get the benefit. - Use of 'None' as a variable, argument or attribute name now issues a SyntaxWarning. In the future, None may become a keyword. - SET_LINENO is gone. co_lnotab is now consulted to determine when to call the trace function. C code that accessed f_lineno should call PyCode_Addr2Line instead (f_lineno is still there, but only kept up to date when there is a trace function set). - There's a new warning category, FutureWarning. This is used to warn about a number of situations where the value or sign of an integer result will change in Python 2.4 as a result of PEP 237 (integer unification). The warnings implement stage B0 mentioned in that PEP. The warnings are about the following situations: - Octal and hex literals without 'L' prefix in the inclusive range [0x80000000..0xffffffff]; these are currently negative ints, but in Python 2.4 they will be positive longs with the same bit pattern. - Left shifts on integer values that cause the outcome to lose bits or have a different sign than the left operand. To be precise: x< -*-" in the first or second line of a Python source file indicates the encoding. - list.sort() has a new implementation. While cross-platform results may vary, and in data-dependent ways, this is much faster on many kinds of partially ordered lists than the previous implementation, and reported to be just as fast on randomly ordered lists on several major platforms. This sort is also stable (if A==B and A precedes B in the list at the start, A precedes B after the sort too), although the language definition does not guarantee stability. A potential drawback is that list.sort() may require temp space of len(list)*2 bytes (``*4`` on a 64-bit machine). It's therefore possible for list.sort() to raise MemoryError now, even if a comparison function does not. See for full details. - All standard iterators now ensure that, once StopIteration has been raised, all future calls to next() on the same iterator will also raise StopIteration. There used to be various counterexamples to this behavior, which could caused confusion or subtle program breakage, without any benefits. (Note that this is still an iterator's responsibility; the iterator framework does not enforce this.) - Ctrl+C handling on Windows has been made more consistent with other platforms. KeyboardInterrupt can now reliably be caught, and Ctrl+C at an interactive prompt no longer terminates the process under NT/2k/XP (it never did under Win9x). Ctrl+C will interrupt time.sleep() in the main thread, and any child processes created via the popen family (on win2k; we can't make win9x work reliably) are also interrupted (as generally happens on for Linux/Unix.) [SF bugs 231273, 439992 and 581232] - sys.getwindowsversion() has been added on Windows. This returns a tuple with information about the version of Windows currently running. - Slices and repetitions of buffer objects now consistently return a string. Formerly, strings would be returned most of the time, but a buffer object would be returned when the repetition count was one or when the slice range was all inclusive. - Unicode objects in sys.path are no longer ignored but treated as directory names. - Fixed string.startswith and string.endswith builtin methods so they accept negative indices. [SF bug 493951] - Fixed a bug with a continue inside a try block and a yield in the finally clause. [SF bug 567538] - Most builtin sequences now support "extended slices", i.e. slices with a third "stride" parameter. For example, "hello world"[::-1] gives "dlrow olleh". - A new warning PendingDeprecationWarning was added to provide direction on features which are in the process of being deprecated. The warning will not be printed by default. To see the pending deprecations, use -Walways::PendingDeprecationWarning:: as a command line option or warnings.filterwarnings() in code. - Deprecated features of xrange objects have been removed as promised. The start, stop, and step attributes and the tolist() method no longer exist. xrange repetition and slicing have been removed. - New builtin function enumerate(x), from PEP 279. Example: enumerate("abc") is an iterator returning (0,"a"), (1,"b"), (2,"c"). The argument can be an arbitrary iterable object. - The assert statement no longer tests __debug__ at runtime. This means that assert statements cannot be disabled by assigning a false value to __debug__. - A method zfill() was added to str and unicode, that fills a numeric string to the left with zeros. For example, "+123".zfill(6) -> "+00123". - Complex numbers supported divmod() and the // and % operators, but these make no sense. Since this was documented, they're being deprecated now. - String and unicode methods lstrip(), rstrip() and strip() now take an optional argument that specifies the characters to strip. For example, "Foo!!!?!?!?".rstrip("?!") -> "Foo". - There's a new dictionary constructor (a class method of the dict class), dict.fromkeys(iterable, value=None). It constructs a dictionary with keys taken from the iterable and all values set to a single value. It can be used for building sets and for removing duplicates from sequences. - Added a new dict method pop(key). This removes and returns the value corresponding to key. [SF patch #539949] - A new built-in type, bool, has been added, as well as built-in names for its two values, True and False. Comparisons and sundry other operations that return a truth value have been changed to return a bool instead. Read PEP 285 for an explanation of why this is backward compatible. - Fixed two bugs reported as SF #535905: under certain conditions, deallocating a deeply nested structure could cause a segfault in the garbage collector, due to interaction with the "trashcan" code; access to the current frame during destruction of a local variable could access a pointer to freed memory. - The optional object allocator ("pymalloc") has been enabled by default. The recommended practice for memory allocation and deallocation has been streamlined. A header file is included, Misc/pymemcompat.h, which can be bundled with 3rd party extensions and lets them use the same API with Python versions from 1.5.2 onwards. - PyErr_Display will provide file and line information for all exceptions that have an attribute print_file_and_line, not just SyntaxErrors. - The UTF-8 codec will now encode and decode Unicode surrogates correctly and without raising exceptions for unpaired ones. - Universal newlines (PEP 278) is implemented. Briefly, using 'U' instead of 'r' when opening a text file for reading changes the line ending convention so that any of '\r', '\r\n', and '\n' is recognized (even mixed in one file); all three are converted to '\n', the standard Python line end character. - file.xreadlines() now raises a ValueError if the file is closed: Previously, an xreadlines object was returned which would raise a ValueError when the xreadlines.next() method was called. - sys.exit() inadvertently allowed more than one argument. An exception will now be raised if more than one argument is used. - Changed evaluation order of dictionary literals to conform to the general left to right evaluation order rule. Now {f1(): f2()} will evaluate f1 first. - Fixed bug #521782: when a file was in non-blocking mode, file.read() could silently lose data or wrongly throw an unknown error. - The sq_repeat, sq_inplace_repeat, sq_concat and sq_inplace_concat slots are now always tried after trying the corresponding nb_* slots. This fixes a number of minor bugs (see bug #624807). - Fix problem with dynamic loading on 64-bit AIX (see bug #639945). Extension modules ----------------- - Added three operators to the operator module: operator.pow(a,b) which is equivalent to: a**b. operator.is_(a,b) which is equivalent to: a is b. operator.is_not(a,b) which is equivalent to: a is not b. - posix.openpty now works on all systems that have /dev/ptmx. - A module zipimport exists to support importing code from zip archives. - The new datetime module supplies classes for manipulating dates and times. The basic design came from the Zope "fishbowl process", and favors practical commercial applications over calendar esoterica. See http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage - _tkinter now returns Tcl objects, instead of strings. Objects which have Python equivalents are converted to Python objects, other objects are wrapped. This can be configured through the wantobjects method, or Tkinter.wantobjects. - The PyBSDDB wrapper around the Sleepycat Berkeley DB library has been added as the package bsddb. The traditional bsddb module is still available in source code, but not built automatically anymore, and is now named bsddb185. This supports Berkeley DB versions from 3.0 to 4.1. For help converting your databases from the old module (which probably used an obsolete version of Berkeley DB) to the new module, see the db2pickle.py and pickle2db.py scripts described in the Tools/Demos section above. - unicodedata was updated to Unicode 3.2. It supports normalization and names for Hangul syllables and CJK unified ideographs. - resource.getrlimit() now returns longs instead of ints. - readline now dynamically adjusts its input/output stream if sys.stdin/stdout changes. - The _tkinter module (and hence Tkinter) has dropped support for Tcl/Tk 8.0 and 8.1. Only Tcl/Tk versions 8.2, 8.3 and 8.4 are supported. - cPickle.BadPickleGet is now a class. - The time stamps in os.stat_result are floating point numbers after stat_float_times has been called. - If the size passed to mmap.mmap() is larger than the length of the file on non-Windows platforms, a ValueError is raised. [SF bug 585792] - The xreadlines module is slated for obsolescence. - The strptime function in the time module is now always available (a Python implementation is used when the C library doesn't define it). - The 'new' module is no longer an extension, but a Python module that only exists for backwards compatibility. Its contents are no longer functions but callable type objects. - The bsddb.*open functions can now take 'None' as a filename. This will create a temporary in-memory bsddb that won't be written to disk. - posix.getloadavg, posix.lchown, posix.killpg, posix.mknod, and posix.getpgid have been added where available. - The locale module now exposes the C library's gettext interface. It also has a new function getpreferredencoding. - A security hole ("double free") was found in zlib-1.1.3, a popular third party compression library used by some Python modules. The hole was quickly plugged in zlib-1.1.4, and the Windows build of Python now ships with zlib-1.1.4. - pwd, grp, and resource return enhanced tuples now, with symbolic field names. - array.array is now a type object. A new format character 'u' indicates Py_UNICODE arrays. For those, .tounicode and .fromunicode methods are available. Arrays now support __iadd__ and __imul__. - dl now builds on every system that has dlfcn.h. Failure in case of sizeof(int)!=sizeof(long)!=sizeof(void*) is delayed until dl.open is called. - The sys module acquired a new attribute, api_version, which evaluates to the value of the PYTHON_API_VERSION macro with which the interpreter was compiled. - Fixed bug #470582: sre module would return a tuple (None, 'a', 'ab') when applying the regular expression '^((a)c)?(ab)$' on 'ab'. It now returns (None, None, 'ab'), as expected. Also fixed handling of lastindex/lastgroup match attributes in similar cases. For example, when running the expression r'(a)(b)?b' over 'ab', lastindex must be 1, not 2. - Fixed bug #581080: sre scanner was not checking the buffer limit before increasing the current pointer. This was creating an infinite loop in the search function, once the pointer exceeded the buffer limit. - The os.fdopen function now enforces a file mode starting with the letter 'r', 'w' or 'a', otherwise a ValueError is raised. This fixes bug #623464. - The linuxaudiodev module is now deprecated; it is being replaced by ossaudiodev. The interface has been extended to cover a lot more of OSS (see www.opensound.com), including most DSP ioctls and the OSS mixer API. Documentation forthcoming in 2.3a2. Library ------- - imaplib.py now supports SSL (Tino Lange and Piers Lauder). - Freeze's modulefinder.py has been moved to the standard library; slightly improved so it will issue less false missing submodule reports (see sf path #643711 for details). Documentation will follow with Python 2.3a2. - os.path exposes getctime. - unittest.py now has two additional methods called assertAlmostEqual() and failIfAlmostEqual(). They implement an approximate comparison by rounding the difference between the two arguments and comparing the result to zero. Approximate comparison is essential for unit tests of floating point results. - calendar.py now depends on the new datetime module rather than the time module. As a result, the range of allowable dates has been increased. - pdb has a new 'j(ump)' command to select the next line to be executed. - The distutils created windows installers now can run a postinstallation script. - doctest.testmod can now be called without argument, which means to test the current module. - When canceling a server that implemented threading with a keyboard interrupt, the server would shut down but not terminate (waiting on client threads). A new member variable, daemon_threads, was added to the ThreadingMixIn class in SocketServer.py to make it explicit that this behavior needs to be controlled. - A new module, optparse, provides a fancy alternative to getopt for command line parsing. It is a slightly modified version of Greg Ward's Optik package. - UserDict.py now defines a DictMixin class which defines all dictionary methods for classes that already have a minimum mapping interface. This greatly simplifies writing classes that need to be substitutable for dictionaries (such as the shelve module). - shelve.py now subclasses from UserDict.DictMixin. Now shelve supports all dictionary methods. This eases the transition to persistent storage for scripts originally written with dictionaries in mind. - shelve.open and the various classes in shelve.py now accept an optional binary flag, which defaults to False. If True, the values stored in the shelf are binary pickles. - A new package, logging, implements the logging API defined by PEP 282. The code is written by Vinay Sajip. - StreamReader, StreamReaderWriter and StreamRecoder in the codecs modules are iterators now. - gzip.py now handles files exceeding 2GB. Files over 4GB also work now (provided the OS supports it, and Python is configured with large file support), but in that case the underlying gzip file format can record only the least-significant 32 bits of the file size, so that some tools working with gzipped files may report an incorrect file size. - xml.sax.saxutils.unescape has been added, to replace entity references with their entity value. - Queue.Queue.{put,get} now support an optional timeout argument. - Various features of Tk 8.4 are exposed in Tkinter.py. The multiple option of tkFileDialog is exposed as function askopenfile{,name}s. - Various configure methods of Tkinter have been stream-lined, so that tag_configure, image_configure, window_configure now return a dictionary when invoked with no argument. - Importing the readline module now no longer has the side effect of calling setlocale(LC_CTYPE, ""). The initial "C" locale, or whatever locale is explicitly set by the user, is preserved. If you want repr() of 8-bit strings in your preferred encoding to preserve all printable characters of that encoding, you have to add the following code to your $PYTHONSTARTUP file or to your application's main(): import locale locale.setlocale(locale.LC_CTYPE, "") - shutil.move was added. shutil.copytree now reports errors as an exception at the end, instead of printing error messages. - Encoding name normalization was generalized to not only replace hyphens with underscores, but also all other non-alphanumeric characters (with the exception of the dot which is used for Python package names during lookup). The aliases.py mapping was updated to the new standard. - mimetypes has two new functions: guess_all_extensions() which returns a list of all known extensions for a mime type, and add_type() which adds one mapping between a mime type and an extension to the database. - New module: sets, defines the class Set that implements a mutable set type using the keys of a dict to represent the set. There's also a class ImmutableSet which is useful when you need sets of sets or when you need to use sets as dict keys, and a class BaseSet which is the base class of the two. - Added random.sample(population,k) for random sampling without replacement. Returns a k length list of unique elements chosen from the population. - random.randrange(-sys.maxint-1, sys.maxint) no longer raises OverflowError. That is, it now accepts any combination of 'start' and 'stop' arguments so long as each is in the range of Python's bounded integers. - Thanks to Raymond Hettinger, random.random() now uses a new core generator. The Mersenne Twister algorithm is implemented in C, threadsafe, faster than the previous generator, has an astronomically large period (2**19937-1), creates random floats to full 53-bit precision, and may be the most widely tested random number generator in existence. The random.jumpahead(n) method has different semantics for the new generator. Instead of jumping n steps ahead, it uses n and the existing state to create a new state. This means that jumpahead() continues to support multi-threaded code needing generators of non-overlapping sequences. However, it will break code which relies on jumpahead moving a specific number of steps forward. The attributes random.whseed and random.__whseed have no meaning for the new generator. Code using these attributes should switch to a new class, random.WichmannHill which is provided for backward compatibility and to make an alternate generator available. - New "algorithms" module: heapq, implements a heap queue. Thanks to Kevin O'Connor for the code and François Pinard for an entertaining write-up explaining the theory and practical uses of heaps. - New encoding for the Palm OS character set: palmos. - binascii.crc32() and the zipfile module had problems on some 64-bit platforms. These have been fixed. On a platform with 8-byte C longs, crc32() now returns a signed-extended 4-byte result, so that its value as a Python int is equal to the value computed a 32-bit platform. - xml.dom.minidom.toxml and toprettyxml now take an optional encoding argument. - Some fixes in the copy module: when an object is copied through its __reduce__ method, there was no check for a __setstate__ method on the result [SF patch 565085]; deepcopy should treat instances of custom metaclasses the same way it treats instances of type 'type' [SF patch 560794]. - Sockets now support timeout mode. After s.settimeout(T), where T is a float expressing seconds, subsequent operations raise an exception if they cannot be completed within T seconds. To disable timeout mode, use s.settimeout(None). There's also a module function, socket.setdefaulttimeout(T), which sets the default for all sockets created henceforth. - getopt.gnu_getopt was added. This supports GNU-style option processing, where options can be mixed with non-option arguments. - Stop using strings for exceptions. String objects used for exceptions are now classes deriving from Exception. The objects changed were: Tkinter.TclError, bdb.BdbQuit, macpath.norm_error, tabnanny.NannyNag, and xdrlib.Error. - Constants BOM_UTF8, BOM_UTF16, BOM_UTF16_LE, BOM_UTF16_BE, BOM_UTF32, BOM_UTF32_LE and BOM_UTF32_BE that represent the Byte Order Mark in UTF-8, UTF-16 and UTF-32 encodings for little and big endian systems were added to the codecs module. The old names BOM32_* and BOM64_* were off by a factor of 2. - Added conversion functions math.degrees() and math.radians(). - math.log() now takes an optional argument: math.log(x[, base]). - ftplib.retrlines() now tests for callback is None rather than testing for False. Was causing an error when given a callback object which was callable but also returned len() as zero. The change may create new breakage if the caller relied on the undocumented behavior and called with callback set to [] or some other False value not identical to None. - random.gauss() uses a piece of hidden state used by nothing else, and the .seed() and .whseed() methods failed to reset it. In other words, setting the seed didn't completely determine the sequence of results produced by random.gauss(). It does now. Programs repeatedly mixing calls to a seed method with calls to gauss() may see different results now. - The pickle.Pickler class grew a clear_memo() method to mimic that provided by cPickle.Pickler. - difflib's SequenceMatcher class now does a dynamic analysis of which elements are so frequent as to constitute noise. For comparing files as sequences of lines, this generally works better than the IS_LINE_JUNK function, and function ndiff's linejunk argument defaults to None now as a result. A happy benefit is that SequenceMatcher may run much faster now when applied to large files with many duplicate lines (for example, C program text with lots of repeated "}" and "return NULL;" lines). - New Text.dump() method in Tkinter module. - New distutils commands for building packagers were added to support pkgtool on Solaris and swinstall on HP-UX. - distutils now has a new abstract binary packager base class command/bdist_packager, which simplifies writing packagers. This will hopefully provide the missing bits to encourage people to submit more packagers, e.g. for Debian, FreeBSD and other systems. - The UTF-16, -LE and -BE stream readers now raise a NotImplementedError for all calls to .readline(). Previously, they used to just produce garbage or fail with an encoding error -- UTF-16 is a 2-byte encoding and the C lib's line reading APIs don't work well with these. - compileall now supports quiet operation. - The BaseHTTPServer now implements optional HTTP/1.1 persistent connections. - socket module: the SSL support was broken out of the main _socket module C helper and placed into a new _ssl helper which now gets imported by socket.py if available and working. - encodings package: added aliases for all supported IANA character sets - ftplib: to safeguard the user's privacy, anonymous login will use "anonymous@" as default password, rather than the real user and host name. - webbrowser: tightened up the command passed to os.system() so that arbitrary shell code can't be executed because a bogus URL was passed in. - gettext.translation has an optional fallback argument, and gettext.find an optional all argument. Translations will now fallback on a per-message basis. The module supports plural forms, by means of gettext.[d]ngettext and Translation.[u]ngettext. - distutils bdist commands now offer a --skip-build option. - warnings.warn now accepts a Warning instance as first argument. - The xml.sax.expatreader.ExpatParser class will no longer create circular references by using itself as the locator that gets passed to the content handler implementation. [SF bug #535474] - The email.Parser.Parser class now properly parses strings regardless of their line endings, which can be any of \r, \n, or \r\n (CR, LF, or CRLF). Also, the Header class's constructor default arguments has changed slightly so that an explicit maxlinelen value is always honored, and so unicode conversion error handling can be specified. - distutils' build_ext command now links C++ extensions with the C++ compiler available in the Makefile or CXX environment variable, if running under \*nix. - New module bz2: provides a comprehensive interface for the bz2 compression library. It implements a complete file interface, one-shot (de)compression functions, and types for sequential (de)compression. - New pdb command 'pp' which is like 'p' except that it pretty-prints the value of its expression argument. - Now bdist_rpm distutils command understands a verify_script option in the config file, including the contents of the referred filename in the "%verifyscript" section of the rpm spec file. - Fixed bug #495695: webbrowser module would run graphic browsers in a unix environment even if DISPLAY was not set. Also, support for skipstone browser was included. - Fixed bug #636769: rexec would run unallowed code if subclasses of strings were used as parameters for certain functions. Tools/Demos ----------- - pygettext.py now supports globbing on Windows, and accepts module names in addition to accepting file names. - The SGI demos (Demo/sgi) have been removed. Nobody thought they were interesting any more. (The SGI library modules and extensions are still there; it is believed that at least some of these are still used and useful.) - IDLE supports the new encoding declarations (PEP 263); it can also deal with legacy 8-bit files if they use the locale's encoding. It allows non-ASCII strings in the interactive shell and executes them in the locale's encoding. - freeze.py now produces binaries which can import shared modules, unlike before when this failed due to missing symbol exports in the generated binary. Build ----- - On Unix, IDLE is now installed automatically. - The fpectl module is not built by default; it's dangerous or useless except in the hands of experts. - The public Python C API will generally be declared using PyAPI_FUNC and PyAPI_DATA macros, while Python extension module init functions will be declared with PyMODINIT_FUNC. DL_EXPORT/DL_IMPORT macros are deprecated. - A bug was fixed that could cause COUNT_ALLOCS builds to segfault, or get into infinite loops, when a new-style class got garbage-collected. Unfortunately, to avoid this, the way COUNT_ALLOCS works requires that new-style classes be immortal in COUNT_ALLOCS builds. Note that COUNT_ALLOCS is not enabled by default, in either release or debug builds, and that new-style classes are immortal only in COUNT_ALLOCS builds. - Compiling out the cyclic garbage collector is no longer an option. The old symbol WITH_CYCLE_GC is now ignored, and Python.h arranges that it's always defined (for the benefit of any extension modules that may be conditionalizing on it). A bonus is that any extension type participating in cyclic gc can choose to participate in the Py_TRASHCAN mechanism now too; in the absence of cyclic gc, this used to require editing the core to teach the trashcan mechanism about the new type. - According to Annex F of the current C standard, The Standard C macro HUGE_VAL and its float and long double analogs, HUGE_VALF and HUGE_VALL, expand to expressions whose values are positive infinities. Python only uses the double HUGE_VAL, and only to #define its own symbol Py_HUGE_VAL. Some platforms have incorrect definitions for HUGE_VAL. pyport.h used to try to worm around that, but the workarounds triggered other bugs on other platforms, so we gave up. If your platform defines HUGE_VAL incorrectly, you'll need to #define Py_HUGE_VAL to something that works on your platform. The only instance of this I'm sure about is on an unknown subset of Cray systems, described here: http://www.cray.com/swpubs/manuals/SN-2194_2.0/html-SN-2194_2.0/x3138.htm Presumably 2.3a1 breaks such systems. If anyone uses such a system, help! - The configure option --without-doc-strings can be used to remove the doc strings from the builtin functions and modules; this reduces the size of the executable. - The universal newlines option (PEP 278) is on by default. On Unix it can be disabled by passing --without-universal-newlines to the configure script. On other platforms, remove WITH_UNIVERSAL_NEWLINES from pyconfig.h. - On Unix, a shared libpython2.3.so can be created with --enable-shared. - All uses of the CACHE_HASH, INTERN_STRINGS, and DONT_SHARE_SHORT_STRINGS preprocessor symbols were eliminated. The internal decisions they controlled stopped being experimental long ago. - The tools used to build the documentation now work under Cygwin as well as Unix. - The bsddb and dbm module builds have been changed to try and avoid version skew problems and disable linkage with Berkeley DB 1.85 unless the installer knows what s/he's doing. See the section on building these modules in the README file for details. C API ----- - PyNumber_Check() now returns true for string and unicode objects. This is a result of these types having a partially defined tp_as_number slot. (This is not a feature, but an indication that PyNumber_Check() is not very useful to determine numeric behavior. It may be deprecated.) - The string object's layout has changed: the pointer member ob_sinterned has been replaced by an int member ob_sstate. On some platforms (e.g. most 64-bit systems) this may change the offset of the ob_sval member, so as a precaution the API_VERSION has been incremented. The apparently unused feature of "indirect interned strings", supported by the ob_sinterned member, is gone. Interned strings are now usually mortal; there is a new API, PyString_InternImmortal() that creates immortal interned strings. (The ob_sstate member can only take three values; however, while making it a char saves a few bytes per string object on average, in it also slowed things down a bit because ob_sval was no longer aligned.) - The Py_InitModule*() functions now accept NULL for the 'methods' argument. Modules without global functions are becoming more common now that factories can be types rather than functions. - New C API PyUnicode_FromOrdinal() which exposes unichr() at C level. - New functions PyErr_SetExcFromWindowsErr() and PyErr_SetExcFromWindowsErrWithFilename(). Similar to PyErr_SetFromWindowsErrWithFilename() and PyErr_SetFromWindowsErr(), but they allow to specify the exception type to raise. Available on Windows. - Py_FatalError() is now declared as taking a const char* argument. It was previously declared without const. This should not affect working code. - Added new macro PySequence_ITEM(o, i) that directly calls sq_item without rechecking that o is a sequence and without adjusting for negative indices. - PyRange_New() now raises ValueError if the fourth argument is not 1. This is part of the removal of deprecated features of the xrange object. - PyNumber_Coerce() and PyNumber_CoerceEx() now also invoke the type's coercion if both arguments have the same type but this type has the CHECKTYPES flag set. This is to better support proxies. - The type of tp_free has been changed from "``void (*)(PyObject *)``" to "``void (*)(void *)``". - PyObject_Del, PyObject_GC_Del are now functions instead of macros. - A type can now inherit its metatype from its base type. Previously, when PyType_Ready() was called, if ob_type was found to be NULL, it was always set to &PyType_Type; now it is set to base->ob_type, where base is tp_base, defaulting to &PyObject_Type. - PyType_Ready() accidentally did not inherit tp_is_gc; now it does. - The PyCore_* family of APIs have been removed. - The "u#" parser marker will now pass through Unicode objects as-is without going through the buffer API. - The enumerators of cmp_op have been renamed to use the prefix ``PyCmp_``. - An old #define of ANY as void has been removed from pyport.h. This hasn't been used since Python's pre-ANSI days, and the #define has been marked as obsolete since then. SF bug 495548 says it created conflicts with other packages, so keeping it around wasn't harmless. - Because Python's magic number scheme broke on January 1st, we decided to stop Python development. Thanks for all the fish! - Some of us don't like fish, so we changed Python's magic number scheme to a new one. See Python/import.c for details. New platforms ------------- - OpenVMS is now supported. - AtheOS is now supported. - the EMX runtime environment on OS/2 is now supported. - GNU/Hurd is now supported. Tests ----- - The regrtest.py script's -u option now provides a way to say "allow all resources except this one." For example, to allow everything except bsddb, give the option '-uall,-bsddb'. Windows ------- - The Windows distribution now ships with version 4.0.14 of the Sleepycat Berkeley database library. This should be a huge improvement over the previous Berkeley DB 1.85, which had many bugs. XXX What are the licensing issues here? XXX If a user has a database created with a previous version of XXX Python, what must they do to convert it? XXX I'm still not sure how to link this thing (see PCbuild/readme.txt). XXX The version # is likely to change before 2.3a1. - The Windows distribution now ships with a Secure Sockets Library (SLL) module (_ssl.pyd) - The Windows distribution now ships with Tcl/Tk version 8.4.1 (it previously shipped with Tcl/Tk 8.3.2). - When Python is built under a Microsoft compiler, sys.version now includes the compiler version number (_MSC_VER). For example, under MSVC 6, sys.version contains the substring "MSC v.1200 ". 1200 is the value of _MSC_VER under MSVC 6. - Sometimes the uninstall executable (UNWISE.EXE) vanishes. One cause of that has been fixed in the installer (disabled Wise's "delete in- use files" uninstall option). - Fixed a bug in urllib's proxy handling in Windows. [SF bug #503031] - The installer now installs Start menu shortcuts under (the local equivalent of) "All Users" when doing an Admin install. - file.truncate([newsize]) now works on Windows for all newsize values. It used to fail if newsize didn't fit in 32 bits, reflecting a limitation of MS _chsize (which is no longer used). - os.waitpid() is now implemented for Windows, and can be used to block until a specified process exits. This is similar to, but not exactly the same as, os.waitpid() on POSIX systems. If you're waiting for a specific process whose pid was obtained from one of the spawn() functions, the same Python os.waitpid() code works across platforms. See the docs for details. The docs were changed to clarify that spawn functions return, and waitpid requires, a process handle on Windows (not the same thing as a Windows process id). - New tempfile.TemporaryFile implementation for Windows: this doesn't need a TemporaryFileWrapper wrapper anymore, and should be immune to a nasty problem: before 2.3, if you got a temp file on Windows, it got wrapped in an object whose close() method first closed the underlying file, then deleted the file. This usually worked fine. However, the spawn family of functions on Windows create (at a low C level) the same set of open files in the spawned process Q as were open in the spawning process P. If a temp file f was among them, then doing f.close() in P first closed P's C-level file handle on f, but Q's C-level file handle on f remained open, so the attempt in P to delete f blew up with a "Permission denied" error (Windows doesn't allow deleting open files). This was surprising, subtle, and difficult to work around. - The os module now exports all the symbolic constants usable with the low-level os.open() on Windows: the new constants in 2.3 are O_NOINHERIT, O_SHORT_LIVED, O_TEMPORARY, O_RANDOM and O_SEQUENTIAL. The others were also available in 2.2: O_APPEND, O_BINARY, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TEXT, O_TRUNC and O_WRONLY. Contrary to Microsoft docs, O_SHORT_LIVED does not seem to imply O_TEMPORARY (so specify both if you want both; note that neither is useful unless specified with O_CREAT too). Mac ---- - Mac/Relnotes is gone, the release notes are now here. - Python (the OSX-only, unix-based version, not the OS9-compatible CFM version) now fully supports unicode strings as arguments to various file system calls, eg. open(), file(), os.stat() and os.listdir(). - The current naming convention for Python on the Macintosh is that MacPython refers to the unix-based OSX-only version, and MacPython-OS9 refers to the CFM-based version that runs on both OS9 and OSX. - All MacPython-OS9 functionality is now available in an OSX unix build, including the Carbon modules, the IDE, OSA support, etc. A lot of this will only work correctly in a framework build, though, because you cannot talk to the window manager unless your application is run from a .app bundle. There is a command line tool "pythonw" that runs your script with an interpreter living in such a .app bundle, this interpreter should be used to run any Python script using the window manager (including Tkinter or wxPython scripts). - Most of Mac/Lib has moved to Lib/plat-mac, which is again used both in MacPython-OSX and MacPython-OS9. The only modules remaining in Mac/Lib are specifically for MacPython-OS9 (CFM support, preference resources, etc). - A new utility PythonLauncher will start a Python interpreter when a .py or .pyw script is double-clicked in the Finder. By default .py scripts are run with a normal Python interpreter in a Terminal window and .pyw files are run with a window-aware pythonw interpreter without a Terminal window, but all this can be customized. - MacPython-OS9 is now Carbon-only, so it runs on Mac OS 9 or Mac OS X and possibly on Mac OS 8.6 with the right CarbonLib installed, but not on earlier releases. - Many tools such as BuildApplet.py and gensuitemodule.py now support a command line interface too. - All the Carbon classes are now PEP253 compliant, meaning that you can subclass them from Python. Most of the attributes have gone, you should now use the accessor function call API, which is also what Apple's documentation uses. Some attributes such as grafport.visRgn are still available for convenience. - New Carbon modules File (implementing the APIs in Files.h and Aliases.h) and Folder (APIs from Folders.h). The old macfs builtin module is gone, and replaced by a Python wrapper around the new modules. - Pathname handling should now be fully consistent: MacPython-OSX always uses unix pathnames and MacPython-OS9 always uses colon-separated Mac pathnames (also when running on Mac OS X). - New Carbon modules Help and AH give access to the Carbon Help Manager. There are hooks in the IDE to allow accessing the Python documentation (and Apple's Carbon and Cocoa documentation) through the Help Viewer. See Mac/OSX/README for converting the Python documentation to a Help Viewer compatible form and installing it. - OSA support has been redesigned and the generated Python classes now mirror the inheritance defined by the underlying OSA classes. - MacPython no longer maps both \r and \n to \n on input for any text file. This feature has been replaced by universal newline support (PEP278). - The default encoding for Python sourcefiles in MacPython-OS9 is no longer mac-roman (or whatever your local Mac encoding was) but "ascii", like on other platforms. If you really need sourcefiles with Mac characters in them you can change this in site.py. ---- **(For information about older versions, consult the HISTORY file.)**