Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > default mutable arguments

Reply
Thread Tools

default mutable arguments

 
 
Gigs_
Guest
Posts: n/a
 
      02-08-2007
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 !!!
 
Reply With Quote
 
 
 
 
Leif K-Brooks
Guest
Posts: n/a
 
      02-08-2007
Gigs_ wrote:
> 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.
 
Reply With Quote
 
 
 
 
Bruno Desthuilliers
Guest
Posts: n/a
 
      02-08-2007
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...
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Should Python raise a warning for mutable default arguments? Steven D'Aprano Python 23 08-24-2008 12:40 AM
Bizarre behavior with mutable default arguments bukzor Python 37 01-02-2008 10:56 AM
function default arguments from other arguments tutmann C++ 4 10-17-2006 08:00 PM
XMLEncoder/XMLDecoder and mutable arguments to getters/setters George Armhold Java 1 09-02-2004 05:43 PM
Difference between default arguments and keyword arguments Edward Diener Python 14 04-05-2004 11:26 PM



Advertisments