Reputation: 11
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!).
Upvotes: 1
Views: 52
Reputation: 6354
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
Upvotes: 1
Reputation: 312404
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.
Upvotes: 0