2016-12-19 11 views
1

importlib.utilimportlib.util 함수를 사용하여 범위에로드 된 활성 객체의 소스 코드를 검색하려면 파이썬의 내성 검사 모듈 inspect을 사용하려고합니다. spec_file 자체 또는 spec 파일의 함수에 inspect.getsource()을 사용하려고하면 원하는 소스 코드가 성공적으로 반환됩니다. 그러나 spec 파일의 클래스 유형에 대한 소스 코드를 검색하는 데 사용 된 것과 동일한 방법을 사용하면 TypeError: None is a built-in class이 발생합니다.소스 코드 정보가 module_from_spec과 함께로드 된 파이썬 클래스에서 누락되었습니다.

from importlib.util import spec_from_file_location, module_from_spec 
spec_file = spec_from_file_location("file_module", 'test_file.py') 
spec_module = module_from_spec(spec_file) 
spec_file.loader.exec_module(spec_module) 

# spec module 
import inspect 
assert isinstance(inspect.getsource(spec_module), str) 

# function in spec module 
func_obj = getattr(spec_module, 'test_function') 
assert isinstance(inspect.getsource(func_obj), str) 

# class in spec module 
class_obj = getattr(spec_module, 'testClass') 
try: 
    inspect.getsource(class_obj) 
except TypeError: 
    print('where did the source code data go?') 

범인 함수 객체가 객체를 반환 추적 체인의 inspect.getfile() 호출 될 것으로 보인다. __code__ 클래스 개체가 모듈을 검색하기 위해 모듈을로드하려고 시도하는 동안 __file__. 클래스에는없는 반면 함수에는 __code__ 메서드가있는 이유는 무엇입니까? 이것은 파이썬이 동적으로로드 된 클래스에 대해 실수로 인트로 스펙 션을 깨는 유형을 처리하는 방식의 부작용입니까?

답변

0

소스 및 모듈 경로가 클래스에 올바르게 반영되도록로드 된 모듈을 sys.modules에 추가해야합니다 (문서에서이 참조를 찾을 수는 없지만). 따라서 sys을 가져오고 sys.modules에 모듈을 추가하면 예제가 작동합니다 (파이썬 3.5와 유사한 예제를 테스트했습니다).