Improve usage of Python 3

Chris Angelico rosuav at gmail.com
Wed Jul 15 03:40:14 EDT 2015


On Wed, Jul 15, 2015 at 2:28 AM, Marcos <bugshideout at gmail.com> wrote:
> And incredibly, there are a few users on the same project who refuse to use
> python 3 simply because of the print statement.

Solution: Explain to them the massive benefits of the print function.
It may be simpler to omit the parentheses in the case where you just
want to print out a single string, but for pretty much everything
else, the function is at least as good.

# I can never remember the syntax for this, and
# have to look it up every time. Can you put the
# file reference at the end? Or only at the start?
print >>sys.stderr, "Hello, world!"

# Keyword-only argument, exactly the way every
# other Python function operates
print("Hello, world!", file=sys.stderr)

# Separated by spaces
print "Hello", "world", "!"

# Separated by spaces
print("Hello", "world", "!")

# Separated by something other than space
# Again, keyword-only args, nice and easy
print("Hello", "world", "!", sep="*")

# No newline at the end: magic
print "Hello, world!",
# Hard to explain the exact semantics of the
# soft space and what happens if you mix
# print and sys.stdout.write(), not to mention
# sys.stderr.write() when they're both attached
# to the same console

# No newline at the end: no magic
print("Hello, world!", end="")

# Need to define a shim function to pass elsewhere
def Print(x):
    print x
walk(tree, Print)
def print_with_star(x):
    print x, "*"
walk(tree, print_with_star)

# Can just use print directly, or use lambda
walk(tree, print)
walk(tree, lambda x: print(x, end="*\n"))

The function is well worth it. Teach people the new way, don't try to
warp the language around maintaining an old way of doing things.
There's really no reason for console output to have magic syntax.

ChrisA



More information about the Python-list mailing list