On string formatting and functional programming
oren-py-l at hishome.net
Mon Dec 3 11:10:14 CET 2001
What takes an object describing some job to be done and a tuple of
arguments and applies the tuple to that object?
There's more than one correct answer to this riddle. It could be either
Python's built-in apply() function or the formatting operator '%'.
The formatting operator '%' is a functional programming operator.
Yes, a format string is a function. But it's a limited function. It can
only insert values into a string by position or by name. You can't embed
an expression into a format string. Or can you? Nothing will stand in the
way of a determined hacker so some brave soul developed the following
def __getitem__(self, expr):
Eval = EvalClass()
a = "string with %(embedded(expression))s using" % Eval
I can appreciate the hack value but this is abuse of the language. What
this trick basically does is emulate functional programming with runtime
Don't fear the lambda.
Why emulate when you can use the real thing? Runtime evaluation of strings
is inefficient and a security risk. Runtime evaluation leads to quoting and
escaping problems. Quoting and escaping have already been solved once in the
Python tokenizer so why solve them over and over again at higher layers?
It's great that Python has an eval() function but...
Abuse of eval is the first step on the road to scripting hell :-)
According to the responses I got to my string interpolation proposal people
have missed the point. I don't really care if the interpolation is done
with dollars, percents, backticks or ampersands. What I care about is that
Python should have a compact and readable syntax for representing a string
with embedded expression and that THESE EXPRESSION ARE NOT EVALUATED AT
RUNTIME. This means that it can only be a language feature, not a module.
If you want to make a formatting template and defer the actual formatting
just stick a "lambda:" in front of it, don't start messing with prefixes,
escapes, quoting and runtime parsing. They are 90% of what I dislike about
so-called scripting languages.
*If* string interpolation is added to Python it should be done this way.
There's another question of whether string interpolation should be added
at all. I will welcome postings from anyone willing to comment or contribute
to the proposal and leave the final decision to the BDFL.
More information about the Python-list