Python Modules
advancedPart of Python in Practice
Theory
Modules and packages are Python's mechanism for organizing code into reusable units. A module is a single .py file. A package is a directory containing an __init__.py file and multiple modules.
Importing modules uses the import statement. Variants include import module, import module as alias, from module import name, and from module import name as alias. Python searches for modules in sys.path, which includes the current directory, PYTHONPATH, and standard library paths.
The Standard Library is one of Python's greatest strengths — "batteries included." Key modules:
os— operating system interface: file paths, environment variables, process managementsys— system-specific parameters: command-line arguments, Python path, exit functionsmath— mathematical functions:sqrt,sin,cos,pi,floor,ceildatetime— date and time handling:date,time,datetime,timedeltarandom— random number generation:randint,choice,shufflejson— JSON encoding/decoding:dumps,loads,dump,loadre— regular expressions:search,match,findall,subcollections— specialized data structures:Counter,defaultdict,namedtuple
Pip is Python's package installer. Install packages from PyPI with pip install package_name. Common third-party packages include requests (HTTP), numpy (numerical computing), pandas (data analysis), and flask (web framework).
Creating modules: Any .py file is a module. Functions and classes defined in it can be imported by other scripts. Use if __name__ == "__main__": to make a file both importable and executable.
Best practices: Group related functions into modules. Use packages for larger projects. Avoid circular imports. Prefer absolute imports over relative imports for clarity.
Exercises
Random Password Generator
Write a Python program that uses the random and string modules to generate a random password of length 12. Use string.ascii_letters + string.digits for characters and random.choice() to pick each character.
Starter Code:
import random\nimport string\n\n# Generate a 12-character random password\nprint(password)Expected Output:
a8Kf3mR9xQ2p (random - any 12-char alphanumeric string is fine)