01110100110101010101011101100010
strange thing in python
i recently noticed this anyone has a proper explanation for this
for literals i get this
>>> def a():
... b = []
... c = {}
...
>>> import dis
>>> dis.dis(a)
2 0 BUILD_LIST 0
3 STORE_FAST 0 (b)
3 6 BUILD_MAP 0
9 STORE_FAST 1 (c)
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
but for constructors i get this
>>> def a():
... b = list()
... c = dict()
...
>>> dis.dis(a)
2 0 LOAD_GLOBAL 0 (list)
3 CALL_FUNCTION 0
6 STORE_FAST 0 (b)
3 9 LOAD_GLOBAL 1 (dict)
12 CALL_FUNCTION 0
15 STORE_FAST 1 (c)
18 LOAD_CONST 0 (None)
21 RETURN_VALUE
i mean why the difference, i was thinking {} and dict() do the same thing, shouldn’t they?
| Print article | This entry was posted by Ankur Shrivastava on February 10, 2010 at 6:22 pm, and is filed under Stuff. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |




about 6 months ago
I am not able to figure out what difference you are seeing over here please elaborate a little more?
about 6 months ago
the problem is using {} is more efficient then using the constructor dict(), see the number of lines disassembled 15 for function with {} and 21 for function with dict()
about 1 month ago
When you call a constructor, a function call should take place. This introduces an overhead which is not there when you use a literal. So, your observation that the literal is faster is correct and here’s some data to back it.
noufal@sanitarium% python /usr/lib/python2.6/timeit.py “x={}”
10000000 loops, best of 3: 0.0477 usec per loop
noufal@sanitarium% python /usr/lib/python2.6/timeit.py “x=dict()”
10000000 loops, best of 3: 0.179 usec per loop