How to convert a string into an identifier in python? - 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.

Related

How to give parameter name for function in function?

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})

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.

Pass in tuple to multi-argument function

The issue here is I want to pass a tuple as an argument to a second function. Before there are outcries of "duplicate!" I have already looked at a post regarding a similar question Expanding tuples into arguments
Here is the code I am testing with:
def producer():
return ('a','b')
def consumer(first, second, third):
print first+second+third
arg = producer()
consumer(*arg, 'c') # expected abc
This outputs the error:
There's an error in your program *** only named arguments may follow *expression
This useful error message has led switch the order of arguments to consumer('c', *arg), but this does not quite solve the issue as it will output 'cab'.
So my question is, is there a better way to pass in a tuple to a multi argument function, and preserve the ordering?
Also for bonus points, what does the '*' operator do? (this was not explained in the previous post)
As the error message states, Python does not allow you to have unnamed arguments after *arg.
Therefore, you need to explicitly name third:
>>> def producer():
... return ('a','b')
...
>>> def consumer(first, second, third):
... print first+second+third
...
>>> arg = producer()
>>> consumer(*arg, third='c')
abc
>>>
If you need to add an argument, concatenate the tuple:
arg += ('c',)
consumer(*arg)
Alternatively, you can name the argument explicitly by using a keyword parameter:
consumer(third='c', *arg)
You cannot put more positional arguments after *arg, these are always added to any explicit positional arguments.

Python notation or operation "**"

I saw the following code:
def __init__(self, fn, **kw):
[setattr(self,k,v) for (k,v) in kw.items()]
......
What does the input argument **kw mean?
kw is bound to a dict mapping keyword argument names to their values.
Try calling
def return_kwargs(**kw):
return kw
as return_kwargs(foo=1, bar="2", baz="hamspamspam").
Suppose you have a dict kw = {'a':1,'b':2}, then calling myfunction(**kw) is equivalent to calling myfunction(a=1,b=2).
This particular construction means what all keyword arguments for the constructor will end up as object attributes.
foo = Foo( func, bar = 1, baz = "aa" )
this would create an object with attribute "bar" set to 1 and "baz" to "aa"
Inside the function, kw is a dictionary that contains all the keyword=value arguments that you gave to your function:
def demo(**kw):
print kw
demo(a=1, b="hello")
Run the above and it will display a dictionary with two keys, a and b. So it works as a way to accept any keyword argument you decide to use when you call the function.
That's what it does. Why would anyone want to do that? Perhaps in a function that calls another function (given as a separate argument), and **kw is to hold options for the second function.

accessing *args from within a function in Python

Hi everyone this is probably something extremely simple that i'm overlooking but can someone point me in the right direction for how to handle this problem.
def nodeFunction(self,*args):
return self[1] + self[2]
Basically what I am trying to do is grab the data passed in through the arguments. I am just stuck on the syntax for referencing the arguments inside the function when using *args.
args is simply a tuple:
def nodeMethod(self, *args):
return args[0], args[1]
Is that what you mean?
Note that there's nothing special about "args". You could use any variable name. It's the * operator that counts.
>>> class Node(object):
... def nodeMethod(self, *cornucopia):
... return cornucopia[0], cornucopia[1]
...
>>> n = Node()
>>> n.nodeMethod(1, 2, 3)
(1, 2)
Still, "args" is the most idiomatic variable name; I wouldn't use anything else without a good reason that would be obvious to others.
def nodeFunction(self, arg1, arg2, *args)
*arg in argument list means: pass the remaning arguments as a list in variable arg. So check how to handle lists. Note: list index starts from 0.

Categories