- Import modules and packages
- Create your own modules
__name__ == "__main__"pattern- Relative imports
| Concept | JavaScript | Python |
|---|---|---|
| Import all | import fs from 'fs' |
import os |
| Named import | import { readFile } |
from os import getcwd |
| Alias | import _ as lodash |
import numpy as np |
| Re-export | export { fn } |
just define in module |
| Module entry | no equivalent | if __name__ == "__main__": |
# Import whole module
import math
print(math.sqrt(16)) # 4.0
# Import specific items
from math import sqrt, pi, floor
print(sqrt(16)) # 4.0 β no math. prefix needed
# Import with alias
import numpy as np # common convention
import pandas as pd
# Import everything (avoid in production)
from math import *
print(sqrt(16)) # works, but pollutes namespace# math_utils.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
PI = 3.14159
# The __name__ guard β runs only when executed directly
if __name__ == "__main__":
print("Testing math_utils directly")
print(add(2, 3)) # 5# main.py β import from math_utils
from math_utils import add, PI
import math_utils
print(add(10, 5)) # 15
print(PI) # 3.14159
print(math_utils.subtract(10, 3)) # 7A package is a directory with an __init__.py file.
my_project/
βββ main.py
βββ utils/
βββ __init__.py β makes utils/ a package
βββ math_utils.py
βββ string_utils.py
# main.py
from utils.math_utils import add
from utils import string_utils
print(add(1, 2))No install needed β built into Python:
import os # file system, env vars
import sys # system info, argv
import json # JSON encode/decode
import csv # CSV files
import re # regular expressions
import math # math functions
import random # random numbers
import datetime # date and time
import pathlib # modern file paths
import collections # Counter, defaultdict, deque
import itertools # powerful iteration tools
import functools # lru_cache, partial, reduce
import time # sleep, timing
import hashlib # MD5, SHA hashing