-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy path02_custom_modules.py
More file actions
443 lines (337 loc) · 11 KB
/
02_custom_modules.py
File metadata and controls
443 lines (337 loc) · 11 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
"""
================================================================================
File: 02_custom_modules.py
Topic: Creating and Using Custom Modules
================================================================================
This file demonstrates how to create your own modules and packages in Python.
Custom modules help organize code, promote reusability, and maintain clean
project structures.
Key Concepts:
- Creating module files
- The __name__ variable
- __init__.py for packages
- Relative imports
- Module documentation
- Publishing modules
================================================================================
"""
# -----------------------------------------------------------------------------
# 1. What is a Module?
# -----------------------------------------------------------------------------
# A module is simply a .py file containing Python code
print("--- What is a Module? ---")
# Any Python file is a module!
# If you have: my_utils.py
# You can: import my_utils
# Example module content (imagine this is saved as 'my_math.py'):
"""
# my_math.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
PI = 3.14159
class Calculator:
def multiply(self, a, b):
return a * b
"""
print("A module is just a Python file that can be imported.")
print("It can contain functions, classes, and variables.")
# -----------------------------------------------------------------------------
# 2. The __name__ Variable
# -----------------------------------------------------------------------------
# __name__ tells you how the module is being used
print("\n--- The __name__ Variable ---")
# When a file is run directly: __name__ == "__main__"
# When a file is imported: __name__ == module_name
print(f"Current __name__: {__name__}")
# Common pattern for executable modules:
"""
# utils.py
def useful_function():
return "I'm useful!"
def main():
print("Running as main program")
print(useful_function())
# This block only runs when file is executed directly
if __name__ == "__main__":
main()
"""
# Demo of the pattern
def demo_function():
"""A function that would be in a module."""
return "Hello from demo!"
def main():
"""Main function that runs when executed directly."""
print("This module is being run directly!")
print(demo_function())
# This is the __name__ check pattern
if __name__ == "__main__":
# This runs only when this file is executed directly
# Not when it's imported
pass # In real code, you'd call main()
print("\nThe 'if __name__ == \"__main__\"' pattern prevents code from")
print("running when the module is imported.")
# -----------------------------------------------------------------------------
# 3. Module Structure Example
# -----------------------------------------------------------------------------
print("\n--- Module Structure ---")
# A well-structured module typically has:
module_template = '''
"""
Module: my_module
Description: What this module does
This module provides functionality for...
"""
# Imports at the top
import os
from typing import List
# Module-level constants
VERSION = "1.0.0"
DEFAULT_TIMEOUT = 30
# Private helpers (convention: prefix with _)
def _internal_helper():
"""Not meant to be used outside this module."""
pass
# Public functions
def public_function(arg1: str) -> str:
"""
This is a public function.
Args:
arg1: Description of argument
Returns:
Description of return value
"""
return f"Result: {arg1}"
# Classes
class MyClass:
"""A class in the module."""
pass
# Main entry point (if applicable)
def main():
"""Entry point when run as script."""
print(public_function("test"))
if __name__ == "__main__":
main()
'''
print("A module should have:")
print(" 1. Module docstring at top")
print(" 2. Imports")
print(" 3. Constants")
print(" 4. Private helpers (prefixed with _)")
print(" 5. Public functions/classes")
print(" 6. Main block if it's executable")
# -----------------------------------------------------------------------------
# 4. Creating a Package
# -----------------------------------------------------------------------------
print("\n--- Creating a Package ---")
# A package is a directory containing:
# - __init__.py (can be empty)
# - One or more module files
package_structure = """
my_package/
__init__.py
module1.py
module2.py
utils/
__init__.py
helpers.py
validators.py
"""
print("Package structure:")
print(package_structure)
# The __init__.py file makes a directory a package
# It can be empty or contain initialization code
init_example = '''
# my_package/__init__.py
# Package version
__version__ = "1.0.0"
# Control what gets imported with "from my_package import *"
__all__ = ['module1', 'module2', 'important_function']
# Import commonly used items for convenient access
from .module1 import important_function
from .module2 import AnotherClass
'''
print("__init__.py can:")
print(" - Define package version")
print(" - Control __all__ exports")
print(" - Import frequently used items for convenience")
# -----------------------------------------------------------------------------
# 5. Import Examples for Packages
# -----------------------------------------------------------------------------
print("\n--- Package Import Examples ---")
import_examples = """
# Given this package structure:
# myapp/
# __init__.py
# core.py
# utils/
# __init__.py
# helpers.py
# Import the package
import myapp
# Import a module from the package
from myapp import core
# Import a function from a module
from myapp.core import process_data
# Import from nested package
from myapp.utils import helpers
from myapp.utils.helpers import format_output
# Relative imports (inside the package)
# In myapp/core.py:
from . import utils # Same-level import
from .utils import helpers # Nested module
from .utils.helpers import format_output
from .. import other_package # Parent-level (if applicable)
"""
print("Package import patterns:")
print(" import package")
print(" from package import module")
print(" from package.module import function")
print(" from package.sub import submodule")
# -----------------------------------------------------------------------------
# 6. Simulating a Module
# -----------------------------------------------------------------------------
print("\n--- Simulated Module Example ---")
# Let's create module-like code inline to demonstrate
# === This would be in: calculator.py ===
class Calculator:
"""A simple calculator class."""
def __init__(self):
self.history = []
def add(self, a, b):
"""Add two numbers."""
result = a + b
self.history.append(f"{a} + {b} = {result}")
return result
def subtract(self, a, b):
"""Subtract b from a."""
result = a - b
self.history.append(f"{a} - {b} = {result}")
return result
def get_history(self):
"""Get calculation history."""
return self.history
# === Using the "module" ===
calc = Calculator()
print(f"5 + 3 = {calc.add(5, 3)}")
print(f"10 - 4 = {calc.subtract(10, 4)}")
print(f"History: {calc.get_history()}")
# -----------------------------------------------------------------------------
# 7. Module Documentation
# -----------------------------------------------------------------------------
print("\n--- Module Documentation ---")
# Good module documentation includes:
# - Module-level docstring
# - Function/class docstrings
# - Type hints
# - Examples
documented_module = '''
"""
mymodule - A demonstration of proper documentation
This module provides utilities for string manipulation
and validation. It follows Google-style docstrings.
Example:
>>> from mymodule import validate_email
>>> validate_email("test@example.com")
True
Attributes:
EMAIL_REGEX (str): Regular expression for email validation
"""
import re
from typing import Optional
EMAIL_REGEX = r'^[\w.-]+@[\w.-]+\.\w+$'
def validate_email(email: str) -> bool:
"""
Validate an email address format.
Args:
email: The email address to validate
Returns:
True if valid format, False otherwise
Raises:
TypeError: If email is not a string
Example:
>>> validate_email("user@domain.com")
True
>>> validate_email("invalid-email")
False
"""
if not isinstance(email, str):
raise TypeError("email must be a string")
return bool(re.match(EMAIL_REGEX, email))
'''
print("Include in your modules:")
print(" - Module docstring explaining purpose")
print(" - Type hints for parameters and returns")
print(" - Examples in docstrings")
print(" - Proper exception documentation")
# -----------------------------------------------------------------------------
# 8. The __all__ Variable
# -----------------------------------------------------------------------------
print("\n--- The __all__ Variable ---")
# __all__ controls what's exported with "from module import *"
all_example = '''
# mymodule.py
# Only these will be exported with "from mymodule import *"
__all__ = ['public_func', 'PublicClass', 'CONSTANT']
CONSTANT = 42
def public_func():
"""This is meant to be used externally."""
pass
def _private_func():
"""This is internal (won't be exported)."""
pass
class PublicClass:
"""This class is for external use."""
pass
'''
print("__all__ defines what gets exported with 'import *'")
print("Items NOT in __all__ won't be exported")
print("Underscore-prefixed items are convention for private")
# -----------------------------------------------------------------------------
# 9. Reloading Modules
# -----------------------------------------------------------------------------
print("\n--- Reloading Modules ---")
# During development, you might need to reload a modified module
from importlib import reload
# If you modify 'mymodule', you can reload it:
# import mymodule
# # ... modify the file ...
# reload(mymodule) # Get the updated version
print("Use importlib.reload() to reload a modified module")
print("Useful during development and debugging")
# -----------------------------------------------------------------------------
# 10. Project Structure Best Practices
# -----------------------------------------------------------------------------
print("\n--- Project Structure Best Practices ---")
project_structure = """
myproject/
README.md
setup.py or pyproject.toml
requirements.txt
.gitignore
src/
mypackage/
__init__.py
core.py
utils.py
models/
__init__.py
user.py
product.py
tests/
__init__.py
test_core.py
test_utils.py
docs/
index.md
scripts/
run_server.py
"""
print("Recommended project structure:")
print(project_structure)
print("Key points:")
print(" - Separate source code (src/) from tests")
print(" - Keep configuration at project root")
print(" - Use __init__.py for all packages")
print(" - Tests mirror source structure")