Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

คำสั่ง from...import * ใน Python (Import All)

from module import * นำเข้าทุก Public Name จาก Module (ยกเว้น _ prefix และ __all__)

ตัวอย่าง

>>> from math import *
>>> sin(0)
0.0
>>> cos(0)
1.0
>>> pi
3.141592653589793

ข้อเสีย (Anti-Pattern)

  • Namespace Pollution: ชื่อชนกัน ทำให้ Bug ยากหา
  • Implicit Dependencies: ไม่รู้ว่ามาจากไหน (Readability ต่ำ)
  • Refactoring ยาก: ลบ Import * ไม่ได้ เพราะไม่รู้ว่าใช้ชื่อไหน
  • Performance: โหลด Symbol มากกว่าจำเป็น

เมื่อไหร่ใช้ได้?

  • Interactive Session (REPL) - ความสะดวก
  • Module ออกแบบมาเพื่อ import * (มี __all__ ชัดเจน)
  • Testing/Debugging ชั่วคราว

Best Practice: Explicit Import

# Good
from math import sin, cos, pi
import numpy as np

# Avoid
from math import *
from numpy import *