default mutable arguments

G

Gigs_

I read that this is not the same:
if arg is None: arg = []
arg = arg or []


def functionF(argString="abc", argList = None):
if argList is None: argList = [] # < this
...
def functionF(argString="abc", argList=None):
argList = argList or [] # and this
...

Why?


thanks !!!
 
L

Leif K-Brooks

Gigs_ said:
I read that this is not the same:
def functionF(argString="abc", argList = None):
if argList is None: argList = [] # < this
...
def functionF(argString="abc", argList=None):
argList = argList or [] # and this
...

Why?

If argList is a false value besides None ("", [], {}, False, etc.), the
second example will replace it with an empty list.
 
B

Bruno Desthuilliers

Gigs_ a écrit :
I read that this is not the same:
if arg is None: arg = []
arg = arg or []


def functionF(argString="abc", argList = None):
if argList is None: argList = [] # < this
...
def functionF(argString="abc", argList=None):
argList = argList or [] # and this
...

Why?

def test(arg=None):
foo = arg or []
print "arg : ", arg, " - foo : ", foo

test()
test(arg=0)
test(arg=False)
test(arg=())
test(arg={})
test(arg='')

etc...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top