Appendix C. What's New in Python 3.1

Python is constantly changing in little ways. Python 3.1 has evolved from version 2.6, but it contains important changes. This appendix introduces you to the changes relevant to the topics covered in this book. This means that this is not an exhaustive treatment by any means but only a selection of topics touched on in the book — topics that you may want to know as someone new to Python.

You can find the official list of changes to Python 3.1 at http://docs.python.org/3.1/whatsnew/3.1.html. If a newer version of Python is available by the time you read this, you can find the list of changes for that version on the Python website as well.

Print Is Now a Function

In the olden days of yore, print was a statement. With version 3.1, it has reached the major leagues and is now a bonafide function — specifically, print().

Certain APIs Return Views and Iterators

The following no longer return lists, but instead return views and iterators:

  • The dict methods — dict.keys(), dict.items(), and dict.values. You will also note that dict.iterkeys(), dict.iteritems(), and dict.itervalues() are no longer supported methods in Python.

  • Both map() and filter() return iterators instead of lists.

  • The range() method has replaced xrange() and is used in the same manner.

  • The zip() method is now used to return an iterator.

Integers

The long data type has been renamed to int (basically the only integral type is now int). It works in roughly the same manner as the long type did. Integers no longer have a limit, and as such, sys.maxint has been deprecated. In addition, when dividing numbers such as 2/4, you will be given a float. If you want to have the results truncated, you can still use 2//4.

Unicode and 8-bit

Unicode and 8-bit strings have been replaced with text and binary data. All text is considered to be Unicode, but the encoded Unicode is now presented as strictly binary data. Hence, text is stored in str, whereas data is stored in bytes. If you should ever try to mix these two data types, it will result in the raising of a TypeError. If you want to mix str and bytes, you must convert them. If you wanted to, for instance, convert a byte to a str, you would use bytes.decode(). To go from a str to a byte, you would likewise use str.encode().

Another change is how you work with literals. The use of u"..." literals for Unicode text has been removed entirely, while the use of b"..." literals for binary data is still usable.

There are many changes to Unicode and 8-bit — far more than I could cover here. See the section on Unicode and 8-bit at the What's New page here: http://docs.python.org/dev/py3k/whatsnew/3.1.html.

Exceptions

The use of raise exception has been replaced. You no longer write it as raise Exception, "I take exception to that!" Instead you would use the following:

exception("I take exception to that!")

Similarly, if you wish to catch an exception, you write it in the following manner:

try:
a=int("hotdog")
except ValueError as oops:
print("ValueError has occurred ", oops)

This would return the result:

ValueError has occurred  invalid literal for int() with base 10: 'hotdog'

Other changes to exceptions exist as well. For instance, all exception objects use the __traceback__ attribute to store the value of the traceback. Additionally, the StandardError was removed.

Classes

Old-style classes have been removed entirely from Python 3.1. This leaves us with a simple, single object model based on new-style classes. Definitions for these classes are similar to their previous versions, however, object is now implicitly a superclass.

Comparisons, Operators, and Methods

There are several changes that have been made to the way comparison operators work in Python 3.1. For starters, comparisons have to make logical sense now. For example, you cannot use 0>none. In past versions this would have returned False, but since you cannot compare zero to nothing, it now returns an error.

The function cmp() and the method __cmp__() have both been removed.

As for Operators, they have experienced the following changes:

  • Unbound methods have been removed.

  • The operator !=now returns the complete opposite of ==.

  • Next() has been renamed and is now __next()__

  • The following have all been removed: __delitem__(), __getslice__(), __hex__(), __members__, __methods__, __oct__(), and __setslice__().

Syntactical Changes

There are many syntax changes in Python 3.1. Again, this list is too much to cover in the limited space we have here, but the following changes are some of the more important ones.

The keywords as, with, True, False, and None have become reserved words.

When working with Metaclasses, it is important to note that the old method

Class Example:
    __metaclass__ = Apple
...

is no longer valid. Instead you would write:

Class Example(metaclass=Apple):
...

In addition, the module-global __metaclass__ variable has been removed.

The old method for writing list comprehensions was to use:

[for var in example1, example2, example 3]

This has now changed to:

[for var in (example1, example2, example3)]

The old standby <> has been removed and replaced with !=.

Both string literals and integer literals have been changed. String literals no longer accept the leading u and U, while integer literals no longer accept the leading l or L.

The keyword exec() has been removed, though it still functions as a function.

Packages and Modules

The following modules have been removed from Python 3.1. Note that this is not a complete list:

  • cfmfile

  • cl

  • md5 and sha (replaced with hashlib)

  • mimetools, MimeWriter, mimify, multifile, and rfc822 (replaced with the e-mail package)

  • posixfile

  • sv

  • timing (use time.clock instead)

  • Canvas

  • commands and popen2 (replaced with subprocess)

  • compiler

  • dircache

  • dl

  • fpformat

  • htmllib (replaced with HTMLParser)

  • mhlib (replaced with mailbox)

  • stat (changed to os.stat)

  • urllib (replaced with urllib2)

In addition, the following modules have been renamed:

  • _winreg is now winreg

  • ConfigParser is now configparser

  • copy_reg is now copyreg

  • Queue is now queue

  • SocketServer is now socketserver

  • markupbase is now _markupbase

  • repr is now reprlib

  • test.test_support is now test.support

To make things simpler, Python 3.1 has also gathered some similar modules and grouped them into a single package. They are listed below:

  • dbm now contains: anydbm, dbhash, dbm, dumbdbm, gdbm, and whichdb.

  • html now contains: HTMLParser andhtmlentitydefs.

  • http now contains: httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, and cookielib.

  • tkinter now contains every Tkinter-related module with the sole exception of turtle.

  • urllib now contains urllib, urllib2, urlparse, and robotparse.

  • xmlrpc now contains xmlrpclib, DocXMLRPCServer, and SimpleXMLRPCServer.

Builtins

The following builtins were removed:

  • apply()

  • callable()

  • coerce()

  • execfile()

  • the file type

  • reduce()

  • reload()

  • dict.has_key()

In addition, raw_input() has been changed to input().

The 2to3 Tool

While not an end all be all to converting your Python 2x code to 3x, the 2to3 tool can certainly help in many areas. Basically, what the program does is take your existing code and apply a set of fixers to it, transforming old code into new. For instance, if you were to run 2to3 on the following code:

print "Hi, my name is James and I am a Pythonaholic"

It would convert it to:
print("Hi, my name is James and I am a Pythonaholic")

Pretty nifty right? There are, of course, many caveats for using the tool. First and foremost, the code you run it against must work properly, so you will want to rigorously test your Python 2x code to ensure there are no errors. Next, you must note that 2to3 will not fix everything; there are some things it has not been programmed to convert. For these things, 2to3 will print a warning, which you will need to manually change.

For more information on using 2to3 and documentation on its fixers, visit the Python documentation at http://docs.python.org/dev/py3k/library/2to3.html#to3-reference.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.72.245