← Back to Python Course | Chapter 8: Modules & Packages | Lesson 1 of 6

Python Modules Introduction

What is a Module?

A module is simply a .py file containing functions, classes, or variables -- once you 'import mymodule', everything defined at that file's top level becomes accessible as mymodule.something, which is how Python breaks large programs into organized, reusable files.

Example: What is a Module?

python
import math
print(math.sqrt(16))

The name Variable

Python sets every module's __name__ to __main__ only when that file is executed directly (python script.py), but to the file's own name when it's imported elsewhere -- this distinction is what the common 'if __name__ == "__main__":' guard relies on.

Example: The name Variable

python
print(__name__)
if __name__ == "__main__":
    print("Running directly")

Mocking Modules in Memory

types.ModuleType lets you construct a module object in memory without a corresponding .py file on disk, which is a niche but genuine technique used in testing frameworks that need to fake an import without touching the filesystem.

Example: Mocking Modules in Memory

python
import types
fake_module = types.ModuleType("fake_module")
fake_module.greet = lambda: print("Hi from fake module")
fake_module.greet()

Active Modules Directory

Every module Python has already imported during a run is cached in the sys.modules dictionary (so re-importing the same module doesn't re-execute its code), while sys.path is the list of directories Python searches when resolving a new import.

Example: Active Modules Directory

python
import sys
import math
print("math" in sys.modules)
print(len(sys.path) > 0)

Reloading Modules

importlib.reload(module) re-runs a module's code and updates its namespace in place, which is occasionally useful in a long-running REPL session after editing a file -- though existing references to old objects from before the reload won't automatically update.

Example: Reloading Modules

python
import importlib
import math
importlib.reload(math)
print(math.pi)
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.