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

2005-02-04 Thread Steven Bethard
Daniel Bickett wrote:
|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
--
http://mail.python.org/mailman/listinfo/python-list


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

2005-02-04 Thread Daniel Bickett
Fredrik Lundh wrote:
> your DeleteKeyAll operation would fit nicely in such an interface, but I'm not
> sure it belongs in the low-level interface, and a higher-level interface 
> consisting
> of just one helper would seem a bit odd.on the other hand, it's about time
> someone wrote that "winreg" module... (hint).

I wasn't aware that was even on our plate ;) Is the intent for it just
to have wrappers around the _winreg functions, or were there things
planned for it?

-- 
Daniel Bickett
dbickett at gmail.com
http://heureusement.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


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

2005-02-03 Thread Fredrik Lundh
Daniel Bickett wrote:

> [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...

from the documentation:

This module exposes a very low-level interface to the Windows registry;
it is expected that in the future a new winreg module will be created
offering a higher-level interface to the registry API.

your DeleteKeyAll operation would fit nicely in such an interface, but I'm not
sure it belongs in the low-level interface, and a higher-level interface 
consisting
of just one helper would seem a bit odd.on the other hand, it's about time
someone wrote that "winreg" module... (hint).

 



-- 
http://mail.python.org/mailman/listinfo/python-list


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

2005-02-03 Thread 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:

>>> string = newstring("foo bar")
>>> string.reverse()
'rab oof'
>>> string.setreplace( { 'f' : 'b' , 'a' : 'o' } )
'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

-- 
Daniel Bickett
dbickett at gmail.com
http://heureusement.org/
-- 
http://mail.python.org/mailman/listinfo/python-list