Live data from Hacker News

Stop writing lambda expressions in Python

treyhunner.com

81–90 of 202 posts

Re: Stop writing lambda expressions in Python

#81
post #71

I generally like coding with lambdas, but in Python one thing I hate is that they will capture a numeric loop index by ref and not by its current value. If you try generating some polynomials x -> x, x^2, x^3 ... in the "obvious" way you'll see what I mean, all polynomials will be the same as the last one after the loop or list compr is done. Theres a workaround using default arg value to capture by val but its ugly…

Do you mind fleshing out your example with some actual code? I'm not quite following, and I'm completely lost by the time you talk about the workaround.

Re: Stop writing lambda expressions in Python

#82
post #63

Earlier quoted context omitted.

i know that. in the example, he assigned the lambda to normalize_case.

Sure, but an object doesn't know what variable it is assigned to (and which variable name should it pick if there's multiple). the def syntax merely sets the name property on the function object too, since it has a name to set available. As said in other comments, nice for interactive use, irrelevant otherwise. >>> normalize_case = lambda s: s.casefold() >>> normalize_case at 0x034B04B0> >>> normalize_case.__qualname…

thank you for clarifying exactly what's going on. other than the __qualname__, in what other ways do the two different bindings differ from each other?

however, this still goes in the bucket of why i personally dislike python. this just seems sloppy and overly complicated.

for example, i tested this out myself.

  > test = lambda x : x*x
  > test
  =>  at 0x7ff6221d76e0>
  > test.__qualname__
  Traceback (most recent call last):
    File "python", line 1, in 
  AttributeError: 'function' object has no attribute '__qualname__'
  > test.__qualname__ = "test"
  > test
  =>  at 0x7ff6221d76e0>
so the repl still reports instead of test. actually it turns out that even def doesn't seem to set the __qualname__ property, so i don't get the same thing as you (i am using repl.it which apparently uses python 2.7.10). however, using dir(test) showed that there is the func_name property.

  > def test2(x):
  >     return x*x
  > test2.__qualname__
  Traceback (most recent call last):
    File "python", line 1, in 
  AttributeError: 'function' object has no attribute '__qualname__'
  > test2.func_name
  => 'test2'
  > test.func_name
  => ''
that seems to be the property that the repl reports, as it gets set by the lambda assignment and the def keyword to the function name. (i verified that by altering the func_name property manually.)

yet, somehow, people call python "simple".

Re: Stop writing lambda expressions in Python

#83
post #41
post #4

all i could think of is "stop writing python". it seems to me that a lot of these problems are fundamental problems with python. i continue to not understand why anybody likes python the language. the fact that creating a function with lambda versus the normal way is different is bonkers. for example, in f# (and other sane languages), the following are identical: let test1 = fun x -> x * x let test2 x = x * x both re…

Guido van Rossum was explicitly against functional programming (well, in the Python language anyway). It's an imperative, object-oriented language that eventually threw functional programmers a bone with map, reduce, and filter, and that's about it.

Could you elaborate further? I wasn't there then, but what you wrote doesn't agree with my understanding.

Lambda, map, reduce, and filter were part of the Python 1.0 release. The actual commit date was Tue Oct 26 17:58:25 1993 +0000:

  commit 12d12c5faf4d770160b7975b54e8f9b12694e012
  Author: Guido van Rossum 
  Date:   Tue Oct 26 17:58:25 1993 +0000

    * compile.[ch]: support for lambda()
    * PROTO.h, mymalloc.h: added #ifdefs for TURBOC and GNUC.
    * allobjects.h: added #include "rangeobject.h"
    * Grammar: added lambda_input; relaxed syntax for exec.
    * bltinmodule.c: added bagof, map, reduce, lambda, xrange.
    * tupleobject.[ch]: added resizetuple().
    * rangeobject.[ch]: new object type to speed up range operations
       (not convinced this is needed!!!)
You can see the commit had its doubts about xrange, but said nothing negative of the functional programming aspects.

