Tip 85 Check, Then Touch

Pythonic Programming — by Dmitry Zinoviev (98 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Compare One to Many | TOC | Assert Conditions 👉

★2.7, 3.4+ Tip 19, Try It, proposes an “optimistic” approach to operations that may fail, such as opening a file or indexing a list/tuple/dictionary: let it fail and catch an exception, if any. However, exception handling is relatively expensive. The “pessimistic” approach endorses safety and calls for checking if an operation may cause a problem before engaging in the operation. If the check is considerably less expensive than handling an exception, go for it.

Lists and tuples do not give you too many choices. The only way to ensure that an item exists, is to check if its index is smaller than the length and larger than or equal to the negative length (for the negative indexes):

​ ​if​ -len(my_list) <= i < len(my_list):
​ ​# Access my_list[i]​

Note that even the first and the last list/tuple elements are not guaranteed to exist.

Dictionaries are more versatile. In addition to the indexing operator [], they have the method dict.get(key). If the key exists in the dictionary, the method returns the associated value. Otherwise, the method returns None (which is against Tip 51, Return Consistently). If you pass the second optional argument d, then dict.get(key, d) returns d on failure.

​ my_dict = {​'Earth'​ : ​'Sun'​, ​'Mars'​ : ​'Sun'​, ​'Dimidium'​: ​'51 Pegasi'​}
​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.