1

Let's say we have the function f and I need the argument b to default to an empty list, but can't set b=[] because of the issue around mutable default args.

Which of these is the most Pythonic, or is there a better way?

def f(a, b=None):
   if not b:
     b = []
   pass

def f(a, b=None):
   b = b or []
   pass
Mike
  • 709
  • 7
  • 19
  • 2
    Possible duplicate: https://stackoverflow.com/questions/366422/what-is-the-pythonic-way-to-avoid-default-parameters-that-are-empty-lists – Toto Lele Jun 03 '18 at 05:17

2 Answers2

5

The first form as it reads easier. Without any specific context, you should explicitly test for the default value, to avoid potential truthiness issues with the passed in value.

def f(a, b=None):
   if b is None:
     b = []
   pass

From PEP 8, Programming Recommendations:

Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

You can see examples of this approach throughout the cpython repository:

chuckx
  • 6,484
  • 1
  • 22
  • 23
0
def f(a, b=''):
   if not b:
      b = []

   print(a)

You can cdo something simple such as "if not b". If you are going to make the default argument an empty string or set it equal to None, you can simply use an if statement to define what B should be if you are never actually going to enter an argument for b. In this example we simply set it to an empty list.

Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27