List of Functions

Chris Angelico rosuav at gmail.com
Mon Mar 28 17:40:04 EDT 2016


On Tue, Mar 29, 2016 at 12:40 AM, Marko Rauhamaa <marko at pacujo.net> wrote:
> Dan Sommers <dan at tombstonezero.net>:
>
>> On Mon, 28 Mar 2016 11:58:54 +0300, Marko Rauhamaa wrote:
>>
>>> As for Python, I don't feel a great need for anonymous functions.
>>> However, I keep running into a need for anonymous classes, or,
>>> rather, classless objects. Not a biggie. I just create a one-off
>>> inner class and instantiate it, but I do appreciate Java's syntactic
>>> innovation.
>>
>> And I always curse Java for having to create an inner class and a
>> method when all I need is a simple function. :-)
>>
>> I think it's Steven D'Aprano who keeps pointing out that you can
>> always name your tiny helper functions instead of using lambda:
>>
>>     def some_complex_function():
>>         def f(x) = x + 2
>>         some_library_that_wants_a_callback(f)
>>         some_library_that_wants_a_callback(lambda x: x + 2)
>>
>> Both calls to some_library_that_wants_a_callback run the same.
>
> Yes, but I've come to realize that I quite often need more than a
> function: I need an object with behavior. The solution is to use a
> "helper" class.

Can you give an example of code that would benefit from a
"lambda-class" construct? Since all functions more complicated than
"return this expression" need statement syntax in Python, you'd be
pretty restricted in what you can do, so I'm thinking that maybe a
SimpleNamespace might suffice:

from types import SimpleNamespace
obj = SimpleNamespace(
    add2=lambda x: x+2,
    squared=lambda x: x*x,
)

But if "behaviour" involves mutable state, it'd be fiddly to squish
that into lambda functions, so a lambda class would be impractical
too.

What you could perhaps do is this:

def one_off(cls): return cls()

@one_off
class obj:
    def func1(self):
        ...
    def func2(self):
        ...

obj.func1()
obj.func2()

It's a statement, with all the costs and benefits thereof, but you
don't have to have "obj = obj()" at the end.

ChrisA



More information about the Python-list mailing list