Search code examples
pythonpython-3.xstringstring-interpolationf-string

What is the name of the internal function that "executes" an f-string?


I've read How do I convert a string into an f-string? and How to postpone/defer the evaluation of f-strings? and have seen many (working) solutions with exec to postpone the execution of an f-string, like:

template = "My name is {name} and I am {age} years old"
name = 'Abcde'
age = 123
s = eval('f"""' + template + '"""')  # My name is Abcde and I am 123 years old

Is there an internal Python function (among the many double underscore __something__ functions), that defines how the interepreter "runs" / "interpolates" an f-string?

Is there something like __runfstring__ in the Python source code, which is responsible for execution of code? If so, could we call this function ourselves with something like:

s = __runfstring__(template)

in the latest Python versions? (3.7 or 3.8+)


Solution

  • Is there an internal Python function (among the many double underscode __something__ functions), that defines how the interepreter "runs" / "interpolates" a f-string

    The answer is no. From PEP 498 which introduces the f-strings:

    The exact code used to implement f-strings is not specified. However, it is guaranteed that any embedded value that is converted to a string will use that value's __format__ method. This is the same mechanism that str.format() uses to convert values to strings.

    And from the docs about Lexical Analysis in Formatted string literals section:

    If a conversion is specified, the result of evaluating the expression is converted before formatting. Conversion '!s' calls str() on the result, '!r' calls repr(), and '!a' calls ascii().

    The result is then formatted using the format() protocol. The format specifier is passed to the __format__() method of the expression or conversion result. An empty string is passed when the format specifier is omitted. The formatted result is then included in the final value of the whole string.

    So nothing new is implemented for them. They are built on top of existing protocols.