default mutable arguments

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gigs_

    #1

    default mutable arguments

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


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

    Why?


    thanks !!!
  • Leif K-Brooks

    #2
    Re: default mutable arguments

    Gigs_ wrote:
    I read that this is not the same:
    def functionF(argSt ring="abc", argList = None):
    if argList is None: argList = [] # < this
    ...
    def functionF(argSt ring="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.

    Comment

    • Bruno Desthuilliers

      #3
      Re: default mutable arguments

      Gigs_ a écrit :
      I read that this is not the same:
      if arg is None: arg = []
      arg = arg or []
      >
      >
      def functionF(argSt ring="abc", argList = None):
      if argList is None: argList = [] # < this
      ...
      def functionF(argSt ring="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...

      Comment

      Working...