This is my first time asking a question in SO, so if I'm somehow not doing it properly don't hesitate to edit it or ask me to modify it.
I think my question is kind of general, so I'm quite surprised for not having found any previous one related to this topic. If I missed it and this question is duplicated, I'll be very grateful if you could provide a link to where it was already answered.
Imagine I need to implement a function with (at least) three parameters: an array a
, a start
index and an end
index. If not provided, the start
parameter should refer to the first position of the array (start = 0
), while the end
parameter should be set to the last position (end = len(a) - 1
). Obviously, the definition:
def function(a, start = 0, end = (len(a) - 1)):
#do_something
pass
does not work, leading to an exception (NameError: name 'a' is not defined
). There are some workarounds, such as using end = -1
or end = None
, and conditionally assign it to len(a) - 1
if needed inside the body of the function:
def function(a, start = 0, end = -1):
end = end if end != -1 else (len(a) -1)
#do_something
but I have the feeling that there should be a more "pythonic" way of dealing with such situations, not only with the length of an array but with any parameter whose default value is a function of another (non optional) parameter. How would you deal with a situation like that? Is the conditional assignment the best option?
Thanks!
Based on the answer provided by @NPE in Function with dependent preset arguments, an alternative to using -1
or (better) None
as sentinel values is using an object (a named object?) which can be used even if None
is a valid value of the function. For example:
default = object()
def function(a, start = 0, end = default):
if end is default: end = (len(a) - 1)
return start, end
allows a call like: function([1,2,3,4])
which returns (0, 3)
I personally find this solution quite convenient, at least for my own purpose
Edit: Maybe the code is even more readable if we use last
instead of default
:
last = object()
def function(a, start = 0, end = last):
if end is last: end = (len(a) - 1)
return start, end
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments