How to call multiple functions as arguments inside another function? [duplicate] - python

This question already has answers here:
passing functions and its arguments to another function
(3 answers)
Closed 5 years ago.
I am struggling with the below exercise:
Arguments to particular functions should be passed to function_results_sum as keywords argumentsand it should look like FUNCTION_NAME=ARGUMENTS
The function_results_sum should return sum of all the results received after running each passing function with arguments
If the function has no arguments, the arguments shouldn't be passed to function_results_sum
If the function takes 1 argument, as keyword argument int will be passed to function_results_sum (for example one_arg_function_name=2)
If function takes more than 1 argument - tuple is expected to be passed (for example two_args_function_name=(1, 2) )
How it should work like:
1st example
functions signatures:
def no_arg()
def one_arg(a)
def multiple_args(a, b, c, e, f)
calling function_results_sum:
function_results_sum(
no_arg, one_arg, multiple_args,
one_arg=23,
multiple_args=(1, 2, 3, 4, 5)
)
2nd example of how to call function_results_sum:
function_results_sum(
no_arg, one_arg, multiple_args,
one_arg=-1245,
multiple_args=(45, 65, 76, 123456, 111.222)
)
! Use name attribute on the function object !
This is what I came up with, however I do not know why I get the result as the addresses of the cells where the outputs are stored:
Console output:
<function ident at 0x00000288C0A72048> <function no_arg at
0x00000288C0A6BF28>
<function mult at 0x00000288C0A720D0>
My implementation:
def function_results_sum(*args, **kwargs):
return [*args]
def no_arg():
return 5
def ident(x):
return x
def mult(x, y):
return x * y
a = function_results_sum(ident, no_arg, mult, ident = 2, mult = (2, 3))
print(a)

Here's a hint that calls the one-argument function:
def function_results_sum(*args, **kwargs):
func = args[0]
function_name = func.__name__
parameter = kwargs[function_name]
return func(parameter)
def ident(x):
return x
a = function_results_sum(ident,ident=2)
print(a)
args will contain a list of the functions to be called, and kwargs contains the list of parameters using the function names as keys. See if you can figure out how to call the three types of functions.

Related

Is there a way to create a class instance passing to the constructor a list of attributes? [duplicate]

This question already has an answer here:
How to pass list elements as arguments
(1 answer)
Closed 11 months ago.
Let's say I have this class
class Foo:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
Is there a way to make a shortcut in the constructor arguments so I don't need to explicitly pass every parameter from a list, for example:
def main():
attributes = [1,2,3]
foo = Foo(attributes) #instead of Foo(attributes[0], ...., ....)
Just use iterable-unpacking to pass your list of arguments as sequential positional arguments:
def main():
attributes = [1,2,3]
foo = Foo(*attributes)
The * in front of attributes in the call means:
attributes is an iterable
It should be unpacked such that the first element becomes the first positional argument (after the implied self), the second element the second positional argument, etc.
You're making an assertion that the number of elements you can pull from attributes matches the argument count expected by Foo (since Foo takes three arguments beyond self, attributes must produce exactly three arguments, no more, no less)

Get function arguments value by pointer to this function?

I'd like to get value of function arguments by pointer to that function.
def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(cons):
# local_a = cons.a
# return local_a
pass
if __name__ == '__main__':
assert car(cons(3, 4)) == 3
You're on the wrong track. Looking at the code in the new version of your question, you're trying to extract the first element of a Church pair.
cons(3, 4) evaluates to a function that, when passed another function f, returns f(3, 4). To extract the 3, you should pass it a function that takes two arguments and returns its first argument:
def car(pair):
def firstarg(x, y):
return x
return pair(firstarg)
Then car(cons(3, 4)) calls cons(3, 4)(firstarg), which calls firstarg(3, 4), which returns 3.
Creating a Signature for the function is easy via the signature function:
from inspect import signature
def someMethod(self, arg1, kwarg1=None):
pass
sig = signature(someMethod)
Now, you can either view its parameters quickly by string it:
str(sig) # returns: '(self, arg1, kwarg1=None)'
or you can also get a mapping of attribute names to parameter objects via sig.parameters.
params = sig.parameters
print(params['kwarg1']) # prints: kwarg1=20
Additionally, you can call len on sig.parameters to also see the number of arguments this function requires:
print(len(params)) # 3
Each entry in the params mapping is actually a Parameter object that has further attributes making your life easier. For example, grabbing a parameter and viewing its default value is now easily performed with:
kwarg1 = params['kwarg1']
kwarg1.default # returns: None
similarly for the rest of the objects contained in parameters.

How to define a function that output another function?

