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 Class | Mô tả |
|---|---|
Warning | Base class của tất cả warning category classes. |
UserWarning | Category mặc định cho warn(). |
DeprecationWarning | Cảnh báo tính năng deprecated dành cho developers. |
SyntaxWarning | Cảnh báo cú pháp đáng ngờ. |
RuntimeWarning | Cảnh báo runtime đáng ngờ. |
FutureWarning | Cảnh báo deprecated features dành cho end users. |
PendingDeprecationWarning | Cảnh báo tính năng sẽ deprecated trong tương lai. |
ImportWarning | Cảnh báo khi import module. |
UnicodeWarning | Cảnh báo liên quan Unicode. |
BytesWarning | Cảnh báo liên quan bytes/bytearray. |
ResourceWarning | Cả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).
| Action | Meaning |
|---|---|
error | Chuyển warning thành exception. |
ignore | Bỏ qua warning. |
always | Luôn phát warning. |
default | In warning lần đầu tiên từ mỗi location. |
module | In warning lần đầu tiên từ mỗi module. |
once | In 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()