I'm learning the concepts of first class functions and closures in Python and I was curious to know:
Given a higher-order function:
def html_tag(tag):
def wrap_text(text):
print("<{0}>{1}</{0}>".format(tag, text))
return wrap_text
1.
print_h1 = html_tag('h1')
print_h1('Test Headline')
print_h1('Another Headline')
2.
html_tag('h1')('Test Headline')
html_tag('h1')('Another Headline')
In the example you give, there's no difference in the result. The second way is less efficient, since you're creating an equivalent function multiple times, which is redundant.
It becomes more relevant when you have functions that keep state between runs.
def counting_tag(tag):
counter = 0
def wrap_text(text):
nonlocal counter
counter += 1
print("<{0}>{1}. {2}</{0}>".format(tag, counter, text))
Every time you call counting_tag()
it will return a function with the counter reset back to 0
.
print_h1 = counting_tag('h1')
print_h1('Test Headline')
print_h1('Another Headline')
This will print
1. Test Headline
2. Another Headline
But if you do it the second way:
counting_tag('h1')('Test Headline')
counting_tag('h1')('Another Headline')
you'll get
1. Test Headline
1. Another Headline