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

I am but an egg, but isn't this the same but shorter?

def f(L=None): L = L or []



It might work the same depending on your use of it but it's not the same. In that instance L will become a blank list if it is equal to None, zero, or a zero length string. There are many cases where this wouldn't affect anything, but there can also be instances where that will cause you to define L as a blank list when you really wanted to keep L's value. I think it's always better to be explicit and test for the value(s) you expect.


Ah.

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


It is these cases that brought the ternary operator to Python:

  def f(x=None): x if x is not None else []


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]


  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.


Thanks for the additional clarity.


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 = []


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.


you forgot 'return'


Yeah, I guess my typing went into "lambda mode" since it was a one liner.


I originally had "don't do that!" in my comment with your exact code, and edited it out for brevity because I've only seen a couple people do it (and they understood the ramifications, which others have told you). If you're interested in brevity, this is as terse as it gets:

    L = [] if L is None else L




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

Search: