default mutable arguments

Discussion in 'Python' started by Gigs_, Feb 8, 2007.

  1. Gigs_

    Gigs_ Guest

    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 !!!
     
    Gigs_, Feb 8, 2007
    #1
    1. Advertising

  2. 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.
     
    Leif K-Brooks, Feb 8, 2007
    #2
    1. Advertising

  3. 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...
     
    Bruno Desthuilliers, Feb 8, 2007
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. George Armhold
    Replies:
    1
    Views:
    1,466
    Chris Riesbeck
    Sep 2, 2004
  2. Edward Diener
    Replies:
    14
    Views:
    5,084
    Josiah Carlson
    Apr 6, 2004
  3. tutmann
    Replies:
    4
    Views:
    454
  4. bukzor
    Replies:
    37
    Views:
    906
  5. Steven D'Aprano
    Replies:
    23
    Views:
    587
    castironpi
    Aug 24, 2008
Loading...

Share This Page