Can I pass "undeclared variable" to function with default value? [duplicate] - python

This question already has answers here:
How to force the default parameter in python
(4 answers)
Call function without optional arguments if they are None
(10 answers)
Closed 1 year ago.
Is there a way to call a function with an argument but have the argument in a way that the default value of the function is used instead? Like
def f(val="hello"):
print(val)
def g(a=Undefined): #replace Undefined with something else
f(a)
>>> g()
hello
The reason is, the called function is not under my control and I want to inherit its default value. Of course I could
def h(a=None):
f(a) if a else f()
or even
def k(a=None):
j = lambda : f(a) if a else f()
j()
since I have to call that function a few times and also pass other parameters. But all that would be much easier if I could just tell the function I want to use its default value.
I could also simply copy paste the default value to my function, but don't want to update my function if the other one changes.

Related

Python sort method key parameter [duplicate]

This question already has answers here:
How does the key argument in python's sorted function work?
(4 answers)
Closed 20 days ago.
In the myFunc function below, where is the (e) argument passed in from? (I hope I'm using the right terminology)
# A function that returns the length of the value:
def myFunc(e):
return len(e)
cars = ['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
the function myFunc is called by cars.sort(key=myFunc) and each item in the list passed as an argument to myFunc. parameter name is not required here as it can work with the positional parameter. but we still need to have one parameter myFunc so that it can receive the passed value.
also the code can be simplified like below by using len() method directly instead of wrapping it in myFunc.
cars.sort(key=len)
Hope this helps.

Weird .get() default [duplicate]

This question already has answers here:
When are function arguments evaluated?
(4 answers)
Closed 1 year ago.
I always assumed that the default value in the myDict.get('key', default_value) expression was never called if the key exists in the dictionary. However, I have recently found out it somehow is. For example, consider the code
def doSomething():
print('Done')
return 'Another value'
myDict = {'key': 'value'}
print(myDict.get('key', doSomething()))
One would expect that since key exists in myDict, then the only thing myDict.get('key', doSomething()) would do is to return value and hence, the function doSomething would never be called. This is not the case however, and running this code in python currently outputs:
Done
value
My question is: why is this the case? Why isn't the default_value ignored completely when the key exists?
And what can be done to change this, that is, to not call the default_value when the key exists?
That's because the get method of a dictionary does not accept a callback as Java's computeIfAbsent, but a value. If you want it to not be called, you can do it using the ternary expression:
print(doSomething() if myDict.get('key') is None else myDict.get('key'))
The way you've written it, doSomething() is executed before myDict.get() is called, and its return value (which is implicitly None, because there's no return statement) is passed in as the default.
print(myDict.get('key', doSomething()))
# evaluates to
print(myDict.get('key', None))
# evaluates to
print('value')
As a rule of thumb, passing an expression as a function argument will always have the expression evaluated first, before its result is passed as that argument.
get() does not have the ability to run a separate function upon a nonexistent key. If you pass a lambda in as the default, you'd get the same lambda back out as the default, uncalled.

How to pass arguments to a function when called by an array? [duplicate]

This question already has answers here:
Pass a list to a function to act as multiple arguments [duplicate]
(3 answers)
Closed 1 year ago.
I have a function and I have an array of arguments that I want to pass to the function when calling it like this:
def function(arg):
pass
function(arg)#call
but I want:
target = function
args = list()
output = call(function,args)
I know, that I can do it with Thread, but I want get a return to main Thread
Thread(target=target,args=args).start() # without output :(
The only possible solution I have come up with is
output = exec('function_name('+','.join(args))
P.S. The functions that I call have a variable number of positional and optional arguments
P.P.S. I can't edit function's code
If those are positional arguments you can use function(*args).

Python tkinter binding a function with multiple parameters [duplicate]

This question already has answers here:
Tkinter binding a function with arguments to a widget
(2 answers)
Closed 8 months ago.
I have a general question that I can't really find an answer to so hopefully you guys can help. I have a function that takes 3 parameters, below is an example of what I have.
def someFunction(self, event, string):
do stuff ..
self.canvas.bind("<Button-1>", self.someFunction("Hello"))
When I run this, I get an error saying that I passed someFunction 2 arguments instead of 3. I'm not sure why ..
Here you're binding the result of someFunction (or trying to anyway). This fails because when python tries to get the result of someFunction, it calls it only passing 1 argument ("Hello") when someFunction really expects 2 explicit arguments. You probably want something like:
self.canvas.bind('<Button-1>',lambda event: self.someFunction(event,"Hello"))
This binds a new function (which is created by lambda and wraps around self.someFunction) which passes the correct arguments.
Or,
def someFunction(self, string):
def fn(*arg)
print string
return fn
self.canvas.bind("<Button-1>",self.someFunction("Hello!"))

What is "lambda binding" in Python? [duplicate]

This question already has answers here:
What do lambda function closures capture?
(7 answers)
Closed 6 months ago.
I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs.
A link to read about it would be great.
A trivial explained example would be even better.
Thank you.
First, a general definition:
When a program or function statement
is executed, the current values of
formal parameters are saved (on the
stack) and within the scope of the
statement, they are bound to the
values of the actual arguments made in
the call. When the statement is
exited, the original values of those
formal arguments are restored. This
protocol is fully recursive. If within
the body of a statement, something is
done that causes the formal parameters
to be bound again, to new values, the
lambda-binding scheme guarantees that
this will all happen in an orderly
manner.
Now, there is an excellent python example in a discussion here:
"...there is only one binding for x: doing x = 7 just changes the value in the pre-existing binding. That's why
def foo(x):
a = lambda: x
x = 7
b = lambda: x
return a,b
returns two functions that both return 7; if there was a new binding after the x = 7, the functions would return different values [assuming you don't call foo(7), of course. Also assuming nested_scopes]...."
I've never heard that term, but one explanation could be the "default parameter" hack used to assign a value directly to a lambda's parameter. Using Swati's example:
def foo(x):
a = lambda x=x: x
x = 7
b = lambda: x
return a,b
aa, bb = foo(4)
aa() # Prints 4
bb() # Prints 7
Where have you seen the phrase used?
"Binding" in Python generally refers to the process by which a variable name ends up pointing to a specific object, whether by assignment or parameter passing or some other means, e.g.:
a = dict(foo="bar", zip="zap", zig="zag") # binds a to a newly-created dict object
b = a # binds b to that same dictionary
def crunch(param):
print param
crunch(a) # binds the parameter "param" in the function crunch to that same dict again
So I would guess that "lambda binding" refers to the process of binding a lambda function to a variable name, or maybe binding its named parameters to specific objects? There's a pretty good explanation of binding in the Language Reference, at http://docs.python.org/ref/naming.html

Categories