February 18, 2010

A Python 3 Idiom?

A while ago I wrote a short Python 3 snippet as an introduction to a post about factory functions. Second thoughts are proverbially the best, and I realised that in the following code:

def powers(a):
    return a, a*a, a*a*a

a, square, cube = powers(10)
print(a, square, cube)

the last two lines could be refactored as:
print(*powers(10))

This technique is ineffective in Python 2, where print is a statement and the syntax would be invalid.

7 comments:

Anonymous said...

Python 3 just cleans off those little last ugly bits of Python. Lovely.

tshirtman said...

well, in python 2.5, the following works...

print powers(10)

not much of a difference... ;)

tshirtman said...

forget it, I read to fast, your point is valid. sorry.

ShadyTyrant said...

Nice find!

নাসিম said...

print(powers(10))

works fine in python 2.5, 2.6. Why it shouldn't be used that way?

Steve said...

@নাসিম: That will produce output, but the output it produces will be the strr() of the resulting tuple, including the parentheses and commas.

In Python 3 the elegant syntax for tuple expansion passes each value as an individual argument to print(), and each value returned appears as a number.

Even if you have redefined the print() function (as one can validly do in Python 3) the updated function will operate correctly.

Wayne Witzel III said...

You can use this import in 2.6 to run the code.

from __future__ import print_function