1

i have this function:


def add_transaction(list_of_items):
    for item in list_of_items:
        if item not in item_dict.keys():
            raise ValueError("You cannot make a transaction containing items that are not present in the items dictionary because it means that the Store does not has those items available, please add the items to the items dictionary first")
    transaction_data.append(list_of_items)
    return list_of_items

Do you know how it is possible to transform that into a lambda function? Thanks in advance

Tried to create the lambda function for this function but not sure of how to make it work.

frank_99_
  • 11
  • 2
  • 3
    Why do you want to do this? The loop can be simplified, but turning it into a lambda will produce confusing code. – Barmar Nov 04 '22 at 21:57
  • What's the use-case for this? A lambda is a callable just like a function and they can be used interchangeably, their byte code is the same. Further, the function modifies a variable (`transaction_data`) which isn't even defined in the code and it returns only the input passed to it. The only way this will be implemented as a lambda is with a list comprehension and it will be ugly. List comprehensions shouldn't be used for side-effects. – Michael Ruth Nov 04 '22 at 21:59
  • Try this : `raise_ = lambda ex: ex ; f = lambda list_of_items : ([i if i in item_dict.keys() else raise_(ValueError) for i in list_of_items])` – McLovin Nov 04 '22 at 22:38

1 Answers1

2

You can do this with set.isssubset() and this hack to raise an exception from a lambda. You'll also need to abuse the or operator to both call transaction_data.append(lst) and return the list.

item_dict = {'a': 1, 'b': 2, 'c': 3}
transaction_data = []

fn = lambda lst: (transaction_data.append(lst) or lst) if set(lst).issubset(item_dict.keys()) else exec("raise ValueError('not in store')")
print(fn(['a', 'c']))  # => ['a', 'c']
print(transaction_data)  # => ['a', 'c']
Michael M.
  • 10,486
  • 9
  • 18
  • 34