Python Forum
Understanding parentage in environment diagrams
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understanding parentage in environment diagrams
#1
I'm confused about defining the parent of a function as the frame in which the function is defined as it pertains to a HOF that defines a function and then drops out of scope.
def foo(x):
    print(f'foo x: {x}')
    return x

def bar(f):
    print(f'bar f: {f}')
    def bat(y):
        print(f'bat f(y): {f(y)}')
        return y
    return bat

new_func = bar(foo)
# f1    bar         parent = global
#       f = foo
#       return bat
# Doesn't f1 cease to exist here? Out of scope

new_func(5)
# f2    new_func    parent = f1
#       y = 5
#       return y
# If f1 is out of scope, how can the parent of f2 be f1?
Reply
#2
I think you need a better example.
def Outer(x):
    def Inner(y):
        return y**x

    return Inner


squares = Outer(2)
cubes = Outer(3)
print(squares, cubes)
for i in range(5):
    print(i, squares(i), cubes(i))
Output:
<function Outer.<locals>.Inner at 0x000001C6CDF6C280> <function Outer.<locals>.Inner at 0x000001C6CE27C280> 0 0 0 1 1 1 2 4 8 3 9 27 4 16 64
squares and cubes each reference a function closure. The difference between a function and a function closure is that the closure also contains all the variables in the enclosed scope. This is how Inner() remembers x==2 when called using squares, and x==3 when called using cubes. Like other objects in Python, the function closures get garbage collected when their reference count goes to zero.
Clunk_Head likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Understanding venv; How do I ensure my python script uses the environment every time? Calab 1 2,390 May-10-2023, 02:13 PM
Last Post: Calab

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020