Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python 경고(Warning) 완벽 정리: 오류와의 차이부터 경고 필터 제어까지

프로그래밍에서 경고(Warning)오류(Error)와 다릅니다. 오류가 발생하면 Python 프로그램은 즉시 종료되지만, 경고는 치명적이지 않습니다. 경고가 표시되더라도 프로그램은 계속 실행됩니다.

경고는 예외(Exception)라고 부르기 애매한 특정 상황을 사용자에게 알리기 위해 발생합니다. 일반적으로 함수, 클래스, 키워드처럼 더 이상 권장되지 않는(deprecated) 프로그래밍 요소를 사용했을 때 나타납니다.

경고 메시지는 Python 표준 라이브러리의 warnings 모듈에 정의된 warn() 함수를 통해 출력됩니다. 실제로 Warning 클래스는 내장 클래스 계층 구조에서 Exception의 하위 클래스이며, 다양한 내장 경고 하위 클래스가 제공됩니다. 물론 사용자가 직접 경고 클래스를 정의하는 것도 가능합니다.

Python의 주요 경고 카테고리

Warning모든 경고 카테고리 클래스의 기본(base) 클래스입니다.
UserWarningwarn() 함수의 기본 경고 카테고리입니다.
DeprecationWarning개발자를 대상으로 하는, 지원 중단(deprecated) 기능에 대한 경고입니다.
SyntaxWarning의심스러운 문법적 특성에 대한 경고입니다.
RuntimeWarning의심스러운 런타임 동작에 대한 경고입니다.
FutureWarning최종 사용자를 대상으로 하는, 지원 중단 예정 기능에 대한 경고입니다.
PendingDeprecationWarning향후 지원이 중단될 예정인 기능에 대한 경고입니다.
ImportWarning모듈 임포트 과정에서 발생하는 경고입니다.
UnicodeWarningUnicode 관련 경고입니다.
BytesWarningbytes 및 bytearray 관련 경고입니다.
ResourceWarning리소스 사용과 관련된 경고입니다.

경고 발생 예제

다음 코드는 지원이 중단된(deprecated) 메서드 하나와, 향후 버전에서 지원이 중단될 예정인 메서드 하나를 가진 클래스를 정의합니다.

# 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()

-Wd 옵션으로 경고 표시하기

위 스크립트를 명령 프롬프트에서 다음과 같이 실행하면:

E:\python37>python warningexample.py

터미널에는 아무런 경고 메시지도 표시되지 않습니다. 기본적으로 DeprecationWarning 같은 개발자용 경고는 숨겨지기 때문입니다. 경고를 확인하려면 -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

대화형 세션에서 경고 확인하기

마찬가지로 다음 대화형 세션에서도 경고 메시지가 표시되지 않습니다.

E:\python37>python
>>> from warningexample import WarnExample
>>> e = WarnExample()
>>> e.method1()
method1 7
>>> e.method2()
method2 7
>>> e.new_method()
new method 7

경고를 보려면 Python 세션을 시작할 때 -Wd 옵션을 함께 지정해야 합니다.

E:\python37>python -Wd
>>> from warningexample import WarnExample
>>> e = WarnExample()
>>> e.method1()
E:\python37\warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead
DeprecationWarning
method1 7
>>> e.method2()
E:\python37\warningexample.py:17: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead
PendingDeprecationWarning
method2 7
>>> e.new_method()
new method 7

경고 필터(Warnings Filter)

경고 필터를 사용하면 경고를 무시할지, 화면에 표시할지, 아니면 예외로 변환해 오류로 처리할지 제어할 수 있습니다. 필터 동작(action)은 다음과 같습니다.

동작(Action)의미(Meaning)
error경고를 예외(exception)로 변환합니다.
ignore경고를 버립니다(무시).
always항상 경고를 출력합니다.
default각 위치(코드 지점)에서 처음 생성될 때 한 번만 경고를 출력합니다.
module각 모듈에서 처음 생성될 때 한 번만 경고를 출력합니다.
once전체 프로그램에서 처음 생성될 때 한 번만 경고를 출력합니다.

simplefilter()로 필터 설정하기

다음 대화형 세션에서는 simplefilter() 함수를 사용해 필터를 'default'로 설정합니다. 이렇게 하면 별도의 -Wd 옵션 없이도 경고가 표시됩니다.

E:\python37>python
>>> import warnings
>>> warnings.simplefilter('default')
>>> from warningexample import WarnExample
>>> e = WarnExample()
>>> e.method1()
E:\python37\warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead
DeprecationWarning
method1 7
>>> e.method2()
E:\python37\warningexample.py:17: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead
PendingDeprecationWarning
method2 7
>>> e.new_method()
new method 7

catch_warnings()로 경고 일시적으로 억제하기

특정 코드 블록에서만 경고를 임시로 숨기고 싶다면, catch_warnings() 컨텍스트 매니저와 함께 simplefilter('ignore')를 사용하면 됩니다. 컨텍스트를 벗어나면 원래의 경고 설정이 자동으로 복원됩니다.

import warnings

def function():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    function()  # 이 블록 안에서는 경고가 출력되지 않음

이처럼 Python의 warnings 모듈을 활용하면 지원 중단 예정 기능을 미리 알리고, 상황에 따라 경고를 표시·무시·예외 처리하며 유연하게 프로그램 동작을 제어할 수 있습니다.