2

I'm coming from a js world and not able to wrap this minor quirk in my head. Consider this simple python program:

lib.py

def test(i, memo=dict()):
  memo[i] = i
  print(memo)
  return i

I'm calling this from repl:

>>> import lib
>>> lib.test(1)
{1: 1}
1

>>> lib.test(2)
{1: 1, 2: 2}
2

>>> lib.test(3)
{1: 1, 2: 2, 3: 3}
3

maybe I'm missing something about python module imports or such - I expected the memo to be initialized with new dictionary each time I call it but it has the knowledge of previous invocations.

Raja
  • 6,354
  • 9
  • 30
  • 34
  • 1
    Functions are also objects and are initialized just once, when they are defined. The `memo=dict()` acts like an instance member for that function and retains its state across call. – cs95 Dec 19 '20 at 23:14

1 Answers1

2

Do it like:

def test(i, memo=None):
  memo = {} if memo is None else memo
  memo[i] = i
  print(memo)
  return i

https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments for more info.

ilov3
  • 427
  • 2
  • 7