Modules in Python import, packages, __init__ is an important Python topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.
For this page, focus on what problem Modules in Python import, packages, __init__ solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .
A strong understanding of Modules in Python import, packages, __init__ should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.
Modules in Python import packages __init__ should be studied as a practical Python lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.
In the python > modules page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.
A module is a Python file (.py) containing functions, classes, and variables that you can reuse in other files. Python has a huge standard library of built-in modules, plus thousands of third-party packages.
import math # import entire module
import math as m # import with alias
from math import sqrt, pi # import specific names
from math import * # import everything (avoid this)
# Using the module
print(math.sqrt(16)) # 4.0
print(m.pi) # 3.141592653589793
print(sqrt(25)) # 5.0
print(pi) # 3.141592653589793
# Common standard library modules
import os
import sys
import json
import datetime
import random
import re
import collections
import itertools
import functools
# mathutils.py
PI = 3.14159
def circle_area(radius: float) -> float:
"""Calculate area of a circle."""
return PI * radius ** 2
def circle_perimeter(radius: float) -> float:
"""Calculate perimeter of a circle."""
return 2 * PI * radius
def is_prime(n: int) -> bool:
"""Check if a number is prime."""
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# main.py - in the same directory
import mathutils
from mathutils import is_prime
print(mathutils.circle_area(5)) # 78.53975
print(mathutils.circle_perimeter(5)) # 31.4159
print(is_prime(17)) # True
print(is_prime(20)) # False
Every module has a __name__ variable. When run directly, it equals "__main__". When imported, it equals the module's filename.
def greet(name):
return f"Hello, {name}!"
def main():
print(greet("World"))
# This block only runs when the file is executed directly
# NOT when it's imported by another module
if __name__ == "__main__":
main()
A package is a directory containing multiple modules and an __init__.py file.
mypackage/
├── __init__.py # makes it a package
├── math_utils.py
├── string_utils.py
└── io/
├── __init__.py
└── file_reader.py
# Importing from a package
from mypackage import math_utils
from mypackage.string_utils import capitalize
from mypackage.io.file_reader import read_csv
import os
import random
import json
from collections import Counter, defaultdict
# os - file system operations
print(os.getcwd()) # current directory
print(os.path.join("folder", "file")) # folder/file
os.makedirs("new_dir", exist_ok=True)
# random - random numbers
print(random.randint(1, 10)) # random int 1-10
print(random.choice(["a", "b", "c"])) # random item
items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items)
# json - encode/decode JSON
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data, indent=2)
print(json_str)
parsed = json.loads(json_str)
print(parsed["name"]) # Alice
# collections.Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
count = Counter(words)
print(count) # Counter({'apple': 3, 'banana': 2, 'cherry': 1})
print(count.most_common(2)) # [('apple', 3), ('banana', 2)]
# collections.defaultdict
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
print(dd) # defaultdict(<class 'list'>, {'fruits': ['apple', 'banana']})
When studying Modules in Python import, packages, __init__, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.
In Python, Modules in Python import, packages, __init__ becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.
def review_modules-in-python-import-packages-init():
value = "sample"
if value:
print("Modules in Python import packages __init__: normal path is ready")
else:
print("Modules in Python import packages __init__: handle the empty path first")
review_modules-in-python-import-packages-init()
items = []
if not items:
print("Modules in Python import packages __init__: no data available, show a fallback")
else:
print(items[0])
Memorizing Modules in Python import packages __init__ without the situation where it is useful.
Connect Modules in Python import packages __init__ to a concrete Python task.
Testing Modules in Python import packages __init__ only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Modules in Python import packages __init__.
Memorizing Modules in Python import packages __init__ without the situation where it is useful.
Connect Modules in Python import packages __init__ to a concrete Python task.
The common mistake is memorizing syntax without understanding when the behavior changes or fails.
Remember the problem it solves in Python, then attach the syntax or steps to that problem.
You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.
They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.