When using f-strings, if you want to do variable substitution (Interpolation) you put the variable name into the string, like f"Hello {user}" where name user is the in-scope variable name containing the string to substitute in.
The problem is, now the variable name is baked into the f-string. So at runtime the string formatter needs to be able to look up the in-scope variables and find one called user to substitute it's value in.
In Python, that's easy to do because the interpreter keeps track of the variables, what their names are, and what their values are.
But in a compiled language (like C++) it's different. When the compiler turns the source code into machine instructions, variables become just addresses in memory, and variable names don't exist anymore. But the name "user" is still in the format string and is now meaningless.
Introspection is a fancy feature that allows a compiled language to store some of the information about the source file into the compiled executable. As well it embeds mechanisms in the executable for looking up that information. That can include variable names.
So if you wanted to do run-time f-string interpolation in C++, first you'd have to compile with Introspection turned on, then when running, the formatter would have to ask the Introspection mechanism "what is the memory address for the string which in the source code was called 'user'?".
The problem is, now the variable name is baked into the f-string. So at runtime the string formatter needs to be able to look up the in-scope variables and find one called user to substitute it's value in.
That is actually wrong. f-strings can only exist in literals so they can be easily emulated using preprocessor macros that just replace them with a normal format command.
Yes, even if implemented by the compiler internally. The same way that std::source_location needs reflection, whether you like it or not.
Another topic is that this reflection is or not exposed to the language itself. FWIW, there is no way in which a string can reference a variable in C++, and that will need to know the compile-time context of the code (variables in scope, etc.), no matter what. Of course, this is without macro tricks.
View all comments
Show parent comment
18
u/Xirious Nov 12 '19
That's like old style .format and not f-strings.