Detecting empty function definitions in python

后端 未结 4 824
野的像风
野的像风 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 01:56

    Why would you do that? It looks like bad design. I would bet you wouldn't make anything faster.

    python -m timeit -s'def a(): pass' -s'def b(): pass' 'if a.__code__.co_code == b.__code__.co_code: pass'
    1000000 loops, best of 3: 0.293 usec per loop
    
    python -m timeit -s 'def a(): pass' -s 'def b(): pass' 'a()'
    10000000 loops, best of 3: 0.0941 usec per loop
    

    It seems like it is magnitude slower to compare than to just do call, because there were 10 times more loops in the latter timeit. The equals operator actually is surely calls a.code.co_code.eq. So you are just making things slower.

提交回复
热议问题