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

Python inspect 모듈로 라이브 객체 검사하기

Python의 inspect 모듈은 모듈, 클래스, 메서드, 함수, 코드 객체 등 실행 중인(live) 객체에 대한 유용한 정보를 제공합니다. 이 모듈의 함수들은 타입 검사, 소스 코드 조회, 클래스와 함수 검사, 인터프리터 스택 분석 등의 작업을 수행할 수 있습니다.

주요 함수 소개

getmembers() — 객체가 가진 모든 멤버를 이름과 값의 쌍으로 된 리스트 형태로 반환하며, 이름순으로 정렬됩니다. 선택적으로 조건자(predicate)를 지정하면 해당 조건이 참을 반환하는 멤버만 포함됩니다.

getmodulename() — 파일 경로로 지정된 모듈의 이름을 반환합니다. 이때 상위 패키지의 이름은 포함되지 않습니다.

예제 스크립트

inspect 모듈의 동작을 이해하기 위해 다음 스크립트를 사용해 보겠습니다.

#inspect-example.py
'''This is module docstring'''
def hello():
   '''hello docstring'''
   print ('Hello world')
   return
#클래스 정의
class parent:
   '''parent docstring'''
   def __init__(self):
      self.var='hello'
   def hello(self):
      print (self.var)
class child(parent):
   def hello(self):
      '''hello function overridden'''
      super().hello()
      print ("How are you?")

모듈의 멤버 중 이름이 '__'로 시작하지 않는 항목만 출력해 보겠습니다.

>>> import inspect, inspect_example
>>> for k,v in inspect.getmembers(inspect_example):
      if k.startswith('__')==False:print (k,v)
child
hello
parent
>>>

조건자(Predicates)

조건자(predicate)는 inspect 모듈의 함수에 적용되는 논리적 조건입니다. 예를 들어 getmembers() 함수는 주어진 조건자 조건이 참인 모듈의 멤버들만 리스트로 반환할 수 있습니다. inspect 모듈에서 정의된 주요 조건자는 다음과 같습니다.

ismodule()객체가 모듈이면 참을 반환합니다.
isclass()객체가 클래스(내장 클래스 또는 Python 코드로 생성된 클래스)이면 참을 반환합니다.
ismethod()객체가 Python으로 작성된 바운드 메서드(bound method)이면 참을 반환합니다.
isfunction()객체가 Python 함수(람다 표현식으로 생성된 함수 포함)이면 참을 반환합니다.
isgenerator()객체가 제너레이터(generator)이면 참을 반환합니다.
iscode()객체가 코드(code) 객체이면 참을 반환합니다.
isbuiltin()객체가 내장 함수 또는 바운드 내장 메서드이면 참을 반환합니다.
isabstract()객체가 추상 기반 클래스(abstract base class)이면 참을 반환합니다.

아래 예시에서는 isclass 조건자를 사용하여 모듈 내 클래스 멤버만 반환받습니다.

>>> for k,v in inspect.getmembers(inspect_example, inspect.isclass):
      print (k,v)
child <class 'inspect_example.child'>
parent <class 'inspect_example.parent'>
>>>

특정 클래스 'child'의 멤버를 조회하려면 다음과 같이 작성합니다.

>>> inspect.getmembers(inspect_example.child)
>>> x=inspect_example.child()
>>> inspect.getmembers(x)

문서 문자열과 소스 코드 조회

getdoc() 함수는 모듈, 클래스 또는 함수의 docstring(문서 문자열)을 가져옵니다.

>>> inspect.getdoc(inspect_example)
'This is module docstring'
>>> inspect.getdoc(inspect_example.parent)
'parent docstring'
>>> inspect.getdoc(inspect_example.hello)
'hello docstring'

getsource() 함수는 함수의 정의 코드를 그대로 가져옵니다.

>>> print (inspect.getsource(inspect_example.hello))
def hello():
    '''hello docstring'''
    print ('Hello world')
    return
>>> sign=inspect.signature(inspect_example.parent.hello)
>>> print (sign)

명령줄 인터페이스

inspect 모듈은 명령줄 인터페이스도 제공합니다. -d 옵션을 사용하면 대상 모듈의 상세 정보를 확인할 수 있습니다.

C:\Users\acer>python -m inspect -d inspect_example
Target: inspect_example
Origin: C:\python36\inspect_example.py
Cached: C:\python36\__pycache__\inspect_example.cpython-36.pyc
Loader: <_frozen_importlib_external.SourceFileLoader object at
0x0000029827BD0D30>

다음 명령은 모듈 내 hello() 함수의 소스 코드를 반환합니다.

C:\Users\acer>python -m inspect inspect_example:hello
def hello():
   '''hello docstring'''
   print ('Hello world')
   return