Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call nested function from another function in python?

Tags:

python

I have a function inside inside another and a third function. How can I call my nested function inside of my third function? Is there any special libraries I can use? I am not allowed to edit a() or b(), only c().

def a():
    def b():
        print("hi")

def c():
    # code only here to call b() to print

2 Answers

When you do this, function b is defined locally within a. This means that it cannot be accessed by default outside of a. There are two main ways to solve this, but both involve modifying a:

  1. The global keyword (not recommended)

    def a():
        global b
        def b():
            print("hi")
    

    Here the global keyword sets b up as a global variable, so that you can then access it by calling it normally from within c. This is generally frowned upon.

  2. Returning the function from a and passing it to c

    def a():
        def b():
            print("hi")
        return b
    
    def c(b):
        #your code
    

    Then, when you call c, you should pass b to it, which a will have returned. You can either do so thus:

    b = a()
    c(b)
    

    Or you can simply call a every time you call c, thus:

    c(a())
    

    If you choose to do this, you can then define c thus:

    def c():
        b = a()
        #your code here
    

    which would allow you to simply call c normally, thus:

    `c()`
    
like image 57
Benedict Randall Shaw Avatar answered Jun 28 '26 18:06

Benedict Randall Shaw


This is not possible due to the way that Python scope works. b() is local to a(), and so does not exist within c().

EDIT: commenter is correct, the suggestion I initially gave doesn't work -- so this definitely just isn't possible.

like image 45
Harshita Gupta Avatar answered Jun 28 '26 17:06

Harshita Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!