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.

3
  • 3
    Why do you want to do this? The loop can be simplified, but turning it into a lambda will produce confusing code. Commented Nov 4, 2022 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. Commented Nov 4, 2022 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]) Commented Nov 4, 2022 at 22:38

1 Answer 1

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']
Sign up to request clarification or add additional context in comments.

4 Comments

@Barmar Oops, sorry. I've updated my answer.
OK, it's possible, it just has to use several gross hacks :)
Amazing solution. Could you explain me how that works?
Very clever. I'm still not suggesting OP do this, but it's clever.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.