List of Functions

Steven D'Aprano steve at pearwood.info
Mon Mar 28 18:52:48 EDT 2016


On Tue, 29 Mar 2016 08:40 am, Chris Angelico wrote:

> 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.

"Classless object" is an oxymoron in Python since all values without
exception have a class. Can you explain what you mean?

Also, for the benefit of those who aren't Java coders, what do you mean
by "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? 

That would be called "type" :-)

type(name, bases, namespace) returns a new class:


py> C = type("MyClass", (object,), {'foo': 1})
py> C
<class '__main__.MyClass'>
py> C.foo
1



-- 
Steven




More information about the Python-list mailing list