首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

python标准库中inspect 模块简单介绍

  • 25-03-03 22:40
  • 2768
  • 7859
blog.csdn.net
inspect 模块简单介绍

inspect 模块 的作用

(1).对是否是模块,框架,函数等进行类型检查。

(2).获取源码
(3).获取类或函数的参数的信息

以下是官方文档说明:

inspect模块提供了几个有用的函数来帮助获取有关活动对象的信息,例如模块,类,方法,函数,回溯,框架对象和代码对象。 例如,它可以帮助您检查类的内容,检索方法的源代码,提取和格式化函数的参数列表,或获取显示详细回溯所需的所有信息。

1 inspect 可以 比较轻松 获取 函数的参数, 通过 signature(foo).bind(xxx,xxx)
就可以了.

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import inspect


def foo(a, b='ham', *args):
    pass


def test(a, *, b):
    print(a,b)


if __name__ == '__main__':
    ba = inspect.signature(foo).bind(a='spam', b='frank')
    ba.apply_defaults()
    print(ba.arguments)  # ordereddict
    

# OrderedDict([('a', 'spam'), ('b', 'frank'), ('args', ())])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
import  inspect 
def foo(a,b,c,*args,**kw):pass

# 拿到函数 签名 
sig  = inspect.signature(foo)
str(sig)
'(a, b, c, *args, **kw)'

## 绑定部分参数,  返回一个 BoundArguments 对象 
sig.bind_partial('frank','165cm')

ba =sig.bind_partial('frank','165cm')

## 对于丢失的参数,可以设置默认值
ba.apply_defaults()
ba.arguments
OrderedDict([('a', 'frank'), ('b', '165cm'), ('args', ()), ('kw', {})])



## signature  还有一个方法  bind

import  inspect 
def foo(a,b,c,*args,**kw):pass

sig =  inspect.signature(foo)

ba = sig.bind('frank','165cm','hello')
ba

ba.arguments
OrderedDict([('a', 'frank'), ('b', '165cm'), ('c', 'hello')])
# 指定默认值 
ba.apply_defaults()
ba.arguments
OrderedDict([('a', 'frank'), ('b', '165cm'), ('c', 'hello'), ('args', ()), ('kw', {})])


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

1-1 bind 和 bind_partial 区别

绑定参数的,如果 用 bind 需要要所有的位置参数 都要绑定.
bind_partial 可以部分进行绑定.

import  inspect 


def foo(a,b,c,*args,**kw):pass

sig =  inspect.signature(foo)
sig

sig

sig.bind('frank','165cm')
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/inspect.py", line 2968, in bind
    return args[0]._bind(args[1:], kwargs)
  File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/inspect.py", line 2883, in _bind
    raise TypeError(msg) from None
TypeError: missing a required argument: 'c'


不支持 部分绑定参数, 所以会报错, 可以使用 sig.bind_partial
sig.bind_partial('frank','165cm')



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

2 The args and kwargs properties can be used to invoke functions:

signature.bind() 返回一个 Boundarguments 对象.
可以通过 args , kwargs 拿到函数的所有参数.


#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import inspect

def test(a, *, b):
    print(a, b)


if __name__ == "__main__":
    sig = inspect.signature(test)
    ba = sig.bind(10, b=20)
    test(*ba.args, **ba.kwargs)  # 10 20

# The args and kwargs properties can be used to invoke functions  
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  1. 可以 有很多实用的方法.

用来判断 函数,类,实例方法, 内建方法, function or method等…


def ismodule(object):

def isclass(object):

def ismethod(object):

def ismethoddescriptor(object):


def isfunction(object):

def isbuiltin(object):

def isabstract(object):

def ismethoddescriptor(object):


def isroutine(object):
    """Return true if the object is any kind of function or method."""

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

3-1 举个例子

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: Frank 
@contact: [email protected]
@file: test_inspect.py
@time: 2018/5/14 下午1:24

"""

from inspect import getmembers, ismethod, isclass, isfunction

def foo(): pass


class Cat(object):

    def __init__(self, name='kitty'):
        self.name = name

    def sayHi(self):
        print(self.name + '  says Hi!')

    def fun1(self):
        print('fun1 is running')


if __name__ == '__main__':
    cat = Cat('frank')
    cat.sayHi()

    print(isclass(cat))  # False
    print(isclass(Cat))  # True
    print(ismethod(cat.sayHi))  # True
    print(isfunction(cat.sayHi))  # False
    print(isfunction(foo))  # true
    print(ismethod(cat.fun1))  # True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  1. getmemory
    https://docs.python.org/3/library/inspect.html#inspect.getmembers
if __name__ == '__main__':
    cat = Cat('frank')

    # print(getmembers(cat))

    for member in getmembers(cat):
        print(member)   
        

# 结果如下
# ('__class__', )
# ('__delattr__', )
# ('__dict__', {'name': 'frank'})
# ('__dir__', )
# ('__doc__', None)
# ('__eq__', )
# ('__format__', )
# ('__ge__', )
# ('__getattribute__', )
# ('__gt__', )
# ('__hash__', )
# ('__init__', >)
# ('__init_subclass__', )
# ('__le__', )
# ('__lt__', )
# ('__module__', '__main__')
# ('__ne__', )
# ('__new__', )
# ('__reduce__', )
# ('__reduce_ex__', )
# ('__repr__', )
# ('__setattr__', )
# ('__sizeof__', )
# ('__str__', )
# ('__subclasshook__', )
# ('__weakref__', None)
# ('fun1', >)
# ('name', 'frank')
# ('sayHi', >)



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42

5 总结
当然inspect 有很多方法, 比如 获取源码这个,这个就我没有太用过. 经常用的可能就是我例子给出的,判断类型,以及拿到函数的参数,用inspect模块非常方便,甚至 可以通过这个模块,拿到函数的参数,写一个装饰器,对函数参数进行检查.

参考文档:
insect 模块

分享快乐,留住感动.2018-10-27 23:42:53 --frank
文章知识点与官方知识档案匹配,可进一步学习相关知识
Python入门技能树进阶语法常用标准库416686 人正在系统学习中
注:本文转载自blog.csdn.net的阿常呓语的文章"https://blog.csdn.net/u010339879/article/details/83451141"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2491) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top