Importing Modules
Python's import system lets you bring in code from the standard library, third-party packages, or your own files.
Basic import
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.14159...from ... import
from math import sqrt, pi, ceil
print(sqrt(25)) # 5.0
print(ceil(4.2)) # 5
# No "math." prefix neededimport ... as (Alias)
import numpy as np # common alias
import pandas as pd # common alias
import matplotlib.pyplot as plt
from datetime import datetime as dt
print(dt.now())Wildcard Import (Avoid)
from math import * # imports everything — pollutes namespace
print(sin(0)) # works but hard to trace where it came fromConditional Import
try:
import ujson as json # fast JSON library
except ImportError:
import json # fallback to stdlibReload a Module
import importlib
import mymodule
importlib.reload(mymodule) # force re-read from disk