. Python 2.1 function attributes

Jeff Petkau jpet at eskimo.com
Sun Jan 28 05:39:33 EST 2001


Barry A. Warsaw <barry at digicool.com> wrote in message
news:mailman.980662113.14859.python-list at python.org...
>
>     JD> Perhaps if "print >> file, something" were written as "print
>     JD> to file, something" there wouldn't be so much controversy over
>     JD> it, even though it wouldn't be doing more or less than it does
>     JD> today.
>
> We tried it.  Using an identifier in that spot caused irreconcilable
> syntactic ambiguities, so we had to pick a non-identifier.  After
> extensive market research <wink> `>>' was picked because it had the

The following seems to work fine for 'print to', even if you insist
on naming your variables 'to'.

In Grammar/Grammar
    print_stmt: 'print' test [test] [',' test]+ [',']

In compile.c:

/* return true if the given test is in fact just a name matching str */
static int
is_literal_test(node *n, char const *str)
{
    static int funky_deep_tree[] = {
        test, and_test, not_test, comparison,
        expr, xor_expr, and_expr, shift_expr,
        arith_expr, term, factor, power, atom,
        0
    };
    int i;
    for (i=0; funky_deep_tree[i]; ++i) {
        if (TYPE(n) != funky_deep_tree[i] || NCH(n)!=1) return 0;
        n = CHILD(n,0);
    }
    /* we're down to the token! */
    return TYPE(n) == NAME && !strcmp(STR(n), str);
}


static void
com_print_stmt(struct compiling *c, node *n)
{
 int i = 1;
 node* stream = NULL;

 REQ(n, print_stmt); /* 'print' test [test] [',' test]+ [','] */

#ifdef USE_PRINT_GOZINTA
    /* are we using the extended print form? (>>) */
    if (NCH(n) >= 2 && TYPE(CHILD(n, 1)) == RIGHTSHIFT) {
        stream = CHILD(n, 2);
        com_node(c, stream);
        /* stack: [...] => [... stream] */
        com_push(c, 1);
        if (NCH(n) > 3 && TYPE(CHILD(n, 3)) == COMMA)
            i = 4;
        else
            i = 3;
    }
#else
    /* 'print to' extended form */
    if (NCH(n) >= 3)
    {
        /* two possibilities: 'print to x ...' or 'print x , ...' */
        if (TYPE(CHILD(n,2)) == COMMA) {
            /* a normal print statement: print x , */
        }
        else if (!is_literal_test(CHILD(n,1), "to")) {
            /* a bad print statement: print foo baz */
            com_error(c, PyExc_SyntaxError, "invalid print syntax");
            return;
        }
        else {
            /* an extended print statement: print to */
            stream = CHILD(n, 2);
            com_node(c, stream);
            /* stack: [...] => [... stream] */
            com_push(c, 1);
            if (NCH(n) > 3 && TYPE(CHILD(n, 3)) == COMMA)
                i = 4;
            else
                i = 3;
        }
    }
#endif

(Sorry this is in such an ugly form. If anyone cares I'll figure
out how to make a proper patch, although I expect it's about a
year too late anyway.)

--Jeff






More information about the Python-list mailing list