Study guide · Python
Python Modules and Imports: What Exams Actually Test
This page contains affiliate links. We may earn a commission at no extra cost to you.
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.
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
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())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.pycollections 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!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.Want a person to help?
Struggling with Python? Work 1:1 with a vetted Python tutor on Wyzant. (affiliate link)
Find a Python tutor →