Reputation: 144
in certain softwares, I have to use a lot the 'with statement' to create a certain context before run some functions (it's not changeable, I have to fit this way of doing it)
So I made a function with the needed 'with statement', to use it in a more simple way with many subfunctions later :
def getContext(subfunction):
context=... #creating the context here
with context:
return subfunction
something = getContext( var.getValue() )
It return an error in my softwares, as it's run the subfunction in argument before passing it to the 'getContext' function.
I've so I tried :
def whatValue(var):
return var.getValue()
def getContext(subfunction):
context=... #creating the context here
with context:
return subfunction
something = getContext( whatValue( var ) )
I gives the exact same error as the first try. so my question is :
how can I pass a subfunction as an argument and make the subfunction runs only in the context function ?
EDIT : to clarify, yes I'm talking about send the function itself, not the result
thank you
Upvotes: 1
Views: 173
Reputation: 889
When you write function_name(...)
, function name will always be executed at this point in time. If you just want to pass the function, you just write function_name
. I.e., in your example:
something = getContext(var.getValue)
or in the version with whatValue
(although that is an unnecessary indirection):
something = getContext(whatValue)
However, I am note sure this solves your context problem. Because within the context context
you return the function itself but the context is then not used by the function being returned, because the context ends when the corresponding block ends.
Upvotes: 1
Reputation: 25980
It seems you mean to send the function itself, and so you need to let the context wrapper call it. Making it a bit more general to handler an arbitrary amount of arguments:
def getContext(subfunction, *args, **kwargs):
context=... #creating the context here
with context:
return subfunction(*args, **kwargs)
something = getContext( var.getValue ) # Can add arguments and named arguments.
Note I pass getValue
rather then getValue()
, and getContext
itself makes the call.
Upvotes: 2