jia Jimmy
jia Jimmy

Reputation: 1848

Why no not defined NameError raised in this example?

Why there's no NameError raised for variable s in below example?

from collections import defaultdict
s = defaultdict(lambda : len(s))

Upvotes: 1

Views: 37

Answers (1)

deceze
deceze

Reputation: 522451

For the same reason that this works:

def foo():
    print(bar)

bar = 'baz'

foo()

The lambda only defines a function. By the time that function is called and it attempts to access s, s exists.

Upvotes: 4

Related Questions