Python-inspect的使用

本文深入解析Python的inspect模块,展示了如何使用其丰富的函数来检查和操纵活动对象,如模块、类、方法、函数等,提供了实用的代码示例,帮助读者理解和掌握inspect模块的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值