Merge Set Add¶
Sourcery refactoring id: merge-set-add
¶
Description:¶
Create the set with values instead of declaring an empty set and adding to it
Before:¶
hats_i_own = set()
hats_i_own.add("panama")
hats_i_own.add("baseball_cap")
hats_i_own.add("bowler")
After:¶
hats_i_own = {"panama", "baseball_cap", "bowler"}
Explanation:¶
When declaring a set and filling it up with values one way that can come naturally is to declare it as empty and then add to it.
This can be done in place, shortening the code and making the intent more explicit. Now I just need to glance at one line to see that I'm filling a variable with hats, rather than four.
Doing it this way is also slightly more performant since it avoids the function
calls to add
. The same holds true for filling up other collection types like
lists and dictionaries.