samuelbrody1249
samuelbrody1249

Reputation: 4767

How to inspect what is being passed to the filter() function

How can I verify the 'context' of a filter statement (normally I would just use a print in a function)? For example:

data=[{'Name':'Greg', 'Age': 10}, {'Name': 'Sarah', 'Age': 20}]
filter(lambda item: item['Name'] == 'Greg', data)
# [{'Age': 10, 'Name': 'Greg'}]

Upvotes: 0

Views: 46

Answers (2)

Carcigenicate
Carcigenicate

Reputation: 45741

I'm not going to claim that this is good practice, but for very quick debugging, you can use a tuple inside the lambda to shimmy a call to print in:

data=[{'Name':'Greg', 'Age': 10}, {'Name': 'Sarah', 'Age': 20}]
print(*filter(lambda item: (print(item), item['Name'] == 'Greg')[1], data))

{'Name': 'Greg', 'Age': 10}
{'Name': 'Sarah', 'Age': 20}
{'Name': 'Greg', 'Age': 10}

lambdas expects a single expression that will eventually be returned. If you want to add in "sequencing" of operations, you need to get a bit creative (although I don't recommend it for real, lasting code).


@juanpa.arrivillaga's idea is cleaner than mine:

lambda item: print(item) or item["Name"] == "Greg"

But it's the same idea. You need to put the print inside in such a way that the internal expression will evaluate in the end to item["Name"] == "Greg". I used the evaluation/indexing of a sequence to do that, while they used the behavior of or.

Upvotes: 1

Grismar
Grismar

Reputation: 31319

Instead of passing it a lambda, define a function that has the print statement and filter using that.

data=[{'Name':'Greg', 'Age': 10}, {'Name': 'Sarah', 'Age': 20}]


def my_filter(item):
    print(f'from inside filter: {item}')
    return item['Name'] == 'Greg'


print(list(filter(my_filter, data)))

Upvotes: 2

Related Questions