-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy path01_imports.py
More file actions
273 lines (206 loc) · 7.69 KB
/
01_imports.py
File metadata and controls
273 lines (206 loc) · 7.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"""
================================================================================
File: 01_imports.py
Topic: Importing Modules and Packages in Python
================================================================================
This file demonstrates how to import and use modules in Python. Modules are
files containing Python code that can be reused across different programs.
Python's extensive standard library and third-party packages make imports
essential for productive development.
Key Concepts:
- import statement
- from ... import ...
- Aliasing with 'as'
- Built-in and standard library modules
- Relative imports
================================================================================
"""
# -----------------------------------------------------------------------------
# 1. Basic Import Statement
# -----------------------------------------------------------------------------
# Import entire module
print("--- Basic Import ---")
import math
# Access functions using module.function
print(f"math.pi = {math.pi}")
print(f"math.sqrt(16) = {math.sqrt(16)}")
print(f"math.ceil(3.2) = {math.ceil(3.2)}")
print(f"math.floor(3.8) = {math.floor(3.8)}")
# -----------------------------------------------------------------------------
# 2. Import Specific Items
# -----------------------------------------------------------------------------
# Import only what you need
print("\n--- From Import ---")
from math import pi, sqrt, pow
# Use directly without module prefix
print(f"pi = {pi}")
print(f"sqrt(25) = {sqrt(25)}")
print(f"pow(2, 8) = {pow(2, 8)}")
# Import multiple items
from datetime import date, time, datetime
today = date.today()
print(f"\nToday's date: {today}")
now = datetime.now()
print(f"Current datetime: {now}")
# -----------------------------------------------------------------------------
# 3. Import with Alias
# -----------------------------------------------------------------------------
# Rename modules or items for convenience
print("\n--- Import with Alias ---")
# Module alias
import random as rnd
print(f"Random number: {rnd.randint(1, 100)}")
print(f"Random choice: {rnd.choice(['apple', 'banana', 'cherry'])}")
# Common conventions
import collections as col
import json as json # Usually kept as is
import os as os # Usually kept as is
# Item alias
from math import factorial as fact
print(f"\nfact(5) = {fact(5)}")
# -----------------------------------------------------------------------------
# 4. Import All (Use Sparingly)
# -----------------------------------------------------------------------------
# Import everything from a module
print("\n--- Import All (Not Recommended) ---")
# from math import *
# This imports everything, but:
# - Can cause naming conflicts
# - Makes it unclear where functions come from
# - Only use in interactive sessions if at all
# Better to be explicit about what you import
# -----------------------------------------------------------------------------
# 5. Useful Standard Library Modules
# -----------------------------------------------------------------------------
print("\n--- Standard Library Examples ---")
# os - Operating system interface
import os
print(f"Current directory: {os.getcwd()}")
print(f"Directory separator: {os.sep}")
# sys - System-specific parameters
import sys
print(f"\nPython version: {sys.version_info.major}.{sys.version_info.minor}")
# collections - Specialized containers
from collections import Counter, defaultdict
word_counts = Counter("mississippi")
print(f"\nCharacter counts: {dict(word_counts)}")
# Default dictionary
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
dd["vegetables"].append("carrot")
print(f"defaultdict: {dict(dd)}")
# json - JSON encoding/decoding
import json
data = {"name": "Alice", "age": 30}
json_string = json.dumps(data, indent=2)
print(f"\nJSON string:\n{json_string}")
# re - Regular expressions
import re
text = "Contact: john@email.com or jane@company.org"
emails = re.findall(r'\b[\w.-]+@[\w.-]+\.\w+\b', text)
print(f"Found emails: {emails}")
# itertools - Iteration utilities
from itertools import combinations, permutations
items = ['A', 'B', 'C']
print(f"\nCombinations of 2: {list(combinations(items, 2))}")
print(f"Permutations of 2: {list(permutations(items, 2))}")
# functools - Higher-order functions
from functools import lru_cache
@lru_cache(maxsize=100)
def fibonacci(n):
"""Cached fibonacci for performance."""
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(f"\nFibonacci(30): {fibonacci(30)}")
print(f"Cache info: {fibonacci.cache_info()}")
# -----------------------------------------------------------------------------
# 6. Checking Module Attributes
# -----------------------------------------------------------------------------
print("\n--- Module Attributes ---")
import math
# List all attributes/functions in a module
print("Math module functions (first 10):")
for name in dir(math)[:10]:
print(f" {name}")
# Module docstring
print(f"\nMath module doc: {math.__doc__[:50]}...")
# Module file location
print(f"Math module file: {math.__file__}")
# -----------------------------------------------------------------------------
# 7. Conditional Imports
# -----------------------------------------------------------------------------
print("\n--- Conditional Imports ---")
# Try to import, use fallback if not available
try:
import numpy as np
HAS_NUMPY = True
print("NumPy is available")
except ImportError:
HAS_NUMPY = False
print("NumPy is NOT available")
# Another pattern
import sys
if sys.version_info >= (3, 9):
from typing import Annotated # Python 3.9+
else:
print("Annotated not available (Python < 3.9)")
# -----------------------------------------------------------------------------
# 8. Module Search Path
# -----------------------------------------------------------------------------
print("\n--- Module Search Path ---")
import sys
print("Python searches for modules in:")
for i, path in enumerate(sys.path[:5]): # First 5 paths
print(f" {i+1}. {path}")
print(f" ... and {len(sys.path) - 5} more locations")
# Adding custom path (temporarily)
# sys.path.append('/my/custom/modules')
# -----------------------------------------------------------------------------
# 9. Import Patterns in Projects
# -----------------------------------------------------------------------------
print("\n--- Import Best Practices ---")
# Standard order for imports:
# 1. Standard library imports
# 2. Third-party imports
# 3. Local/project imports
# Example of well-organized imports:
"""
# Standard library
import os
import sys
from datetime import datetime
from typing import List, Dict
# Third-party (installed via pip)
import requests
import numpy as np
import pandas as pd
# Local/project modules
from myproject.utils import helper
from myproject.models import User
"""
print("Import order: Standard -> Third-party -> Local")
print("Group imports with blank lines between groups")
# -----------------------------------------------------------------------------
# 10. Practical Example: Building a Utility
# -----------------------------------------------------------------------------
print("\n--- Practical Example ---")
# Using multiple modules together
import os
import json
from datetime import datetime
from pathlib import Path
def get_system_info():
"""Gather system information using various modules."""
return {
"python_version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
"platform": sys.platform,
"cwd": os.getcwd(),
"home_dir": str(Path.home()),
"timestamp": datetime.now().isoformat(),
"path_separator": os.sep
}
info = get_system_info()
print("System Info:")
print(json.dumps(info, indent=2))