Search code examples
pythonoptimizationcpython

Detecting blank/empty function in cpython calls?


We have an application that allows users to override optional python callback functions.

Example when serial data is received, an optional user-defined python function is called:

def onDataReceived(bytes, timeStamp, address, peer):
    return

This is not from a source file, but compiled in the app.

Note that the application is a real-time processing engine in C++ so any calls to the cpython interpreter consumes quite a bit of overhead. I do have access to the precompiled functions so is there any way to determine if its trivially blank/empty as above without resorting to hand parsing the text directly?

Thanks.


Solution

  • You could check the func.__code__.co_code (Python 3; on Python 2 use func_code instead of co_code). This is a byte string containing the function's byte code.

    Thus:

    >>> def foo():
    ...     return
    ... 
    >>> def bar():
    ...     pass
    ... 
    >>> import dis
    >>> dis.dis(foo)
      2           0 LOAD_CONST               0 (None)
                  3 RETURN_VALUE
    >>> dis.dis(bar)
      2           0 LOAD_CONST               0 (None)
                  3 RETURN_VALUE
    >>> foo.__code__.co_code
    b'd\x00\x00S'
    

    So you can create a function that compares the __code__.co_code against a known empty function:

    def empty():
        pass
    
    empty_code = empty.__code__.co_code
    
    def is_empty(func):
        return hasattr(func, '__code__') and func.__code__.co_code == empty_code
    

    Note that functions that have a docstring, have slightly different bytecode (the docstring takes up a constant slot), and so forth. For more sophisticated ones you can inspect the byte-code disassembler output output.