A question about readability

M

Marco

Hi all, do you think this code:

$ more myscript.py
for line in open('data.txt'):
result = sum(int(data) for data in line.split(';'))
print(result)

that sums the elements of the lines of this file:

$ more data.txt
30;44;99;88
11;17;16;50
33;91;77;15
$ python3.3 myscript.py
261
94
216

is explicit enough? Do you prefer a clearer solution?
Thanks in advance, Marco
 
R

Roy Smith

Marco said:
Hi all, do you think this code:

$ more myscript.py
for line in open('data.txt'):
result = sum(int(data) for data in line.split(';'))
print(result)

That sum() line is a bit of a mouthful. I would refactor it into
something like this:
for line in open('data.txt'):
fields = line.split(';')
print sum(int(i) for i in fields)

It's the same number of lines, but I think it's easier to read.

BTW, are you using Python 2 or 3? It helps when asking these kinds of
questions to let people know. I assumed 2 in my answer above.
 
S

Steven D'Aprano

Hi all, do you think this code:

$ more myscript.py
for line in open('data.txt'):
result = sum(int(data) for data in line.split(';'))
print(result) [...]
is explicit enough? Do you prefer a clearer solution? Thanks in advance,

It's perfectly fine for such a simple script. It is readable and explicit.
 
R

rusi

Hi all, do you think this code:

$ more myscript.py
for line in open('data.txt'):
     result = sum(int(data) for data in line.split(';'))
     print(result)

that sums the elements of the lines of this file:

$ more data.txt
30;44;99;88
11;17;16;50
33;91;77;15
$ python3.3 myscript.py
261
94
216

is explicit enough? Do you prefer a clearer solution?
Thanks in advance, Marco

Interpreting your question as a general question of stylistics, my
experience is that a 3 line script often becomes a 10 line or a 50
line script at which point the direct printing will have to be
modified to create an internal data structure.

So on the whole I find it expedient to start with that assumption and
write it as:

def linesums(file):
return [sum(int(i) for i in l.split(';')) for l in open(file, 'r')]

Whether this one-liner is readable or not and how to make it more so
etc is probably bikeshedding.

More important questions are for example:
- Should you protect the open with a try
- When to list and when to generate(or)

All these are nice features of python but can lead to over-engineered
code
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top