[Python-Dev] Optional arguments for str.encode /.decode (original) (raw)
Raymond Hettinger raymond.hettinger at verizon.net
Fri Nov 7 02:33:54 EST 2003
- Previous message: [Python-Dev] Code to prevent modification on builtins classes also abusively (IMHO) prevents modifications on extensions modules, some ideas on this.
- Next message: [Python-Dev] Optional arguments for str.encode /.decode
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Idea for the day: Let the str.encode/decode methods accept keyword arguments to be forwarded to the underlying codec.
For example, zlib_codec.py can then express its encoding function as:
def zlib_encode(input,errors='strict', **kwds): assert errors == 'strict' if 'level' in kwds: output = zlib.compress(input, kwds['level']) else: output = zlib.compress(input) return (output, len(input))
The user can then have access to zlib's optional compression level argument:
'which witch has which witches wristwatch'.encode('zlib', level=9) 'x\x9c+\xcf\xc8L\xceP(\xcf,\x01\x92\x19\x89\xc5\n\xe5\x08~*\x90W\x94Y\R \x9e\x08\xe4\x00\x005\xe5\x0fi'
This small extension to the protocol makes it possible to use codecs for a wider variety of applications:
msg = 'beware the ides of march'.encode('des', key=0x10ab03b78495d2) print msg.decode(('des', key=0x10ab03b78495d2) beware the ides of march'
template = '${name} was born in ${country}' print template.encode('pep292codec', name='Guido', country='Netherlands') 'Guido was born in the Netherlands'
A key advantage of extending the codec protocol is that new or experimental services can easily be added or tried out without expanding the API elsewhere. For example, Barry's simpler string substitutions can be implemented without adding a new string method to cook the text.
Already, the existing protocol has provided consistent, uniform access to a variety of services:
text.encode('quotedprintable')
text.encode('rot13')
text.encode('palmos')
The proposed extension allows this benefit to apply to an even broader range of services.
Raymond Hettinger
- Previous message: [Python-Dev] Code to prevent modification on builtins classes also abusively (IMHO) prevents modifications on extensions modules, some ideas on this.
- Next message: [Python-Dev] Optional arguments for str.encode /.decode
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]