Python에 내장된 예외(Exception)와 오류(Error)의 전체 계층 구조를 한눈에 확인하고 싶다면 inspect 모듈의 getclasstree() 함수를 활용하면 됩니다.
inspect.getclasstree()는 주어진 클래스 목록을 중첩된 리스트 형태의 계층 구조로 정리해 주는 함수입니다. 여기에 각 클래스의 __subclasses__() 메서드를 재귀적으로 호출하면 상속 트리를 따라 아래로 내려가면서 모든 하위 예외 클래스를 순차적으로 출력할 수 있습니다.
예제 코드
아래는 원본 예제입니다. Python 2 문법(print 문)으로 작성되어 있으며, 그 아래에 Python 3에서 그대로 실행 가능한 버전을 함께 제공합니다.
Python 2 스타일
import inspect
print "The class hierarchy for built-in exceptions is:"
inspect.getclasstree(inspect.getmro(BaseException))
def classtree(cls, indent=0):
print '.' * indent, cls.__name__
for subcls in cls.__subclasses__():
classtree(subcls, indent + 3)
classtree(BaseException)
Python 3 호환 버전
import inspect
print("내장 예외의 클래스 계층 구조:")
inspect.getclasstree(inspect.getmro(BaseException))
def classtree(cls, indent=0):
print('.' * indent, cls.__name__)
for subcls in cls.__subclasses__():
classtree(subcls, indent + 3)
classtree(BaseException)
코드의 핵심 로직은 다음과 같습니다.
1. classtree() 함수는 현재 클래스 이름을 들여쓰기(점 개수)와 함께 출력합니다.
2. cls.__subclasses__()로 해당 클래스의 직계 자식 클래스를 모두 가져옵니다.
3. 각 자식 클래스에 대해 함수를 재귀 호출하며, 이때 indent 값을 3씩 늘려 계층 깊이를 시각적으로 표현합니다.
실행 결과
위 코드를 실행하면 BaseException을 최상위 루트로 하는 전체 예외 계층이 들여쓰기 형태로 출력됩니다. 아래 결과는 Python 2.x 환경 기준이며, Python 3에서는 StandardError, WindowsError 등 일부 클래스가 제거되거나 통합되었으므로 출력 내용이 다소 달라질 수 있습니다.
The class hierarchy for built-in exceptions is: BaseException ... Exception ...... StandardError ......... TypeError ......... ImportError ............ ZipImportError ......... EnvironmentError ............ IOError ............ OSError ............... WindowsError ......... EOFError ......... RuntimeError ............ NotImplementedError ......... NameError ............ UnboundLocalError ......... AttributeError ......... SyntaxError ............ IndentationError ............... TabError ......... LookupError ............ IndexError ............ KeyError ............ CodecRegistryError ......... ValueError ............ UnicodeError ............... UnicodeEncodeError ............... UnicodeDecodeError ............... UnicodeTranslateError ......... AssertionError ......... ArithmeticError ............ FloatingPointError ............ OverflowError ............ ZeroDivisionError ......... SystemError ............ CodecRegistryError ......... ReferenceError ......... MemoryError ......... BufferError ...... StopIteration ...... Warning ......... UserWarning ......... DeprecationWarning ......... PendingDeprecationWarning ......... SyntaxWarning ......... RuntimeWarning ......... FutureWarning ......... ImportWarning ......... UnicodeWarning ......... BytesWarning ...... _OptionError ...... error ...... Error ...... TokenError ...... StopTokenizing ...... error ...... EndOfBlock ... GeneratorExit ... SystemExit ... KeyboardInterrupt
출력 결과를 보면 예외들이 크게 네 가지 최상위 분기로 나뉩니다. 실제 프로그램에서 대부분 처리하게 되는 일반적인 오류는 Exception 계열이고, 나머지 GeneratorExit, SystemExit, KeyboardInterrupt는 일반적인 오류가 아닌 제어 흐름 관련 신호에 가깝다는 점을 참고하시기 바랍니다.