ingolemo / python-lenses

A python lens library for manipulating deeply nested immutable structures
GNU General Public License v3.0
313 stars 19 forks source link

Fix error in Item lens when deleting key that does not exist #41

Closed cebamps closed 1 year ago

cebamps commented 1 year ago

Hello! Thank you for this library. I discovered it today and both the lib and its documentation are a real treat. I used it to transform a deep json payload in a mitmproxy script, and it was perfect for that.

I however encountered a bug in the Item lens in a use case I had. It was similar to this example: a traversal over values of existing "foo" entries in a list of dictionaries. I figured I would contribute a test case and a fix.

With this PR, this now returns true:

from lenses import lens

foo_values = lens.Each().Item("foo").Filter(bool)[1]
("hello " + foo_values)([{}, {"foo": "world"}]) == [{}, {'foo': 'hello world'}]

In current version 1.1.0, it crashes with KeyError: 'foo' in the setter method of ItemLens.

Note that this is not the same traversal as lens.Each().Get("foo").Filter(bool), whose use instead results in [[{'foo': None}, {'foo': 'hello world'}] (which, incidentally, had me a bit confused at first).

ingolemo commented 1 year ago

Thank you for this.