.inspect java_inspect模块--幫你檢視記憶體中 Python 物件的好工具

inspect — 检测 Python 物件內容

用 inspect 檢查物件的形态

>>> import inspect

>>> inspect.ismodule(inspect) # 檢查 inspect 是否為模組

True

>>> inspect.ismethod(inspect) # 檢查 inspect 是否為物件方法

False

>>> inspect.isfunction(len) # 檢查 len 是否為函式

True

>>> inspect.isbuiltin(len) # 檢查 len 是否為內建函式

True

>>> inspect.isawaitable(inspect) # 檢查 inspect 是否可用於 await expression

False

>>>

透過 inspect 取得物件內的資訊,例如說物件的 docstring、comment 甚至是 source code:

>>> inspect.getdoc(len) # 取得 len 的 docstring

'Return the number of items in a container.'

>>> inspect.getsource(inspect) # 取得 inspect 的 source code

'"""Get useful information from live Python objects.\n\n

This module encapsulates the interface provided by the

internal special\nattributes (co_*, im_*, tb_*, etc.) in ...'

>>>

透過 inspect.getmembers,我們可以取得一個物件裏面所有的 member:

>>> inspect.getmembers(len)

[('__call__',

),

('__class__', ),

('__delattr__',

...,

('__setattr__',

),

('__sizeof__',

),

('__str__',

),

('__subclasshook__',

),

('__text_signature__', '($module, obj, /)')]

>>> import tabnanny

>>> inspect.getmembers(tabnanny, inspect.isfunction) # get only function

[('check', ),

('errprint', ),

('format_witnesses', ),

('main', ),

('process_tokens', )]

inspect.signature,可以獲得 callable 的 Signature 物件

>>> def foo(name, a: int, b: float):

... pass

...

>>> sig = inspect.signature(foo)

>>> sig

>>> str(sig)

'(name, a:int, b:float)'

>>> sig.parameters

mappingproxy(OrderedDict([('name', ), ('a', ), ('b', )]))

透過 Signature.bind,我們可以把參數給綁定到 signature 上:

>>> args = ('foobar', 10)

>>> kwargs = {'b': 23.4}

>>> bound = sig.bind(*args, **kwargs) # bind args to signature parameters

>>> bound

>>> bound.arguments['name']

'foobar'

>>> bound.arguments['a']

10

>>> bound.arguments['b']

23.4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值