How to give parameter name for function in function? - python

I need choose which parameter i use for function in function.
For example:
def some(key, gey, mey):
return 0
def any(parameter_name, parameter_value):
some(parameter_name=parameter_value)
any(mey, "May")
any(mey, "May") should equel some(mey="May")

You can use the **kwargs syntax. It will filter attribute by attribute_value.
def get_object_id(attribute: str, attribute_value):
MyModel.objects.get(**{attribute: attribute_value})

Related

How to handle the *args in Python when no arguments are passed over to the Function parameter

Let's say I have a function given below:
def splitter(*params):
rep, msg = params
if rep:
for i in range(rep):
print(i)
else:
print('-----------------------------------')
splitter(2,'Let the Game Begin!! 🏏')
Now, in the above case it will pass since I'm giving the arguments, but what I want is, that suppose I don't want to give the arguments when calling the function, then how can I handle it? Since *args cannot have a default value.
Define the function with named arguments having default values:
def splitter(rep=None, msg=None):
if rep is not None:
...

function as an optional parameter python

i am trying to write a function to check if a parameter was passed to it (which is a function ) if so call that function with an argument else if there wasn't any argument given return a value so my approach was like this :
def nine(fanc=None):
if(fanc!=None): return fanc(9,fanc)
return 9
but this code rise an error which is :
TypeError: 'int' object is not callable
i know that this approach isn't correct but i couldn't find any other way to do so
i have also tried using *args this way but end up with the same results :
def nine(*args):
if(len(args)!=0): return args[0](9,args)
return 9
I try to guess what you want but this snippet might help you:
def fct(**kwargs):
if 'func' in kwargs:
f = kwargs['func']
return f(9)
else:
return 9
def f(x):
return x**2
print(fct()) # result = 9
print(fct(func=f)) # result = 81
You might use callable built-in function, consider following example
def investigate(f=None):
if callable(f):
return "I got callable"
return "I got something else"
print(investigate())
print(investigate(min))
output:
I got something else
I got callable
Beware that callable is more broad term that function, as it also encompass objects which have __call__ method.
If you want to check whether the passed argument is a function and, if yes, then execute it with fixed arguments, you could try the following:
from typing import Union
from types import FunctionType
def nine(func: Union[FunctionType, None] = None):
if type(func) is FunctionType:
return func(9)
return 9

Redefining a function by supplying some of its arguments

let's suppose there is a function like below:
def func(arg1, args2):
# do sth using arg1 and arg2
In the runtime, I would like to keep use some value for args2 which we can't know when defining the func.
So what I would like to do is:
func_simpler = func(, args2=some_value_for_arg2)
func_simpler(some_value_for_arg1) # actual usage
Any idea on it? I know that there is a walk-around such as defining func better, but I seek for a solution more like func_simpler thing.
Thanks in advance!
You can use lambda in python
Original function
def func(arg1, arg2):
Then you get the value you want as default for arg2 and define simple_func
simple_func = lambda arg1 : func(arg1, arg2=new_default)
Now you can run simple_func
simple_func("abc") #"abc" = value for arg1
Hope I could help you
I was trying to solve this myself and I found a not-bad solution:
def func(a, b):
print(a, ": variable given everytime the model is used")
print(b, ": variable given when the model is defined")
enter code here
def model(b):
def model_deliver(a):
func(a, b)
return model_deliver
s = model(20)
s(12) #prints result as below
# 12 : variable given everytime the model is used
# 20 : variable given when the model is defined
Use functools.partial:
from functools import partial
def func(arg1, arg2):
print(f'got {arg1!r} and {arg2!r}')
simple_func = partial(func, arg2='something')
simple_func("value of arg1")
# got 'value of arg1' and 'something'
Using partial produces an object which has various advantages over using a wrapper function:
If the initial function and its arguments can be pickled, the partial object can be pickled as well.
The repr/str of a partial object shows the initial function information.
Repeated application of partial is efficient, as it flattens the wrappers.
The function and its partially applied arguments can be inspected.
Note that if you want to partially apply arguments of a method, use functools.partialmethod instead.

Passing arguments of a function as parameter names in other function

Lets assume we have two functions foo and get_idin Python3. I want to call the get_id function inside the foo function while using an argument of the foo function as an argument name in the get_id function. For example:
I call the foo function:
result = foo("Person","name","John")
while the body of the function is:
def foo(arg_1, arg_2, arg_3):
res = get_id(arg_1, arg_2 = arg_3)
return res
What i want is:
res = get_id("Person", name = "John")
so that the get_id function will be parameterized by the arg_2 argument of the foo function. However, the way i am doing it so far results in error as python interpretes it as a String.Any advice is welcome.
I should probably not try to understand why you want to do this :) but here is a solution maybe:
def foo(arg_1, arg_2, arg_3):
kwargs = {
'arg_1_name': arg_1,
arg_2: arg_3,
}
return get_id(**kwargs)
just make sure to replace arg_1_name with the actual name of the parameter used in the get_id function
This is the way to pass parameter name as string :
def test(a):
print(a)
test(**{'a': 'hello world'})
I'm sure you can adapt this solution to your problem

How to convert a string into an identifier in python?

Say I have a list of similar functions:
def func1(a)
foo(a=a)
def func2(b)
foo(b=b)
...
the only difference of them is the argument name of foo, is that a short way to define them as one function, such as passing a argument name to the functions?
You can do it by unpacking a keyword argument dictionary:
def combined(name, value):
foo(**{name:value})
Then combined('a', a) is equivalent to func1(a). Whether this is a good idea is a separate consideration.

Categories