在python中检测空函数定义 [英] Detecting empty function definitions in python

查看:141
本文介绍了在python中检测空函数定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检测一个函数是否为空定义.可能是这样的:

I need to detect whether a function is an empty definition or not. It can be like:

def foo():
    pass

或类似的

def foo(i, *arg, **kwargs):
    pass

或类似的

foo = lambda x: None

使用检查"模块检测到它们的最优雅方法是什么?有没有比这更好的方法了?

What is the most elegant way to detect them using the 'inspect' module? Is there a better way than this:

def isEmptyFunction(func):
    e = lambda: None
    return func.__code__.co_code == e.__code__.co_code

推荐答案

您提出的方法不太有效,因为具有文档字符串的空函数的字节码略有不同.

The method you propose does not quite work because empty functions that have docstrings have a slightly different bytecode.

对于没有文档字符串的空函数,func.__code__.co_code的值为'd\x00\x00S',而对于没有文档字符串的函数的func.__code__.co_code值为'd\x01\x00S'.

The value of func.__code__.co_code for an empty function with no docstring is 'd\x00\x00S', while the value of it for a function with a docstring is 'd\x01\x00S'.

出于我的目的,它仅用于添加要测试的其他案例:

For my purposes, it works just to add the additional case to test for:

def isEmptyFunction(func):
    def empty_func():
        pass

    def empty_func_with_doc():
        """Empty function with docstring."""
        pass

    return func.__code__.co_code == empty_func.__code__.co_code or \
        func.__code__.co_code == empty_func_with_doc.__code__.co_code

这篇关于在python中检测空函数定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