Python development [note]: Explore Python F-strings, pythonf-strings
F-strings
In python3.6.2, PEP 498 proposes a new string Formatting Mechanism called "string interpolation" or a more common term:F-strings(Mainly because the first letter of this string is f)
Easy to understand:
① F-strings provides a clear and convenient way to embed python expressions into strings for formatting:
import mathradius = 10pi = math.piprint(f'Circumference of a circle with radius {radius}:{2*pi*radius}')# Circumference of a circle with radius 10:62.83185307179586
② Similarly, in F-strings, we can also execute the function:
import mathradius = 10def area_of_circle(radius): return 2 * math.pi * radiusprint(f'Area of a circle with radius {radius}:{area_of_circle(radius=radius)}')# Area of a circle with radius 10:62.83185307179586
③ F-strings runs fast. It is much faster than the %-string and str. format () Formatting methods -- these two are the two most commonly used string formatting methods.
In most cases, F-string is faster than %-string, but occasionally it is not necessarily (cannot be explained)
1 from timeit import timeit 2 a = 1 3 b = 2 4 5 print(timeit('''f"{a} + {b} = {a + b}" ''',number=100000,globals=globals())) 6 print(timeit('''"{} + {} = {}".format(a, b, a + b) ''',number=100000,globals=globals())) 7 print(timeit('''"%s + %s = %s"%(a, b, a + b) ''',number=100000,globals=globals())) 8 9 # 0.0359373150684931510 # 0.05211441095890411611 # 0.0491952511415525Test comparison
Comparative analysis:
① Why is F-strings running so fast? How do they run? PEP 498 provides the following clues:
Using the smallest syntax, F-strings provides a method to embed expressions in strings. Note that F-strings is an expression formed during running, rather than a constant value. In Python source code, F-strings is a string prefixed with f, which contains the expression. The result of the expression is displayed in the position where it is located.
The key point is that F-strings is the expression for calculation during the running process, rather than a constant value. This means that F-strings, like other python expressions, calculates the result during running. The CPython compiler significantly improves performance when parsing F-strings into strings and expressions to generate an appropriate abstract syntax tree:
We use the ast module to view the abstract syntax tree of a + B in the F-strings and other conditions. We can see that the expression in expression F-strings is parsed into a common binary operation, which is the same as the result parsed by a + B. Even at the bytecode level, we can see that the F-strings expression is calculated as a normal expression.
The add_two function simply adds two local variables a and B and returns the result value. The add_two_fstring function provides similar functions, but the added expression is placed in f-strings. In the bytecode decompiled by the add_two_fstring function, the FORMAT_VALUE command (this command appears here because, after all, an F-strings needs to stringize its internal expression ), the result is the same as that of expression a + B without F-strings.
The F-strings process is divided into two steps: one is to calculate the expression in curly brackets (the same as a normal Python expression), and then fill the result in the curly brackets, return the combined string as the result. No additional running process is required for these steps. This makes F-strings faster and more efficient.
② Why is str. format () much slower than F-strings? After reading the corresponding disassembly bytecode, the reason is obvious.
In the deserialized bytecode, the first two bytecode commands are displayed: LOAD_METHOD and CALL_METHOD. When str. format () is used, the format function must be searched globally. This step is implemented through the LOAD_METHOD command. Global Variable Search is a costly operation, including a series of steps (if you are interested, you can refer to my previous blog on Attribute search ). Once the format function is located, the binary addition operation (BINARY_ADD) will be awakened to add the variables a and B. Finally, call the format function using the CALL_METHOD bytecode command and return the formatted result. Function calls in Python have considerable overhead. When str. format () is used, additional time consumed on LOAD_METHOD and CALL_METHOD causes str. format () to be much slower than F-strings.
③ Why is the %-strings formatting method? The previous results show that the running speed is between str. format () and F-strings. Let's take another look at the byte code after the %-strings formatting method is used to find some clues:
In an instant, we found that the bytecode does not contain the LOAD_METHOD and CALL_METHOD commands -- so the %-string method avoids the overhead of global property search and function call. This explains why %-strings is faster than str. format. But why is the running speed of %-strings still slower than that of f-strings? %-Strings may consume additional time on the BINARY_MODULO bytecode command. I did not get the result by analyzing the BINARY_MODULO bytecode, but after reading the CPython source code, we can understand why BINARY_MODULO calls produce a small extra cost.
The Python source code shows that the BINARY_MODULO operation is overloaded. Each time it is called, it always needs to check the type of the computing object to determine whether the object is a string object (line 7-13 of the Code ). If they are, then modulo executes the string format operation. If not, it executes the daily module (returns the remainder of the first and second parameters ). Although small, this type of check does produce some additional overhead, and F-strings does not have these problems.
I hope this article will give you some inspiration and help you understand why F-strings stands out from many string formatting methods. F-strings is fast, easy to learn, and practical. It can effectively reduce the amount of code. Why not use it quickly!
Original ENGLISH: Simplified