The final literals vs constructors argument

04 February 2010 (updated 04 March 2015)

>>> def literal():
...     a = {}
...     b = []
...
>>> def builtinconstructor():
...     a = dict()
...     b = list()
...
>>> import dis
>>> dis.dis(literal)
  3           0 BUILD_MAP                0
              3 STORE_FAST               0 (a)

  4           6 BUILD_LIST               0
              9 STORE_FAST               1 (b)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE
>>> dis.dis(builtinconstructor)
  3           0 LOAD_GLOBAL              0 (dict)
              3 CALL_FUNCTION            0
              6 STORE_FAST               0 (a)

  4           9 LOAD_GLOBAL              1 (list)
             12 CALL_FUNCTION            0
             15 STORE_FAST               1 (b)
             18 LOAD_CONST               0 (None)
             21 RETURN_VALUE
>>>

Seriously now, is there any reason to use constructors instead of literals for empty dicts/lists?

This entry was tagged as python