python 3's adoption

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Jan 27 03:20:57 EST 2010


On Tue, 26 Jan 2010 23:37:00 -0800, Paul Rubin wrote:

> Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes:
>> Sorry, I meant consistent with the rest of Python, which mostly uses
>> functions/methods and only rarely statements (e.g. del and import).
> 
> yield, assert, if/else, return, etc.  If we're after that kind of
> consistency, why not get rid of all those statements too?  They have
> already partly done it with yield, and they ended up introducing a new
> separate if/else expression syntax as an alternative to the statement.

Without becoming a purely functional language, you won't get rid of all 
statements. In my opinion, outside of such purely functional languages 
and unconventional languages like Forth, statements play a valuable role 
in that they are controlling syntax. For example:

for, while, if, try, break, yield, return

are all used for flow control, and should remain as statements. But print 
is not -- it's a function disguised as a statement. print, after all, is 
just sugar for stdout.write, which is fine as far as it goes, but when 
you want to do something slightly different from what the sugar does, it 
becomes terribly inconvenient.

A consequence of print being a statement is that my modules are often 
filled with functions and methods called "print_". Suppose I want to 
print the type of each argument as well as it's value. I would like to do 
this:


def decorator(pr):
    def inner(*args, **kwargs):
         args = [(type(a), a) for a in args]
         pr(*args, **kwargs)
    return inner

print = decorator(print)


and then use print as normal, but of course I can't. So instead I do 
something like this:


def print_(*args, **kwargs):
    args = [(type(a), a) for a in args]
    kw = {'file': sys.stdout, 'sep': ' ', 'end': '\n'}
    kw.update(kwargs)
    if len(kw) != 3:
        raise TypeError('invalid keyword argument')
    file = kw['file']
    sep = kw['sep']
    end = kw['end']
    for arg in args:
        print >>file, (str(arg) + sep),  # Don't forget the comma.
    print >>file, end,  # Another comma.


And then, I have to remember to call print_ instead of print.



-- 
Steven



More information about the Python-list mailing list