Please create an account to participate in the Slashdot moderation system

 



Forgot your password?
typodupeerror
×
Programming

Journal mshomphe's Journal: A new Python Enhancement Proposal?

I use Python at work. Gets a lot of stuff done and done well. I used to be nutz about Perl, now I'm nutz about Python. Not that I don't like Perl anymore (I still have my thinkgeek #! /usr/bin/perl shirt).

One of the functions that I use quite a bit is what I'll call striplist(). This takes a list of strings and returns it with the whitespace removed. I used to have a function that was something like:

def striplist(l):
    return(map(lambda x: x.strip(), l))

However, the processing overhead was INCREDIBLE for this function. Not only were you penalized for calling the function, there were two function calls (map & lambda), each which had their own penalties. It was faster to call .strip() on each argument in the list that I was using (since they were never terribly long lists).

This solution seemed inelegant, so I've been rewriting the function. This is what I have now:

def striplist(l):
    return([x.strip() for x in l])

This is a lot faster. However, it got me thinking about how this would be an amazingly useful method to have on the list object. [].strip() would return the list with the whitespace removed.

(As an aside, I took this to its logical conclusion in my head -- a general [].method(args=None) idiom. However, it seems to be too confusing. How do you know if the method is supposed to apply to the list or the objects in the list. What if it's a list of lists and you call a method? Do you do it recursively? In other words, it got way too unwieldy. So I decided that since .strip() only applies to strings [theoretically], this would be a special case.

Of course, it might stand to reason to have a special class for a list of strings, that way all methods available strings would be available to apply to the entire list.)

So my proposal is this: A new nethod on the list class .strip(char=string.whitespace) that returns the list of objects with the method .strip() applied to them.

The reason for doing this is twofold:

  1. It's a nice idiom to use, and
  2. I would suggest pushing it as far down into C as possible to make it as fast as possible.
    .

Here's example code:

class sList(list):
    def __init__(self, args=None):
        list.__init__(args)
    def strip(c=None):
        return([x.strip(c) for x in self])

If only GvR were reading this :)

I welcome your comments!

This discussion has been archived. No new comments can be posted.

A new Python Enhancement Proposal?

Comments Filter:

Always draw your curves, then plot your reading.

Working...