Search code examples
pythonlambdaautovivification

Recursive definitions in Python


I just run into the following way of implementing AutoVivification in Python:

from collections import defaultdict

Tree = lambda: defaultdict(Tree)

# common name by class, order, genus, and type-species
common_name = Tree()
common_name['Mammalia']['Primates']['Homo']['H. sapiens'] = 'human being'

How does the following construction work?

Tree = lambda: defaultdict(Tree)

Tree does not seem to be defined before the body of the lambda function, and it is not passed as an argument.

How does the body of the lambda function know of Tree before it is defined? What other types of recursive definitions are supported by the language?


Solution

  • That's the great thing about a dynamic language like python -- Tree is defined by the time you call it. It's no different than any other recursive function really ...

    e.g. you probably wouldn't bat an eye to see this:

    def recurse(i):
        if i > 0:
            recurse(i-1)
    

    This works because python creates the recurse function. Then when you call it, python looks up the recurse function when it gets to that line and calls it and ...

    In this case, it's really not much different -- Your lambda could be written (maybe more clearly) like this:

    def Tree():
        return defaultdict(Tree)