0

In google's pydoc styleguide I stumbled upon 2.14.4

Yes:

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

No:

 ...
 def f(x=None):
     x = x or []

I wonder, why if statement is preferred over x = x or []? Is there some deeper meaning behind this?

Drey
  • 3,314
  • 2
  • 21
  • 26
  • It's a style guide, so generally readability is a focus. Also note these two examples aren't semantically equivalent, exactly, but probably close enough in reality – juanpa.arrivillaga Dec 09 '21 at 17:59
  • I do not think this question is a duplicate (especially with regard to explanation of google style docs). I asked for the reasoning and Bill Shubert *actually* provided a simple and clear answer that I was not aware of. The linked duplicate post don't even go there. – Drey Dec 10 '21 at 16:38

1 Answers1

4

If x is false (the boolean value), then it will be replaced with []. Usually you only want to replace when it is actually None.

Bill Shubert
  • 496
  • 3
  • 12
  • 3
    If x is *fasley*; empty strings, `0`, etc.. would also apply to this – Wondercricket Dec 09 '21 at 17:40
  • 1
    This function is presumably meant to accept a list, so the problem is when you pass an empty list it doesn't retain a reference to the actual empty list that is passed; this means any mutations won't be made to the argument, which is different behaviour to when the argument is a non-empty list. – kaya3 Dec 09 '21 at 17:42
  • More exactly if x is falsey which means x is something for which "bool(x) == False". – Michael Butscher Dec 09 '21 at 17:43