4 ms·
Generally it is un-pythonic to assign lambda to a variable. Lots of linters will complain if you do this.
by blester 5y ago
Generally it is un-pythonic to assign lambda to a variable. Lots of linters will complain if you do this.
- sharikous 5y agoSo do a "def" instead, it can be even inlined. def add_fun(x,y): return x+y But I wouldn't mind irritating the linter with an assigned lambda. I fail to see what's the problem with it
- ViViDboarder 5y agoBut if you’re doing that, why not just import the identical function?
- sharikous 5y agoOne major point of OP was that the functions defined in operators are faster. Grandparent comment argued that there is a measurement error that invalidates this point, since properly defined lambdas (or defs) are just as fast. Of course the point regarding the simplicity of importing a function instead of defining it still stands. I personally wouldn't mind defining those functions as they are very immediate. So from the article I would take only the part about the more exotic "operator".
- klyrs 5y agoThe timings are certainly closer, but the built-in function imported from operator is still faster than the user-defined function. Not a big deal if you're doing simple stuff, but if this code is in a hot loop that 30% can make a measurable difference.
- kevin_thibedeau 5y agoLambdas don't know their name and weaken debug info.
- elteto 5y agoIt seems like an implementation issue of the interpreter no? There’s no reason lambdas _have_ to be this way.
- jonathrg 5y agolambdas don't have names, how could the interpreter possibly improve in this regard?
- zodiakzz 5y agoJS arrow functions don't have names either, it's inferred from the left hand side variable name. Can't Python do something similar?
- jonathrg 5y agoIf you assign a lambda to a variable, you might as well use a def. A more typical use of a lambda is as an arguments to a function call. What would be the name of, say, the first argument to map(lambda x: x*2, numbers)?
- ris 5y agoLinters will complain about all sorts of nonsense, and I'll have to continue to remind people that pep8 was only supposed to be guidance, and never something that was enforced. In short: being picked up by a linter does not mean that something is un-pythonic.
- elteto 5y agoThe reasoning that I’ve seen for this is that you lose context information (file, line, etc) when using lambdas. Is that it? If so it seems like a an interpreter implementation issue.
- jonathrg 5y agoThe point is that the function is created only once, like when you pass a lambda to map/filter/reduce or any function that takes a callback. The fact that it is assigned here is just a neccessary step for the timeit command to do the right thing