News for hackers. Stuff that matters.
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:

    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!
Re:Stop writing classes... by scott_s on Sunday March 18, 2012 @11:29AM (#3719876)
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.
Re:Stop writing classes... by tomp on Sunday March 18, 2012 @12:19PM (#3719998)
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.

Re:Stop writing classes... by pjscott on Sunday March 18, 2012 @03:44PM (#3720676)
Everything 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.