Skip to Content
Course content

157: The import Statement and Its Variants

Click on the "Edit" button in the top corner of the screen to edit your slide content.

By now, you've probably been using import for a while, but if you're just doing import math or import os, you're missing out on some of the nuance that makes large projects manageable. When a project grows from one file to fifty, how you bring in your dependencies determines whether your code is a clean map or a tangled web of naming conflicts.

Let's build a simple "Expense Reporter." I've already written a helper module called finance_utils.py that contains a few functions for currency formatting and tax calculation. Here is what that file looks like:

# finance_utils.py
def format_to_usd(amount):
    return f"${amount:,.2f}"

def calculate_vat(amount, rate=0.20):
    return amount * rate

def clear_screen():
    print("\n" * 50)

Bringing in the whole toolbox

The most straightforward way to use this is the basic import statement. I'll start my main script, report.py, like this:

import finance_utils

price = 1200.50
print(finance_utils.format_to_usd(price))

This is the safest approach. It creates a clear namespace. Whenever I see finance_utils.something(), I know exactly where that function came from. However, if I'm calling these functions twenty times in one file, typing finance_utils over and over gets tedious and clutters the line.

Plucking specific tools with from

Since I know I only really need the currency formatter for this specific report, I can use the from ... import ... variant. This brings the function directly into my local scope.

from finance_utils import format_to_usd

price = 1200.50
# Now I don't need the module prefix
print(format_to_usd(price))

This reads much more like natural English. But here is where I usually make my first mistake when I'm rushing. Watch what happens when I try to use another function from that same module without importing it explicitly.

from finance_utils import format_to_usd

price = 1200.50
print(format_to_usd(price))
print(calculate_vat(price)) # NameError: name 'calculate_vat' is not defined

I forgot that from finance_utils import format_to_usd doesn't import the module; it only imports that one specific object. I've basically told Python, "Just give me this one tool and ignore the rest of the shed." To fix this, I can either import both from finance_utils import format_to_usd, calculate_vat or just go back to import finance_utils.

The danger of the wildcard

You'll see some tutorials use from module import *. It looks tempting because it imports everything at once. Let's see why I avoid this in professional code.

from finance_utils import *

# Imagine I already had a function in this file called clear_screen
def clear_screen():
    print("My custom local clear screen logic")

# Now, because of the wildcard import, 
# the version in finance_utils.py has overwritten my local one!
clear_screen() 

This is called "namespace pollution." When you use *, you're blindly dumping every function and variable from another file into your current one. If both files have a function with the same name, the last one imported wins, and you'll spend an hour debugging why your function is behaving strangely.

Shortening names with aliases

Finally, there's the as keyword. This is a lifesaver when you're dealing with modules that have long names or when you want to avoid conflicts. I use this constantly with libraries like Pandas (import pandas as pd) or NumPy. For our project, let's say I want the safety of the full module but without the typing fatigue.

import finance_utils as fu
import datetime as dt

price = 1200.50
today = dt.date.today()

print(f"Report Date: {today}")
print(f"Total: {fu.format_to_usd(price)}")

Now I have the best of both worlds: the code is concise, but the fu. prefix still tells me exactly where format_to_usd lives.




📋 Practical Task

Exercise: Refactoring the Geometry Calculator Imports

You have been given a file called geometry_helpers.py containing the following code:

# geometry_helpers.py
import math

def calculate_circle_area(radius):
    return math.pi * (radius ** 2)

def calculate_rectangle_area(width, height):
    return width * height

def get_pi_constant():
    return math.pi

Your task is to create a new file called main.py that does the following:

  1. Imports the geometry_helpers module using an alias called gh.
  2. Imports the math module using an alias called m.
  3. Uses the gh alias to call calculate_circle_area with a radius of 5.
  4. Uses the m alias to print the value of m.sqrt(144).
  5. Uses a from ... import ... statement to bring calculate_rectangle_area directly into the namespace and call it with a width of 10 and height of 20.

Ensure your output clearly labels each result.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.