inspect
模块提供了几个有用的函数来帮助获取有关于活动对象的信息,如模块、类、方法、函数、回溯、框架对象和代码对象。例如,它可以帮助您检查类的内容、检索方法的源代码、提取和格式化函数的参数列表,或者获得显示详细回溯所需的所有信息。下面来看一下inspect
模块中一些常用的方法:
类型方法
getmodulename(path)
getmodulename
根据路径获取模块名称
import os
from inspect import getmodulename
path = 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 ismodule
class Student(object):
def __init__(self):
self.name = "laozhang"
self.age = 20
print(ismodule(os)) # True
print(ismodule(Student())) # False
isclass(object)
isclass
判断对象是否是个类
from inspect import isclass
class Student(object):
def __init__(self):
self.name = "laozhang"
self.age = 20
print(isclass(Student)) # True
print(isclass(Student())) # False
ismethod(object)
ismethod
判断对象是否是个方法
from inspect import ismethod
class Student(object):
def __init__(self):
self.name = "laozhang"
self.age = 20
def say(self):
print("hello world!")
s = Student()
print(ismethod(s.say)) # True
print(ismethod(s.name)) # False
isfunction(object)
isfunction
判断对象是否是个函数,包括匿名函数,不包括内置函数
from inspect import isfunction
class Student(object):
def __init__(self):
self.name = "laozhang"
self.age = 20
def 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 isgeneratorfunction
class Student(object):
def __init__(self):
self.name = "laozhang"
self.age = 20
def say(self):
print("hello world!")
yield
print("hello python")
yield
print("hello java")
def say():
print("hello world!")
yield
print("hello python")
yield
print("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 isgenerator
def say():
print("hello world!")
yield
print("hello python")
yield
print("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 iscoroutinefunction
async def coroutine():
print("coroutine")
def func():
n = 0
yield n
print("OK")
print(iscoroutinefunction(coroutine)) # True
print(iscoroutinefunction(func)) # False
iscoroutine(object)
iscoroutine
判断对象是否是async def
定义的函数创建的协程
from inpsect import iscoroutine
def say():
print("hello world!")
yield
print("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 isawaitable
def yield_func():
print("yield_func_1")
yield
print("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 isframe
try:
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 isbuiltin
def say():
print("Hello World!")
print(isbuiltin(say)) # False
print(isbuiltin(max)) # True
isroutine(object)
isroutine
判断对象是否是内置函数、函数、方法或者方法描述符
from inspect import isroutine
class 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 ismethoddescriptor
print(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 getdoc
class Student(object):
"""
Student类
"""
def __init__(self):
pass
def 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():
pass
print(getcomments(Student)) # # Student类
print(getcomments(say)) # None
getfile(object)
getfile
返回定义对象的文件路径
from inspect import getfile
n = 20
class Student(object):
pass
def say():
pass
print(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 getmodule
n = 20
class Student(object):
pass
def say():
pass
print(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