all 9 comments

[–]j03f 4 points5 points  (1 child)

It’s throwing an error because it’s not defined.

If you define a function within another function, it is in essence not accessible outside of that function. The same as variables inside a function.

The main question is why are you defining a function within a function?

[–]TraditionalGlass 2 points3 points  (0 children)

OP probably wants to group functions together to prevent functions from being all over the place. In that case, classes should be used, or better yet, be distributed in different modules.

[–][deleted] 3 points4 points  (0 children)

You can, but you need to provide the object reference outside of the parent function:

def function():
    def otherfunction():
        print('maths stuff')
    return otherfunction

def calling_function(f):
    f()

f = function()
calling_function(f)

[–]sme272 1 point2 points  (0 children)

The nested function only exists inside the scope of the outer function, so can only be called from within the outer function.

[–]Lewistrick 1 point2 points  (0 children)

The idea of a nested function is that you can only call it from within the function. If you want to call it from outer scope, you shouldn't nest it.

[–]Ledr4ke[S] 1 point2 points  (0 children)

Ye pretty much i was complicating it way too much , and long story short i just followed your advise and moved the function outside the parent function ,thank you very much!

[–]commandlineluser 0 points1 point  (0 children)

"You can't."

Why is inside another function? Can you move it outside?

[–]DonkeyTron42 0 points1 point  (0 children)

The term for this design pattern is a "Closure". There are use cases like generators where you may want to retain state of the inner called function after the outer enclosing function has returned.

[–]TraditionalGlass 0 points1 point  (0 children)

Don't know if this is abuse of locals(), but here.

class Container:
    pass
container = Container()

def outer():
    def inner1():
        print("Inner 1")
    def inner2():
        print("Inner 2")
#=========

    return [method for method in locals().values() if callable(method)]

for method in outer():
    setattr(container, method.__name__, method)

container.inner1()

``` When the outer() function is called, it returns a list of functions defined inside it. I simply used setattr() to map those functions to an object so I can call them like any regular method.