[Python-Dev] Optional arguments for str.encode /.decode

Raymond Hettinger raymond.hettinger at verizon.net
Fri Nov 7 02:33:54 EST 2003

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'])
        output = zlib.compress(input)
    return (output, len(input))

The user can then have access to zlib's optional compression level

>>> 'which witch has which witches wristwatch'.encode('zlib', level=9)

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('pep292_codec', name='Guido',
'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:


The proposed extension allows this benefit to apply to an even broader
range of services.

Raymond Hettinger

More information about the Python-Dev mailing list