pylint
pylint copied to clipboard
New check: Use single-statement dict initialization
Here's an ugly pattern, commonly found in eg config files:
config = {}
config['dir'] = 'bin'
config['user'] = 'me'
config['workers'] = 5
An empty dict is initialized and then mutated several times. It would be better to use declarative literal syntax:
config = {
'dir': 'bin',
'user': 'me',
'workers': 5,
}
No mutation! No repetition!
I'm imagining a check that would look for an empty dict initialization and then see if any following lines are bare dict assignments. It could get tricky though, as this pattern horrible pattern is sometimes recursive:
config = {}
config['dir'] = 'bin'
config['user'] = 'me'
config['workers'] = 5
config['options'] = {}
config['options']['debug'] = False
config['options']['verbose'] = True
Yuck!
And I know, a check like this gets released, CIs start showing failing builds, and everyone thinks the sky is falling. Maybe make it optional? Or a warning or something? Anything to discourage this pattern.
Sounds like a good improvement @nickdrozd This can be an optional check for now, in the form of an extension pylint.checkers.extensions
, which needs to be explicitly enabled in the configuration file. Maybe we can enable it by default in pylint 3.0.
@PCManticore I'd like to work on this one, but I'm not sure exactly where to start. What kind of node would this check attach to? One approach would be to look for assign statements with {}
on the right side, then collect all immediately following assign statements where the right side indexes into the variable assigned to by the first statement. Does that sound right? Are there any existing checks that do something similar?
@nickdrozd That approach sounds right to me. You should find some similar checks in checkers.refactoring
, consider-using-get
and simplifiable-if-statement
come to mind.
I changed the title of this issue to accommodate https://github.com/PyCQA/pylint/issues/4365