0

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?

1
  • 1
    it doesnt ... lambda's are executed when they are called ... Commented Jan 22, 2015 at 1:01

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Although, to be fair, you can implement recursive functions in much less dynamic languages as well -- You can even do it in a standardized way in C or Fortran (90)!
2

It's the equivalent of:

def Tree():
    return defaultdict(Tree)

The contents of the function aren't evaluated immediately, only when it gets called, at which time it can know about Tree. This is the reason recursive functions can work at all.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.