Detecting empty function definitions in python

后端 未结 4 821
野的像风
野的像风 2021-02-20 01:37

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

def foo():
    pass

or like:

def foo(i, *arg         


        
4条回答
  •  礼貌的吻别
    2021-02-20 02:02

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

    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
    

提交回复
热议问题