Initialise Containers With Literals
ID |
python.init_dicts_with_literals |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Python |
Tags |
code-style, efficiency |
Description
Reports calls to the empty constructors dict(), list(), tuple(), str(). The literal forms ({}, [], (), "") are shorter, slightly faster (no global name lookup), and clearer.
cache = dict() # FLAW — use {}
items = list() # FLAW — use []
empty = str() # FLAW — use ""
cache = {} # OK
items = [] # OK
empty_set = set() # OK — no empty-set literal
Rationale
The empty constructor calls perform a name lookup, allocate, and return — every iteration of the program. The literal forms are produced by the bytecode compiler as a single opcode. The savings are tiny per call but consistent, and the literal form is the canonical Python style.
set() is exempt because {} is a dict literal in Python — there is no empty-set literal.
Remediation
Replace the constructor with the literal:
cache = {}
items = []
empty = ""
unit = ()
Constructors with arguments (dict(a=1), list(some_iter)) are out of scope.