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

这个模块提供了四种主要的服务:

类型检查,

获取源代码,

检查类和函数,

以及检查解释器堆栈

一、type and members

1. inspect.getmembers(object[, predicate])

第二个参数通常可以根据需要调用如下16个方法;

返回值为object的所有成员,以(name,value)对组成的列表

inspect.ismodule(object): 是否为模块

inspect.isclass(object):是否为类

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

inspect.isfunction(object):是否为函数(python function, including lambda expression)

inspect.isgeneratorfunction(object):是否为python生成器函数

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

inspect.istraceback(object): 是否为traceback

inspect.isframe(object):是否为frame

inspect.iscode(object):是否为code

inspect.isbuiltin(object):是否为built-in函数或built-in方法

inspect.isroutine(object):是否为用户自定义或者built-in函数或方法

inspect.isabstract(object):是否为抽象基类

inspect.ismethoddescriptor(object):是否为方法标识符

inspect.isdatadescriptor(object):是否为数字标识符,数字标识符有__get__ 和__set__属性; 通常也有__name__和__doc__属性

inspect.isgetsetdescriptor(object):是否为getset descriptor

inspect.ismemberdescriptor(object):是否为member descriptor

inspect的getmembers()方法可以获取对象(module、class、method等)的如下属性:

Type Attribute Description Notes
module __doc__ documentation string  
  __file__ filename (missing for built-in modules)  
class __doc__ documentation string  
  __module__ name of module in which this class was defined  
method __doc__ documentation string  
  __name__ name with which this method was defined  
  im_class class object that asked for this method (1)
  im_func or __func__ function object containing implementation of method  
  im_self or __self__ instance to which this method is bound, or None  
function __doc__ documentation string  
  __name__ name with which this function was defined  
  func_code code object containing compiled function bytecode  
  func_defaults tuple of any default values for arguments  
  func_doc (same as __doc__)  
  func_globals global namespace in which this function was defined  
  func_name (same as __name__)  
generator __iter__ defined to support iteration over container  
  close raises new GeneratorExit exception inside the generator to terminate the iteration  
  gi_code code object  
  gi_frame frame object or possibly None once the generator has been exhausted  
  gi_running set to 1 when generator is executing, 0 otherwise  
  next return the next item from the container  
  send resumes the generator and “sends” a value that becomes the result of the current yield-expression  
  throw used to raise an exception inside the generator  
traceback tb_frame frame object at this level  
  tb_lasti index of last attempted instruction in bytecode  
  tb_lineno current line number in Python source code  
  tb_next next inner traceback object (called by this level)  
frame f_back next outer frame object (this frame’s caller)  
  f_builtins builtins namespace seen by this frame  
  f_code code object being executed in this frame  
  f_exc_traceback traceback if raised in this frame, or None  
  f_exc_type exception type if raised in this frame, or None  
  f_exc_value exception value if raised in this frame, or None  
  f_globals global namespace seen by this frame  
  f_lasti index of last attempted instruction in bytecode  
  f_lineno current line number in Python source code  
  f_locals local namespace seen by this frame  
  f_restricted 0 or 1 if frame is in restricted execution mode  
  f_trace tracing function for this frame, or None  
code co_argcount number of arguments (not including * or ** args)  
  co_code string of raw compiled bytecode  
  co_consts tuple of constants used in the bytecode  
  co_filename name of file in which this code object was created  
  co_firstlineno number of first line in Python source code  
  co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg |8=**arg  
  co_lnotab encoded mapping of line numbers to bytecode indices  
  co_name name with which this code object was defined  
  co_names tuple of names of local variables  
  co_nlocals number of local variables  
  co_stacksize virtual machine stack space required  
  co_varnames tuple of names of arguments and local variables  
builtin __doc__ documentation string  
  __name__ original name of this function or method  
  __self__ instance to which a method is bound, or None  

2. inspect.getmoduleinfo(path): 返回一个命名元组<named tuple>(name,
suffix, mode, module_type)

  name:模块名(不包括其所在的package)

suffix:

mode:open()方法的模式,如:'r', 'a'等

module_type: 整数,代表了模块的类型

3. inspect.getmodulename(path):根据path返回模块名(不包括其所在的package)

二、Retrieving source code

1. inspect.getdoc(object): 获取object的documentation信息

2. inspect.getcomments(object)

3. inspect.getfile(object): 返回对象的文件名

4. inspect.getmodule(object):返回object所属的模块名

5. inspect.getsourcefile(object): 返回object的python源文件名;object不能使built-in的module, class, mothod

6. inspect.getsourcelines(object):返回object的python源文件代码的内容,行号+代码行

7. inspect.getsource(object):以string形式返回object的源代码

8. inspect.cleandoc(doc):

三、class and functions

1. inspect.getclasstree(classes[, unique])

2. inspect.getargspec(func)

3. inspect.getargvalues(frame)

4. inspect.formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue, join])

5. inspect.formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue, join])

6. inspect.getmro(cls): 元组形式返回cls类的基类(包括cls类),以method resolution顺序;通常cls类为元素的第一个元素

