2

I ran into these lines of code in the QPYTHON Android app. They are part of a sample that uses the Bottle module to create a simple Web server that seems to work fine.

app = Bottle()
app.route('/', method='GET')(home)
app.route('/__exit', method=['GET','HEAD'])(__exit)
app.route('/__ping', method=['GET','HEAD'])(__ping)
app.route('/assets/<filepath:path>', method='GET')(server_static)

Now, I know that all the functions in parentheses after the call have already been wrapped with the @route decorator above this. For example:

@route('/__ping')
def __ping():
 return "ok"

But I have no idea what putting things in parentheses after other things does in Python, and after trying a hundred different permutations of "functions in parentheses after functions" I gave up.

I throw myself on the mercy of the Exchange.

Dan1701
3,1081 gold badge17 silver badges25 bronze badges
asked Jul 9, 2015 at 10:34
2
  • It looks like the function route returns another function, and that dynamically selected function is then called with the argument home (for instance). Look up higher-order functions. Commented Jul 9, 2015 at 10:43
  • 3
    "putting things in parentheses after other things" calls the other things - foo(bar, baz) calls foo with the arguments bar and baz, foo(bar)(baz) calls foo with the argument bar and then calls whatever foo returns with the argument baz. In this case, @route is a decorator (i.e. a callable that returns a callable) that takes parameters: stackoverflow.com/questions/5929107/… Commented Jul 9, 2015 at 11:27

2 Answers 2

8

This:

app.route('/', method='GET')(home)

... Is the same as this:

func = app.route('/', method='GET')
func(home)

In other words, app.route(...) returns a function, which is then called.

answered Jul 9, 2015 at 13:12
3
def a():
 def b(arg):
 return arg * 2
 return b
print(a()(5))
c = a()
print(c(5))
Output:
10
10

You are basically providing an argument for the function within the function, a.k.a inner function

answered Apr 1, 2022 at 5:33

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.