Skip to Content
Menu
This question has been flagged
3 Replies
6563 Views

Hi, I am newbie on OpenERP ... and Python

For example in the "idea" module, I don't understand the syntax about "lambda"

In idea_idea class, why the code is :

_defaults = {
       'state':  lambda *a: 'draft',
  }

rather than simply :

_defaults = {
       'state':   'draft',
   }

?

Avatar
Discard
Best Answer

That's entirely unnecessary. You're absolutely right, the second version would work perfectly fine. In OpenERP 6.0 and earlier, even simpler defaults like Boolean values needed a lambda function to properly interpret. Works fine now, just ignore that bad example.

Lambda is a peculiar Python concept to understand, at least in my experience. Basically once Python reaches that line at runtime, the lambda function would generate a completely new anonymous function to compute that value every single time it's encountered. It makes more sense to use it on something like time.now(), although there is a shortcut for that as well to avoid writing a lambda. If you use time.now() without a lambda function, it will take the timestamp when the code is loaded into memory, and then use that one timestamp every single time it's called until OpenERP shuts down. Lambda forces the code to be re-evaluated every single time.

Outside of OpenERP, it's also used for things like, sorting a list of tuples by one of the values inside the tuple without needing to write your own sorting algorithm. Every time you get to another tuple, you need to read one of the elements at a certain position to find out where the entire tuple would go. If you understand what's happening, it can make your code much more readable, but almost any situation that you'd make good use of lambda in could be written without it, you just need to write additional bits of code.

You can try Googling lambda function explanations for Python, but I've never found any decent ones personally.

Avatar
Discard
Author

thanks a lot

Best Answer

lambda functions are anonymous functions which does not have a name. Please find the link below for 'lambda' functions in Python:

http://www.secnetix.de/olli/Python/lambda_functions.hawk

Avatar
Discard