Van Rossum described that history at https://python-history.blogspot.com/2009/04/origins-of-pytho... . I don't see anything which sounds like "throwing a bone", much less being "explicitly against functional programming" when that discussion occurred.

My understanding is that he wasn't opposed to their inclusion initially but became negative towards them only years later.

Re: Stop writing lambda expressions in Python

#84
post #4

all i could think of is "stop writing python". it seems to me that a lot of these problems are fundamental problems with python. i continue to not understand why anybody likes python the language. the fact that creating a function with lambda versus the normal way is different is bonkers. for example, in f# (and other sane languages), the following are identical: let test1 = fun x -> x * x let test2 x = x * x both re…

Re: use of map / filter type stuff. Yep. Had a coworker like that recently. Loved “simple” code, chock full of mutable data everywhere, where everything was written out a good 3 or 4 times longer than I would have liked to see it. I call that sort of “simple, explicit” (repetitive) code “My Summer Vacation” code, after a bit in an old Cheech and Chong skit where the highschool kids have to read their essays to the cl…

Simple and explicit code? sounds easy to read and debug!

Re: Stop writing lambda expressions in Python

#85

Earlier quoted context omitted.

Why does it need that, though? What's wrong with just naming the function?

There's real readability and clarity to positioning an anonymous function right at the point in the code that it will be used. When you name and define a function some other place and use it elsewhere, you have increased the overall complexity. What is this named function? Where is it used? Is it accessed by other bits of code? Should it be? All these questions come up when you see a named function. It is in fact les…

Python has a convention for "private" functions, which is to prepend "_" to the name.

> It's hard to make a strong case just in words, but once you really understand the power of the fat arrow syntax for anonymous inline functions then you use it more and more and it becomes second nature and the programs you write have a completely different style, oriented towards neatly positioned inline anonymous functions everywhere that typically can be read and understood at a glance as you skip through the code.

This is exactly why I think Python has such limited anonymous functions: because it does not want to promote that style.

> There is simply no other way to write a function that absolutely cannot be called by some other bit of code.

Python also believes that you do not need to defend against this possibility, as long as you make it clear to other developers that they should not call your "private function". This is also why the language allows monkey patching anything at will. If someone wants to ignore good sense, let them.

Re: Stop writing lambda expressions in Python

#86
post #13

> I’d say that using lambda expressions is acceptable only if your situation meets all four of these criteria: > 1. The operation you’re doing is trivial: the function doesn’t deserve a name Sure. > 2. Having a lambda expression makes your code more understandable than the function names you can think of This is just vague. Locally defining a function right where you need it makes code much more understandable to me…

Also, wouldn't the existence of a library function (#3) imply that what you're doing is either non-trivial or common enough that someone has already given the function a name? Seems like #1 is sufficient.

Re: Stop writing lambda expressions in Python

#87
post #85

Earlier quoted context omitted.

There's real readability and clarity to positioning an anonymous function right at the point in the code that it will be used. When you name and define a function some other place and use it elsewhere, you have increased the overall complexity. What is this named function? Where is it used? Is it accessed by other bits of code? Should it be? All these questions come up when you see a named function. It is in fact les…

Python has a convention for "private" functions, which is to prepend "_" to the name. > It's hard to make a strong case just in words, but once you really understand the power of the fat arrow syntax for anonymous inline functions then you use it more and more and it becomes second nature and the programs you write have a completely different style, oriented towards neatly positioned inline anonymous functions everyw…

Private functions do not restrict the usage of that function to one point in the code. There's a world of difference between a coding convention - essentially a comment to say "please don't access this function from outside the current class" versus it simply being impossible to do so. And the "private" convention does not say "don't use this function at any other point except one", it says "please don't access this function from outside the current class", which is completely different to the point I make. Anonymous inline functions reduce lines of code and complexity.

>>because it does not want to promote that style.

Why would Python not want to promote a more readable, simple, powerful, reliable and maintainable programming style?

