frank_99_
frank_99_

Reputation: 11

Transform normal python function to lambda

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.

Upvotes: 1

Views: 88

Answers (1)

Michael M.
Michael M.

Reputation: 11080

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']

Upvotes: 2

Related Questions