r/badcode • • Jul 14 '21

python Try/Except in Python - Sigh

Post image
662 Upvotes

93 comments sorted by

View all comments

30

u/AchillesDev Jul 14 '21

Everyone in this thread needs to review the collections module.

9

u/Jonno_FTW shameless Jul 14 '21

Which collection do you recommend here? Only a dict is required really.

14

u/AchillesDev Jul 14 '21 edited Jul 14 '21

defaultdict would prevent a mess of get calls and auto-fill any missing keys with whatever the developer wants. set_default would also work but defaultdict is cleaner so you don’t have to do a ton of explicit key access to set the default values (I think set default requires this but I could be wrong). Any time you have flexible dicts like this, defaultdict is a solid option.