Can you reference anything to back this assertion?

Re: Stop writing lambda expressions in Python

#88
post #72

Personally, I use them often and disagree with a lot of this sentiment. I also disagree with a significant portion of PEP8, however. Anonymous functions are vital to any modern high level language. I think most people get hung up on the word. If the keyword was changed from “lambda” to “fun” for example I think it wouldn’t be as obtuse to more intermediate developers. To be honest I think the lambda does Python a ser…

> Anonymous functions are vital to any modern high level language. I don’t think you’re wrong, but I am also not experienced enough to know why this would be the case. What is the virtue of having an anonymous function? I get that it makes code somewhat easier to read and write if you’re only using the function once and it’s short, but that seems like an edge case. What am I missing?

This is a great question with many great answers. The process of discovering those answers will illuminate huge swaths of the computer science landscape beyond the tiny, relatively insignificant patch that people call "programming."

You are about to embark on a great adventure. I wish you luck on your quest!

Re: Stop writing lambda expressions in Python

#89
post #80

Personally, I use them often and disagree with a lot of this sentiment. I also disagree with a significant portion of PEP8, however. Anonymous functions are vital to any modern high level language. I think most people get hung up on the word. If the keyword was changed from “lambda” to “fun” for example I think it wouldn’t be as obtuse to more intermediate developers. To be honest I think the lambda does Python a ser…

Van Rossum started to work on Python in 1989 and released the first version in 1991. Python is modern in the sense of being still very well alive but it's deeply rooted in the 80s, and it shows with all those double underscore __magic functions__, the self argument in methods (the way we were doing object oriented programming in C, without the ++) and others. Compared to JavaScript it didn't evolve it's syntax much.…

`self` is about being explicit with parameters. Rust does the same thing and that's a more "modern" language.

The `__magic__` is about avoiding naming conflicts while still being explicit. It's a choice between magic or reserving a lot of names.

Re: Stop writing lambda expressions in Python

#90
post #65

Earlier quoted context omitted.

f# (and also ocaml and sml) have all those and much more. they are much more consistent and principled in their design, which makes things simpler to understand. for example, in all three languages above, expressions are much easier to understand because they always return a value. this makes code easier to reason about. this is not true in python. the languages i mentioned do have static typing but they have type in…

> f# (and also ocaml and sml) have all those and much more F# has curly braces. Also, as you say, it requires some type annotations. I see that F# has a REPL, but it seems bolted on as an afterthought instead of being an integral part of the language. (Also, it's not clear whether the REPL is available in Mono on Linux. I am allergic to Windows and anything built by Microsoft.) > expressions are much easier to unders…

okay, f# has curly braces. but not in the sense of other C-like languages like c++, java, and c#. they are primarily used for sequence expressions and computation expressions like async.

> I see that F# has a REPL, but it seems bolted on as an afterthought instead of being an integral part of the language. (Also, it's not clear whether the REPL is available in Mono on Linux. I am allergic to Windows and anything built by Microsoft.)

well that first sentence is simply not true, and i don't know what gave you that impression. f#'s repl, f# interactive, is available on linux through mono and will soon be available through .net core. i can't help you being needlessly allergic to a major operating system or company. f# came out of microsoft research.

> Huh? Python expressions always return a value.

they do? take:

  def test(x):
    "something"
so what does

  test(2)
return?

> I don't owe it to myself to learn anything unless I decide to. I wasn't trying to convince anyone else to use Python; I was just giving reasons why I like Python. Please extend me the same courtesy when you talk about things you like about your favorite languages.

i don't know why you're upset. i am not for sure where i was discourteous. i didn't mean anything by my statement other than to check out the languages and courses (the coursera one is very good). if those are your reasons for python, i just thought you would honestly like an ML-based language. i just used "owe it to yourself" as an expression, which apparently came out wrong through text. of course you don't owe anyone anything. i was just making a suggestion.

Post reply on HN