from — Expert Examples
Used with import to bring in specific names from a module
from bytecode: IMPORT_FROM
How 'from' import compiles differently.
python
import dis def import_module(): import json def from_import(): from json import dumps def from_import_as(): from json import dumps as d print("import json:") dis.dis(import_module) print("\nfrom json import dumps:") dis.dis(from_import) print("\nfrom json import dumps as d:") dis.dis(from_import_as) # 'import X' -> IMPORT_NAME + STORE_NAME # 'from X import Y' -> IMPORT_NAME + IMPORT_FROM + STORE_NAME # IMPORT_FROM is an extra step that extracts the attribute
'from X import Y' compiles to IMPORT_NAME (load module) + IMPORT_FROM (extract attribute) + STORE_NAME. The module itself is not stored — only the imported name is bound.
Want to try these examples interactively?
Open Expert Playground