Class getting kwargs from closed volume

Python seems to pull some kwargs out of the scope of the class method, and I'm not sure why. I implement Trie:

class TrieNode(object):
  def __init__(self, value = None, children = {}):
    self.children = children
    self.value = value

  def __getitem__(self, key):
    if key == "":
        return self.value
    return self.children[key[0]].__getitem__(key[1:])

  def __setitem__(self, key, value):
    if key == "":
        self.value = value
        return
    if key[0] not in self.children:
        self.children[key[0]] = TrieNode()
    self.children[key[0]].__setitem__(key[1:], value)

In the second and last line, I create a new TrieNode with an apparently empty dictionary for children. However, when I check the resulting data structure, all TrieNodes in the tree using the same child dictionary. Visas if we do this:

>>>test = TrieNode()
>>>test["pickle"] = 5
>>>test.children.keys()
['c', 'e', 'i', 'k', 'l', 'p']

While the children of the test should consist only of "p" pointing to the new TrieNode. On the other hand, if we go to the second and last line of this code and replace it with:

        self.children[key[0]] = TrieNode(children = {})

Then it works as expected. Somehow, the dictionary self.children gets implicitly as kwarg for TrieNode (), but why?

+4
2

. __init__ ,

def __init__(self, value=None, children=None):
    if not children:
        children = {}

, , dict .

>>> def f(seq=[]):
...     seq.append('x') #append one 'x' to the argument
...     print(seq) # print it
>>> f() # as expected
['x']
>>> f() # but this appends 'x' to the same list
['x', 'x']
>>> f() # again it grows
['x', 'x', 'x']
>>> f()
['x', 'x', 'x', 'x']
>>> f()
['x', 'x', 'x', 'x', 'x']

, , python.

+7

, , :

def __init__(self, value = None, children = {}):

children = {} . , ( ). , None ( None , ):

def __init__(self, value = None, children = None):
    self.children = children if children else {}
    self.value = value
0

All Articles