1

The Decorator Function of Python has this simple template

@A

@B

def C():

It modify the C function to C=A(B(C));

Let's give a more specific example

@request("POST", "%(channel)d/sequence/%(args)s") 
@response("%d")

    def outputSequence(self, channel, args):
        self.checkDigitalChannelExported(channel)
        self.checkPostingValueAllowed()
        self.checkDigitalChannel(channel)
        (period, sequence) = args.split(",")
        period = int(period)
        GPIO.outputSequence(channel, period, sequence)
        return int(sequence[-1])

So from the above, would the transformed function be

like request(response(outSequence(self, channel, args))?

2
  • Do you mean function decorators? To my knowledge there is no such thing as a decorative function in python. Commented Mar 6, 2014 at 2:15
  • It's not entirely clear what you're asking. As per my question. Are you trying to make sense of decorators that take arguments? Commented Mar 6, 2014 at 2:47

2 Answers 2

5

Parameterized decorators behave a bit differently. The function request accepts only the arguments, it's a decorator maker:

def request(arg1, arg2):
    def my_decorator(func):
        def wrapper():
           #do something
        return wrapper
    return my_decorator

So the function calls is like:

decorator = request(arg1, arg2)
response_decorator = decorator(response(arg1, arg2))
outputSequence = response_decorator(outputSequence(self, arg1, arg2))

Here's a tiny example:

>>> def make_decorators(arg1, arg2):
        def decorator(func):
            def wrapper():
                print("We got here!")
            return wrapper
        return decorator

>>> @make_decorators(1, 2)
    def my_func():
        pass


>>> my_func()
We got here!
Sign up to request clarification or add additional context in comments.

Comments

2

Close. When a decorator is given one or more arguments, the effect is to call the decorator, which returns a function that is then applied to the function it is decorating. The effect is something more like (as Niklas B. pointed out):

request("POST", "%(channel)d/sequence/%(args)s")(
   response("%d")(
       outputSequence))(self, channel, args)

1 Comment

Actually calling the function would be more like request("POST", "%(channel)d/sequence/%(args)s")(response("%d")(outputSequence))(self, channel, args). However, what the decorator does is outputSequence = request(...)(response(...)(outputSequence))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.