Python-inspect的使用
inspect
模块提供了几个有用的函数来帮助获取有关于活动对象的信息,如模块、类、方法、函数、回溯、框架对象和代码对象。例如,它可以帮助您检查类的内容、检索方法的源代码、提取和格式化函数的参数列表,或者获得显示详细回溯所需的所有信息。下面来看一下inspect
模块中一些常用的方法:
类型方法
getmodulename(path)
getmodulename
根据路径获取模块名称
import os
from inspect import getmodulenamepath = os.path.join(os.getcwd(), "inspect.py")
name = getmodulename(path)
print(name, type(name)) # inspect_1 <class 'str'>name = getmodulename(os.getcwd())
print(name) # None
ismodule(object)
ismodule
判断对象是否是模块
import os
from inspect import ismoduleclass Student(object):def __init__(self):self.name = "laozhang"self.age = 20print(ismodule(os)) # True
print(ismodule(Student())) # False
isclass(object)
isclass
判断对象是否是个类
from inspect import isclassclass Student(object):def __init__(self):self.name = "laozhang"self.age = 20print(isclass(Student)) # True
print(isclass(Student())) # False
ismethod(object)
ismethod
判断对象是否是个方法
from inspect import ismethodclass Student(object):def __init__(self):self.name = "laozhang"self.age = 20def say(self):print("hello world!")s = Student()
print(ismethod(s.say)) # True
print(ismethod(s.name)) # False
isfunction(object)
isfunction
判断对象是否是个函数,包括匿名函数,不包括内置函数
from inspect import isfunctionclass Student(object):def __init__(self):self.name = "laozhang"self.age = 20def say(self):print("hello world!")def say():print("hello world!")s = Student()
print(isfunction(say)) # True
print(isfunction(s.say)) # False
isgeneratorfunction(object)
isgeneratorfunction
判断对象是否是个生成器函数或方法,包括匿名函数
from inspect import isgeneratorfunctionclass Student(object):def __init__(self):self.name = "laozhang"self.age = 20def say(self):print("hello world!")yieldprint("hello python")yieldprint("hello java")def say():print("hello world!")yieldprint("hello python")yieldprint("hello java")s = Student()
g = (item for item in range(10))
print(isgeneratorfunction(say)) # True
print(isgeneratorfunction(s.say)) # True
print(isgeneratorfunction(g)) # False
isgenerator(object)
isgenerator
判断是否是生成器,不包括函数或方法
from inspect import isgeneratordef say():print("hello world!")yieldprint("hello python")yieldprint("hello java")g = (item for item in range(10))print(isgenerator(say)) # False
print(isgenerator(say())) # True
print(isgenerator(g)) # True
iscoroutinefunction(object)
iscoroutinefunction
判断对象是否是由async def
定义的协程函数
from inspect import iscoroutinefunctionasync def coroutine():print("coroutine")def func():n = 0yield nprint("OK")print(iscoroutinefunction(coroutine)) # True
print(iscoroutinefunction(func)) # False
iscoroutine(object)
iscoroutine
判断对象是否是async def
定义的函数创建的协程
from inpsect import iscoroutinedef say():print("hello world!")yieldprint("hello python")async def coroutine():print("coroutine")g = (item for item in range(10))
print(iscoroutine(say)) # False
print(iscoroutine(say())) # False
print(iscoroutine(coroutine)) # False
print(iscoroutine(coroutine())) # True
print(iscoroutine(g)) # False
isawaitable(object)
isawaitable
如果对象可以用在await
表达式中,则返回True。可用于区分基于生成器的协程和常规生成器
import asyncio
from inspect import isawaitabledef yield_func():print("yield_func_1")yieldprint("yield_func_2")async def asyncio_func():print("asyncio_func_1")r = await asyncio.sleep(1)print("asyncio_func_2")print(isawaitable(yield_func())) # False
print(isawaitable(asyncio_func())) # True
istraceback(object)
istraceback
判断对象是否是回溯对象
import sys
from inspect import istraceback
try:raise TypeError
except TypeError:exec = sys.exc_info()print(exec) # (<class 'TypeError'>, TypeError(), <traceback object at 0x103c09788>)
print(istraceback(exec[2])) # True
isframe(object)
isframe
判断对象是否是frame
对象
import sys
from inspect import isframetry:raise TypeError
except TypeError:exec = sys.exc_info()print(exec[2]) # <traceback object at 0x103c29788>
print(exec[2].tb_frame) # <frame object at 0x101e07ad8>
print(isframe(exec[2].tb_frame)) # True
isbuiltin(object)
isbuiltin
判断对象是否是内置函数
from inspect import isbuiltindef say():print("Hello World!")print(isbuiltin(say)) # False
print(isbuiltin(max)) # True
isroutine(object)
isroutine
判断对象是否是内置函数、函数、方法或者方法描述符
from inspect import isroutineclass Student(object):def say(self):print("method hello world!")def say():print("Hello World!")print(isroutine(max)) # True
print(isroutine(say)) # True
print(isroutine(Student().say)) # True
print(isroutine(Student.__eq__)) # True
ismethoddescriptor(object)
ismethoddescriptor
判断对象是否是个方法描述符,即判断该对象是否是有__get__()
方法,没有__set__()
方法。但如果ismethod()
、isfunction()
、isclass()
或者isbuiltin()
为True,则返回False
from inspect import ismethod
from inspect import ismethoddescriptorprint(ismethod(int.__add__)) # False
print(ismethoddescriptor(int.__add__)) # True
isdatadescriptor(object)
isdatadescriptor
判断对象是否是个数据描述符,即判断该对象是否同时包含__set__()
和__get__()
方法。但如果ismethod()
、isfunction()
、isclass()
或者isbuiltin()
为True,则返回False
检索源代码
getdoc(object)
getdoc
获取对象的文档字符串,如果没有则返回None
from inspect import getdocclass Student(object):"""Student类"""def __init__(self):passdef say():"""say函数"""print(getdoc(Student), type(getdoc(Student))) # Student类 <class 'str'>
print(getdoc(say), type(getdoc(say))) # say函数 <class 'str'>
getcomments(object)
getcomments
以单个字符串的形式返回紧位于对象源代码(用于类、方法或者函数)之前的任何注释行,或者位于Python源文件的顶部(如果对象是个模块)。如果源代码不可用则返回None。
from inspect import getcomments# Student类
class Student(object):pass# say函数def say():passprint(getcomments(Student)) # # Student类
print(getcomments(say)) # None
getfile(object)
getfile
返回定义对象的文件路径
from inspect import getfilen = 20
class Student(object):passdef say():passprint(getfile(Student)) # /Users/xxx/PycharmProjects/Demo/xxx/inspect_5.py
print(getfile(say) # /Users/xxx/PycharmProjects/Demo/xxx/inspect_5.py
print(getfile(Student())) # TypeError: <__main__.Student object at 0x102ace9e8> is not a module, class, method, function, traceback, frame, or code object
print(getfile(say()) # TypeError: None is not a module, class, method, function, traceback, frame, or code object
print(getfile(max)) # TypeError: <built-in function max> is not a module, class, method, function, traceback, frame, or code object
print(getfile(n)) # TypeError: 20 is not a module, class, method, function, traceback, frame, or code object
getmodule(object)
getmodule
尝试猜测对象定义在哪个模块当中
from inspect import getmodulen = 20
class Student(object):passdef say():passprint(getmodule(Student)) # <module '__main__' from '/Users/xxx/PycharmProjects/Demo/xxx用/inspect_5.py'>
print(getmodule(say)) # <module '__main__' from '/Users/xxx/PycharmProjects/Demo/xxx/inspect_5.py'>
print(getmodule(Student())) # <module '__main__' from '/Users/xxx/PycharmProjects/Demo/xxx/inspect_5.py'>
print(getmodule(say())) # None
print(getmodule(max)) # <module 'builtins' (built-in)>
print(getmodule(n)) # None
更多操作:https://docs.python.org/3.6/library/inspect.html
Python-inspect的使用相关推荐
- python inspect.stack() 的简单使用
1. #python # -*- encoding: utf-8 -*- #获取函数的名字 import inspect def debug():callnamer = inspect.stack() ...
- python inspect模块解析
来源:https://my.oschina.net/taisha/blog/55597 inspect模块主要提供了四种用处: (1) 对是否是模块,框架,函数等进行类型检查. (2) 获取源码 (3 ...
- python inspect
inspect模块主要提供了四种用处: 对是否是模块.框架.函数进行类型检查 获取源码 获取类或者函数的参数信息 解析堆栈解析堆栈 http://www.cnblogs.com/yaohong/p/8 ...
- python inspect模块
inspect模块的四种用处: 1)对是否是模块,框架,函数等进行类型检查 2)获取源码 3)获取类或函数的参数的信息 4)解析堆栈. inspect.stack()[1][3] #当前运行的函数的函 ...
- python inspect —— 查看类的继承体系
1. inspect.getmro mro:method resolution order: 查看 defaultdict 的继承体系: >> import inspect >> ...
- Python语法学习记录(24):inspect模块介绍及常用使用方式
1.简述 获取函数签名对象. 函数签名包含了一个函数的信息,包括函数名.它的参数类型.它所在的类和名称空间及其他信息). 2.基本用法 inspect模块主要提供了四种用处: 1.对是否是模块.框架. ...
- python模块—inspect
python inspect type and member Retrieving source code class and functions The interpreter stack insp ...
- 无法嵌入互操作类型 请改用适用的接口_可微编程-自上而下的产品形态 4 Python互操作性...
原文:Python互操作性 如设计概述文档所述,Python API互操作性是本项目的一个重要需求.虽然Swift被设计为与其他编程语言(及其运行时)集成,但动态语言的本质并不需要支持静态语言所需的深 ...
- python描述器 有限状态机_笨办法学 Python · 续 练习 30:有限状态机
练习 30:有限状态机 每当你阅读一本关于解析的书,都有一个可怕的章节,关于有限状态机(FSM).他们对"边"和"节点"进行了详细的分析,每个可能的" ...
- 笨办法学 Python · 续 练习 30:有限状态机
练习 30:有限状态机 原文:Exercise 30: Finite State Machines 译者:飞龙 协议:CC BY-NC-SA 4.0 自豪地采用谷歌翻译 每当你阅读一本关于解析的书,都 ...
最新文章
- 成为大厂AI算法工程师,“NLP/CV”都是你必须过的坎!
- JavaScript学习笔记01【基础——简介、基础语法、运算符、特殊语法、流程控制语句】
- JFinal开发框架简介
- Git - 修改用户名
- 【原创】MVC+ZTree实现权限树的功能
- Laravel 5.1 源码阅读
- UI实用素材|字体在设计中的重要性
- html代码如何查看视频,Web前端
- python保存html图_如何保存“完整网页”不仅仅是使用Python的基本HTML
- 通信原理 简易蒙特卡洛仿真法仿真无码间干扰基带系统误码率的matlab实现
- 云南省21年春季高中信息技术学业水平考试真题
- (原创)Android 清除第三方应用的数据缓存实现(包括清除系统应用缓存)
- CISCO Switchport trunk encap dot1q 与 Switchport trunk 区别
- ogre 学习笔记 - Day 7
- CCF认证201403-1相反数
- 华为路由器hilink怎么用_HUAWEI HiLink 两个华为路由器无线中继实测效果【图解】...
- Cantor表 [cantor]
- 编写一个用于字符串比较的函数
- 窗口桌面置顶(主窗口和子窗口)
- 三国杀开源系列之二105@365
热门文章
- 微信小程序 对onShareAppMessage进行封装,分为分享到个人和分享到群
- BERT gated multi-window attention network for relation extraction 用于关系抽取的BERT门控多窗口注意力网络
- 深信服2020校招研发类笔试题 解密游戏
- 制作地址栏中的小图标
- Python的序列和切片
- Ira and Flamenco
- o.h.hql.internal.ast.ErrorTracker : Unable to locate class [xxx]
- 【OpenGL进阶】05.绘制3D模型
- java编程求卡特兰数_卡特兰数(Catalan Number)
- 备份微信聊天(电脑端)记录小技巧