(editors: check NEWS.help for information about editing NEWS using ReST.)
Release date: 30-MAR-2005
Release date: 17-MAR-2005
Release date: 10-MAR-2005
Bug #1091468: make frameworkinstall now works with DESTROOT builds
On 10.3 and later extensions are built with -undefined dynamic_lookup. This ensures that extensions can be built in older versions of Python after a newer framework has been installed. In addition, an extension will not accidentally pull in another copy of the Python interpreter.
On 10.2 and earlier (or if MACOSX_DEPLOYMENT_TARGET is set to a value <= 10.2) extensions are linked directly to the dylib in the framework, in stead of against the framework itself. This ensures that extensions can be built in older versions of Python after a newer framework has been installed.
PackageManager and the underlying pimp.py module have been updated to version 0.5, which greatly simplifies maintainance of the package databases.
Release date: 30-NOV-2004
Release date: 18-NOV-2004
Release date: 03-NOV-2004
The Python Software Foundation changed the license under which Python is released, to remove Python version numbers. There were no other changes to the license. So, for example, wherever the license for Python 2.3 said "Python 2.3", the new license says "Python". The intent is to make it possible to refer to the PSF license in a more durable way. For example, some people say they're confused by that the Open Source Initiative's entry for the Python Software Foundation License:
http://www.opensource.org/licenses/PythonSoftFoundation.php
says "Python 2.1.1" all over it, wondering whether it applies only to Python 2.1.1.
The official name of the new license is the Python Software Foundation License Version 2.
Release date: 15-OCT-2004
Release date: 02-SEP-2004
Release date: 05-AUG-2004
Patch #980695: Implements efficient string concatenation for statements of the form s=s+t and s+=t. This will vary across implementations. Accordingly, the str.join() method is strongly preferred for performance sensitive code.
PEP-0318, Function Decorators have been added to the language. These are implemented using the Java-style @decorator syntax, like so:
@staticmethod def foo(bar):
(The PEP needs to be updated to reflect the current state)
When importing a module M raises an exception, Python no longer leaves M in sys.modules. Before 2.4a2 it did, and a subsequent import of M would succeed, picking up a module object from sys.modules reflecting as much of the initialization of M as completed before the exception was raised. Subsequent imports got no indication that M was in a partially- initialized state, and the importers could get into arbitrarily bad trouble as a result (the M they got was in an unintended state, arbitrarily far removed from M's author's intent). Now subsequent imports of M will continue raising exceptions (but if, for example, the source code for M is edited between import attempts, then perhaps later attempts will succeed, or raise a different exception).
This can break existing code, but in such cases the code was probably working before by accident. In the Python source, the only case of breakage discovered was in a test accidentally relying on a damaged module remaining in sys.modules. Cases are also known where tests deliberately provoking import errors remove damaged modules from sys.modules themselves, and such tests will break now if they do an unconditional del sys.modules[M].
u'%s' % obj will now try obj.__unicode__() first and fallback to obj.__str__() if no __unicode__ method can be found.
Patch #550732: Add PyArg_VaParseTupleAndKeywords(). Analogous to PyArg_VaParse(). Both are now documented. Thanks Greg Chapman.
Allow string and unicode return types from .encode()/.decode() methods on string and unicode objects. Added unicode.decode() which was missing for no apparent reason.
An attempt to fix the mess that is Python's behaviour with signal handlers and threads, complicated by readline's behaviour. It's quite possible that there are still bugs here.
Added C macros Py_CLEAR and Py_VISIT to ease the implementation of types that support garbage collection.
Compiler now treats None as a constant.
The type of values returned by __int__, __float__, __long__, __oct__, and __hex__ are now checked. Returning an invalid type will cause a TypeError to be raised. This matches the behavior of Jython.
Implemented bind_textdomain_codeset() in locale module.
Added a workaround for proper string operations in BSDs. str.split and str.is* methods can now work correctly with UTF-8 locales.
Bug #989185: unicode.iswide() and unicode.width() is dropped and the East Asian Width support is moved to unicodedata extension module.
Patch #941229: The source code encoding in interactive mode now refers sys.stdin.encoding not just ISO-8859-1 anymore. This allows for non-latin-1 users to write unicode strings directly.
Added new codecs and aliases for ISO_8859-11, ISO_8859-16 and TIS-620
Thanks to Edward Loper, doctest has been massively refactored, and many new features were added. Full docs will appear later. For now the doctest module comments and new test cases give good coverage. The refactoring provides many hook points for customizing behavior (such as how to report errors, and how to compare expected to actual output). New features include a <BLANKLINE> marker for expected output containing blank lines, options to produce unified or context diffs when actual output doesn't match expectations, an option to normalize whitespace before comparing, and an option to use an ellipsis to signify "don't care" regions of output.
Tkinter now supports the wish -sync and -use options.
The following methods in time support passing of None: ctime(), gmtime(), and localtime(). If None is provided, the current time is used (the same as when the argument is omitted). [SF bug 658254, patch 663482]
nntplib does now allow to ignore a .netrc file.
urllib2 now recognizes Basic authentication even if other authentication schemes are offered.
Bug #1001053. wave.open() now accepts unicode filenames.
gzip.GzipFile has a new fileno() method, to retrieve the handle of the underlying file object (provided it has a fileno() method). This is needed if you want to use os.fsync() on a GzipFile.
imaplib has two new methods: deleteacl and myrights.
nntplib has two new methods: description and descriptions. They use a more RFC-compliant way of getting a newsgroup description.
Bug #993394. Fix a possible red herring of KeyError in 'threading' being raised during interpreter shutdown from a registered function with atexit when dummy_threading is being used.
Bug #857297/Patch #916874. Fix an error when extracting a hard link from a tarfile.
Patch #846659. Fix an error in tarfile.py when using GNU longname/longlink creation.
The obsolete FCNTL.py has been deleted. The builtin fcntl module has been available (on platforms that support fcntl) since Python 1.5a3, and all FCNTL.py did is export fcntl's names, after generating a deprecation warning telling you to use fcntl directly.
Several new unicode codecs are added: big5hkscs, euc_jis_2004, iso2022_jp_2004, shift_jis_2004.
Bug #788520. Queue.{get, get_nowait, put, put_nowait} have new implementations, exploiting Conditions (which didn't exist at the time Queue was introduced). A minor semantic change is that the Full and Empty exceptions raised by non-blocking calls now occur only if the queue truly was full or empty at the instant the queue was checked (of course the Queue may no longer be full or empty by the time a calling thread sees those exceptions, though). Before, the exceptions could also be raised if it was "merely inconvenient" for the implementation to determine the true state of the Queue (because the Queue was locked by some other method in progress).
Bugs #979794 and #980117: difflib.get_grouped_opcodes() now handles the case of comparing two empty lists. This affected both context_diff() and unified_diff(),
Bug #980938: smtplib now prints debug output to sys.stderr.
Bug #930024: posixpath.realpath() now handles infinite loops in symlinks by returning the last point in the path that was not part of any loop. Thanks AM Kuchling.
Bug #980327: ntpath not handles compressing erroneous slashes between the drive letter and the rest of the path. Also clearly handles UNC addresses now as well. Thanks Paul Moore.
bug #679953: zipfile.py should now work for files over 2 GB. The packed data for file sizes (compressed and uncompressed) was being stored as signed instead of unsigned.
decimal.py now only uses signals in the IBM spec. The other conditions are no longer part of the public API.
codecs module now has two new generic APIs: encode() and decode() which don't restrict the return types (unlike the unicode and string methods of the same name).
Non-blocking SSL sockets work again; they were broken in Python 2.3. SF patch 945642.
doctest unittest integration improvements:
o Improved the unitest test output for doctest-based unit tests
DocTestSuites.
The threading module has a new class, local, for creating objects that provide thread-local data.
Bug #990307: when keep_empty_values is True, cgi.parse_qsl() no longer returns spurious empty fields.
Implemented bind_textdomain_codeset() in gettext module.
Introduced in gettext module the l*gettext() family of functions, which return translation strings encoded in the preferred encoding, as informed by locale module's getpreferredencoding().
optparse module (and tests) upgraded to Optik 1.5a1. Changes:
Release date: 08-JUL-2004
Release date: 29-Jul-2003
Release date: 24-Jul-2003
Release date: 18-Jul-2003
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.
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.
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.
Release date: 29-Jun-2003
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.
None this time.
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
Release date: 25-Apr-2003
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.)
None this time.
Release date: 19-Feb-2003
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 <http://www.python.org/sf/661086>. 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 <http://www.python.org/sf/660872>.
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.
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.
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 <http://fink.sf.net/>.
A new Makefile target, scriptsinstall, installs a number of useful scripts from the Tools/scripts directory.
Release date: 31-Dec-2002
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<<n where this currently doesn't yield the same value as long(x)<<n; in Python 2.4, the outcome will be long(x)<<n.
- Conversions from ints to string that show negative values as unsigned ints in the inclusive range [0x80000000..0xffffffff]; this affects the functions hex() and oct(), and the string formatting codes %u, %o, %x, and %X. In Python 2.4, these will show signed values (e.g. hex(-1) currently returns "0xffffffff"; in Python 2.4 it will return "-0x1").
The bits manipulated under the cover by sys.setcheckinterval() have been changed. Both the check interval and the ticker used to be per-thread values. They are now just a pair of global variables. In addition, the default check interval was boosted from 10 to 100 bytecode instructions. This may have some effect on systems that relied on the old default value. In particular, in multi-threaded applications which try to be highly responsive, response time will increase by some (perhaps imperceptible) amount.
When multiplying very large integers, a version of the so-called Karatsuba algorithm is now used. This is most effective if the inputs have roughly the same size. If they both have about N digits, Karatsuba multiplication has O(N**1.58) runtime (the exponent is log_base_2(3)) instead of the previous O(N**2). Measured results may be better or worse than that, depending on platform quirks. Besides the O() improvement in raw instruction count, the Karatsuba algorithm appears to have much better cache behavior on extremely large integers (starting in the ballpark of a million bits). Note that this is a simple implementation, and there's no intent here to compete with, e.g., GMP. It gives a very nice speedup when it applies, but a package devoted to fast large-integer arithmetic should run circles around it.
u'%c' will now raise a ValueError in case the argument is an integer outside the valid range of Unicode code point ordinals.
The tempfile module has been overhauled for enhanced security. The mktemp() function is now deprecated; new, safe replacements are mkstemp() (for files) and mkdtemp() (for directories), and the higher-level functions NamedTemporaryFile() and TemporaryFile(). Use of some global variables in this module is also deprecated; the new functions have keyword arguments to provide the same functionality. All Lib, Tools and Demo modules that used the unsafe interfaces have been updated to use the safe replacements. Thanks to Zack Weinberg!
When x is an object whose class implements __mul__ and __rmul__, 1.0*x would correctly invoke __rmul__, but 1*x would erroneously invoke __mul__. This was due to the sequence-repeat code in the int type. This has been fixed now.
Previously, "str1 in str2" required str1 to be a string of length 1. This restriction has been relaxed to allow str1 to be a string of any length. Thus "'el' in 'hello world'" returns True now.
File objects are now their own iterators. For a file f, iter(f) now returns f (unless f is closed), and f.next() is similar to f.readline() when EOF is not reached; however, f.next() uses a readahead buffer that messes up the file position, so mixing f.next() and f.readline() (or other methods) doesn't work right. Calling f.seek() drops the readahead buffer, but other operations don't. It so happens that this gives a nice additional speed boost to "for line in file:"; the xreadlines method and corresponding module are now obsolete. Thanks to Oren Tirosh!
Encoding declarations (PEP 263, phase 1) have been implemented. A comment of the form "# -- coding: <encodingname> --" 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 <http://www.python.org/sf/587076> 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', 'rn', 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).
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
_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.
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 rn (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.
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.
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.
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).
Release date: 21-Dec-2001
Release date: 14-Dec-2001
Guido's tutorial introduction to the new type/class features has been extensively updated. See
That remains the primary documentation in this area.
Fixed a leak: instance variables declared with __slots__ were never deleted!
The "delete attribute" method of descriptor objects is called __delete__, not __del__. In previous releases, it was mistakenly called __del__, which created an unfortunate overloading condition with finalizers. (The "get attribute" and "set attribute" methods are still called __get__ and __set__, respectively.)
Some subtle issues with the super built-in were fixed:
Previously, hash() of an instance of a subclass of a mutable type (list or dictionary) would return some value, rather than raising TypeError. This has been fixed. Also, directly calling dict.__hash__ and list.__hash__ now raises the same TypeError (previously, these were the same as object.__hash__).
New-style objects now support deleting their __dict__. This is for all intents and purposes equivalent to assigning a brand new empty dictionary, but saves space if the object is not used further.
Release date: 16-Nov-2001
Multiple inheritance mixing new-style and classic classes in the list of base classes is now allowed, so this works now:
class Classic: pass class Mixed(Classic, object): pass
The MRO (method resolution order) for each base class is respected according to its kind, but the MRO for the derived class is computed using new-style MRO rules if any base class is a new-style class. This needs to be documented.
The new builtin dictionary() constructor, and dictionary type, have been renamed to dict. This reflects a decade of common usage.
dict() now accepts an iterable object producing 2-sequences. For example, dict(d.items()) == d for any dictionary d. The argument, and the elements of the argument, can be any iterable objects.
New-style classes can now have a __del__ method, which is called when the instance is deleted (just like for classic classes).
Assignment to object.__dict__ is now possible, for objects that are instances of new-style classes that have a __dict__ (unless the base class forbids it).
Methods of built-in types now properly check for keyword arguments (formerly these were silently ignored). The only built-in methods that take keyword arguments are __call__, __init__ and __new__.
The socket function has been converted to a type; see below.
Release date: 19-Oct-2001
A very subtle syntactical pitfall in list comprehensions was fixed. For example: [a+b for a in 'abc', for b in 'def']. The comma in this example is a mistake. Previously, this would silently let 'a' iterate over the singleton tuple ('abc',), yielding ['abcd', 'abce', 'abcf'] rather than the intended ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']. Now, this is flagged as a syntax error. Note that [a for a in <singleton>] is a convoluted way to say [<singleton>] anyway, so it's not like any expressiveness is lost.
getattr(obj, name, default) now only catches AttributeError, as documented, rather than returning the default value for all exceptions (which could mask bugs in a __getattr__ hook, for example).
Weak reference objects are now part of the core and offer a C API. A bug which could allow a core dump when binary operations involved proxy reference has been fixed. weakref.ReferenceError is now a built-in exception.
unicode(obj) now behaves more like str(obj), accepting arbitrary objects, and calling a __unicode__ method if it exists. unicode(obj, encoding) and unicode(obj, encoding, errors) still require an 8-bit string or character buffer argument.
isinstance() now allows any object as the first argument and a class, a type or something with a __bases__ tuple attribute for the second argument. The second argument may also be a tuple of a class, type, or something with __bases__, in which case isinstance() will return true if the first argument is an instance of any of the things contained in the second argument tuple. E.g.
isinstance(x, (A, B))
returns true if x is an instance of A or B.
doctest now excludes functions and classes not defined by the module being tested, thanks to Tim Hochberg.
HotShot, a new profiler implemented using a C-based callback, has been added. This substantially reduces the overhead of profiling, but it is still quite preliminary. Support modules and documentation will be added in upcoming releases (before 2.2 final).
profile now produces correct output in situations where an exception raised in Python is cleared by C code (e.g. hasattr()). This used to cause wrong output, including spurious claims of recursive functions and attribution of time spent to the wrong function.
The code and documentation for the derived OldProfile and HotProfile profiling classes was removed. The code hasn't worked for years (if you tried to use them, they raised exceptions). OldProfile intended to reproduce the behavior of the profiler Python used more than 7 years ago, and isn't interesting anymore. HotProfile intended to provide a faster profiler (but producing less information), and that's a worthy goal we intend to meet via a different approach (but without losing information).
Profile.calibrate() has a new implementation that should deliver a much better system-specific calibration constant. The constant can now be specified in an instance constructor, or as a Profile class or instance variable, instead of by editing profile.py's source code. Calibration must still be done manually (see the docs for the profile module).
Note that Profile.calibrate() must be overridden by subclasses. Improving the accuracy required exploiting detailed knowledge of profiler internals; the earlier method abstracted away the details and measured a simplified model instead, but consequently computed a constant too small by a factor of 2 on some modern machines.
quopri's encode and decode methods take an optional header parameter, which indicates whether output is intended for the header 'Q' encoding.
The SocketServer.ThreadingMixIn class now closes the request after finish_request() returns. (Not when it errors out though.)
The nntplib module's NNTP.body() method has grown a 'file' argument to allow saving the message body to a file.
The email package has added a class email.Parser.HeaderParser which only parses headers and does not recurse into the message's body. Also, the module/class MIMEAudio has been added for representing audio data (contributed by Anthony Baxter).
ftplib should be able to handle files > 2GB.
ConfigParser.getboolean() now also interprets TRUE, FALSE, YES, NO, ON, and OFF.
xml.dom.minidom NodeList objects now support the length attribute and item() method as required by the DOM specifications.
Installer: If you install IDLE, and don't disable file-extension registration, a new "Edit with IDLE" context (right-click) menu entry is created for .py and .pyw files.
The signal module now supports SIGBREAK on Windows, thanks to Steven Scott. Note that SIGBREAK is unique to Windows. The default SIGBREAK action remains to call Win32 ExitProcess(). This can be changed via signal.signal(). For example:
# Make Ctrl+Break raise KeyboardInterrupt, like Python's default Ctrl+C # (SIGINT) behavior. import signal signal.signal(signal.SIGBREAK, signal.default_int_handler) try: while 1: pass except KeyboardInterrupt: # We get here on Ctrl+C or Ctrl+Break now; if we had not changed # SIGBREAK, only on Ctrl+C (and Ctrl+Break would terminate the # program without the possibility for any Python-level cleanup). print "Clean exit"
Release date: 28-Sep-2001
Release Date: 07-Sep-2001
Conversion of long to float now raises OverflowError if the long is too big to represent as a C double.
The 3-argument builtin pow() no longer allows a third non-None argument if either of the first two arguments is a float, or if both are of integer types and the second argument is negative (in which latter case the arguments are converted to float, so this is really the same restriction).
The builtin dir() now returns more information, and sometimes much more, generally naming all attributes of an object, and all attributes reachable from the object via its class, and from its class's base classes, and so on from them too. Example: in 2.2a2, dir([]) returned an empty list. In 2.2a3,
>>> dir([]) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__eq__', '__ge__', '__getattr__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
dir(module) continues to return only the module's attributes, though.
Overflowing operations on plain ints now return a long int rather than raising OverflowError. This is a partial implementation of PEP 237. You can use -Wdefault::OverflowWarning to enable a warning for this situation, and -Werror::OverflowWarning to revert to the old OverflowError exception.
A new command line option, -Q<arg>, is added to control run-time warnings for the use of classic division. (See PEP 238.) Possible values are -Qold, -Qwarn, -Qwarnall, and -Qnew. The default is -Qold, meaning the / operator has its classic meaning and no warnings are issued. Using -Qwarn issues a run-time warning about all uses of classic division for int and long arguments; -Qwarnall also warns about classic division for float and complex arguments (for use with fixdiv.py). [Note: the remainder of this item (preserved below) became obsolete in 2.2c1 -- -Qnew has global effect in 2.2]
Using -Qnew is questionable; it turns on new division by default, but only in the __main__ module. You can usefully combine -Qwarn or -Qwarnall and -Qnew: this gives the __main__ module new division, and warns about classic division everywhere else.
Many built-in types can now be subclassed. This applies to int, long, float, str, unicode, and tuple. (The types complex, list and dictionary can also be subclassed; this was introduced earlier.) Note that restrictions apply when subclassing immutable built-in types: you can only affect the value of the instance by overloading __new__. You can add mutable attributes, and the subclass instances will have a __dict__ attribute, but you cannot change the "value" (as implemented by the base class) of an immutable subclass instance once it is created.
The dictionary constructor now takes an optional argument, a mapping-like object, and initializes the dictionary from its (key, value) pairs.
A new built-in type, super, has been added. This facilitates making "cooperative super calls" in a multiple inheritance setting. For an explanation, see http://www.python.org/2.2/descrintro.html#cooperation
A new built-in type, property, has been added. This enables the creation of "properties". These are attributes implemented by getter and setter functions (or only one of these for read-only or write-only attributes), without the need to override __getattr__. See http://www.python.org/2.2/descrintro.html#property
The syntax of floating-point and imaginary literals has been liberalized, to allow leading zeroes. Examples of literals now legal that were SyntaxErrors before:
00.0 0e3 0100j 07.5 00000000000000000008.
An old tokenizer bug allowed floating point literals with an incomplete exponent, such as 1e and 3.1e-. Such literals now raise SyntaxError.
New function PyObject_Dir(obj), like Python __builtin__.dir(obj).
Note that PyLong_AsDouble can fail! This has always been true, but no callers checked for it. It's more likely to fail now, because overflow errors are properly detected now. The proper way to check:
double x = PyLong_AsDouble(some_long_object); if (x == -1.0 && PyErr_Occurred()) { /* The conversion failed. */ }
The GC API has been changed. Extensions that use the old API will still compile but will not participate in GC. To upgrade an extension module:
- rename Py_TPFLAGS_GC to PyTPFLAGS_HAVE_GC
- use PyObject_GC_New or PyObject_GC_NewVar to allocate objects and PyObject_GC_Del to deallocate them
- rename PyObject_GC_Init to PyObject_GC_Track and PyObject_GC_Fini to PyObject_GC_UnTrack
- remove PyGC_HEAD_SIZE from object size calculations
- remove calls to PyObject_AS_GC and PyObject_FROM_GC
Two new functions: PyString_FromFormat() and PyString_FromFormatV(). These can be used safely to construct string objects from a sprintf-style format string (similar to the format string supported by PyErr_Format()).
Release Date: 22-Aug-2001
Release date: 18-Jul-2001
TENTATIVELY, a large amount of code implementing much of what's described in PEP 252 (Making Types Look More Like Classes) and PEP 253 (Subtyping Built-in Types) was added. This will be released with Python 2.2a1. Documentation will be provided separately through http://www.python.org/2.2/. The purpose of releasing this with Python 2.2a1 is to test backwards compatibility. It is possible, though not likely, that a decision is made not to release this code as part of 2.2 final, if any serious backwards incompatibilities are found during alpha testing that cannot be repaired.
Generators were added; this is a new way to create an iterator (see below) using what looks like a simple function containing one or more 'yield' statements. See PEP 255. Since this adds a new keyword to the language, this feature must be enabled by including a future statement: "from __future__ import generators" (see PEP 236). Generators will become a standard feature in a future release (probably 2.3). Without this future statement, 'yield' remains an ordinary identifier, but a warning is issued each time it is used. (These warnings currently don't conform to the warnings framework of PEP 230; we intend to fix this in 2.2a2.)
The UTF-16 codec was modified to be more RFC compliant. It will now only remove BOM characters at the start of the string and then only if running in native mode (UTF-16-LE and -BE won't remove a leading BMO character).
Strings now have a new method .decode() to complement the already existing .encode() method. These two methods provide direct access to the corresponding decoders and encoders of the registered codecs.
To enhance the usability of the .encode() method, the special casing of Unicode object return values was dropped (Unicode objects were auto-magically converted to string using the default encoding).
Both methods will now return whatever the codec in charge of the requested encoding returns as object, e.g. Unicode codecs will return Unicode objects when decoding is requested ("äöü".decode("latin-1") will return u"äöü"). This enables codec writer to create codecs for various simple to use conversions.
New codecs were added to demonstrate these new features (the .encode() and .decode() columns indicate the type of the returned objects):
Name |
.encode() |
.decode() |
Description |
---|---|---|---|
uu |
string |
string |
UU codec (e.g. for email) |
base64 |
string |
string |
base64 codec |
quopri |
string |
string |
quoted-printable codec |
zlib |
string |
string |
zlib compression |
hex |
string |
string |
2-byte hex codec |
rot-13 |
string |
Unicode |
ROT-13 Unicode charmap codec |
Some operating systems now support the concept of a default Unicode encoding for file system operations. Notably, Windows supports 'mbcs' as the default. The Macintosh will also adopt this concept in the medium term, although the default encoding for that platform will be other than 'mbcs'.
On operating system that support non-ASCII filenames, it is common for functions that return filenames (such as os.listdir()) to return Python string objects pre-encoded using the default file system encoding for the platform. As this encoding is likely to be different from Python's default encoding, converting this name to a Unicode object before passing it back to the Operating System would result in a Unicode error, as Python would attempt to use its default encoding (generally ASCII) rather than the default encoding for the file system.
In general, this change simply removes surprises when working with Unicode and the file system, making these operations work as you expect, increasing the transparency of Unicode objects in this context. See [????] for more details, including examples.
Float (and complex) literals in source code were evaluated to full precision only when running from a .py file; the same code loaded from a .pyc (or .pyo) file could suffer numeric differences starting at about the 12th significant decimal digit. For example, on a machine with IEEE-754 floating arithmetic,
x = 9007199254740992.0 print long(x)
printed 9007199254740992 if run directly from .py, but 9007199254740000 if from a compiled (.pyc or .pyo) file. This was due to marshal using str(float) instead of repr(float) when building code objects. marshal now uses repr(float) instead, which should reproduce floats to full machine precision (assuming the platform C float<->string I/O conversion functions are of good quality).
This may cause floating-point results to change in some cases, and usually for the better, but may also cause numerically unstable algorithms to break.
The implementation of dicts suffers fewer collisions, which has speed benefits. However, the order in which dict entries appear in dict.keys(), dict.values() and dict.items() may differ from previous releases for a given dict. Nothing is defined about this order, so no program should rely on it. Nevertheless, it's easy to write test cases that rely on the order by accident, typically because of printing the str() or repr() of a dict to an "expected results" file. See Lib/test/test_support.py's new sortdict(dict) function for a simple way to display a dict in sorted order.
Many other small changes to dicts were made, resulting in faster operation along the most common code paths.
Dictionary objects now support the "in" operator: "x in dict" means the same as dict.has_key(x).
The update() method of dictionaries now accepts generic mapping objects. Specifically the argument object must support the .keys() and __getitem__() methods. This allows you to say, for example, {}.update(UserDict())
Iterators were added; this is a generalized way of providing values to a for loop. See PEP 234. There's a new built-in function iter() to return an iterator. There's a new protocol to get the next value from an iterator using the next() method (in Python) or the tp_iternext slot (in C). There's a new protocol to get iterators using the __iter__() method (in Python) or the tp_iter slot (in C). Iterating (i.e. a for loop) over a dictionary generates its keys. Iterating over a file generates its lines.
The following functions were generalized to work nicely with iterator arguments:
map(), filter(), reduce(), zip() list(), tuple() (PySequence_Tuple() and PySequence_Fast() in C API) max(), min() join() method of strings extend() method of lists 'x in y' and 'x not in y' (PySequence_Contains() in C API) operator.countOf() (PySequence_Count() in C API) right-hand side of assignment statements with multiple targets, such as :: x, y, z = some_iterable_object_returning_exactly_3_values
Accessing module attributes is significantly faster (for example, random.random or os.path or yourPythonModule.yourAttribute).
Comparing dictionary objects via == and != is faster, and now works even if the keys and values don't support comparisons other than ==.
Comparing dictionaries in ways other than == and != is slower: there were insecurities in the dict comparison implementation that could cause Python to crash if the element comparison routines for the dict keys and/or values mutated the dicts. Making the code bulletproof slowed it down.
Collisions in dicts are resolved via a new approach, which can help dramatically in bad cases. For example, looking up every key in a dict d with d.keys() == [i << 16 for i in range(20000)] is approximately 500x faster now. Thanks to Christian Tismer for pointing out the cause and the nature of an effective cure (last December! better late than never).
repr() is much faster for large containers (dict, list, tuple).
(For information about older versions, consult the HISTORY file.)