3 ms·
In Python, you can get that exact same behavior by writing a generator function. I'm sure this code has shortcomings -- it doesn't handle comment lines, for exa
by pjscott 15y ago
In Python, you can get that exact same behavior by writing a generator function. I'm sure this code has shortcomings -- it doesn't handle comment lines, for example -- but something like this will parse basic CSV:
def readcsv(file):
for line in file:
if line:
yield tuple(field.strip() for field in line.split(','))
No explicit class definitions necessary! And you can write the same kind of code. Or, if you want to be a bit too clever for your own good, you can shorten it to this:
rows = readcsv(open('data.csv', 'r'))
vals, avgs, stds = zip(*[map(int, row) for row in rows])
At no point here have I used the "class" keyword!
- scott_s 15y agoYou and jules provided excellent examples for how to do my example without classes - but you do assume that the csv parser never needs to peek across lines. That's probably fine for csv files, but in general, lexers/parsers may need to. My point is, you're taking advantage of the fact that files are already objects which can be processed line by line. You can't always do this. I think that things like files and sockets are very nice to have as objects.
- tomp 15y agoI a way, you could think of the generator function as an object with a specific interface. In fact, I think that's how generators are implemented in python, the language just hides this fact away from the programmer.
- pjscott 15y agoEverything in Python is an object under the scenes. If you look at the CPython extension API, it turns out that pretty much everything is a PyObject.