[Python-Dev] transitioning from % to {} formatting (original) (raw)

Brett Cannon brett at python.org
Fri Oct 2 01:35:44 CEST 2009


On Thu, Oct 1, 2009 at 15:19, Steven Bethard <steven.bethard at gmail.com> wrote:

On Thu, Oct 1, 2009 at 11:03 AM, Brett Cannon <brett at python.org> wrote:

So I created this last night:

import collections class bracesfmt(str):  def mod(self, stuff):  if isinstance(stuff, tuple):  return self.class(self.format(*stuff))  elif isinstance(stuff, collections.Mapping):  return self.class(self.format(**stuff))  else:  return self.class(self.format(stuff)) The biggest issue is that "%s" % {'a': 42} substitutes the dict instead of throwing an error that str.format() would do with the code above. But what's nice about this is I think I can use this now w/ any library that expects % interpolation and it should basically work. I see how this could allow a user to supply a {}-format string to an API that accepts only %-format strings. But I still don't see the transition strategy for the API itself. That is, how does the %-format API use this to eventually switch to {}-format strings? Could someone please lay it out for me, step by step, showing what happens in each version?

First off, a wrapper like this I think is a temporary solution for libraries that do not have any transition strategy, not a replacement for one that is thought out (e.g. using a flag when appropriate). With that said, you could transition by:

  1. Nothing changes as hopefully the wrapper works fine (as people are pointing out, though, my approach needs to override str() to return 'self', else the str type will just return what it has internally in its buffer).

  2. Raise a deprecation warning when isinstance(ob, brace_fmt) is false. When a class is passed in that is a subclass of brace_fmt, call ob.format() on it.

  3. Require the subclass.

  4. Remove the requirement and always call ob.format().

-Brett



More information about the Python-Dev mailing list