18 comments:

Thanks! Yes. I needed it. If you have a better suggestion, I'm all ears, but my scenario involves me trying to discover Autodesk Maya's next script job number and to do so I can't rely on the most recent script job. Instead, I have to create a new script job, get its ID and then just delete it. Thing is, I don't actually want this script job to do anything, but it *requires* a function. So, I need an empty lambda. lambda:pass was improper syntax, but lambda:None works beautifully. Thanks!

I wanted (using the verb 'need' implies there is no other way around this, which I am unsure of) to do this in order to give an empty function to threading.Timer. Of course lambda:0 or any expression that does not mess with program or system memory (maybe other considerations?) would have done the trick, but sometimes it is nice to use the official null object identifier in order to clarify intent.

Technically, it shouldn't ever truly be "necessary" but it is more desirable when the cost of changing source or somebody else's (or your own) code would take way too long. In my case, I wasn't about to modify the threading module. Although there may have been some other workaround.

One of my methods has an optional argument that is a callback function. By default it should do nothing, so I needed to test if it was None or not in the function, and then call the callback or not. By defining my argument as "callback = lambda x : None" I eliminate this bothersome test.

As far as I know, this is what we call a special case object. So, I disagree with John E on that 'it shouldn't ever truly be "necessary"'. It is as necessary as empty lists, empty sets, empty iterators, empty queues, emptry trees, zeros, ones (neutral element of multiplication) etc.The emtpy set for instance is the very foundation of every single piece of math we know of today (cf. http://www.science.uva.nl/~seop/entries/set-theory/primer.html). So, declaring this SCO a something unnecessary is quite naive.

Thanks anyway for this pyhton idiom. :) However, the title could be more constructive. ;)

I mostly agree with you. The title was never meant to be very serious ;)

The reason that the empty function feels more artificial in Python than an empty list is maybe because I am not a functional programmer (and it is debatable in how far it is possible to write functional code in Python).

So functions don't really feel to me like "just another object" - not claiming that this isn't naive ;)

"empty function" is _not_ the same as the rest of your examples. Your "special case object" is in fact neutral element: empty list for concatenation, empty set for union, empty iterator for chaining, zeros for addition, ones for multiplication.

In that sense, "neutral function" is in fact identity: lambda x:x, neutral for composition. lambda:None is something else, kinda like _terminal_ object (something like NaN for numbers) but not quite.