Skip to content

New check: Use single-statement dict initialization #2876

Closed
@nickdrozd

Description

@nickdrozd

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Enhancement ✨Improvement to a componentGood first issueFriendly and approachable by new contributorsHacktoberfestHelp wanted 🙏Outside help would be appreciated, good for new contributors

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions