Possible additions to the standard library? (WAS: About standardlibrary improvement)

D

Daniel Bickett

I was reading the thread by Frank Bello[1] about his offered addition
to the xmlrpclib module, and it reminded me of a few methods I had
made in the past that I considered worthy of being a part of the
standard library.

Rather than reiterate his question of how one gets one's patch into
the standard library -- as I can simply read the answers from his
thread -- I am posting here asking the opinion of the Python community
as to whether *you* consider these worthy of standard library
implementation.

The first one is a function I made for the _winreg module[2]. The
commentary, I think, explains what it does and why it had to be
written very clearly, so I'll just copy and paste it:[3]

|def DeleteKeyAll( key , subKey ):
| """
| Since DeleteKey() can't remove keys that contain subkeys, this serves
| to iterate through a key and delete every single subkey, and then the
| key itself.
|
| Note: This function assumes that _winreg has been imported using:
| from _winreg import *
| It can be easily converted by simply prepending all of the
| applicable statements with `_winreg.' if you have imported
| it otherwise.
| """
| # try to open the specified key
| try:
| handle = OpenKey( key , subKey )
| except EnvironmentError:
| return False
| # now, iterate through the subkeys and remove
| # each of them (recursively)
| while True:
| nextKey = QueryInfoKey( handle )[0]
| if not nextKey:
| # if there aren't any more subkeys, delete the key at hand
| try:
| DeleteKey( key , subKey )
| return True
| except EnvironmentError:
| break
| else:
| # otherwise, recursively delete the subkeys
| DeleteKeyAll( key , subKey + "\\" + EnumKey( handle , 0 ) )

These next two are methods that I've applied to my own version of the
string object from time to time:

|class newstring( str ):
| def setreplace( self , set ):
| """
| Do multiple replaces at once, using dictionary `set' as a legend,
| where each instance of each key is to be replaced with that key's
| value.
| """
| if type( set ) == dict:
| result = self.__str__()
| for key, value in set.iteritems():
| if type( key ) == str and type( key ) == str:
| result = result.replace( key , value )
| else:
| raise TypeError, "All items of parameter set must
be strings"
| return result
| else:
| raise TypeError, "Parameter set must be a dictionary"
|
| def reverse( self ):
| """
| Return a reversed copy of string.
| """
| string = [ x for x in self.__str__() ]
| string.reverse()
| return ''.join( string )

In action:
'boo bor'

I actually went on to write a method that reversed an integer
(inspired by an SAT question -- I had time to kill) using the
newstring's reverse() method, but it's hard enough justifying having a
string reverse method (though not impossible,) let alone an integer
reverse method, so I left that one on my hard drive :)

One more thing worth noting is that I'm not educated in the ways of
standard library etiquette, so I was more or less going out on the
limb doing type-checking in setreplace(). For all I know that's some
sort of paradox and you're supposed to let the user feel the pain, but
I did what I felt was right at the time.

This is basically all about commentary and criticism, and your opinion
of whether or not these deserve to be added to the library (or rather,
added as a patch, I presume). Thank you all for your time :)

P.S.:
I have included all of the methods in this post for the sake of
accessibility, and i have preceded all of the code with `|' because I
am unaware of the status of google's whitespace problem. If you want
to more easily copy and paste this code, I have posted it on nopaste:

DeleteKeyAll: http://rafb.net/paste/results/Yh6x0598.html
newstring methods: http://rafb.net/paste/results/O51kja41.html

NOTES:
[1] http://tinyurl.com/4dkgw
[2] I'm currently unaware if _winreg is a c extension module or pure
python, but I'm assuming it's C, so I don't know how possible it is to
add pure python to it...
[3] I made a few quick edits after I pasted it in, so please bring to
my attention any errors or inconsistencies you see
 
S

Steven Bethard

Daniel said:
| def setreplace( self , set ):
| """
| Do multiple replaces at once, using dictionary `set' as a legend,
| where each instance of each key is to be replaced with that key's
| value.
| """
| if type( set ) == dict:
| result = self.__str__()
| for key, value in set.iteritems():
| if type( key ) == str and type( key ) == str:
| result = result.replace( key , value )
| else:
| raise TypeError, "All items of parameter set must
be strings"
| return result
| else:
| raise TypeError, "Parameter set must be a dictionary"

Yeah, the type-checking is probably not the way to go. If you want to
give useful error messages, use try/except statements, e.g.:

py> def setreplace(self, mapping):
.... result = self
.... try:
.... keys = iter(mapping)
.... except TypeError:
.... raise TypeError('first argument to setreplace must '
.... 'be mapping')
.... for key in keys:
.... try:
.... value = mapping[key]
.... except TypeError:
.... raise TypeError('first argument to setreplace must '
.... 'be mapping')
.... try:
.... result = result.replace(key, value)
.... except TypeError:
.... raise TypeError('mapping items must be strings')
.... return result
....

Note that also, instead of iteritems, I use the mapping protocol. This
means users of your class can supply any mapping type.

Of course, the str object is written in C, so if you want this added to
Python standard, you'll need to write a patch using the C API...
| def reverse( self ):
| """
| Return a reversed copy of string.
| """
| string = [ x for x in self.__str__() ]
| string.reverse()
| return ''.join( string )

Simpler version for Python 2.4:

py> def reverse(self):
.... return ''.join(reversed(self))
....

Simpler version for Python < 2.4:

py> def reverse(self):
.... lst = list(self)
.... lst.reverse()
.... return ''.join(lst)
....

Note that you shouldn't need to invoke self.__str__ to iterate -- just
use self. And the list comprehension:

[x for x in y]

can generally be reduced to:

list(y)



As far as usefulness is concerned, I would most likely make use of
str.setreplace (though I'd perhaps prefer a name like 'mappingreplace'),
but I probably wouldn't have much of a use for str.reverse. Of course,
YMMV.

Steve
 
K

Kent Johnson

Daniel said:
| def reverse( self ):
| """
| Return a reversed copy of string.
| """
| string = [ x for x in self.__str__() ]
| string.reverse()
| return ''.join( string )

def reverse(self):
return self[::-1]

Kent
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top