Python wart

Chris Angelico rosuav at gmail.com
Fri Nov 1 19:13:26 EDT 2013


On Sat, Nov 2, 2013 at 8:47 AM, Peter Cacioppi <peter.cacioppi at gmail.com> wrote:
> I always thought printf was sort of crappy.
>
> I thought the C++ << business even worse.

Oh, you'll get no argument from me about the std::*stream types! When
I write C++ code, I almost exclusively use C-style formatted strings,
even sometimes going to the extent of using fopen() just so I can use
fprintf() rather than fstream. Also, I often create a class something
like this:

struct format
{
    char *data;
    format(const char *fmt, ...);
    operator char *() {return data;}
};

where the constructor calls vsprintf and there's a bit of new/delete
work to manage memory, but that's all under the covers; in code, I use
it like this:

some_function_call(format("Hello, %s!", "world"));

making it almost as if it's a function returning a string, like you
would in Python.

Most of the problems with printf come from the fragility of C's
variadic functions. Some C compilers can deal with that (gcc happily
checks printf args), but there are still fundamentally hard problems
around it. They don't apply in Python (or Pike, which has an sprintf
function[1] with even more power), as issues can be signalled with
exceptions - clean, easy, safe.

ChrisA

[1] http://pike.lysator.liu.se/generated/manual/modref/ex/predef_3A_3A/sprintf.html



More information about the Python-list mailing list