Closed as not planned
Closed as not planned
Description
Feature or enhancement
Proposal:
If we collapse statements of the form:
X = expr
X = expr that immediately and only once references X (i.e. X.a or X().y+2)
we can compose the RHS of the first line into the second line, i.e.
X = y() ; X = X.k()**2
⟶ X = y().k()**2
Test (Ryzen 7 3800X, locked to 1 core, Python 3.13.3, no FT/JIT) sees f2 being ~2% faster than f1
import timeit
class B:
def __init__(self):
self.c = 42
class A:
def __init__(self):
self.b = B()
def f1():
a = A()
return a.b.c
def f2():
a = A()
a = a.b
return a.c
number = 100_000_000
for _ in range(25):
t1 = timeit.timeit('f1()', globals=globals(), number=number)
t2 = timeit.timeit('f2()', globals=globals(), number=number)
print(f'{t1:.9f} {t2:.9f} ⇒ {(t2/t1-1)*100:.9f}%')
We observe the slightly larger bytecode output (68 vs 64 instr):
Has this already been discussed elsewhere?
I don't think