smartyfy.mrindigi.com

Python Master Course V2 — 061. Importing Modules

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 07 — MODULES AND PACKAGES · LESSON 061 / 200

Importing Modules

Estimated study: 60–90 minutes. Prerequisites: functions, collections, control flow and the preceding lesson. Level: intermediate Python.

Course hub

Video lesson

Video not yet available. Reserved for a verified video URL/player; written learning materials are available now.

Learning outcomes

Use import, from-import and aliases. After completing this lesson, you should be able to explain the underlying mechanism, run the example, identify a boundary case, and apply the concept in a practical program.

Understand and apply: Importing Modules

Imports connect a program to named functionality

A module is a unit of Python code with its own namespace. Importing gives your program access to its functions, classes, and other names. Start with a module-qualified import when clarity matters: math.sqrt shows where sqrt comes from. An import statement is executable code, so the relevant binding must exist before a statement uses it. Imports usually belong near the top of a file so dependencies are easy to find.

Python code

import math
import statistics as stats
from math import ceil

print(math.sqrt(81))
print(stats.mean([4, 8, 12]))
print(ceil(2.2))

Expected output

9.0
8
3

The first form binds math to the module object. The alias form binds stats to the statistics module; it does not create a new copy or require an installation. The from-import form binds ceil directly in the current namespace, so the call does not need a math prefix. Choose aliases that are familiar or clearer than the original name. A cryptic one-letter alias can make a short example harder to read.

Names imported by one form are not all imported by another

After only from math import sqrt, sqrt is available directly but the name math has not been bound by that statement. Calling math.sqrt(9) then raises NameError unless something else previously imported math. Avoid from module import * in these lessons: it hides where names came from and increases accidental collisions. Be especially careful in interactive sessions, where old bindings can conceal a missing import in a script.

On a normal first import in a process, Python locates and initializes the module, executing its top-level code. It caches the resulting module in sys.modules. A later ordinary import of that same module name generally reuses the cached object rather than running the file again. Starting a new Python process starts a new import session. Do not rely on repeatedly importing a helper to repeat work or to pick up edits during a long interactive session.

A small imported statistics workflow

Python code

import math
from statistics import mean

def root_mean_square(values):
    if not values:
        raise ValueError("values must not be empty")
    squares = [value * value for value in values]
    return math.sqrt(mean(squares))

print(root_mean_square([3, 3]))
print(root_mean_square([0]))

Expected output

3.0
0.0

This helper’s teaching contract is a nonempty list of finite ordinary numeric measurements small enough that squaring does not overflow. It squares each value, takes the arithmetic mean, and then the square root. The explicit empty-input guard explains the failure at the boundary rather than leaving the learner to infer it from statistics.mean. A production input boundary should validate the measurement types and finiteness if data comes from an external source.

Diagnose the kind of import failure

ModuleNotFoundError usually means Python could not locate a requested module or a dependency it needs. ImportError can indicate that a requested name could not be imported from a located module. NameError means the name used in your code is not bound in that scope. Read the traceback to distinguish these cases before installing anything. A file named statistics.py in your project can shadow the standard-library module; rename the conflicting file and restart the process.

For a located module, inspecting its __file__ attribute often helps identify its source; some built-in modules do not have that attribute. Standard-library math and statistics do not require pip installation. The next lesson separates your own helper into a module, using the same import mechanism while making startup behavior visible.

Runnable Python example

Requires Python 3.10+. Save the example as lesson61.py and run python lesson61.py (or python3). If it writes a file, run it in a disposable practice directory.

import math
print(math.sqrt(81))
from statistics import mean
print(mean([4, 8, 12]))

Expected output:

9.0
8

Step-by-step walkthrough

Read each statement in execution order. Identify imported modules, assigned variables, functions and the result passed to print(). Compare the output with the expected output and then change one input. Explain why the behavior changed. When an exception occurs, read the final traceback line and inspect the call that produced it.

Extension example

Refactor the central calculation or operation into a named function with a docstring and type hints. Add a caller that invokes it twice with different inputs. Test both results with assertions; for file operations, also test that the expected file exists and clean up practice files afterward.

Guided project — Importing Modules application

Create a statistics utility that imports math and statistics safely.

  1. Write a short requirements document specifying input data, output data and expected errors.
  2. Implement one focused function or module for the core behavior.
  3. Write a separate program entry point to collect or construct example input.
  4. Add validation and informative errors where appropriate.
  5. Test a normal case, a boundary case and an invalid case.
  6. Write a README showing how to run and test the program.

Acceptance criteria: clear behavior, no unexplained dependencies, reproducible execution and a documented result. The project is a guided assignment; its implementation must be completed and tested by the learner.

Common mistakes, debugging and best practices

  • Importing a local file with the same name as a standard-library module, causing shadowing.
  • Using broad exception handlers that conceal the real defect.
  • Assuming a path or dependency exists on every computer.
  • Mixing input/output and reusable business logic into one difficult-to-test function.
  • Testing only the happy path rather than edge cases and failures.

Debugging procedure: reproduce the failure with the smallest input; read the traceback; verify assumptions and data types; change one thing; rerun the same test; add a regression test after the fix.

Practice and explained answers

Try each question before opening its answer. These self-checks do not record course completion.

1. After import statistics as stats, which name should the caller use?

Need a hint?

Look at the name introduced after as.

Reveal answer and explanation

Answer and reasoning: Use stats.mean(...). The alias is the name bound in the current namespace. That statement alone does not also bind the name statistics there.

2. Does from math import sqrt automatically make math.sqrt available?

Reveal answer and explanation

Answer and reasoning: No. It binds sqrt directly. Use sqrt(9), or separately import math and call math.sqrt(9). A previous interactive import can hide this distinction, so test scripts in a fresh process.

3. Why does importing the same helper twice normally not print its startup message twice?

Reveal answer and explanation

Answer and reasoning: The first normal import initializes it and caches the module object. The second ordinarily reuses that object from sys.modules. Explicit reloading or a new process is a different situation.

4. What should you inspect if statistics.mean appears to be missing?

Reveal answer and explanation

Answer and reasoning: Read the traceback and check whether the imported module is your own file named statistics.py. Inspecting statistics.__file__ can reveal shadowing. Rename the local conflict and restart rather than installing an unrelated package.

5. What is the smallest valid root_mean_square input here, and what should empty input do?

Reveal answer and explanation

Answer and reasoning: A single finite measurement such as [0] is valid and returns 0.0. An empty list raises ValueError under the stated contract because there is no mean to calculate. This tests validity rather than assuming every collection is meaningful.

Mastery checkpoint and summary

Demonstrate the concept without copying, explain one failure mode, complete the guided project and write three independent tests. These are suggested mastery checks, not account-synchronized completion records.

Key takeaway: Use import, from-import and aliases. Apply it through clear contracts, thoughtful error handling, and repeatable testing.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.