While there is a lot of discussion around construction and use of nested functions, there is very little info on when to use them. What I'm trying to find out is: when is it idiomatic to use a nested function? When should you use lambda x: <function>
over a nested function?
Python is a language that lets you do a lot of things you shouldn't (ie: using globals). Is this a feature that, while you can use it, you should not?
A scenario I envisioned for using one is in unit testing. Let's say you a method defined like this:
def FunctionOne(varone: int, vartwo: object) -> None:
assert varone == vartwo()
vartwo is a function that is passed into the function. Now we want to unittest this. So we write a (partial) unit test that looks like this:
def unittest() -> None:
def test_function() -> int:
return 1
FuncitonOne(1, test_function)
The specifics here are:
- The function is only needed in the scope of the unit test function.
- The function is never called elsewhere.
Therefore, to summarize: when should you (if ever) use a nested function with Python?