Thursday, December 27, 2012

print() and win.print()

Python vs Brython vs Javacript


Before Python 3, print was a keyword, and not a function. With Python 3, print() is a built-in function.

Brython follows the syntax of Python 3, so one would expect a print() function. However that since its inception, it has been suggested that print() didn't make sense in the context of a web browser, and to use log() instead. win.print() was the call to the window.print() Javascript equivalent:

Javascript has a print() function too. It is actually a method of window, and brings up a print dialog to print a web page from a web browser.

The lightbulb moment

I didn't see it coming, but as Pierre was working with the Brython demo console (and I'm guessing from feedback from people who got confused by it) and thought that perhaps print() wasn't such a bad idea after all.

And here's what he came up with:
- for standard output there was a Brython-specific builtin function log() : it is now replaced by the usual Python function print(), with the syntax used in Python 3, including the keyword argument "end"
By default, print() sends its arguments to the browser console. This can be changed by setting sys.stdout to an object with a method write(). For instance, in the online console, to send the output to the textarea with the id "console" the code is (remember that classes are not implemented yet...)


import sys
sys.stdout = object()
def write(data):
    doc["console"].value += data
sys.stdout.write = write

Errors can also be redirected using sys.stderr

sys.stderr = object()
sys.stderr.write = write

But what about the javascript functionality of print(), did we loose that at the same time?

Thankfully, Pierre didn't hardwire conversion of keywords without keeping in mind the scope, and that means that the following works:


<!DOCTYPE html>
<html>
    <head>
        <title>Brython test</title>
        <script src="brython.js"></script>
    </head>
    <body onLoad="brython()">
        <script type="text/python">
        def printandprint():
            print("hello")
            win.print()

        doc <= BUTTON('Print and print', onClick='printandprint()')
        </script>
    </body>
</html>

You'll see in your debug console the word hello printed through print("hello"), and a print dialog will open when win.print() is called.

Try it:
 

No comments: