3 ms·
Upon reading the title, I was not enthusiastic. Yet another way to format strings? What's wrong with String.format()? Get off my lawn! However upon reading the
by korethr 6y ago
Upon reading the title, I was not enthusiastic. Yet another way to format strings? What's wrong with String.format()? Get off my lawn!
However upon reading the article, it does feel more ergonomic to prepend your string literal with an 'f', and have it automagically reach out into the surrounding scope for the variables to format into the string.
I do worry a bit however about formatting not just expressions, but being able to call other code. Yes, that could be quite convenient for keeping the code concise and avoiding the kind of verbosity that confuses. However, I could also see someone forgetting to sanitize user-input data, and combined with the f-string, creating a remote arbitrary code-execution vulnerability. Sure, an attacker can't immediately start scribbling on memory in Python, there's more work he has to do first. But, he possibly could hijack the Python process to run whatever Python code he wanted.
- ericvsmith 6y agoExecuting user-provided code isn't possible. f-strings must be literals, so there's no user-defined strings involved. You could of course eval something the user provided, but there's no more of a risk with f-strings than there is with regular code. This is addressed in PEP 498.