[Python-ideas] str.rreplace
Steven D'Aprano
steve at pearwood.info
Tue Jan 28 17:02:52 CET 2014
On Tue, Jan 28, 2014 at 03:07:15PM +0200, Serhiy Storchaka wrote:
> 28.01.14 14:33, Steven D'Aprano написав(ла):
> >As a general rule, when you have a function that takes a parameter which
> >selects between two different sets of behaviour, and you normally
> >specify that parameter as a literal or constant known at edit time, then
> >the function should be split into two.
> >
> >E.g.:
> >
> ># Good API
> >string.upper(), string.lower()
> >
> ># Bad API
> >string.convert_case(to_upper=True|False)
>
> # Good API
> binascii.hexlify(data), zlib.compress(data)
Sure. Nothing wrong with them.
> # Bad API
> codecs.encode(data, encoding='hex_codec'|'zlib_codec')
But that's not how the codecs.encode function is usually used. Like my
earlier example of sorted(), sometimes you know in advance what
encoding you want to use:
codecs.encode(text, encoding="uft-8")
but for many applications, the encoding parameter is not known until
runtime:
DEFAULT_ENCODING = "utf-8"
encoding = get_encoding() or DEFAULT_ENCODING
codecs.encoding(text, encoding=encoding)
I can't think of an application where I would want to choose between
hex_codec and zlib_codec at runtime, but that's because they are codecs
with completely different purposes. A better example might be an
application where I choose between compression methods at runtime:
def get_compression():
# returns the name of a compression codec
# e.g. zlib_codec, bz2_codec, xz_codec, lmza_codec
# some of these may not be in the std lib at this time
...
codecs.encoding(data, encoding=get_compression())
So the codecs.encoding function does not fail my test of "parameter is
nearly always known at edit-time", and it is not a bad API.
--
Steven
More information about the Python-ideas
mailing list