Tip 19 Try It

Pythonic Programming — by Dmitry Zinoviev (28 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Pass It | TOC | Embrace Comprehensions 👉

★★2.7, 3.4+ There are two programming approaches to coding an operation that may fail: an optimistic and a pessimistic one. The pessimistic approach explained in Tip 85, Check, Then Touch implies that failures are frequent and costly to repair. It is cheaper to avoid them by checking some precondition.

The optimistic approach, on the contrary, implies that failures are rare. It is cheaper to try and then recover if anything goes wrong using the exception handling mechanism (try/except). One of the most illustrative examples of an optimistic scenario is checking whether a string represents a number.

Though not trivial, it is possible to describe a valid string representation of a floating-point number with an exponential part using a regular expression. However, it is much easier to pretend that a string represents such a number and attempt to convert it. If the conversion is successful, the string is a number. Otherwise, it is not (Tip 47, Discover an Infinity):

​ ​def​ ​string_to_float​(s):
​ ​try​:
​ ​return​ float(s)
​ ​except​ ValueError:
​ ​return​ float(​'nan'​)

Another common application of the optimistic method is opening a file for reading. You can open a file for reading if it exists, is indeed a file (not a directory), it belongs to you, and is readable. You can replace this sequence of…

--

--

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.