Modules and imports
Functions and modules5 min readLesson 3 of 3
A file is a module. Importing it runs the file once and binds its names.
python
import math
math.sqrt(16) # 4.0
from math import sqrt # bring one name in
sqrt(16)
import numpy as np # an alias, the usual conventionEverything in the standard library is already installed. A short list worth knowing:
python
import json, re, pathlib, datetime, statistics, itertoolsKeep imports at the top of the file, grouped: standard library, third-party, then local. That order makes a missing dependency obvious.
A module runs its top-level code on import. Guard the part that should only run from the command line:
python
def main():
...
if __name__ == "__main__":
main()