by chrisshroba · 9y ago · 0 comments
"My name is {} and I am {} years old".format(name, age)
"My name is %s and I am %s years old" % (name, age)
"My name is {name} and I am {age} years old".format(name=name, age=age)
Now, we can finally use f-strings, where anything in brackets is eval'ed, with the result subbed in: f"My name is {name} and I am {age} years old."Yes, I know you can do more with format strings than plain interpolation, but that's all that the basic examples show.
(Also: Perl has allowed underscores in number literals for ages).
Python just got one more way of doing string interpolation.
This is a textbook example of string interpolation.
You can look it up on wikipedia. I am not sure what you mean.
See: list comprehensions obsoleting most uses of map() and filter(), then generator expressions obsoleting any uses of list comprehensions that don't need a list object
Here's four ways to do the same thing.
Naïve way:
foo = []
for x in bar:
if meets_some_condition(x):
foo.append(transform(x))
do_something_with(foo)
With map/filter: do_something_with(map(transform, filter(meets_some_condition, bar)))
With list comprehensions: do_something_with([transform(x) for x in bar if meets_some_condition(x)])
With generator expressions: do_something_with(transform(x) for x in bar if meets_some_condition(x))
All four of those are valid in modern Python, but the latter and only the latter is the right way to do it.Before Python 2.0, either map/filter or the naïve way was the right way (TBH, I'm not familiar with what was considered right in the old days). When Python 2.0 came out, list comprehensions became the right way. When Python 2.4 came out, generator expressions became the right way. The right way depends on your version of Python.
Or for that matter, look at old-style classes vs. new-style classes. When new-style classes came out, they immediately became the one and only right way to do classes, but old style classes still stuck around for the rest of the 2.x series.
--- "Avoid programming languages starting with the letter P except Prolog"
"My name is {name} and I am {age} years old".format(**locals())
... but I always felt a little guilty like this is some kind of dynamic-programming-on-steroids trick that I should use sparingly.Though I think it would be cool if you could have a deferred format string, like so:
template = 'My name is {name} and I am {age} years old. Next year I will be {age + 1}!'
name = 'Amy'
age = 32
formatted = template.apply()
# formatted = 'My name is Amy and I am 32 years old. Next year I will be 33!'
So that way you could store the template as a constant somewhere and apply it after receiving input from the source of your choice.You can kind of do that with [0], but it doesn't evaluate expressions (so the age + 1 thing won't work).
[0] .format(**locals()) # putting it here because HN eats the asterisks if it's not indented def template(name, age):
return f"My name is {name} and I am {age} .."
formatted = template('Amy', 32)
?[Edit: I only started learning Python recently, and this is how I'd think of doing it come from JS:
const template = (name, age) => `My name is ${name} and I am ${age}`;
const formatted = template('Amy', 32);
](Conflict between improvement and backward compatibility, but I miss it.)
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
It pretty clear that if you support python 3.6 you should use `f` strings.And if you support any earlier version of python, you cannot use f strings. Hence, there is a conflict between improvement and backward compatibility.
Python is no longer inferior to Bash and Perl for short scripts and more concise. Looking across the modern language landscape, this functionality is becoming an industry standard. The format string is also a little more sophisticated that it looks on the surface.
Still, I was a bit down that so many showed up to complain about it, mostly with purity or adversity-builds-character arguments. I'm glad lots of people are enjoying it.
For the example above, this might be fine, but most examples that I see using this kind of thing are things like:
"select * from foo where id = '%s'" or "<input type='hidden' name='foo' value='%s'/>" or "rm -rf /path/to/customer/%s"
I tend to think that in general appending strings is more often than not quite a dangerous operation, and it behooves the caller to need to have a long think about exactly how the strings being substituted in need to be escaped - as it's pretty rare that they don't need to be.
I think you just have to play it by ear. Old formatting styles seem like one of those things you want to leave alone for a really long time, because they're so common that it'd be a major PITA to fix all occurrences, and because it doesn't seem like there's an obvious negative ramification to allowing the old styles to continue to evaluate according to the old methods.
I mean, there’s a precedent for short built-in functions like len(), and apparently 'print "x"' as a statement was terrible so 'print("x")' replaced it. If they wanted such consistency, shouldn’t they have used 'f("{a} {b}")' or something? Or alternately, allow p-strings like 'p"hello, world"' to print?
Other cases such as redirecting to a file, and changing the line ending are handled much more intuitively with the print function.
In fact, I don't think it would be possible to write such a function in the general case, because it's ambiguous what environment you would need to use.
For example:
def call(func, arg):
a = 2
return func(arg)
a = 1print(call(f, "{a}"))
Does this print 1 or 2?
One reason might be that f-strings work in expressions, while statements do not. Even with the BDFLs apparent distaste for functional programming constructs, syntax that works within expressions has lots of practical advantages over statements.
>>> 1 + '1'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
No. >>> float('inf') < 'hi'
True
Fixed in Python 3, but still. There are more of these things.I mean that it feels so much nicer to do:
let x = [ 1, 2, 3].map(i => i * 10)
than x = list(map((lambda i: i * 10), [ 1, 2, 3 ])) x = [i * 10 for i in [1, 2, 3]]In typical perl^Wpython spirit, we now can save a few characters by typing:
f"My name is {name} and I am {age} years old."
instead of: "My name is {name} and I am {age} years old.".format(**locals())
Look how much typing we saved! Now we just have to explain to new users that their strings get eval'd for stuff in brackets, but only when the string is prefixed by `f`...Well that's a definite code smell.
The only way `str.format_map(locals())` is a code-smell is if the people working on the code don't actually know Python. Builtin methods of core types, dictionary unpacking, and builtin functions are all extremely common and only complete novices at python would find any issue with them. Compare that to what you need to know when you encounter `f"hello {name}"`:
0) am I working with Python 3.6+?
1) when does replacement happen?
2) what scopes are examined for substitution?
Of course, 2) is a trick question because you EVALUATE ARBITRARY PYTHON EXPRESSIONS IN THE FORMAT STRING![2]
[1] Technically, PEP-0498 states that we're not exposing a full locals() or globals(), but this actually matters very little. The danger here is that both .format() and f"" use object.__format__() (falling back __repr__ IIRC) to figure out the replacement. If your object.__format__() is malicious, it gets access to more data than it needs. However, since python has zero security model, if it's malicious, it pings whatever command and control server it's reporting to and starts up a thread listening for commands anyway (aka you're fucked). Realistically, this means that, you might leak credentials (or other sensitive information) to third party loggers, but only if your method for censoring outgoing log/exception data is a a poorly-built blacklist.
[2] https://www.python.org/dev/peps/pep-0498/#supporting-full-py...
print("My robot's name is {}. It's {} years old.".format(name, years_old))
Seems reasonable to me. I don't really see any reason to hack in the locals splat. I guess the one thing it saves you is ordering issues, but in practice, I haven't found those to be terribly inconvenient, and in the rare case they are, you can just do "{name}, {age}".format(name=name, age=years_old)).Yes, both forms are a little longer, but as you state, it's easier to see what's going on. One of Python's biggest attractions, IMO, is that it's batteries included, but not batteries-sealed-under-1000-layers-of-carbonite-locked-by-a-mystical-incantation, like many other dynamic languages. It's usually pretty easy to get in there and see what's happening without having to traverse tons of indirection due to Python's design principle favoring explicit programming styles.
I won't lie and say I've never wished for more conventional style string interpolation, but it certainly wasn't a showstopper, and it's not something we should assume we get for free.
Second, the parser at compile time pulls out the actual expressions and fills them in to a .format call. It _does not_ use locals!
... and your worries about security are not useful, you could make the same statements about an entire code base.