Is your code being called "Messy Import" behind your back?
Organize your imports this way, and your colleagues will love you.
Properly organizing your imports gives you two perks:
you’ll make great first impressions,
your colleagues will love you.
Let’s reap these perks, shall we? 😉
Your imports are your code’s first impression
Let’s say you’re tasked with updating a script you haven’t seen before.
Let’s say you don’t feel like doing it, but you know, it’s work, so you have to.
You open up the script, and here’s what you see:
“OMG” – this is what you think.
Sigh – this is what you do.
I feel you. You want to get a quick overview of the code ASAP, but you get stuck at the beginning. It’s impossible to quickly grasp what modules are used, what you need to pip install
and so on.
With no other option, you start a painful, line-by-line check.
As you do this, you start to dislike the person who wrote the code. Rightfully so, because their messy imports waste your precious time, which you could've spent in a thousand better ways.
You also start to suspect that the code following the imports is a mess too. Now you feel even less like working with this script (or the person who wrote it).
🙁🙁🙁
All these negative feelings just because of some disorganized imports.
You don't want to leave first impressions like this. You don’t want your code to be called “Messy Import” behind your back.
You want your colleagues to think of you as someone they love to work with.
This brings us to our next point: code is more often read than written, so you should make your code easy to read.
“Easy to read” fosters faster understanding. Faster understanding lets code readers spend their valuable brainpower and time on actually doing something useful (like coding).
This means you can potentially save them time – and if you do that, they’ll like you and you’ll build a good rep for yourself in the long term. 😉
Okay. Point taken.
So, how do you do imports properly? 🤔
Here’s how you do imports in Python that look like something a pro would do
Again, this is our BAD version:
Now we’ll turn it into COOL. Here’s our 2-step game plan:
Separate the libraries into different groups, with a blank line between them:
put the built-ins first (=the ones that come preinstalled with Python),
then third parties (=the ones you
pip install
),finally, your own modules (=the ones you created).
Then, order the libraries/modules within each group alphabetically:
OMG.
But this time in a good way. 🎉
It has everything we wanted: it'll deliver a great first impression and make it easy for anyone to review the imports – and they'll love you for that!
Anyways.
Thanks for reading this & don’t forget to have an awesome day! 😎