merits of Lisp vs Python

George Sakkis george.sakkis at gmail.com
Tue Dec 12 13:14:19 EST 2006


Robert Uhl wrote:

> o Macros
>
> As mentioned above, macros can make one's life significantly nicer.  I
> use Python a lot (it's currently a better choice than Lisp for many of
> the problems I face), and I find myself missing macros all the time.
> The ability to take some frequently-used idiom and wrap it up in a macro
> is wonderful.  E.g. a common idiom in Python is:
>
>   file = open(path, 'r')
>   for line in file.readlines():
>       foo(line)
>       bar(line)
>       baz(line)
>
> Even this isn't much nicer:
>
>   for line in open(path, 'r').readlines():
>       foo(line)
>       bar(line)
>       baz(line)
>
> Wouldn't it be nice to have a macro with-open-file?
>
>   filefor line in path:
>           foo(line)
>           bar(line)
>           baz(line)
>

You probably need to refresh your Python skills if you want to be more
productive in it. Files have been iterable for the last couple of years
(since 2.1-2.2, don't remember).

for line in open(path):
    foo(line)
    bar(line)
    baz(line)

You can also iterate through the lines of more than one files using the
fileinput module (http://docs.python.org/lib/module-fileinput.html):

import fileinput

# iterate over the lines of the files passed as command line
# arguments (sys.argv[1:]) or sys.stdin for no arguments
for line in fileinput.input():
    foo(line)


I'm sure there should be more convincing examples for macros, but
neither this nor the 'unless' syntax sugar cuts it.
 
George




More information about the Python-list mailing list