Python Programing for the Absoulte Beginner

Chris Angelico rosuav at gmail.com
Sat Aug 2 18:55:31 EDT 2014


On Sun, Aug 3, 2014 at 8:41 AM, Seymore4Head
<Seymore4Head at hotmail.invalid> wrote:
>>If the book is for Python 2 and you have 3.3 it should be print("Game Over")
>
> Thanks
>
> I am sure they had a good reason to add using 2 more characters for
> doing the same job.

One more, since you'll normally have a space after the word "print" anyway. :)

Language keywords are inflexible. Sure, it's nice and simple to do
straightforward output, but when you want to send that to stderr
instead of stdout, or change the separator between args, or change
what's at the end of what's printed (a newline, normally), or anything
like that, there needs to be special magical syntax added. Plus, it's
nearly impossible to do a simple replacement of print with something
else; pretty much the only way is to play with the code as it's being
compiled. With a function, all that is fixed; there are standard ways
of providing extra information (keyword arguments), you can replace
print with any other function just by shadowing it, and all this can
be done with perfectly normal syntax. This is how to tee print to a
file as well as stdout:

log_file = open("print.log","w")
orig_print = print
def print(*args, **kw):
    if "file" not in kw: orig_print(*args, **kw, file=log_file)
    orig_print(*args, **kw)

So easy! You can grab a reference to the original print functionality
with ordinary assignment (functions can be passed around and
referenced by names; statements can't), you can replace it just by
creating something else of the same name, and all its magic just comes
through as arguments.

There has been a move, now and then, to allow parens-free function
calls. If some such scheme were accepted, you could then use the
Python 2 syntax, and it would call the function; additionally, you
could use the shorthand for any other function, too - "sys.exit 1" for
instance. So far, there hasn't been a proposal that's satisfied all
the requirements and given a compelling argument for acceptance, but I
don't think the Python devs are philosophically opposed to the
concept.

ChrisA



More information about the Python-list mailing list