On 2-May-08, at 4:03 PM, Terry Reedy wrote: > Some people write > somename = lambda args: expression > instead of the more obvious (to most people) and, dare I say, standard > def somename(args): return expression > > The difference in the result (the only one I know of) is that the > code and > function objects get the generic name '<lambda>' instead of the more > informative (in repr() output or tracebacks) 'somename'. I consider > this a > disadvantage. > > In the absence of any compensating advantages (other than the trivial > saving of 3 chars), I consider the def form to be the proper Python > style > to the point I think it should be at least recommended for the > stdlib in > the Programming Recommendations section of PEP 8. > > There are currently uses of named lambdas at least in urllib2. This > to me > is a bad example for new Python programmers. > > What do our style mavens think? I'm not a style maven, but I'll put forward why I don't think this is bad style. Most importantly, these statements can result from sensible changes from what is (I believe) considered good style. For example, consider: registerCallback(lambda: frobnicate(7)) what if there are too places that the callback needs to be registered? registerCallback(lambda: frobnicate(7)) registerCallback2(lambda: frobnicate(7)) DRY leads to factoring this out into a variable in a straightforward manner: callback = lambda: frobnicate(7) registerCallback(callback) registerCallback2(callback) Another thing to consider is that the def() pattern is only possible when the bound variable has no dots. A common pattern for me is to replace an instances method with a lambda to add monitoring hooks or disable certain functionality: inst.get_foo = lambda: FakeFoo() This is not replacable in one line with a def (or without locals() detritius). Assuming this is good style, it seems odd that inst.get_foo = lambda: FakeFoo() is acceptible style, but get_foo = lambda: FakeFoo() isn't. (I also happen to think that the def pattern is less clear in some situations, but that speaks more to personal taste so isn't particularly relevant) -Mike
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4