Python ต้อง Import ก่อนใช้ (Explicit) ไม่เหมือนภาษาบางตัวที่ Auto-load
ตัวอย่าง
>>> math.cos(0)
NameError: name 'math' is not defined
>>> import math
>>> math.cos(0)
1.0
สิ่งที่ Built-in (ไม่ต้อง Import)
- Types:
int, float, str, list, dict, set, tuple - Functions:
print, len, range, open, input, type, isinstance - Exceptions:
Exception, ValueError, TypeError, ... - Constants:
True, False, None, Ellipsis, NotImplemented
สิ่งที่ต้อง Import
- Standard Library Modules:
math, json, os, sys, datetime, re, ... - Third-party Packages:
requests, numpy, pandas, django, ... - Local Modules:
import mymodule
หลักการ: Explicit is better than implicit (PEP 20)
Import ทำให้ Dependency ชัดเจน โค้ดอ่านง่าย Maintain ได้