1

This simple Python code gets "False".

def foo():
    def bar():
        return 0
    return bar
print(foo() == foo())

When I request

print(foo(),foo())

I get

<function foo.<locals>.bar at 0x03A0BC40> <function foo.<locals>.bar at 0x03C850B8>

So does Python store the result of the bar function every time in the new memory slot? I'd be happy if someone explain how it works behind the scene and possibly how this code can be a little bit modified to get "True" (which still seems logical to me!).

1
  • Each invocation creates a new function object, *that is the whole point of defining a function inside another Commented Dec 9, 2019 at 18:09

2 Answers 2

1

Each def statement defines a new function. The same name and body doesn't really matter. You're basically doing something like this:

def foo():
    pass

old_foo = foo

def foo():
    pass

assert old_foo == foo # will fail

Sign up to request clarification or add additional context in comments.

1 Comment

But if I try with only one def foo() of your version of the code (which would be more close to the one I provided in the question), I get True!
0

bar is locally defined within foo the same way a local variable would be each time you call the foo().

As you can see by the defult __repr__, they have different memory addresses, and since bar does not implement __eq__, the two instances of bar will not be equal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.