An opinionated approach to structure your try-except code

Exceptions mechanism is widely adopted among modern programming languages, and Python is not an exception. (Pun intended!) Though this topic could seem obvious, like wrap your code blocks with try-catch clauses, and that’s all, there are some minor but important details, and taking them into account should make your code a bit cleaner.

In this post, I’m going through some guidelines on how to structure error processing in Python that I derived from my personal experience.

Image for post
Image for post
Photo by Sarah Kilian on Unsplash

Use Meaningful Classes

It is very tempting to write the following code, and I’ve seen it several times in projects where I was a collaborator.

if something_is_wrong():
raise Exception('error!') …

Using the standard library to convert a function’s signature into a console arguments parser

When working on machine leanring projects, you need to write lots of ad-hoc code snippets: downloading and reading/unpacking the data, converting the data into a convenient format, building training pipelines, and many more. You probably reuse some of these scripts, but the rest of them you’ll throw away after a few iterations, or when switching to another task.

You need somehow parameterize your scripts, i.e., set up input/output folders, tune the training parameters, or replace one architecture with another. For this purpose, you should write a proper argument parser that converts your CLI parameters into script variables or function parameters. …


A parable about missed deadlines and over-engineering

Some time ago I attended to a coding interview for the position of Data Scientist at one start-up. I felt myself well-prepared and confident, practicing lots of programming puzzles, coding various Machine Learning techniques from scratch, and having several years of programming experience under the belt. What can go wrong?

Unfortunately, I failed at the thing that doesn’t have any relation to the Gradient Descent methods or Time Complexity analysis. No, the failure was related to something very different and much more complicated. It was a Tic-Tac-Toe game!

I bet at this moment, some of you just close this story with thoughts: What, a Tic-Tac-Toe game? How can one fail to implement such a simple thing? You should be a total newbie, man, not being able to solve such a trivial exercise!

About

Ilia Zaitsev

Software Developer & AI Enthusiast. Working with Machine Learning, Data Science, and Data Analytics. Writing posts every once in a while.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store