Code:
def evaluate_fruit(fruits):
for fruit in fruits:
if fruit == "Apple":
print("Good choice!")
else:
print("Meh its okay")
list_o_fruits = ["Apple", "Banana", "Orange"]
eval_list = (lambda x=list_o_fruits: evaluate_fruit(x))
eval_list()
Output:
Good choice!
Meh its okay
Meh its okay
When running the code above, the output is as expected however PyCharm doesn't like it when I pass a list/dictionary (mutable) into the lambda function. To my understanding, it is bad practice to declare a list/dictionary as a function's default value and that makes sense. However what if I only read the content of the list/dictionary and not alter it in any way inside the function, would it be acceptable then?
Either way, what would be a better approach to declare my lambda function with a list/dictionary argument? The web has suggested a workaround for passing a mutable as a default in a 'normal' function by setting the default to 'None' then using an if-statement:
def evaluate_fruits(fruits=None):
if fruits is None:
fruits = []
.
.
.
I could possibly utilize this concept for lambda function too but then that would make the function inconveniently long and redundant as I would have to create an if-statement condition for each generated lambda from evaluate_fruits()
(it kind of defeats the purpose of using lambda).
An example would be if I had five lists (list_o_fruits1
, list_o_fruits2
, ..., list_o_fruits5
) and I wanted to created a lambda function for each of them (eval_list1
, eval_list2
, ..., eval_list3
) from evaluate_fruits()
.
Could I be missing something?