Defaultdict, functions and lambdas

I played by default and I'm confused

Why this does not work:

Example 1

def hi(name):
    return "hi " + name

a = defaultdict(hi)
print(a["hello"]("jane"))

Output Example 1

TypeError: hi() missing 1 required positional argument: 'name'

but it does:

Example 2

def hi(name):
        return "hi " + name

a = {"hello":hi}
print(a["hello"]("jane"))

Output Example 2

hi jane

also using lambda would make it work

Example 3

def hi(name):
    return "hi " + name

a = defaultdict(lambda: hi)
print(a["hello"]("jane"))

Output Example 3

hi jane

Why does Example 1 return an error, but Example 3 does not work?

What's happening?

+4
source share
1 answer

If defaultdict does not find the key, it calls the function without any parameters. FROM

def hi(name):
    return "hi " + name

a = defaultdict(hi)
a["hello"]

hi , , . hi - , , hi(), .. TypeError, .

( )

def hi(name):
    return "hi " + name

def make_hi():
    return hi

a = defaultdict(make_hi)
print(a["hello"]("jane"))

a["hello"] make_hi, hi, ("jane").

+4

Source: https://habr.com/ru/post/1607708/


All Articles