Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Comparing 3 Ways to Import Multiple Things from the Same Python Module

blog/cards/comparing-3-ways-to-import-multiple-things-from-the-same-python-module.jpg

We'll go with IMO the least error prone and most readable solution which explicitly defines them with their full module path.

Quick Jump: Reviewing 3 Ways to Format Multiple Imports

Lately I’ve been formatting multiple imports from the same module like this:

# On its own line with the full module path for each import.
from hello.extensions import db
from hello.extensions import debug_toolbar
from hello.extensions import flask_static_digest

As opposed to:

# Comma separated and on 1 line.
from hello.extensions import db, debug_toolbar, flask_static_digest

# On its own line using parenthesis and 1 module path.
from hello.extensions import (
  db,
  debug_toolbar,
  flask_static_digest,
)

All 3 strategies give the same end result but in my opinion the first one is the least error prone because it avoids potential merge conflicts that can occur and is IMO less ugly than the third example while also using less lines.

This video goes into a bit more detail on comparing them.

Reviewing 3 Ways to Format Multiple Imports

Timestamped Table of Contents

  • 0:36 – There’s multiple ways to import more than 1 variable from the same file
  • 1:31 – Lately I’ve been putting each import on its own line
  • 1:55 – This new style reduces merge conflicts
  • 2:57 – Another common way avoids merge conflicts too but it requires decisions
  • 4:34 – You’ll occasionally be typing a little bit more but it’s not bad
  • 4:51 – The 1 liner approach makes it harder to sort your imports
  • 6:17 – This new style may or may not involve more lines total (it depends)
  • 7:40 – Which import style do you prefer?

How do you prefer formatting multiple imports? Let me know below.

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per month (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments