4 ms·
some_collection.where(x -> x.name == 'foo').sort_by(x -> x.age) These functions are tiny and trivial. They don't need names, and if you were to give them names
by barrkel 12y ago
some_collection.where(x -> x.name == 'foo').sort_by(x -> x.age)
These functions are tiny and trivial. They don't need names, and if you were to give them names, the extra weight becomes burdensome. Not just in syntax duplication, but the redundancy of the name as a comment on the trivial function body.
nameIsFoo = x -> x.name == 'foo'
getAge = x -> x.age
some_collection.where(nameIsFoo).sort_by(getAge)
Note that giving the functions names has also changed the source order of the function bodies. Now you need to do a mental cross-reference to follow, instead of being able to read the definitions inline.
- andreasvc 12y agoSure, but those are one-line functions, which Python supports through lambdas. (Incidentally, some of them could be done with the operator module, without defining a new function). I would argue that once you write a multi-line function, it makes sense to give it a name and define it separately, which makes the "no multi-line anonymous functions" complaint less pressing.
- BugBrother 12y agoLet me give you an example from my experience. I wrote an elegant parser definition library, used for parsing specialized output of ... never mind. It had hierarchic specifications (regular expressions etc) of parsing states, along with anonymous functions which stored away parsed data and sent the parser among different states. New juniors could after a few hours use this to quickly parse complex text documents. I cursed a lot while trying to port this to Python. :-( A dozen named sub-ten lines functions specified by names and referenced inside a parser structure? Just didn't work. Edit: The point is, there are use cases where real lambdas are useful (except from map etc). It is just weird to argue otherwise.
- jsmeaton 12y agoI'm a python guy and I totally agree that multiline anonymous functions greatly enhance the readability of code in certain applications. You can do everything with named functions, but it's not always the best method for conveying meaning. I can live without multiline anonymous functions - but I'd make use of them if they did exist.