top | item 31243529

(no title)

darkfirefly | 3 years ago

Python's default arguments are evaluated and stored once. This can cause issues, for example the naive "default to []" program:

    >>> def function(b, a=[]):
    ...     a.append(b)
    ...     print(a)
    ... 
    ...     
    >>> function(1)
    [1]
    >>> function(2)
    [1, 2]
    >>> function(3, [4])
    [4, 3]
    >>> function(5)
    [1, 2, 5]
A correct implementation would be:

    >>> def function2(b, a=None):
    ...     if a is None: a = []
    ...     a.append(b)
    ...     print(a)

discuss

order

MisterBiggs|3 years ago

Surprised to see this works for list() as well.

  >>> def func(b, a=list()):
  ...     a.append(b)
  ...     print(a)
  ...
  >>> func(3)
  [3]
  >>> func(3)
  [3, 3]
Honestly surprised this quirk hasn't bit me yet