# Bank accounts using closures in Python def newaccount(name): balance = 0 def inquiry(): print(name,"has a balance of",balance) def deposit(n): nonlocal balance if n>0: balance +=n def withdraw(n): nonlocal balance if n>0 and balance-n>0: balance -= n def public_interface(request): if request=="inquiry": return inquiry() elif request=="deposit": return deposit elif request=="withdraw": return withdraw else: print("Invalid request",request) return None #public_interface return public_interface #newaccount myaccount = newaccount("Liang") youraccount = newaccount("Student") myaccount("deposit")(100) # myaccount.deposit(100), ((myaccount 'deposit) 100) youraccount("deposit")(200) youraccount("withdraw")(40) myaccount("deposit")(150) myaccount("withdraw")(50) myaccount("inquiry") youraccount("inquiry") """ But what the heck is happening in memory? This clearly won't work in C. So it must be that the values of balance and name are not just popped from the stack after newaccount exits: they somehow got moved to the heap where they can persist, and eventually get garbage collected. Let's call this "extending the lifetime" of data. Notice that we cannot, in general, determine at compile time how many times newaccount is called, thus requiring dynamic allocation. That all sounds expensive but how else can you get closures? Can closures, aka "objects" be created another way, without moving data from stack to heap without a garbage collector? Let's look at how one might solve the problem in modern C++, which has lambda terms and type inference, but C++ will never move things from stack to heap "behind the scenes". And it will never have a garbage collector. """