Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Import module trong Python - Các cách và best practice


Câu lệnh import nạp module/thư viện vào namespace hiện tại.

1. Import toàn bộ module (Phổ biến nhất)

import math
print(math.log10(100))  # 2.0

2. Import function cụ thể (Tiết kiệm namespace)

from math import pi
print(pi)  # 3.141592653589793

3. Import tất cả (*) - KHÔNG KHUYẾN NGHỊ

from math import *
print(log10(100))  # 2.0
# Rủi ro: namespace pollution, conflict tên, khó debug

4. Import với alias (Đặt bí danh)

import math as m
import numpy as np
import pandas as pd

print(m.log10(100))  # 2.0

5. Import tương đối (Relative import) - Trong package

# Trong package/submodule
from . import sibling_module
from ..parent_package import something

Best Practices (PEP 8)

  1. Import ở đầu file.
  2. Thứ tự: stdlib → third-party → local.
  3. Mỗi import một dòng (trừ nhóm từ cùng module).
  4. Tránh from module import *.
  5. Dùng alias chuẩn: np, pd, plt...
# Ví dụ import đúng chuẩn
import os
import sys
from pathlib import Path

import numpy as np
import pandas as pd
import requests

from mypackage import utils
from mypackage.models import User

Kết luận

Import rõ ràng, tường minh, tránh import *. Tuân thủ PEP 8 để code dễ bảo trì.