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 #!
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
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
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
The reason for doing this is twofold:
- It's a nice idiom to use, and
- 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!
A new Python Enhancement Proposal? More Login
A new Python Enhancement Proposal?
Slashdot Top Deals