HomeGuidesPythonPython Modules and Imports Explained — import, from, __name__
🐍 Python

Python Modules and Imports: What Exams Actually Test

Imports and modules are tested more than most people study them. Here's what you need to know — from import syntax to __name__ to packages.

Examifyr·2026·5 min read

Import syntax

There are several ways to import. Each has different implications for how you access the imported names.

import math              # access via math.sqrt()
import math as m         # alias: m.sqrt()
from math import sqrt    # direct: sqrt()
from math import sqrt, pi
from math import *       # imports everything (avoid)

print(math.sqrt(16))     # 4.0
print(m.sqrt(16))        # 4.0
print(sqrt(16))          # 4.0
Note: `from module import *` is considered bad practice because it pollutes the namespace.

__name__ == "__main__"

When you run a file directly, __name__ is "__main__". When imported as a module, __name__ is the module filename.

# mymodule.py
def helper():
    return "I help"

if __name__ == "__main__":
    # Only runs when executed directly
    # NOT when imported
    print(helper())
Note: This pattern is the standard way to write code that runs when a file is executed but not when imported. Every Python exam tests this.

The standard library

Know these modules for exams.

import os, sys, math, random, datetime, json, re
from collections import defaultdict, Counter, deque

os.path.join("dir", "file.txt")
os.getcwd()
sys.argv
random.choice([1, 2, 3])
json.dumps({"key": "value"})
json.loads('{"key": "value"}')

Creating your own module

Any .py file is a module. Any directory with an __init__.py is a package.

# utils.py
def add(a, b):
    return a + b

# main.py
import utils
print(utils.add(2, 3))  # 5

# Package structure:
# mypackage/
#   __init__.py
#   math_utils.py

collections module

The collections module provides specialised data structures tested in Python exams.

from collections import Counter, defaultdict

words = ["apple", "banana", "apple", "cherry", "apple"]
count = Counter(words)
print(count.most_common(2))
# [('apple', 3), ('banana', 1)]

dd = defaultdict(list)
dd["fruits"].append("apple")  # no KeyError!

Exam tip

The `if __name__ == "__main__":` pattern is tested in virtually every Python exam. Know that this block runs when the file is executed directly but NOT when imported.

🎯

Think you're ready? Prove it.

Take the free Python readiness test. Get a score, topic breakdown, and your exact weak areas.

Take the free Python test →

Free · No sign-up · Instant results

← Previous
Python String Methods — Complete Reference with Code Examples
Next →
Python File I/O Explained — open(), read, write & Context Managers
← All Python guides