AlgoViz

Destructors and finalizers

medium 45 min

Some things must be given back: files, connections, locks.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:37

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

block{ ... }fileFileHandlerstatusallocatedfile.txtopenbuffernonesystemoperating systemopen files1open

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

mainserverrunning1databasepart 1staterunningcachepart 2statenot startedworkerpart 3statenot startedportpart 4statenot startedstart

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

    critical

    An error or early return skips it.

    Wrong
    f = open(path)rows = parse(f)f.close()
    Right
    with open(path) as f:    rows = parse(f)
  • Cleanup in __del__

    major

    It may run late or not at all, and errors in it are only printed.

    Wrong
    def __del__(self):    self.conn.close()
    Right
    def __exit__(self, *error):    self.conn.close()
  • Giving back twice

    critical

    The same number is free twice, and two jobs share one connection.

    Wrong
    def close(self):    self.pool.free.append(self.number)
    Right
    def close(self):    pool, self.pool = self.pool, None    if pool is not None:        pool.free.append(self.number)
  • Swallowing in __exit__

    critical

    Returning True hides every error of the block.

    Wrong
    def __exit__(self, *error):    self.close()    return True
    Right
    def __exit__(self, *error):    self.close()    return False
  • Stopping at the first failed cleanup

    major

    Everything after it leaks.

    Wrong
    for c in reversed(cleanups):    c()
    Right
    for 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