Re:Stop writing classes...
by pjscott on Saturday March 17, 2012 @08:51PM
(#3718721)
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:
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:
At no point here have I used the "class" keyword!
[ Parent
| on HN ]
You 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.
I 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.