[Python-ideas] Allow callables in slices
Michael Selik
mike at selik.org
Sat Jun 9 10:39:45 EDT 2018
On Sat, Jun 9, 2018 at 6:28 AM Michel Desmoulin <desmoulinmichel at gmail.com>
wrote:
> Example, open this files, load all lines in memory, skip the first line,
> then get all the line until the first comment:
>
> import itertools
>
> def is_commented(line):
> return lines.startwith('#')
>
> def lines():
> with open('/etc/fstab'):
> lines = f.readlines()[1:]
> return list(itertools.dropwhile(lines, is_commented)
>
> Becomes:
>
> def is_commented(line):
> return lines.startwith('#')
>
> def lines():
> with open('/etc/fstab'):
> return f.readlines()[1:is_commented]
>
> It's not about how much shorter is is, but it is very nice to read.
>
If you're going to put it in a function anyway, why something like this?
def lines():
with open('/etc/fstab'):
f.readline()
for line in f:
if line.startswith('#'):
break
yield line
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180609/60d05ef7/attachment.html>
More information about the Python-ideas
mailing list