I wonder how to correctly use python 2.7 callback functions.
I have some callback functions from Cherrypy auth examples in my code.
(These callbacks return a function that can evaluate to True or False, depending on the logged in user being in a group or not.)
I wonder if a callback is executed or not if I write a piece of code like this:
Given the definition from the library is:
def member_of(groupname):
def check():
if groupname == 'admin':
if cherrypy.request.login == 'joe':
return True
if cherrypy.request.login == 'toni':
return True
return False
return False
# .... (other groups checked in the same way)
return check # returns a callback function from my understanding?
How can I apply and execute the callback in my code?
If I put it like this:
if member_of('admin'):
do_something()
else:
do_something_else()
Will this execute the calllback and check for the admin group? Or will it find out if the value of "member_of" is a function definition and a function definition is probably always a "True" value (or maybe a False value) but both are wrong, because it needs to be executed
Can you enlighten me on this? How can I make sure a callback is executed? An how can I pass it around as it is?
If you execute it, it is plain simple.
member_of()
will return method object check. you have to execute to get result by doing something like ifmember_of('admin')()
: or,To do your task.
In python, like in many other languages, a variable can also contain a function and you can pass them around like other variables that contain e.g. numbers or strings.
CherryPy's
member_of
function itself does return a function in your example.I am explaining it in simple steps:
If you write
member_of()
it returns the result of the function member_of() which is the function with the namecheck
in this case.At this point the variable
cb_function
holds the result of calling the functionmember_of
, and in the last linemember_of
returnscheck
, which was defined within the functionmember_of
as another function!You have to call the first result again, because you can and you have to treat it in almost the same way as a local function, that you defined in the current context, to get the final result, by doing something like:
And then you would continue and use the result. For example you could check its boolean value:
The 3 steps from above together can be written shorter:
Or even shorter:
At first it may appear a little strange in python to have the double
()()
, but if you think about it for a while it makes sense.