Nhảy đến nội dung chính

Dynamic import (runtime import)

Giúp bạn import module hoặc class dựa theo tên chuỗi, rất mạnh khi viết plugin hoặc hệ thống mở rộng.

import importlib

module = importlib.import_module("math")
print(module.sqrt(16))  # 4.0

Hoặc:

def dynamic_import(path):
    module_path, class_name = path.rsplit(".", 1)
    module = importlib.import_module(module_path)
    return getattr(module, class_name)