I’ve just run into the following code, it’s working fine but it seems weird to me since it’s not even a closure, I’m wondering if it’s the right way to code in terms of performance or best practices, or should all this be replaced with a regular for loop with all the logic inside ?
mylist = [
{'one': 20,
'two': 4},
{'one': -6,
'two': 64},
{'one': 18,
'two': 1},
{'one': 16,
'two': 100},
# ...
]
def business_function(a_list):
def compute_function(row):
"""
suppose some more complex computations + appending extra values
than this dummy example
"""
row['total'] = row['one'] + row['two']
return row
def filter_function(item):
"""
suppose some complex logic here
"""
return item['one'] > 5
# suppose there is some code here ...
filtered_list = [compute_function(item) for item in a_list if filter_function(item)]
# and some more code here ...
return filtered_list
print business_function(mylist)
I see no problems with using locally-scoped functions like these.
Unless the outer function is going to be called a lot the performance impact would be minimal; the code for both functions is already compiled when the outer function is being called, for instance. All that happens extra is that the code object constant is loaded, attached to a function and that function is stored in a local variable.
By keeping them locally scoped you make it abundantly clear that their utility is to the
business_functionscope only.