BenDundee
BenDundee

Reputation: 4521

Correct way to specify default empty list/dict/set/etc as function arg

What is the correct way to specify an empty dict or list for a function?

def func_a(l=list(), d=dict()):
    pass

def func_b(l=[], d={}):
    pass

Upvotes: 2

Views: 430

Answers (2)

andersschuller
andersschuller

Reputation: 13907

Neither. Default arguments in Python are evaluated once, at function definition. The correct way is to use None and check for it in the function:

def func(l=None):
    if l is None:
        l = []
    ...

See the discussion in this SO question.

Upvotes: 3

mgilson
mgilson

Reputation: 310069

Either of those is fine if you're not going to mutate the input arguments...

However, if you're planning on mutating the list or the dict inside the function, you don't want to use either of the forms that you've supplied... You want to do something more like this:

def func(l=None, d=None):
    if l is None:
       l = list()  #or l = []
    if d is None:
       d = dict()  #or d = {}

Note that [] and {} will result in marginally faster execution. If this is in a really tight loop, I'd use that.

Upvotes: 7

Related Questions