smarie / python-pep-ideas

4 stars 0 forks source link

More user-friendly lambda functions #4

Open smarie opened 4 years ago

smarie commented 4 years ago

Our original need was to raise user-friendly errors in case of failed validation. It is very frequent that a validation operation just consists in a few operations, and it is therefore quite convenient to express it as a lambda function. There are two main issues then:

For this reason I created mini-lambda but it has some major limitations (one input only, and some python operators can not be used because the corresponding magic method has too much constraints).

Maybe we could propose a PEP about

See also this stackoverflow post

plammens commented 3 years ago

I like the idea of adding a str representation of lambdas that includes the source code. Some concerns (perhaps not really concerning, but just a couple of things that came to mind):

I'm not so sure about shortcuts for "implicit lambdas". The lambda expression syntax is already compact enough, and "explicit is better than implicit". This of course doesn't mean such a thing doesn't have a place, for example, as an external package, like your mini-lambda, but I think its benefit is too small in comparison to the added complexity to be added to the language or even the standard library.

smarie commented 3 years ago

Thanks @plammens for this relevant comment ! Indeed global and local names must be taken into account, and depending on usage some people will wish to resolve them, resolve some of them, or resolve them with a different globals + locals dictionary (a bit like in typing.get_type_hints that accepts custom locals and globals.

The limitation with my mini-lambda is that it forces users to replace their coding habit with another (importing mini_lambda and using the variable symbols inside it to declare their lambdas).

For this reason I would rather prefer to have in the stdlib some helper function lambda_to_str(resolve_closure=False, globals=None, locals=None) or a class method <lambda>.to_str(resolve_closure=False, globals=None, locals=None). If resolve_closure=False (default), the bare lambda expression is returned. If it is True, closure symbols would be replaced with their string representation. Custom globals and locals would enable users to pass other replacement values (objects that would be repr-ed, or directly strings)

That way it would remain optional and allow for the various flexible usages you mention concerning globals and locals. What do you think ?