Directory Stacks with Python
Academic/formal is not what's needed here. Simple is what's needed.

A dict whose keys are all integers from 0 to n is suspicious. Why not use a list instead? You can add items to the end with .append and remove them with .pop. Then you don't have to bother with max(_directory_stack.keys()).

This is the usual way to implement a stack in Python.

Edit: oh, wait, here's an academic/formal issue: popd doesn't restore correctly with relative paths. For example:

pushd('foo')
pushd('bar')
popd()


Should the directory now be foo or foo/bar/foo?

There are two ways to fix this:


pushd can convert the path to an absolute path with os.path.abspath.
Instead of saving the directory it's changing to, pushd can save the current directory (getcwd), and popd can just chdir to whatever it popped.


Which one to do depends on where you want to restore to if someone changes the directory without telling pushd. Consider this sequence:

pushd('/foo')
chdir('bar')
pushd('/baz')
popd()


Should the directory now be /foo or /foo/bar?