Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Another handy one I saw recently:

  varname, = [x for x in l if predicate_with_single_truth_value(x)]
The comma after varname is an implicit assert that the list comprehension only contains one element.


Trailing commas are really easy to miss. When reading this line of code, I did not notice it immediately; I originally assumed that varname was being assigned a list.

This sort of code would be very confusing when I'm just quickly reading through a procedure trying to find the potential bug.


Indeed. I prefer the following variant which is more explicit and thus (IMHO) more in the spirit of Python:

   (varname,) = [x for x in l if predicate_with_single_truth_value(x)]


Agreed. It could be written much more clearly in my opinion like this:

    [varname] = [x for x in l if predicate_with_single_truth_value(x)]


I had to check that on the REPL. I'm surprised that even works and I can't think of a good reason why should list syntax be allowed as a lvalue, in addition to tuple syntax.


It's called destructuring assignment. It's been around for a while.

http://dunsmor.com/lisp/onlisp/onlisp_22.html


I mean why would you want to allow both list and tuple syntax for exactly the same semantics, when either of them would be enough.


I just wish we had destructing assignment for other types as well. And maybe a proper pattern matching!


Good idea!


You could also use the ,= operator, of course:

varname ,= [...]


It appears to me that there is actually no such operator in Python; cf. http://docs.python.org/reference/simple_stmts.html#augmented...

Superficially it looks like an operator, but I suspect that's merely because of whitespace freedom; i.e., a, = [0] is equivalent to a,=[0] and a ,= [0].


I assume it was a joke; a pop culture reference to this stack overflow question:

http://stackoverflow.com/questions/1642028/what-is-the-name-...


  Sure it is! And in Python 3 there's the ,_*= operator, similar to lisp's car:

  varname ,_*= [1, 2, 3] # varname == 1


HN isn't the place for facetiousness.


Apparently it isn't the place for humour either.


Trailing commas are a bit subtle and readers of the code may think it was a mistake. (We spend more time reading code later than writing it in the first place.)

Even Python removed one of its most prominent cases of this, the print command. In Python 2.x you could have a trailing comma after a print to omit the new-line but Python 3's print() function requires print('something', end=' ') to be more explicit about it.


A better way: varname = (x for x in l if predicate_with_single_truth_value(x)).next()


That avoids the construction of the list, but doesn't check that the sequence only contains one value, which was the point of the example.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: