Chapter 10: Advanced Topics / Lesson 51

Modules and Packages

Introduction to Modules and Packages

Modules are Python files containing functions, classes, and variables that you can import and use in other programs. Packages are collections of modules organized in directories. Using modules and packages helps organize code, avoid repetition, and build on others' work.

Python comes with a vast standard library of modules, and you can also create your own modules or install third-party packages.

Importing Modules

Use the import statement to use modules in your code:

importing.py
# Import entire module import math result = math.sqrt(16) # 4.0 print(math.pi) # 3.14159... # Import specific items from math import sqrt, pi result = sqrt(25) # 5.0 print(pi) # Import with alias import datetime as dt now = dt.datetime.now() # Import all (not recommended) from math import * result = sqrt(36)

Common Standard Library Modules

Python's standard library includes many useful modules:

  • math - Mathematical functions
  • random - Random number generation
  • datetime - Date and time operations
  • os - Operating system interface
  • sys - System-specific parameters
  • json - JSON data handling
  • re - Regular expressions

Creating Your Own Modules

You can create your own modules by saving Python code in a .py file:

my_module.py
# my_module.py def greet(name): return f"Hello, {name}!" def add(a, b): return a + b PI = 3.14159 # In another file: # import my_module # print(my_module.greet("Alice")) # result = my_module.add(5, 3)

Packages

Packages are directories containing multiple modules. They must have an __init__.py file:

package_structure.py
# Package structure: # mypackage/ # __init__.py # module1.py # module2.py # Import from package from mypackage import module1 from mypackage.module2 import some_function # Or import mypackage.module1

Best Practices

✅ Module Usage Tips

• Use specific imports instead of import *

• Organize related functions into modules

• Use packages for larger projects

• Follow Python naming conventions (lowercase, underscores)

• Document your modules with docstrings

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...