This is the 15th in a series of Python tutorials; for more, visit my Python collection!
A module is actually a file (ending in .py). The advantage of using modules is that they are easy to maintain and reuse code.
To create a module, simply write a new text file and save it with a .py extension.
1 Introducing Modules
1.1 Importing the entire module
import mymodule
mymodule.some_function()
1.2 Importing a specific function or class
from mymodule import some_function
some_function()
1.3 Importing all content
from mymodule import *
some_function() # Call the function directly without prefixing the module
1.4 Use of aliases
import mymodule as mm
mm.some_function()
2 Common Modules
Python's standard library is very large and provides a large number of built-in modules to support a variety of programming tasks. Here's a list of some common modules and their main uses:
2.1 Standard library module
2.1.1 os
Operating system related functions such as reading environment variables, changing directories, etc.
import os
print(()) # Get the current working directory
2.1.2 sys
Some system-specific variables and functions, such as getting command line arguments, exiting the program, etc.
import sys
print() # Get command line arguments
2.1.3 math
Math functions such as square roots, logarithms, etc.
import math
print((16)) # Calculate square root
2.1.4 random
Generate random numbers.
import random
print((1, 100)) # Generate a random integer between 1 and 100
2.1.5 datetime
Date and time operations.
from datetime import datetime
print(()) # Get the current date and time.
2.1.6 re
Regular expression support.
import re
pattern = r'\d+'
result = (pattern, '123 abc 456')
print(result) # Output all strings that match a number
2.1.7 json
JSON encoding and decoding.
import json
data = {'name': 'John', 'age': 30}
json_str = (data)
print(json_str) # Convert the dictionary to a JSON string.
2.1.8 collections
Advanced container types such asdefaultdict
, Counter
, deque
etc.
from collections import defaultdict
d = defaultdict(int)
d['a'] += 1
print(d['a']) # exports: 1
2.1.9 itertools
Iteration tool that provides efficient loop iterators.
import itertools
for x in (start=1).
print(x)
if x > 10.
break # Count indefinitely until 10 is exceeded
2.1.10 functools
Higher-order function tools such as decorators, biased functions, etc.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print(fib(10)) # Calculate the Fibonacci series number10classifier for principles, items, clauses, tasks, research projects etc
2.1.11 pathlib
Modern interface for handling paths.
from pathlib import Path
p = Path('/etc') / 'passwd'
print(p) # Output: /etc/passwd
12. argparse
Parses command line arguments and options.
import argparse
parser = ()
parser.add_argument("--input", help="input file")
args = parser.parse_args()
print()
2.2 Third-party modules
In addition to the standard library, there are many third-party modules that can be installed and used, for example:
- NumPy - Numerical calculations.
- Pandas - Data analysis.
- Matplotlib - Data visualization.
- Requests - Sends an HTTP request.
- Flask - Web development framework.
- SQLAlchemy - Database abstraction layer.