The usual reason for nesting functions like this is for function decoration. I asked a question a few months ago, and one of the answers seems to fit almost perfectly for your use case. Essentially you're trying to do this:
def outer(n):
def action(x):
def action2(y):
return x**n / y
return action2
return action
Which is a bit of a strange way to do
def action(n, x, y):
return x**n / y
But we'll roll with it. In any case, let's return to our canonical function decorator and see how it compares.
def decorator(func):
def wrapped(*args, **kwargs):
print("Calling inner function")
return func(*args, **kwargs)
return wrapped
@decorator
def foo(some_txt):
print("Hello, ", some_txt)
# EXAMPLE OUTPUT
>>> foo("World!")
Calling inner function
Hello, World!
This is one layer too shallow for what you're trying to do. If we return back to the question I linked earlier on, we'll talk about a validator.
max_len_12 = lambda n: len(n) <= 12 # 12 character max field length
def validation(v):
"""ensures the result of func passes a validation defined by v"""
def outer(func):
def inner(*args, **kwargs):
while True:
result = func(*args, **kwargs)
# if validation passes
if v(result):
return result
return inner
return outer
@validation(max_len_12)
def valid_input(prompt):
return input(prompt)
# EXAMPLE
>>> valid_input("Enter your name (max 12 chars): ")
Enter your name (max 12 chars): Adam YouBetYourAss Smith
Enter your name (max 12 chars): Adam Smith
'Adam Smith'
Or more easily:
valid_input = validation(max_len_12)(raw_input)
# same as previous function
Since it's difficult to know EXACTLY what it is you're trying to do from your example code, hopefully this gives you a good leg to stand on when it comes to decorators and closures. Note that there's a whole world of things you have to do to make your functions introspectable, most of which can be taken care of by functools.wraps
actionalways returns in the line before that.actionreturnsx ** n, and everything after that on the same indentation level and below isn't ever executed. Also, is it intentional that you dividexbynwithout actually using the parametery?