thanks_in_advance
thanks_in_advance

Reputation: 2743

why won't this Closure attempted with Python work?

This prints something:

def foo(message):
    print(message)

foo("baba booey")

Python Tutor link

Why doesn't this print anything:

def foo(message):
    def bar():
        print(message)

foo("baba booey")

Python Tutor link

Per this tutorial, they should both work.

Upvotes: 0

Views: 27

Answers (1)

mitoRibo
mitoRibo

Reputation: 4548

You just need to add a return statement in the foo function to return the bar function:

def foo(message):
    def bar():
        print(message)
    return bar #<-- have to return bar function

ret = foo("baba booey") #<-- ret is now the bar function
ret #<-- again returns the bar function but doesn't execute it
ret() #<-- executes the bar function and prints "baba booey"

currently you are not calling bar anywhere in the code, even though foo is getting called. You can check this by:

def foo(message):
    print("In foo before bar")
    def bar():
        print(message)
    print("In foo after bar")
    bar()
    print("Just called bar from within foo")

foo("baba booey")

Upvotes: 1

Related Questions