7. inspect.getcallargs(func[, *args][, **kwds]):将args和kwds参数到绑定到为func的参数名;对bound方法,也绑定第一个参数(通常为self)到相应的实例;返回字典,对应参数名及其值;

  1. >>> from inspect import getcallargs
  2. >>> def f(a, b=1, *pos, **named):
  3. ... pass
  4. >>> getcallargs(f, 1, 2, 3)
  5. {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
  6. >>> getcallargs(f, a=2, x=4)
  7. {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
  8. >>> getcallargs(f)
  9. Traceback (most recent call last):
  10. ...
  11. TypeError: f() takes at least 1 argument (0 given)

四、The interpreter stack

1. inspect.getframeinfo(frame[, context])

2. inspect.getouterframes(frame[, context])

3. inspect.getinnerframes(traceback[, context])

4. inspect.currentframe()

5. inspect.stack([context])

6. inspect.trace([context])

今天看RYU源码时,发现一个inspect模块,RYU使用了该模块的getmembers函数来获取ryu app的app类。

函数原型是 inspect.getmembers(object[, predicate])

功能: 从一个Object中获取符合predicate的元素的list,元素的形式是(name,value)
predicate可以是ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),isroutine(),这些验证函数。

看一个例子

  1. import inspect
  2. class C():
  3. class CC():
  4. def foo3():
  5. print "foo3"
  6. def foo():
  7. print "foo"
  8. def foo2():
  9. print "foo2"
  10. cls = inspect.getmembers(C,inspect.ismethod)
  11. print cls

执行的结果是

inspect模块---检查活动对象的更多相关文章

  1. 14 - 函数参数检测-inspect模块

    目录 1 python类型注解 2 函数定义的弊端 3 函数文档 4 函数注解 4.1 annotation属性 5 inspect模块 5.1 常用方法 5.2 signature类 5.3 par ...

  2. inspect模块详解

    inspect模块主要提供了四种用处: (1).对是否是模块,框架,函数等进行类型检查. (2).获取源码 (3).获取类或函数的参数的信息 (4).解析堆栈 使用inspect模块可以提供自省功能, ...

  3. python之inspect模块

      inspect模块主要提供了四种用处: 1.对是否是模块.框架.函数进行类型检查 2.获取源码 3.获取类或者函数的参数信息 4.解析堆栈 回到顶部 一.type and members 1. i ...

  4. Python多进程(2)——mmap模块与mmap对象

    本文介绍Python mmap模块与mmap对象的用法. mmap 模块提供“内存映射的文件对象”,mmap 对象可以用在使用 plain string 的地方,mmap 对象和 plain stri ...

  5. js基础梳理-究竟什么是变量对象,什么是活动对象?

    首先,回顾下上篇博文中js基础梳理-究竟什么是执行上下文栈(执行栈),执行上下文(可执行代码)?的执行上下文的生命周期: 3.执行上下文的生命周期 3.1 创建阶段 生成变量对象(Variable o ...

  6. python的inspect模块

    一.type and members 1. inspect.getmembers(object[, predicate]) 第二个参数通常可以根据需要调用如下16个方法: 返回值为object的所有成 ...

  7. python——inspect模块

    inspect模块常用功能 import inspect # 导入inspect模块 inspect.isfunction(fn) # 检测fn是不是函数 inspect.isgenerator((x ...

  8. javascript活动对象的理解——伪单例模式

    在自己研究javascript各种设计模式的过程中,偶然写出的一段代码让自己理解的更深刻了,之所以称之为伪单例模式,是因为这段代码造成的结果很想单例模式,但是实际上是活动对象捣乱所造成的误会. 代码很 ...

  9. 图解Javascript——变量对象和活动对象

    span { line-height: 1.5 } 这是由一段代码引发的思考: var laterDeclaredVar = 'I am a global variable ...'; (functi ...

随机推荐

  1. 图灵机器人,web录音实现自动化交互问答

    一.图灵机器人 介绍 图灵机器人 是以语义技术为核心驱动力的人工智能公司,致力于“让机器理解世界”,产品服务包括机器人开放平台.机器人OS和场景方案. 官方地址为: http://www.tuling ...

  2. sqlserver 把SELECT结果集中一列的所有的值 用逗号隔开放进一个字段内

    首先我们有一个表 查询结果如下: 现在我们想要把USER_NAME这一列的内容 放到一个字段里面去: 一行sql语句解决问题: SELECT STUFF(( SELECT ',' +convert(V ...

  3. fhq-treap模板

    模板保存. #include<iostream> #include<cstdio> #include<cstring> #include<ctime> ...

  4. 介绍个好点的,JAVA技术群

    java技术交流,意义是以QQ群为媒介,添加一些有多年工作经验和技术的人群,为有问题的人群解答在工作中遇到的各种问题为思想,java技术交流群号161571685,创建时间为2010年,走过将近5年的 ...

  5. 【转】浏览器中F5和CTRL F5的行为区别

    原文地址:http://www.cnblogs.com/jiji262/p/3410518.html 前言 在印象中,浏览器中的F5和刷新按钮是一样的效果,都是对当前页面进行刷新:Ctrl-F5的行为 ...

  6. WEB前端--JavaScript

    JavaScript JavaScript基础 一.JavaScript简介 JavaScript是一种嵌入到HTML文件中的描述性语言,由浏览器的解释器将其动态地处理成可执行的代码,能独立地完成与客 ...

  7. p5156 [USACO18DEC]Sort It Out

    传送门 分析 我们发现对于没有发现的点相对位置不会发生改变 于是我们可以吧问题转化为求一个lis 于是我们字典序第k小的答案就是字典序第k大的lis 代码 #include<iostream&g ...

  8. html5 存储方式

    localstorage(永久保存)&&sessionstorage(重新打开浏览器会消失) sessionStorage用于本地存储一个会话(session)中的数据,这些数据只有在 ...

  9. Request[]与Request.Params[] 差别

    Request[]与Request.Params[] ,这二个属性都可以让我们方便地根据一个KEY去[同时搜索]QueryString.Form.Cookies 或 ServerVariables这4 ...

  10. AutoLayout自动布局,NSLayoutConstraint 视图约束使用

    一.方法 NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:<#(id)#> attribut ...