Destructors and finalizers
medium 45 minSome things must be given back: files, connections, locks.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Who holds what, and when it goes back.
Operations
The life of a file
Created, used, out of scope, released, reclaimed.
Step 1 of 5
Creation
The constructor opens the file and gets a handle from the system.
Step 1: Creation
with FileHandler("file.txt") as file: # opened file.write("Hello, World!") # in use# end of the block: __exit__ closes the file# later or at once: the memory is reclaimed- Shows
- Destructor at the brace
- Remember
- Two steps: release, reclaim
Releasing the resource and freeing the memory are two different things.
In the real world
The same destructors and finalizers doing real jobs. Pick one and step through it.
Four parts of a server.
Step 1 of 6
Database first
Everything else needs it.
Step 1: Database first
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Close as the last line
criticalAn error or early return skips it.
Wrongf = open(path)rows = parse(f)f.close()Rightwith open(path) as f: rows = parse(f)Cleanup in __del__
majorIt may run late or not at all, and errors in it are only printed.
Wrongdef __del__(self): self.conn.close()Rightdef __exit__(self, *error): self.conn.close()Giving back twice
criticalThe same number is free twice, and two jobs share one connection.
Wrongdef close(self): self.pool.free.append(self.number)Rightdef close(self): pool, self.pool = self.pool, None if pool is not None: pool.free.append(self.number)Swallowing in __exit__
criticalReturning True hides every error of the block.
Wrongdef __exit__(self, *error): self.close() return TrueRightdef __exit__(self, *error): self.close() return FalseStopping at the first failed cleanup
majorEverything after it leaks.
Wrongfor c in reversed(cleanups): c()Rightfor c in reversed(cleanups): try: c() except Exception as e: errors.append(e)
Interview tips
Find the owner
- One at a time
- Say who closes
- Do not close what was lent
Walk the exits
- End
- Return
- Exception
- Failed second acquire
Harden close
- Twice is fine
- Runs to the end
- Keeps the first error
Think past the process
- Signal: orderly stop
- Kill: expiry
- Power cut: replay