What's new in Python 3

Clean-Up Work

Wherever changes occur, it is also necessary to ditch some ballast. This affects libraries that have been removed, that have been repackaged, or that coexist in C and Python implementations. The popular Python idiom (Listing 4) of importing the fast C implementation of a module first and then falling back on the Python implementation if this fails is no longer necessary. Python does this automatically. More details are available on changes to the standard library [11].

Listing 4

Import Idiom

01 try:
02    import cPickle as pickle
03 except ImportError:
04    import pickle

All exceptions must derive from BaseException. This implies, in particular, that string exceptions are no longer supported. The exception object now has a new __traceback__ attribute, which contains the traceback of the exception. The approach to both calling and fielding exceptions with arguments has changed. Programmers can now throw exceptions with arguments using raise BaseException(args) and field them with except BaseException as variable (Figure 3).

Figure 3: The new traceback attribute for exceptions.

Python 3 also includes other changes to make life easier for programmers. For example, in cooperative super calls, it is no longer necessary to name the class instance and the class name. Old-style classes, which were deprecated at some previous time, no longer exist in Python 3.0; this removes the need to derive from object to use Python's newer features.

Direct evaluation of input via the input() command is no longer supported, as the input is available as an input string. This approach closes a critical security hole (Figure 4). It was only logical to rename the raw_input() function input() and to remove raw_input.

Figure 4: Direct evaluation of input via the input command is no longer supported in Python 3.

Of course, any description of the new features can't hope to be exclusive. If you want to know more, check out the reference document by von Rossum, "What's New In Python 3.0" [12].

Porting to Python 3.0

A clear migration path is available for porting Python 2 code to Python 3 (Figure 5), but you will need to test the code and fix any bugs at each step of the way.

Figure 5: The recommended migration path for porting Python 2.6 code to version 3.

The four lines of code in Listing 5 will serve as an example for migrating Python 2 to Python 3.0. All four lines defined functional components of Python. The first function calculates the sum of three numbers, 2, 3, and 4, by applying these arguments to the Lambda function. The reduce built-in successively reduces the list of all numbers from 1 to 10 by multiplying the results of the last multiplication with the next number in the sequence. The last two functions filter words, starting with filtering uppercase letters out of a string.

Listing 5

Code for Port

01 print "sum of the integers: " , apply(lambda a,b,c: a+b+c , (2,3,4))
02 print "factorial of 10 :", reduce(lambda x,y: x*y, range(1,11) )
03 print "titles in text: ", filter( lambda word: word.istitle(),"This is a long Test".split())
04 print "titles in text: ", [ word for word in "This is a long Test".split() if word.istitle()]

The code works on Python 2.6, and you only need to perform Steps 3 and 4 for the port. The source code for this example is stored in a file called port.py.

Calling the Python 2.6 interpreter with the -3 option (Figure 6) shows incompatibilities with version 3: Both the apply function and the reduce function are no longer built-ins in Python 3.0. The code is easily fixed (Listing 6), and the deprecation warnings then stop.

Figure 6: The Python 3 option in v.2.6 points to issues with the port.

Listing 6

Removing the Deprecation Warning

01 print "sum of the integers: " , (lambda a,b,c: a+b+c)(*(2,3,4))
02 import functools
03 print "factorial of 10 :", functools.reduce(lambda x,y: x*y, range(1,11) )
04 print "titles in text: ", filter( lambda word: word.istitle(),"This is a long Test".split())
05 print "titles in text: ", [ word for word in "This is a long Test".split() if word.istitle()]

The code generator 2to3 is really useful if you need to correct your Python 2 code; the generator's final step is to automatically generate code for versions 3.0 and 3.1. The tool offers several options for this (Figure 7). The direct approach is to overwrite the original file: 2to3 port.py -w. The result is the ported source code for Python 3.0 (Listing 7).

Figure 7: The 2to3 code generator has a large number of options.

Listing 7

Code Ported to Python 3.0

01 print("sum of the integers: " , (lambda a,b,c: a+b+c)(*(2,3,4)))
02 print("factorial of 10 :", reduce(lambda x,y: x*y, list(range(1,11)) ))
03 print("titles in text: ", [word for word in "This is a long Test".split() if word.istitle()])
04 print("titles in text: ", [ word for word in "This is a long Test".split() if word.istitle()])

When to Make the Move

Python 3.0 originally placed more emphasis on functionality, and this meant that it was about 10 percent slower than Python 2. The required optimization occurred in Python 3.1 [13]. This optimization relates to special handling of small integers. On top of this, Python 3.1's I/O library is implemented in C, which makes it between 2 and 20 times faster. Decoding of the UTF-8, UTF-16, and Latin-1 character sets is now twice to four times as fast.

If you are still waiting for third-party libraries to be ported, there is no point porting your application code to Python 3. von Rossum also recommends [14] not writing any code that will run on both Python 2.6 and Python 3 without modifications. It is preferable to maintain the source code as Python 2.6 code and then use automated tools to port to Python 3.0 or 3.1. Christopher Neugebauer has the final word in his video talk on Python 3000: "Learn 2.6, but keep 3k in mind."

The Author

Rainer Grimm has been a software developer since 1999 at Science + Computing AG in Tübingen, Germany. In particular, he holds training sessions for the in-house product SC Venus.

Read full article as PDF:

042-045_python.pdf (408.84 kB)

Related content

  • Optimizing Python

    The trick to optimization is to save time in the right places.

  • Boo

    Hooked on Python's "wrist-friendly" syntax? Enamored of .NET architecture but equally appreciative of C#'s strong typing? Boo offers the best of three worlds.

  • Dotnet Scripting with Boo

    Boo is a scripting language tailor-made for Mono and .NET. This haunting mixture of Python and C# may be just what you need to get started with the .NET framework.

  • Workspace: EasyGUI

    If you need to add graphical elements to Python script, EasyGUI can help beginners and experts alike.

  • Practical Python in Linux

    We’ll introduce you to Python, an easy-to-learn scripting language, and also help you get started creating your own practical Python scripts.

Comments

  • It is not named as snake, but you missed the point

    The title of the article does not have anything to do with what inspired or not the creator of this language. The above comment just demonstrates the most ridiculous and basic lacking of any creativity or humor and denotes a very primitive and intolerant mind, which does not seem to even have noticed that the logo of Python is that of a SNAKE and not exactly a picture of Monty Python.

    The article is very good.

    Sadly, for some people it is easier to destroy and insult than to be creative and positive about anything.
  • Ancestor python

    Yeah so what if it was not named after a snake. Monty Python's ancestors derived their surname from the python snake itself which was commonly found in their area where they originated from; so it's still from the snake. Heh heh!
  • Python is not named after a snake

    It's hard to imagine how the author could get this so fundamentally wrong. Hear this: Python is not named after the snake; it's named after Monty Python, as any cursory survey of its history will reveal.
comments powered by Disqus

Direct Download

Read full article as PDF:

042-045_python.pdf (408.84 kB)

News

njobs Europe
What:
Where:
Country:
Njobs Netherlands Njobs Deutschland Njobs United Kingdom Njobs Italia Njobs France Njobs Espana Njobs Poland
Njobs Austria Njobs Denmark Njobs Belgium Njobs Czech Republic Njobs Mexico Njobs India Njobs Colombia