Is there any way to use the value of an argument to dynamically set the default of a keyword argument? I was thinking of something like this:
def foo(lst, r = 0, l = len(lst)): #I am referring to the "l = len(lst)" part
print r, l
foo([1,2,3])
This gives the following traceback:
Traceback (most recent call last):
File "C:/Python27/quicksort.py", line 25, in <module>
def foo(lst, r = 0, l = len(lst)):
NameError: name 'lst' is not defined
One could do something similar to this:
def foo(lst, r = 0, l = None):
if l is None:
l = len(lst)
print r, l
But I am hoping for a more elegant solution. Can anybody help?
Is there any way to use the value of an argument to dynamically set the default of a keyword argument?
Unfortunately no. This can be shown with a simpler example:
>>> def func(a, b=a):
return a, b
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
def func(a, b=a):
NameError: name 'a' is not defined
As said in the comments, Python keyword argument values are evaluated when the function is defined, but the value of any arguments are not know until the function is called. Thus, something like this in Python simply isn't feasible.
However, you can make your code more compact by using the ternary operator:
def foo(lst, r=0, l=None):
l = l if l is not None else len(lst)
print(r, l)