ใช้ from module import function นำเข้าฟังก์ชันเฉพาะตัว
ตัวอย่าง
>>> from math import sin
>>> sin(0)
0.0
# ใช้ sin() โดยตรง ไม่ต้อง math.sin()
Alias
>>> from math import cos as cosine
>>> cosine(0)
1.0
เปรียบเทียบ
| Style | Code | ใช้งาน |
|---|---|---|
| Module Import | import math; math.sin(0) | หลายฟังก์ชัน ชื่อชัดเจน |
| Specific Import | from math import sin; sin(0) | 1-2 ฟังก์ชัน ใช้บ่อย |
| Alias | from math import cos as cosine | ชื่อชน หรือ อ่านง่ายขึ้น |
PEP 8: ยอมรับได้ทั้งคู่ เลือกตาม Context ความสำคัญคือ Consistent ภายใน Project