Python Modules and Packages: import, from import, __name__ == '__main__'
1. What are modules in Python, and how do you import standard and custom modules?
Q: What are modules?
Modules: Python files (.py) containing reusable code (functions, classes, variables).
Standard Modules: Built into Python (e.g., math, random).
Custom Modules: User-defined .py files with custom code.
Importing: Use the import statement to access module contents.
Syntax:
import module_name
import module_name as alias
from module_name import item
Use Case: Organizing code, reusing functionality, or accessing built-in utilities.
2. Can you give an example of importing standard and custom modules?
# custom_module.py
def calculate_bonus(salary):
return salary * 0.1
# Importing standard and custom modules
import math
import custom_module as cm
# Using standard module
print(f"Square root of 16: {math.sqrt(16)}")
print(f"Pi: {math.pi}")
# Using custom module
salary = 50000
bonus = cm.calculate_bonus(salary)
print(f"Bonus for ${salary}: ${bonus}")
Output:
Square root of 16: 4.0
Pi: 3.141592653589793
Bonus for $50000: $5000.0
Note:
mathis a standard module;custom_moduleis a user-defined .py file in the same directory.ascreates an alias for convenience.
3. What is the from import... syntax in Python?
Q: What is from import?
Syntax: Imports specific items (functions, classes, variables) from a module, reducing namespace clutter.
Forms:
from module_name import item
from module_name import item1, item2
from module_name import item as alias
Use Case: Accessing specific module components without full qualification.
Caution: Avoid from module import * to prevent namespace pollution.
4. Can you give an example of from import... syntax?
# from import... syntax example
from math import sqrt, pi
from random import randint as random_int
# Using imported items
print(f"Square root of 25: {sqrt(25)}")
print(f"Pi: {pi}")
print(f"Random integer: {random_int(1, 10)}")
Output (Sample):
Square root of 25: 5.0
Pi: 3.141592653589793
Random integer: 7
Note:
- Imports
sqrtandpifrommath,randintasrandom_intfromrandom. - Direct use of imported names improves readability.
5. What are some popular built-in Python modules, and how are they used?
Q: What are common built-in modules?
math: Mathematical functions and constants.
- Examples:
math.sqrt(x),math.sin(x),math.pi.
random: Random number generation.
- Examples:
random.randint(a, b),random.choice(sequence),random.shuffle(list).
datetime: Date and time manipulation.
- Examples:
datetime.datetime.now(),datetime.date.today().
os: Operating system interactions.
- Examples:
os.getcwd(),os.listdir(),os.path.join().
sys: System-specific parameters and functions.
- Examples:
sys.argv,sys.exit(),sys.version.
Use Case: Calculations, randomization, file system operations, or system info.
6. Can you give an example using these built-in modules?
# Built-in modules: math, random, datetime, os, sys
import math
import random
import datetime
import os
import sys
# math
print(f"Cosine of 0: {math.cos(0)}")
# random
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(f"Shuffled numbers: {numbers}")
print(f"Random choice: {random.choice(numbers)}")
# datetime
current_time = datetime.datetime.now()
print(f"Current time: {current_time.strftime('%Y-%m-%d %H:%M:%S')}")
# os
current_dir = os.getcwd()
print(f"Current directory: {current_dir}")
files = os.listdir()
print(f"Files in directory: {files}")
# sys
print(f"Python version: {sys.version.split()[0]}")
Output (Sample):
Cosine of 0: 1.0
Shuffled numbers: [3, 1, 5, 2, 4]
Random choice: 2
Current time: 2025-09-12 10:41:23
Current directory: /home/user/project
Files in directory: ['builtin_modules.py']
Python version: 3.12.4
Note:
- Demonstrates key functions from each module.
- Output varies based on system state (e.g., directory, time).
7. What are packages in Python, and how do you create and use them?
Q: What are packages?
Packages: Directories containing modules and a __init__.py file, allowing hierarchical organization.
Structure:
my_package/
├── __init__.py
├── module1.py
└── module2.py
Creating:
- Create a directory (e.g.,
my_package). - Add an
__init__.pyfile (can be empty or include initialization code). - Add .py modules with functions/classes.
Using: Import modules or items from the package using dot notation.
Syntax: import my_package.module1 or from my_package.module1 import func.
Use Case: Organizing large projects or reusable libraries.
8. What is if __name__ == '__main__' and best practices?
Q: What is if __name__ == '__main__'?
When a module is run directly, __name__ is '__main__'. When imported, it's the module name. This idiom allows code to run only as a script, not on import.
Q: Best practices?
- Use meaningful module/package names.
- Prefer explicit imports over
*. - Use
__init__.pyto control package imports. - Place executable code under
if __name__ == '__main__':. - Document modules with docstrings.