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

Steven Bethard steven.bethard at gmail.com
Fri Feb 4 11:45:01 EST 2005


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



More information about the Python-list mailing list