News for hackers. Stuff that matters.
Re:A few things to remember while coding in Python by chernevik on Saturday May 19, 2012 @10:39PM (#3997744)
Ah.

These are the little assumptions that keep blowing off my feet. Thanks.

Re:A few things to remember while coding in Python by SoftwareMaven on Sunday May 20, 2012 @12:13AM (#3997921)
It is these cases that brought the ternary operator to Python:

  def f(x=None): x if x is not None else []
Re:A few things to remember while coding in Python by chernevik on Sunday May 20, 2012 @08:46PM (#4000753)
I'm a little confused about this as an assignment to a variable. Is that because of the 'return' omission referred to below? If all function f did was return x, I could see how this works with a 'return' prepended.

But if this expression is a line in a larger function, and is intended to reset the value of argument x if no other value is passed in for it, does this really act as an assigment to x? Because I sort of read this expression as evaluating to some value -- the passed value for x, or a [] -- but does this assign that value to the argument x? Or must it be x = [expression]

Re:A few things to remember while coding in Python by coderdude on Sunday May 20, 2012 @11:37PM (#4001150)

  def f(x=None):
        x = x if x is not None else []
        return x
Now it will assign that value back to x. Otherwise it would just evaluate the expression.
Re:A few things to remember while coding in Python by chernevik on Monday May 21, 2012 @06:00AM (#4002086)
Thanks for the additional clarity.
Re:A few things to remember while coding in Python by iki23 on Sunday May 20, 2012 @04:48AM (#3998323)
Yes, but why? Actually, it's No, because python culture aims to use one way to do thing, the least surprising one. In this case it's:

  def f(x=None): if x is None: x = []
Re:A few things to remember while coding in Python by SoftwareMaven on Sunday May 20, 2012 @05:07PM (#4000109)
Because that "if" is a statement whereas the ternary expression is, well, an expression. There are places expressions can be used that statements can't (eg lambdas) and that x or [] won't work (eg when x is False).

That said, people still seem to favor your form as the more Pythonic way. Personally, I think that's just because the ternary expression is relatively new.

Re:A few things to remember while coding in Python by jongraehl on Sunday May 20, 2012 @02:41PM (#3999628)
you forgot 'return'
Re:A few things to remember while coding in Python by SoftwareMaven on Sunday May 20, 2012 @05:02PM (#4000093)
Yeah, I guess my typing went into "lambda mode" since it was a one liner.