ingolemo / python-lenses

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

Use varname to get %= #31

Closed Gurkenglas closed 3 years ago

Gurkenglas commented 3 years ago

Haskell's lens has x %= f for x = f(x). Could you use https://github.com/pwwang/python-varname to get foo(x).Each() + 1 instead of x = bind(x).Each() + 1?

ingolemo commented 3 years ago

Heh. Coincidentally I already implemented something like this myself a couple of months ago, but didn't push it to the repo yet as I'm not sure if I like it. I've just pushed a few commits, one of which allows you to rewrite x = bind(x).Each() + 1 as x &= lens.Each() + 1. I used &= since bitwise operators are less frequently used in python, and the lenses library already assigns special meaning to the & symbol anyway. Changing it to use %= instead is possible. Opinions?

Thinking about it, it would be theoretically possible to support a syntax like foo(x).Each() + 1, using varname as one component of it as you say, but it would break python programmers expectations about how scopes work. A better syntax would be something like x = bind().Each() + 1 (bind automatically figures out it's argument from the assignment), but I don't think it's necessary given the syntax I explained above.

Gurkenglas commented 3 years ago

I have no strong feelings between either of &= and %= :). After reflection, I opine that programmers (and static analysis tools) should be allowed to trust that x = ... with x not used in ... won't read the previous value of x.