Below is the basic logic for function foo:
def foo(item_lst):
val_in_foo_scope = 1
for item in item_lst:
# some logic to deal with item
# val_in_foo_scope used
pass
return 0
The logic in the loop can be very complex, in order to make the code more clear, I want to split the logic with a separate function.
With inner function:
def foo(item_lst):
val_in_foo_scope = 1
def some_logic(item):
# val_in_foo_scope used
pass
for item in item_lst:
some_logic(item)
return 0
With outer function:
def some_logic(item, val):
# val used
pass
def foo(item_lst):
val_in_foo_scope = 1
for item in item_lst:
some_logic(item, val_in_foo_scope)
return 0
The inner function version
- val_in_foo_scope can be used directly -- good
- we can easily know that the some_logic is relevant with foo, actually only be used in function foo -- good
- each time function foo is called, a new inner function will be created -- not so good
The outer function version
- val_in_foo_scope can not be used directly -- not so good
- we can not see the relevance between some_logic and foo directly -- not so good
- some_logic will be created one time -- good
- there will be so many functions in the global namespace -- not so good
So, which solution is better or is there any other solutions?
Factors below or any other factors you come up with can be considered:
- val_in_foo_scope is used or not
- whether the time cost to create inner function each time can be ignored