Explanation
I’ve been exploring the PEP series on with
statement in Python, which I found something interesting about VB language, the VB’s with
statement, with which you can do this:
With theCustomer
.Name = "Coho Vineyard"
.URL = "http://www.cohovineyard.com/"
.City = "Redmond"
End With
In the __init__
method of Python classes, we often do this:
class Spam:
def __init__(self, a, b, c, d, e, f):
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e
self.f = f
If we look at the bytecode of Spam
class:
There are two performance penalties:
- 6
LOAD_FAST
’s forself
- 6
STORE_ATTR
instruction (one per attrubute)
Even if we cache self
in the execution (which I don’t know if Python does that or not,) we will still have one STORE_ATTR
for each of the attibute stores on self
.
What if we had one byte code to do several STORE_ATTR
s at once?**
Consider this series of byte code:
1 0 LOAD_FAST 0 (self)
2 LOAD_FAST 1 (a)
4 LOAD_FAST 2 (b)
6 LOAD_FAST 3 (c)
8 LOAD_FAST 4 (d)
10 LOAD_FAST 5 (e)
12 LOAD_FAST 6 (f)
14 **STORE_ONCE** 7
16 POP_TOP
28 LOAD_CONST 0 (None)
20 RETURN_VALUE
Doing several I/O operation like memory access, like what we do now (several STORE_ATTR
on one object) is slow. If there were an instruction like STORE_ONCE
and doing the store on the object in one instruction, many ceval.c
loops’ time would be saved and execution would be faster.
Syntax
For the syntax I’ve came up with a syntax like the VB’s, but after talking with my friends they suggested a cleaner syntax:
class Spam:
def __init__(self, a, b, c, d, e, f):
self.(
a=a, b=b, c=c, d=d, e=e, f=f
)
This idea is not limited to just __init__
method, anywhere we can use this:
object.(attr1=arg1, attr2=arg2, attr3=arg3, ...)
and the generated byte code for this will be named: STORE_ONCE
and CPython will access memory once and assign the properties at once.
But one restriction is that we must use keyword only arguments on this.
Faster CPython
I think this idea is more related to Faster CPython team
@markshannon
@brandtbucher
(sorry if you are one of the team and I missed you, I just knew these people. I saw the Members · People · faster-cpython · GitHub)
I thank you for the time you spent on reading this and I really appreciate any feedback on this post.
Thank you