Python performance: Try-except or not in?

前端 未结 5 791
南笙
南笙 2020-12-19 19:32

In one of my classes I have a number of methods that all draw values from the same dictionaries. However, if one of the methods tries to access a value that isn\'t there, it

5条回答
  •  情深已故
    2020-12-19 20:10

    Checking if a key exists is cheaper or at least as cheap as retrieving it. So use the if not in solution which is much cleaner and more readable.

    According to your question a key not existing is not an error-like case so there's no good reason to let python raise an exception (even though you catch it immediately), and if you have a if not in check, everyone knows your intention - to get the existing value or otherwise generate it.

提交回复
热议问题