Programmare in Python - Parte 16

Testo originale

A while ago, I promised someone that I would discuss the differences between Python 2.x and 3.x. Last time, I said that we would continue our pygame programming, but I felt that I should keep my promise, so we'll delve into pygame more next time.

Many changes have gone into Python 3.x. There is a large amount of information about these changes on the Web, and I'll include a few links at the end of the article. There are also many concerns about making the change. I'm going to concentrate on changes that affect the things you've learned so far.

Let's get started.

PRINT

As I've said before, one of the most important issues is the way we deal with the Print command. Under 2.x we simply can use:

print “This is a test”

and be done with it. However under 3.x, if we try that we will get the error message shown above right.

Not happy. In order to use the print command, we must put what we want to print in parentheses like this:

print(“this is a test”)

Not a very big change, but something we have to be aware of. You can get ready for your own migration by using this syntax under python 2.x.

Formatting and variable substitution

Formatting and variable substitution have also changed. Under 2.x, we have used things like the example shown below left, and, under 3.1, you can get the proper result. However, that is due to change since the '%s' and '%d' formatting functions are going away. The new way is to use '{x}' replacement statements is shown below.

It seems to me to be actually easier to read. You can also do things like this:

>>> print("Hello {0}. I'm glad you are here at {1}".format("Fred","MySite.com"))

Hello Fred. I'm glad you are here at MySite.com

>>>

Remember, you can still use '%s' and so on, but they will be going away.

Numbers

Under Python 2.x, if you did: x = 5/2.0 x would contain 2.5. However if you did: x = 5/2 x would contain 2 due to truncation. Under 3.x, if you do: x = 5/2 you still get 2.5. To truncate the division you have to do: x = 5//2

INPUT

A while back, we dealt with a menu system that used raw_input() to get a response from the user of our application. It went something like this:

response = raw_input('Enter a selection -> ')

That was fine under 2.x. However, under 3.x we get:

Traceback (most recent call last):

NameError: name 'raw_input' is not defined

This isn't a big issue. The raw_input() method has been replaced with input(). Simply change the line to:

response = input('Enter a selection -> ')

and it works just fine.

Not Equal

Under 2.x, we could test for ‘not equal’ with “<>”. However, that's not allowed in 3.x The test operator is now “!=”.

Converting older programs to Python 3.x

Python 3.x comes with a utility to help convert a 2.x application to 3.x compliant code. This doesn't always work, but it will get you close in many cases. The conversion tool is named (aptly) “2to3”. Let's take a really simple program as an example. The example below is from way back in Beginning Python Part 3.

When run under 2.x, the output looks like that shown above right.

Of course, when we run it under 3.x, it doesn't work.

SyntaxError: invalid syntax

We'll try to let the conversion app fix it for us. First, we should create a backup of our application that will be converted. I do it by creating a copy of the file, and append a “v3” to the end of the filename:

cp pprint1.py pprint1v3.py

There's multiple ways to run the app. The simplest way is just to let the app check our code and tell us where the problems are, which is shown below left.

Notice that the original source code is not changed. We have to use the “-w” flag to tell it to write the changes to the file. This is shown below right.

You'll also notice that the output is the same. This time, however, our source file (shown on the next page) is changed to a “version 3.x compatible” file.

Now the program works as it is supposed to under 3.x. And, since it was simple, it still runs under version 2.x as well.

Do I switch to 3.x now?

Most of the issues are common to any change in a programming language. Syntax changes abound with every new version. Short cuts like += or -= sometimes come out of the blue and actually make our lives easier.

What's the downside to simply migrating to 3.x right now? Well, there's a little bit. Many of the library modules that we've used are not available for version 3.x right now. Things like Mutegen that we've used a few articles back just aren't available yet. While this is a stumbling block, it doesn't require you to completely give up on Python v3.x.

My suggestion is to start coding using proper 3.x syntax now. Python version 2.6 supports almost everything you would need to write in the 3.x way. This way, you will be good to go once you have to change to 3.x. If you can live with the standard module library, go ahead and make the plunge. If, on the other hand, you push the envelope, you might just want to wait until the module library catches up. It will.

Below are some links that I thought might be helpful. The first is to the usage page of 2to3. The second is a 4-page cheat sheet that I have found to be a very good reference. The third is to what I consider to be just about the best book on using Python. (That is until I get around to writing mine.)

We'll see you next time.

Links

2to3 usage http://docs.python.org/library/2to3.html

Moving from Python 2 to Python 3 (A 4 page cheat sheet) http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/promotions/python/python2python3.pdf

Dive into Python 3 http://diveintopython3.org/

Traduzione italiana

Incollare la traduzione qui al posto di questa riga e anche nel paragrafo "Revisione".

Revisione

Incollare la revisione qui al posto di questa riga.


CategoryHomepage

MarcoBuono/Prova02 (l'ultima modifica è del 09/06/2011 09.39.45, fatta da AldoLatino)