[Python-3000] More PEP 3101 changes incoming

Jim Jewett jimjjewett at gmail.com
Thu Aug 16 17:17:18 CEST 2007


On 8/13/07, Carl Johnson <carlmj at hawaii.edu> wrote:
> I also like the idea of using "!r" for calling repr ...

> s = "10"
> print("{0!i:+d}".format(s)) #prints "+10"

> The !i attempts to cast the string to int. ...
> The logic is that ! commands are abbreviated functions ...

Which does the "i" mean?
    (1)  Call s.__format__(...) with a flag indicating that it should
format itself like an integer.
    (2)  Ignore s.__format__, and instead call s.__index__().__format__(...)

If it is (case 1) an instruction to the object, then I don't see why
it needs to be special-cased; objects can handle (or not) any format
string, and "i" may well typically mean integer, but not always.

If it is (case 2) an instruction to the format function, then what are
the limits?  I see the value of r for repr, because that is already a
built-in alternative representation.  If we also allow int, then we
might as well allow arbitrary functions to check for validity
constraints.


    def valcheck(val, spec=None):
        v=index(v)
        if not v in range(11):
            raise ValueError("Expected an integer in [0..10], but got
{0!r}".format(v))
        if spec is None:
            return v
        return spec.format(v)

...

    "You rated your experience as {0!valcheck:d} out of 10."

> ... is this too TMTOWTDI-ish, since one could
> just write int(s) instead?

You can't write int(s) if you're passing a mapping (or tuple) from
someone else; at best you can copy the mapping and modify certain
values.

-jJ


More information about the Python-3000 mailing list