Python检查模块

本文介绍了Python的inspect模块,它用于检查程序中的活对象,查看模块、类和函数的源代码。文章通过示例展示了如何使用inspect模块来获取模块、类、方法的源代码、docstring、对象详情以及方法签名等。
摘要由CSDN通过智能技术生成

Python检查模块 (Python inspect module)

Python inspect module is a very useful module which is used to introspect live objects in a program and look at the source code of modules, classes and functions which are used throughout a program. This is powerful because this module can actually be used to extract the source code of a function itself, parse the arguments which that function accepts and related library documentation.

Python inspect模块是一个非常有用的模块 ,用于对程序中的活动对象进行自检,并查看整个程序中使用的模块, 函数的源代码。 这功能强大,因为此模块实际上可以用于提取函数本身的源代码,解析该函数​​接受的参数以及相关的库文档。

提供样品模块 (Providing sample module)

To take a sample to be used throughout this lesson, we will construct a very small sample module with some functions, classes and Python docstrings. Here is the code snippet for sample.py:

为了获得在本课程中使用的示例,我们将构建一个非常小的示例模块,其中包含一些函数,类和Python文档字符串。 这是sample.py的代码片段:

def module_funct(arg1, arg2 = 'default', *args):
    """This is a module-level function."""
    local_var = arg1 * 3
    return local_var

class X(object):
    """Definition for X class."""

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

    def get_name(self):
        "Returns the name of the instance."
        return self.name

x_obj = X('sample_instance')

class Y(X):
    """This is the Y class, 
    child of X class.
    """

    # This method is not part of X class.
    def do_something(self):
        """Anything can be done here."""

    def get_name(self):
        "Overrides version from X"
        return 'Y(' + self.name + ')'

Now that we have a sample module ready for usage, we can start extract and introspecting its source code, docstring and object details. Let’s get started.

现在,我们已经准备好使用一个示例模块,我们可以开始提取并自检其源代码,文档字符串和对象详细信息。 让我们开始吧。

内省模块 (Introspecting module)

Let us start by introspecting the sample module we defined. Note that for this, we have the sample module file sample.py in the same directory as we execute our scripts in. Here is a sample code snippet on how we can inspect our module:

让我们从内省我们定义的样本模块开始。 请注意,为此,我们在其中执行脚本的目录中有示例模块文件sample.py 。这是有关如何检查模块的示例代码片段:

import inspect
import sample

for name, data in inspect.getmembers(sample):
    if name.startswith('__'):
        continue
    print('{} : {!r}'.format(name, data))

Let’s see the output for this program:

让我们看一下该程序的输出:

python inspect module

Introspecting module with inspect

带有检查的自检模块

自检模块中的类 (Introspecting classes in a module)

We can get all the classes which are present in a module and take action when we find the class we were looking for:

我们可以获取模块中存在的所有类,并在找到所需的类时采取行动:

import inspect
import sample

for key, data in inspect.getmembers(sample, inspect.isclass):
    print('{} : {!r}'.format(key, data))

Let’s see the output for this program:

让我们看一下该程序的输出:

python inspect class

Introspecting module classes with inspect

使用inspect内省模块类


With a simple identification with the help of
借助 isclass property, we were able to get the classes of the modules. isclass属性的简单标识,我们就能获得模块的类。

类中的自省方法 (Introspecting methods in a classes)

This time, we go deeper by inspecting the methods which are present in a class. Notice that we use the same method getmembers and only the property identifier is different, i.e. isfunction:

这次,我们通过检查类中存在的方法来做更深入的研究。 注意,我们使用相同的方法getmembers ,只是属性标识符不同,即isfunction

import inspect
from pprint import pprint
import sample

pprint(inspect.getmembers(sample.X, inspect.isfunction))

Let’s see the output for this program:

让我们看一下该程序的输出:

python inspect methods

Introspecting methods of a class

一类的自省方法

内省一个类的对象 (Introspecting objects of a class)

With the inspect module, it is possible to keep track of all the instances of a class made in a program simply with a single function call:

使用inspect模块,可以通过单个函数调用来跟踪程序中创建的类的所有实例:

import inspect
from pprint import pprint
import sample

x = sample.X(name='inspect_getmembers')
pprint(inspect.getmembers(x, inspect.ismethod))

Let’s see the output for this program:

让我们看一下该程序的输出:

python inspect example objects

Inspecting objects of a class

检查类的对象

为课程获取文档字符串 (Getting Docstring for class)

inspect module is often used in Python tools which automate the process of extracting a class and their methods docstrings which can be presented to end-users. This means that a developer can simply put docstrings in a method and the same docstring can be used to be presented to another developer of the application as well which reduces developer effort:

inspect模块通常用在Python工具中,该工具可以自动提取一个类及其方法docstring,这些过程可以呈现给最终用户。 这意味着开发人员可以简单地将文档字符串放入方法中,并且相同的文档字符串也可以用于呈现给应用程序的其他开发人员,从而减少了开发人员的工作量:

import inspect
import sample

print('X.__doc__:')
print(sample.X.__doc__)
print()
print('getdoc(X):')
print(inspect.getdoc(sample.X))

Let’s see the output for this program:

python inspect getdoc example

让我们看一下该程序的输出:

获取课程来源 (Getting Source of class)

In intelligent environments like an IDE, inspect module is used to present the source code of modules, classes, and functions:

在像IDE这样的智能环境中,inspect模块用于显示模块,类和函数的源代码:

import inspect
import sample

print(inspect.getsource(sample.Y))

Let’s see the output for this program:

让我们看一下该程序的输出:

python inspect source code

Getting Source code of a class

获取类的源代码


Complete source code of the class was printed for the class
该类的完整源代码已为该类打印, without any docstring. 没有任何文档字符串

获取方法来源 (Getting Source of method)

This time, we get teh source code of a single method only:

这次,我们仅获得单个方法的源代码:

import inspect
import sample

print(inspect.getsource(sample.Y.get_name))

Let’s see the output for this program:

让我们看一下该程序的输出:

python inspect source method

Getting Source code of a method

获取方法的源代码

获取方法签名 (Getting Method Signature)

For a final example, we will get the signature of a method which is used a lot in Intellisense of an IDEs to present to developers what arguments does a method accepts:

对于最后一个示例,我们将获得方法的签名,该方法在IDE的Intellisense中经常使用,以向开发人员提供方法接受的参数:

import inspect
import sample

print(inspect.signature(sample.module_funct))

Let’s see the output for this program:

让我们看一下该程序的输出:

python inspect signature

Getting Signature of method

获取方法签名

结论 (Conclusion)

In this lesson, we studied an excellent Python module, inspect which is used a lot in Code tools like IDEs and documentation tools as well.

在本课中,我们学习了一个出色的Python模块,检查了IDE和文档工具等Code工具中是否经常使用该模块。

Reference: API Doc.

参考: API Doc

翻译自: https://www.journaldev.com/19946/python-inspect-module

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值