[Python-3000] Implementing % formatting in terms of str.format()

skip at pobox.com skip at pobox.com
Sat Apr 12 16:26:32 CEST 2008


    Nick> That's exactly the problem though - while a 2to3 fixer can be
    Nick> written for a tiny subset of formatting calls (those that meet the
    Nick> constraints you gave)...

In my personal experience, either the LHS will be a string literal or the
RHS will be locals(), globals() or a tuple.  Yes, you will have a hard, if
not impossible, time with the general x % y.  Still, I think a fixer that
only addresses the "tiny subset" would go a long ways to converting existing
code.  For the rest it could insert special comments so the programmer can
grep for the problematic cases.  As a quick back-of-the-envelope check, I
counted the number of occurrences of ' % ' in the 2.5 source and found 4555
instances.  Of those, either a single quote or a double quote preceded the
leading space in 3943 cases.  In 2051 cases (obviously overlapping with the
preceding count) the trailing space was followed by a left paren or left
brace.  In 21 cases the trailing space was followed by a call to locals() or
globals().  I think something like 85-90% of the uses in the Python core
should be able to be converted mechanically.

    Nick> So my understanding matches Benjamin's: while string %-formatting
    Nick> is definitely a 'second way' to do something for which str.format
    Nick> will be the preferred approach, getting rid of it for Py3k just
    Nick> isn't worth the staggering amount of breakage that would result.

True, I'm not implying anything should be broken, just that much of the work
can be mechanical conversion.  Also, for some of us, % formatting will
remain the "first way" of generating formatted string output as long as it
exists in the language.

Skip


More information about the Python-3000 mailing list