Let us give an example.
If we have a function def f(func): ..., where func is a parameter corresponding to a function.
If we make the following call f(merge), I would like to return another function name (not a text) merge_ext that could be then executed.
I have identified the fact that a function name col be extract with the syntax my_function.__name__, but how can I generate the new function name that could be used as a function?
It looks like you're after decorators.
A decorator is a function that takes a function as arguments, and returns a function. Simple example :
def simple_decorator(func):
return func
You can use it with the # syntax :
#simple_decorator
def decorated_function(some_arg):
return something
In that case, calling function will call the function returned by the call simple_decorator(function), which means you cannot access the orginal function anymore.
But this can also be expressed like this :
def no_yet_decorated_function(some_arg):
return something
decorated_function = simple_decorator(no_yet_decorated_function)
Now, you can access both your functions.
Related
So I use a bunch of files. Each file will trigger when lets say variable x = function. I know this is confusing but pretty much I need to be able to use a variable name which depending on what the variable is equal to will call that function. I am using python for this.
Based on your question, it looks like you want some sort of factory where the function to call is determined by the value of the variable passed in.
Here's a simple way of doing it:
x = 2 # determines which function to call
# possible functions to call
def f0(p): print('called f0',p)
def f1(p): print('called f1',p)
def f2(p): print('called f2',p)
def f3(p): print('called f3',p)
lstFunc = [f0, f1 ,f2, f3] # create list of functions
lstFunc[x]('test') # x=2, call function at index 2 (f2)
Output
called f2 test
For something more complicated, you would use a function which returns another function based on the variable value. In this example, I'm just using a list of functions.
I'm trying to understand the behavior of decorator.
I understand that a decorator has to return an object so I can understand the syntax below:
def my_deco(fonction):
print("Deco is called with parameter the function {0}".format(fonction))
return fonction
#my_deco
def hello():
print("hello !")
Deco is called with parameter the function <function salut at 0x00BA5198>
Here the decorator does not do much, but in the case I need to modify the function, I'd define a decorator like this
def my_deco(fonction):
def modified_func():
print("Warning ! calling {0}".format(fonction))
return fonction()
return modified_func
#my_deco
def hello():
print("Salut !")
The initial function behavior is modified through modified_func.This is fine
It includes the call to the initial function. This is fine
Now what I don't understand is: why do we return the result of the function? in my case the function is a simple 'print' so I don't get why I should return something
Thanks for your explanation
As it is in the comments: usually when you write a decorator, you make it so that it can be used with any possible function. And the way to do that is to return either whatever the original function returned, or transform that return value (which can also be done in the wrapper function).
In Python, all functions actually do return something. Functions without an explicit return statement return the value None. So, if your wrpper function, inside the decorator, always returns whatever the decorated function returned, it will be on the safe side: even if the decorated function had no explicit return, it will return a None that is just forwarded by your wrapper.
Now, that is not "mandatory". If you know beforehand that your decorator will only be applied to functions with no return value, you are free not to put a return statement in the wrapper function as well - it is not an incorrect syntax (but it is likely a trap for your future self).
I'm new to programming and I've been stuck on this issue and would really like some help!
One of the parameters in my function is optional, but can take on multiple default values based on another function. Both functions take in the same input (among others). When I try to assign a default using the function as illustrated below:
def func(foo):
# returns different values of some variable k based on foo
def anotherFunc(foo, bar, k=func(foo)):
# this is the same foo input as the previous function
I get the following error:
NameError: name 'foo' is not defined
The thing is, the user can call 'anotherFunc' with any value of 'k' they want, which complicates things. Is there any way to have a function with arguments in it as a parameter in another function? Or is there any way for me to set multiple default values of 'k' based on the previous function while still allowing the user to choose their own 'k' if they wanted?
Thanks!
foo at the moment of defining the function acts as placeholder for the first function argument. It has no value until the function is called, for which its value can be accessed in the function body, like so:
def another_func(foo, bar, k=None):
if k is None:
k = func(foo)
...
You would probably want to do something like:
def func(foo):
return foo
def anotherfunc(foo, bar, k=None):
if k == None:
k = func(foo)
#process whatever
I am Trying to emulate the following code with something more elegant:
def makeHomeFunc(axisNumber):
def fClosure(null_pass):
stage.home(axisNumber)
return fClosure
In short this is a function factory, that acts like functools.partial with the additional property of discarding the values passed to the produced function, and running the inner wrapped function with the factory's call.
Thanks
I have the following python code using the twisted API.
def function(self,filename):
def results(result):
//do something
for i in range(int(numbers)) :
name = something that has to do with the value of i
df = function_which_returns_a defer(name)
df.addCallback(results)
It uses the Twisted API. What i want to achieve is to pass to the callbacked function (results) the value of the name which is constructed in every iteration without changing the content of the functions_which_returns_a defer() function along with the deferred object of course. In every result of the functions_which_returns_a deffer the value of the name should be passed to results() to do something with this. I.e: at the first iteration when the execution reach the results function i need the function hold the result of the deffered object along with the value of name when i=0,then when i=1 the defered object will be passed with the value of name, and so on.So i need every time the result of the defer object when called with the name variable alond with the name variable. When i try to directly use the value of nameinside results() it holds always the value of the last iteration which is rationale, since function_which_returns_a defer(name) has not returned.
You can pass extra arguments to a Deferred callback at the Deferred.addCallback call site by simply passing those arguments to Deferred.addCallback:
def function(self,filename):
def results(result, name):
# do something
for i in range(int(numbers)) :
name = something that has to do with the value of i
df = function_which_returns_a defer(name)
df.addCallback(results, name)
You can also pass arguments by keyword:
df.addCallback(results, name=name)
All arguments passed like this to addCallback (or addErrback) are passed on to the callback function.