[Python-Dev] Add transform() and untranform() methods
Steven D'Aprano
steve at pearwood.info
Fri Nov 15 11:28:35 CET 2013
On Fri, Nov 15, 2013 at 10:22:28AM +0100, Antoine Pitrou wrote:
> On Fri, 15 Nov 2013 09:03:37 +1000 Nick Coghlan <ncoghlan at gmail.com> wrote:
> >
> > > And add transform() and untransform() methods to bytes and str types.
> > > In practice, it might be same codecs registry for all codecs just with
> > > a new attribute.
> >
> > This is completely the wrong approach. There's zero justification for
> > adding new builtin methods for this use case - encoding and decoding are
> > generic operations, they should use functions not methods.
>
> I'm sorry, I disagree. The question is what use case it is solving, and
> there's zero benefit in writing codecs.encode("zlib") compared to e.g.
> zlib.compress().
One benefit is:
import codecs
codec = get_name_of_compression_codec()
result = codecs.encode(data, codec)
versus:
codec = get_name_of_compression_codec()
if codec == "zlib":
import zlib
encoder = zlib.compress
elif codec == "bz2"
import bz2
encoder = bz2.compress
elif codec == "gzip":
import gzip
encoder = gzip.compress
elif codec == "squash":
import mySquashLib
encoder = mySquashLib.squash
elif ...:
# and so on
result = encoder(data)
> A transform() or untransform() method, however, allows for a much more
> convenient spelling, with easy cascading, e.g.:
>
> b.transform("zlib").transform("base64")
Yes, that's quite nice. Although it need not be a method, a built-in
function works for me too:
# either of these:
transform(transform(b, "zlib"), "base64")
encode(encode(b, "zlib"), "base64")
If encoding/decoding is intended to be completely generic (even if 99%
of the uses will be with strings and bytes), is there any reason to
prefer built-in functions rather than methods on object?
--
Steven
More information about the Python-Dev
mailing list