A member of the data science team wrote the following normalize
function:
https://gist.github.com/fe267ab16e764386e9281a4d8ec11f7c
You're assigned with the task of testing it. Here's the first test you write, checking for errors:
https://gist.github.com/554fa92fb17d28c5fac0d65208bfa42c
When you run the test, it fails!
https://gist.github.com/1ea81b692491bc988436afe8132403f6
When did division by zero became OK in Python? You fire up IPython and start checking:
https://gist.github.com/a55da5bd02c41677577adf82c8fb95b7
Ah! Now you remember, the boolean operators in Python (and
& or
) are short-circuited.
Short-circuiting means that Python evaluates only as much as it need in order to give an answer.
When you write 0 and 1/0
, Python know after evaluating the 0
that the result is going to be False
and does not continue to evaluate 1/0
.
Python is not unique by short-circuiting boolean operators, most languages do that. Once you understand this, you can use short-circuiting for your advantage. For example, assume you want to query a database for a user by login name, but only if the login name if not empty. You can write:
https://gist.github.com/2971c57735714006baa2980930575919
Due to short-circuiting, db.find_user
won't be called if login
is empty (which evaluates to False
).
Note that you can't write code that short-circuits yourself. When you write a function, all values to the function are evaluated before the function call.
One place you can have issue with this behaviour is when logging. Say you'd like to log the current user details, but only in DEBUG
level. You can write something like:
https://gist.github.com/851d074de9da48dd61caaa4a358d14b2
If you'll debug or profile the code, you'll see that db.find_user
is called regardless of the logging level. Since log.debug
is a function call, Python will evaluate db.find_user(login)
before calling the function. Inside the function, the logging module will check the level and won't print anything.
To overcome this issue, logging objects provides a isEnabledFor
method. Now you can write:
https://gist.github.com/19a1e6e1c894ef865c571574f2f5c0f2
Know these and other feature of Python, will help you to gain deeper understanding the language and to become a better developer. If you want to learn more, why note buy my Python Brain Teasers book? It's full of such gems.