Python標准庫--inspect


 

inspect模塊是針對模塊,類,方法,功能等對象提供些有用的方法。例如可以幫助我們檢查類的內容,檢查方法的代碼,提取和格式化方法的參數等。

import inspect
import os

class Test(object):
    """Test Class """

    def test(self):
        self.fuc = lambda x: x

class Testone(Test):
    pass

print(inspect.ismodule(os))         # True
print(inspect.isclass(Test))        # True
print(inspect.getdoc(Test))         # Test Class

print(inspect.getsourcefile(Test))   # 文件路徑
print(inspect.getsourcelines(Test))  # 代碼塊,每行一個元素,組成數組
print(inspect.getsource(Test))       # 獲取代碼塊原本內容,帶縮進

 打印全局中的變量

#打印全局變量中的模塊對象
myglobals = {}
myglobals.update(globals())
modules = [value
           for key, value in myglobals.items()
           if inspect.ismodule(value)]
print(modules)

輸出結果:
[<module 'builtins' (built-in)>, <module 'inspect' from 'D:\\python\\python\\lib\\inspect.py'>, <module 'os' from 'D:\\python\\python\\lib\\os.py'>]

 查看類和類對象有哪些方法可以調用 

# 查看類的可調用方法
for name, value in inspect.getmembers(Test, callable):
    print("    Callable:", name)

for name, value in inspect.getmembers(Test(), callable):
    print(" Instance Callable:", name)

獲取棧的全部調用信息

def debug():
    import inspect
    print(inspect.stack()[0][3])
    print(inspect.stack()[1][3])
    caller_name = inspect.stack()[1][3]
    # print("[DEBUG]: enter {}()".format(caller_name) )

def say_hello():
    debug()
    # print("hello!")

def say_goodbye():
    debug()
    # print("goodbye!")

if __name__ == '__main__':
    say_hello()
    say_goodbye()

運行結果:
debug
say_hello
debug
say_goodbye

  

 

  1. inspect.ismodule(object): 是否為模塊

  2. inspect.isclass(object):是否為類

  3. inspect.ismethod(object):是否為方法(bound method written in python)

  4. inspect.isfunction(object):是否為函數(python function, including lambda expression)

  5. inspect.isgeneratorfunction(object):是否為python生成器函數

  6. inspect.isgenerator(object):是否為生成器

  7. inspect.istraceback(object): 是否為traceback

  8. inspect.isframe(object):是否為frame

  9. inspect.iscode(object):是否為code

  10. inspect.isbuiltin(object):是否為built-in函數或built-in方法

  11. inspect.isroutine(object):是否為用戶自定義或者built-in函數或方法

  12. inspect.isabstract(object):是否為抽象基類

  13. inspect.ismethoddescriptor(object):是否為方法標識符

  14. inspect.isdatadescriptor(object):是否為數字標識符,數字標識符有__get__ 和__set__屬性; 通常也有__name__和__doc__屬性

  15. inspect.isgetsetdescriptor(object):是否為getset descriptor

  16. inspect.ismemberdescriptor(object):是否為member descriptor

 

 

 

 

 

 

  

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM