[Python-3000] print() parameters in py3k

George Sakkis gsakkis at rutgers.edu
Tue Nov 21 16:10:43 CET 2006


On 11/21/06, Fredrik Lundh <fredrik at pythonware.com> wrote:
> Adam Olsen wrote:
>
> >> (1)  Is this an explicit rejection of a keyword for a format string, such as
> >>
> >>     print (x, y, z, fmt="My X: %s, Your Y: %s, His Z: %s")
> >
> > Although odd, this appeals to me somehow.  It avoids the risk of
> > passing an untrusted string as the format (even if that's much less
> > dangerous than in C).
>
> it doesn't read well, though.
>
> but if we take the print, printf, and str.format trojka, the rather
> common mistake you mention, and my preference for designing API:s that
> have room for performance optimizations, and refactor things a bit, we
> can do as follows:
>
> 1) move formatting to a separate object.
>
>      str.format(args)
>
> becomes one or more of
>
>      format(str).format(args) # object style
>      format(str)(args) # partial application style
>      format(str) % (args) # old-style
>
> this allows the formatter object to parse the formatting string (and
> possibly also cache it), and also opens up for alternative target API:s
> (e.g. tostringlist, etc).
>
> and the format object should somewhat modular and fully subclassable, of
> course, so Barry can prototype all his ideas all on his own ;-)
>
> 2) for convenience, extend print to treat a format object as a format
> specifier for the following arguments:
>
>      print (x, y, z, fmt="My X: %s, Your Y: %s, His Z: %s")
>
> becomes
>
>      print(format("My X: %s, Your Y: %s, His Z: %s"), x, y ,z)
>
> 3) get rid of printf.
>
> 4) go to Iceland and optimize the heck out of format/print.

I like the idea of a format object and (1),(3) and (4), but (2)
doesn't feel "right":
a. Will print have to do an isinstance(args[0], format) to decide what
to do ? If so, don't the usual arguments for duck typing and against
type checking apply here ? Even if print uses duck typing (e.g. tries
to call a format() method), it still doesn't feel right (wouldn't like
to pass some HardDrive object as first argument <wink>).
b. print(a,b,c) is no longer obvious whether it prints 3 unformatted
objects or 2 formatted, if you don't know what a is.
b. What if for some reason one actually wants to print the format
object instead of interpreting as a format specifier ?

I think format should be either a positional argument at a fixed
position or a keyword argument. Between the two there is a tradeoff;
the former is more readable but requires a separate printf() function,
the latter is less readable but we can get away with just print(). I'm
not strongly inclined for either, but they both look better than an
optional positional format argument.

George


More information about the Python-3000 mailing list