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

Warning Control (Kiểm soát cảnh báo) trong Python Programs

Warning (cảnh báo) khác với error (lỗi). Gặp error, chương trình Python dừng ngay. Warning không fatal: hiển thị thông báo nhưng chương trình tiếp tục. Warning cảnh báo user về điều kiện không phải exception. Thường xuất hiện khi dùng deprecated (lỗi thời) keyword/function/class.

Warning message hiển thị bởi hàm warn() trong module warnings của thư viện chuẩn. Warning là subclass của Exception trong built-in class hierarchy. Có nhiều built-in Warning subclass. User cũng có thể định nghĩa subclass riêng.

Warning ClassMô tả
WarningBase class của tất cả warning category classes.
UserWarningCategory mặc định cho warn().
DeprecationWarningCảnh báo tính năng deprecated dành cho developers.
SyntaxWarningCảnh báo cú pháp đáng ngờ.
RuntimeWarningCảnh báo runtime đáng ngờ.
FutureWarningCảnh báo deprecated features dành cho end users.
PendingDeprecationWarningCảnh báo tính năng sẽ deprecated trong tương lai.
ImportWarningCảnh báo khi import module.
UnicodeWarningCảnh báo liên quan Unicode.
BytesWarningCảnh báo liên quan bytes/bytearray.
ResourceWarningCảnh báo liên quan resource usage.

Ví dụ Warning

Code định nghĩa class với method deprecated và method dự kiến deprecated trong phiên bản sau:


# warningexample.py
import warnings

class WarnExample:
    def __init__(self):
        self.text = "Warning"
    def method1(self):
        warnings.warn("method1 is deprecated, use new_method instead", DeprecationWarning)
        print('method1', len(self.text))
    def method2(self):
        warnings.warn("method2 will be deprecated in version 2, use new_method instead", PendingDeprecationWarning)
        print('method2', len(self.text))
    def new_method(self):
        print('new method', len(self.text))

if __name__ == '__main__':
    e = WarnExample()
    e.method1()
    e.method2()
    e.new_method()

Chạy từ command prompt:


E:\python37>python warningexample.py

Không hiển thị warning. Cần dùng switch -Wd:


E:\python37>python -Wd warningexample.py
warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead
DeprecationWarning method1 7
warningexample.py:19: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead
PendingDeprecationWarning method2 7
new method 7

Tương tự interactive session không show warning trừ khi start Python với -Wd hoặc dùng warnings.simplefilter('default').

Warnings Filters (Bộ lọc cảnh báo)

Warnings filter kiểm soát warning bị bỏ qua, hiển thị, hoặc biến thành error (raise exception).

ActionMeaning
errorChuyển warning thành exception.
ignoreBỏ qua warning.
alwaysLuôn phát warning.
defaultIn warning lần đầu tiên từ mỗi location.
moduleIn warning lần đầu tiên từ mỗi module.
onceIn warning lần đầu tiên được generate.

Session interactive đặt filter default bằng simplefilter():


>>> import warnings
>>> warnings.simplefilter('default')
>>> from warningexample import WarnExample
>>> e = WarnExample()
>>> e.method1()
... DeprecationWarning ...
>>> e.method2()
... PendingDeprecationWarning ...
>>> e.new_method()
new method 7

Để tạm ẩn warning, đặt simplefilter = 'ignore':


import warnings
def function():
    warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    function()