I want to define a function that takes some arguments as input, and uses them to make another function, then outputs the new function.
For example:
makeIncrease(n) --> return a function that takes an argument, and return (argument + n)
applyIncrease(increaseFn, m) --> will apply increaseFn to argument m
So if I do this: applyIncrease(makeIncrease(n), m) --> will return m+n
How can I do it in python?
You can read about decorators in Python for more on this. For your specific question:
def applyIncrease(increaseFn, m):
return increaseFn(m)
def makeIncrease(n):
def _innerFn(arg):
return arg + n
return _innerFn
applyIncrease accepts a function and argument, and applies the function to the argument.
makeIncrease accepts an argument n.
Let's say n=2 for the sake of an example. makeIncrease(2) returns a function that takes an argument and adds 2 to it.
Although I began _innerFn with an underscore, this is only a convention - the underscore is not required for the decorator to work.
Note also that functions are first class objects in Python, and that makeIncrease returns _innerFn and not _innerFn(). Return functions exactly as you would variables or object references - no parentheses.
Here are your functions in the interpreter. Note that the object reference wrapped_function refers to _innerFn, i.e. the return value of makeIncrease(2)
>>> wrapped_function = makeIncrease(2)
>>> wrapped_function
<function _innerFn at 0x100496758>
>>> total = applyIncrease(wrapped_function, 3)
>>> total
5
class Example:
def result():
def nestedResult(a,b):
multiply = a*b
return multiply
return nestedResult
if __name__ == "__main__":
x = result()
print "multiplication_result:", x(1,10)

How to bind arguments to given values in Python functions? [duplicate]

This question already has answers here:
Python Argument Binders
(7 answers)
Closed 4 years ago.
I have a number of functions with a combination of positional and keyword arguments, and I would like to bind one of their arguments to a given value (which is known only after the function definition). Is there a general way of doing that?
My first attempt was:
def f(a,b,c): print a,b,c
def _bind(f, a): return lambda b,c: f(a,b,c)
bound_f = bind(f, 1)
However, for this I need to know the exact args passed to f, and cannot use a single function to bind all the functions I'm interested in (since they have different argument lists).
>>> from functools import partial
>>> def f(a, b, c):
... print a, b, c
...
>>> bound_f = partial(f, 1)
>>> bound_f(2, 3)
1 2 3
You probably want the partial function from functools.
As suggested by MattH's answer, functools.partial is the way to go.
However, your question can be read as "how can I implement partial". What your code is missing is the use of *args, **kwargs- 2 such uses, actually:
def partial(f, *args, **kwargs):
def wrapped(*args2, **kwargs2):
return f(*args, *args2, **kwargs, **kwargs2)
return wrapped
You can use partial and update_wrapper to bind arguments to given values and preserve __name__ and __doc__ of the original function:
from functools import partial, update_wrapper
def f(a, b, c):
print(a, b, c)
bound_f = update_wrapper(partial(f, 1000), f)
# This will print 'f'
print(bound_f.__name__)
# This will print 1000, 4, 5
bound_f(4, 5)

Python - Passing a function into another function [duplicate]

This question already has answers here:
Python function as a function argument?
(10 answers)
Closed last month.
I am solving a puzzle using python and depending on which puzzle I am solving I will have to use a special set of rules. How can I pass a function into another function in Python?
Example
def Game(listA, listB, rules):
if rules == True:
do...
else:
do...
def Rule1(v):
if "variable_name1" in v:
return False
elif "variable_name2" in v:
return False
else:
return True
def Rule2(v):
if "variable_name3" and "variable_name4" in v:
return False
elif "variable_name4" and variable_name1 in v:
return False
else:
return True
This is just a pseudo code and therefore not specific but I get the code to compile but I need to know how to call the function Game and whether it's correctly defined since rules will be switched for either Rule1(v) or Rule2(v).
Just pass it in like any other parameter:
def a(x):
return "a(%s)" % (x,)
def b(f,x):
return f(x)
print b(a,10)
Treat function as variable in your program so you can just pass them to other functions easily:
def test ():
print "test was invoked"
def invoker(func):
func()
invoker(test) # prints test was invoked
For passing both a function, and any arguments to the function:
from typing import Callable
def looper(fn: Callable, n:int, *args, **kwargs):
"""
Call a function `n` times
Parameters
----------
fn: Callable
Function to be called.
n: int
Number of times to call `func`.
*args
Positional arguments to be passed to `func`.
**kwargs
Keyword arguments to be passed to `func`.
Example
-------
>>> def foo(a:Union[float, int], b:Union[float, int]):
... '''The function to pass'''
... print(a+b)
>>> looper(foo, 3, 2, b=4)
6
6
6
"""
for i in range(n):
fn(*args, **kwargs)
Depending on what you are doing, it could make sense to define a decorator, or perhaps use functools.partial.
Just pass it in, like this:
Game(list_a, list_b, Rule1)
and then your Game function could look something like this (still pseudocode):
def Game(listA, listB, rules=None):
if rules:
# do something useful
# ...
result = rules(variable) # this is how you can call your rule
else:
# do something useful without rules
A function name can become a variable name (and thus be passed as an argument) by dropping the parentheses. A variable name can become a function name by adding the parentheses.
In your example, equate the variable rules to one of your functions, leaving off the parentheses and the mention of the argument. Then in your game() function, invoke rules( v ) with the parentheses and the v parameter.
if puzzle == type1:
rules = Rule1
else:
rules = Rule2
def Game(listA, listB, rules):
if rules( v ) == True:
do...
else:
do...

Categories

Resources