Strangeness with a decorator

拜拜、爱过 提交于 2019-12-08 14:48:54

问题


I want to make a decorator which will catch exceptions and adequately logged their.

def logger(foo):
    try:
        print foo()
    except Exception as e:
        print e

@logger
def d():
    return 2/2

if __name__ == '__main__':
    d()

Thats right i think, but then I run it and I have an exception like this:

1

Traceback (most recent call last):

  File "log.py", line 14, in <module>

    d()

TypeError: 'NoneType' object is not callable

Why interpreter tells me that the function has None type, but call it and print answer?


回答1:


Your decorator needs to return a function, but it's not returning anything, hence the 'TypeError: 'NoneType' object is not callable'. You can implement it this way:

def logger(foo):
    def fn():
        try:
            print foo()
        except Exception as e:
            print e
    return fn

Check out This question for a good example of how to write/use a decorator.




回答2:


logger as you have defined, does not return a value. All such functions can be thought of as returning None. You have not defined your decorator correctly. It should look more like this:

def logger(foo):
    def _logger(foo):
        try:
            print foo()
         except Exception as e:
            print e
    return _logger

...but keep in mind that this loses a great deal of information, catches and swallows a great deal of exceptions, and also swallows any return values from the foo function so decorated. While you probably do something different in your production code than what you have shown here, the important thing is that the decorator function must itself return a function that can be called (_logger in my example).



来源:https://stackoverflow.com/questions/8855183/strangeness-with-a-decorator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!