So I was reading this wonderful piece which tries to explain decorators in python.
My question is specific to this code snippet.
def surround_with(surrounding):
"""Return a function that takes a single argument and."""
def surround_with_value(word):
return '{}{}{}'.format(surrounding, word, surrounding)
return surround_with_value
def transform_words(content, targets, transform):
"""Return a string based on *content* but with each occurrence
of words in *targets* replaced with
the result of applying *transform* to it."""
result = ''
for word in content.split():
if word in targets:
result += ' {}'.format(transform(word))
else:
result += ' {}'.format(word)
return result
markdown_string = 'My name is Jeff Knupp and I like Python but I do not own a Python'
markdown_string_italicized = transform_words(markdown_string, ['Python', 'Jeff'],
surround_with('*'))
print(markdown_string_italicized)
What I don't understand is how did the function surround_with() get the variable word (when passed on by transform(word) inside transform_words()) in it's scope? I mean we have only declared a holding variable (as a function argument) for what the surrounding value should be and nothing else. Then how was word available to it?
What am I missing here?
transform_words, the functionsurround_with_valueistransform. So when we calltransform(word), we're actually callingsurround_with_value(word), because those two names refer to the same function (not quite, actually, assurround_with_valuegoes out of scope whensurround_withends, but this is the easiest way to think about it).