Python decorator? - can someone please explain this?

前端 未结 6 968
离开以前
离开以前 2020-11-29 10:42

Apologies this is a very broad question.

The code below is a fragment of something found on the web. The key thing I am interested in is the line beginning @protect

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-29 11:26

    The decorator syntax:

    @protected(check_valid_user) 
    def do_upload_ajax():
        "..."
    

    is equivalent to

    def do_upload_ajax():
        "..."
    do_upload_ajax = protected(check_valid_user)(do_upload_ajax)
    

    but without the need to repeat the same name three times. There is nothing more to it.

    For example, here's a possible implementation of protected():

    import functools
    
    def protected(check):
        def decorator(func): # it is called with a function to be decorated
            @functools.wraps(func) # preserve original name, docstring, etc
            def wrapper(*args, **kwargs):
                check(bottle.request) # raise an exception if the check fails
                return func(*args, **kwargs) # call the original function
            return wrapper # this will be assigned to the decorated name
        return decorator
    

提交回复
热议问题