Decorators run before function it is decorating is called?

后端 未结 4 1813
逝去的感伤
逝去的感伤 2020-12-06 02:13

As an example:

def get_booking(f=None):
    print "Calling get_booking Decorator"
    def wrapper(request, **kwargs):
        booking = _get_booking         


        
相关标签:
4条回答
  • 2020-12-06 02:16

    I believe python decorators are just syntactic sugar.

    @foo
    def bar ():
        pass
    

    is the same thing as

    def bar ():
        pass
    bar = foo(bar)
    

    As you can see, foo is being called even though bar has not been called. This is why you see the output from your decorator function. Your output should contain a single line for every function you applied your decorator to.

    0 讨论(0)
  • 2020-12-06 02:24

    A decorator is called as soon as the decorated function is defined. It is equivalent to writing something like this:

    def __do_stuff(...):
        ...
    
    do_stuff = get_booking(__do_stuff)
    
    0 讨论(0)
  • 2020-12-06 02:37

    Since you are starting with decorators, I think reading these will be helpful, so that you know the pitfalls and workarounds beforehand.

    Here are two links to earlier discussions on decorators.

    Python decorator makes function forget that it belongs to a class What does functools.wraps do?

    Moreover the second link mentions 'functools' a module for higher-order functions, that act on or return other functions. Use of functools.wraps is advised since it preserves the doc string of the original function(decorated one).

    Another issue was wrong method signatures while generating automatic docs for my project. but there is a workaround: Preserving signatures of decorated functions

    Hope this helps.

    0 讨论(0)
  • 2020-12-06 02:38

    python decorators are functions applied to a function to transform it:

    @my_decorator
    def function (): ...
    

    is like doing this:

    def function():...
    function = my_decorator(function)
    

    What you want to do is:

    def get_booking(f=None):
        def wrapper(request, **kwargs):
            print "Calling get_booking Decorator"
            booking = _get_booking_from_session(request)
            if booking == None:
                # we don't have a booking in our session.
                return HttpRedirect('/')
            else:
                return f(request=request, booking=booking, **kwargs)
        return wrapper
    
    0 讨论(0)
提交回复
热议问题