A Python tutorial I came across mentions that new instances of local function are created every time the enclosing function is called.
I tried to test that out with below two examples:
Example 1: I am fetching object id
of local function from within local function , new instances created for every function call. This work as expected.
>>> def outer():
... def inner():
... print(inner)
... inner()
...
>>> outer()
<function outer.<locals>.inner at 0x7f7b143bd620>
>>> outer()
<function outer.<locals>.inner at 0x7f7b143bd6a8>
Example 2: But when object id
of local function is fetched from the outer function, Python doesn't seem to create new instances of local function for every call of outer function.
>>> def outer2():
... def inner2():
... pass
... print(inner2)
... inner2()
...
>>> outer2()
<function outer2.<locals>.inner2 at 0x7f7b143bd7b8>
>>> outer2()
<function outer2.<locals>.inner2 at 0x7f7b143bd7b8>
Can anyone please point out what is happening here?
i do understand that :
The id of an object is only guaranteed to be unique during that object's
lifetime, not over the entire lifetime of a program.
my question here is :
why both examples behaves differently , although in both cases the object ceases to exist after print statement is executed.