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
1

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.