Python Worst Practices

Christian Gollwitzer auriocus at gmx.de
Wed Mar 4 15:27:43 EST 2015


Am 04.03.15 um 00:12 schrieb Chris Angelico:
> The problems come from needing more than two components at each step,
> like with string formatting. You could write it like this:
> 
> "Hello, %s from %s!" % name % location
> 
> but then it'd be really hard to track down errors - the modulo
> operator would have to handle the first percent sign and leave any
> others unchanged. Plus there'd need to be some weird and funky magic
> to mark the "current interpolation position" in order to cope with %%
> becoming %, and the possibility that the person's name contains a
> percent sign. 

boost::format does it like this, but not in a magic string processing
way as you desribe it. The string is parsed and some funny template
magic ensures that the arguments are inserted into it.

>>> Operator overloading in each case here is "cute", not optimally practical.
>>
>> Maybe just sub-optimal? With today's C++ one could use a variadic
>> template and still have type-safe compile-time bound output formatting.
>> This hasn't been possible in the original iostream library back then.
> 
> I'm not sure how that would work, but the main question is: How is it
> advantageous over a simple call? Actually, here's a simple way to do
> it: Make the stream object callable.
> 
> cout("Hello, world!\n");

Well variadic templates make it possible to do this:

string name="Chris";
int age=36;
cout("Hello ", name, "your age is ", age);

with any number of arguments of any (supported) type. This seems trivial
in Python, but is quite hard to do for a statically compiled language. A
type-safe printf-style function is one of the prime examples for
variadic templates: http://en.wikipedia.org/wiki/Variadic_template

> You can take as many args as you want, precedence and associativity
> won't bite you, and it still reads reasonably well. The operator
> method has to prove that it's better than that.

Agreed. The operator method was necessary in C++ because there simply
was no other way to create this interface. C++11 gained a lot more
features, but iostreams is still the thing from the very first design of
C++.

	Christian



More information about the Python-list mailing list