Hacker Read top | best | new | newcomments | leaders | about | bookmarklet login

Don't try to fake anonymous functions in Python. Use its strengths: decorators, generators, etc.

Anonymous functions work well (err, passably) in JavaScript and Perl. They don't really work in Python, and of course you'll just run into pain if you try to force them to.

Perhaps also make some noise about this PEP: http://legacy.python.org/dev/peps/pep-0403/



sort by: page size:

The Python package lambdex [1] provides a way to write multi-line anonymous functions in Python, with a syntax that's close enough to the "normal" Python.

[1]: https://pythonrepo.com/repo/hsfzxjy-lambdex


Nice article, though I already understood the matter. Thanks for the link to PEP 463[1], though; I can see it cleaning up some of our code. Do you know if there have been any developments into implementing it?

[1] http://legacy.python.org/dev/peps/pep-0463/



It's a controversial PEP https://www.python.org/dev/peps/pep-0572/ which allows you to write Python like this:

    def foo():
        if n := randint(0, 3):
            return n ** 2
        return 1337


    [(x, y, x/y) for x in input_data if (y := f(x)) > 0]


Precisely my thought :).

Also, what about the builtin array module? https://docs.python.org/3.7/library/array.html



Indeed, AFAIK this is the relevant pep:

http://legacy.python.org/dev/peps/pep-0450/

Note especially the pitfalls highlighted around naive diy solutions (not sure if this is actually taken care of in the module, but I hope so! :-).


I think the nonlocal keyword would make your second example work as you expect (but I can't test it as I don't have Python 3.0 installed here).

See http://www.python.org/dev/peps/pep-3104/


Neat, but you should check out PEP 8 at some point. An empty line between a decorator and the decorated function (flask) is confusing, and whitespace in keyword arguments just looks off.

http://www.python.org/dev/peps/pep-0008/


You can go even further now with PEP508 https://peps.python.org/pep-0508/

Python's list of built-in functions is fairly small https://docs.python.org/3/library/functions.html#built-in-fu... (but to be clear, I wouldn't ding somebody for forgetting about one of them).

This is also a good addition for functional programming in Python:

https://github.com/kachayev/fn.py



It is indeed a decorator. It's relying on https://peps.python.org/pep-0614/




This is certainly an interesting idea. A quick Google search gave me this toy example: [1][2]

Of course making it work for all cases would be very hard due to the excessive dynamism of Python, but for simple arithmetic operations it could be made to work fairly well.

[1] http://tomforb.es/automatically-inline-python-function-calls

[2] https://github.com/orf/inliner

next

Legal | privacy