Hi,

I am reading a book where it says that:

Just like module-level function definitions, the definition of a local function 
happens at run time when the def keyword is executed. Interestingly, this means 
that each call to sort_by_last_letter results in a new definition of the 
function last_letter. That is, just like any other name bound in a function 
body, last_letter is bound separately to a new function each time 
sort_by_last_letter is called. 

If that above is true, why the below program shows the same object reference 
for last_letter every time I call function sort_by_last_letter.

# file name is sample.py

def sort_by_last_letter(strings):
    def last_letter(s):
        return s[-1]
    print(last_letter)
    return sorted(strings, key=last_letter)

python3 -i sample.py 
>>> sort_by_last_letter(['ghi', 'def', 'abc'])
<function sort_by_last_letter.<locals>.last_letter at 0x1051e0730>
['abc', 'def', 'ghi']
>>> sort_by_last_letter(['ghi', 'def', 'abc'])
<function sort_by_last_letter.<locals>.last_letter at 0x1051e0730>
['abc', 'def', 'ghi']
>>> sort_by_last_letter(['ghi', 'def', 'abckl'])
<function sort_by_last_letter.<locals>.last_letter at 0x1051e0730>
['def', 'ghi', 'abckl']
>>> 


Thanks,

Arup Rakshit
a...@zeit.io



-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to