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

Cơ chế import trong Python với importlib

Package importlib triển khai câu lệnh import bằng Python thuần túy, dễ hiểu hơn bản C. Cung cấp API để tạo custom importer.

Hàm quan trọng

import_module(name, package=None)

Import module theo chương trình. Tham số 2 tùy chọn cho relative import.

invalidate_caches()

Xóa cache của finders. Gọi khi tạo/cài module mới trong runtime.

reload(module)

Nạp lại module đã import (sau khi sửa source file).

Ví dụ cơ bản

Tạo module1.py và module2.py:

# module1.py / module2.py
def main():
    print('module imported', __name__)

if __name__ == '__main__':
    main()

Import động:

import importlib

mod = importlib.import_module('module1')
print(mod.__name__)  # module1

mod = importlib.import_module('module2')
print(mod.__name__)  # module2
mod.main()           # module imported module2

Các submodule

importlib.abcAbstract base classes cốt lõi cho import
importlib.resourcesTruy cập resource trong package
importlib.machineryFinder/loader objects
importlib.utilUtility cho importer

importlib.util - Hàm tiện ích

find_spec(name, package=None)

Tìm spec của module. Tự động import parent nếu submodule.

module_from_spec(spec)

Tạo module mới từ spec.

Ví dụ nâng cao: Kiểm tra và import động

import importlib.util

def check_module(mod):
    spec = importlib.util.find_spec(mod)
    if spec is None:
        print('Module: {} not found'.format(mod))
        return None
    else:
        print('Module: {} can be imported!'.format(mod))
        return spec

def import_module(spec):
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod

if __name__ == '__main__':
    spec = check_module('notamodule')
    spec = check_module('module1')
    if spec:
        mod = import_module(spec)
        mod.main()

Kết quả

Module: notamodule not found
Module: module1 can be imported!
module imported module1