Directory Stacks with Python I implemented basic pushd and popd functionality for a Python script. What's a more academic/formal way to implement a directory stack?

_directory_stack = {0:getcwd()}

def pushd(target: str):
    """Push a new directory to the top of the stack and changes to it.

    Arguments:
        target {str} -- Where you want to go
    """
    highest_seen = max(_directory_stack.keys())
    _directory_stack[highest_seen+1] = target
    chdir(target)

def popd():
    """Pops the most recent directory off the stop of the stack and returns you to the previous directory
    """
    current_top = max(_directory_stack.keys())
    _directory_stack.pop(current_top, None)
    chdir(_directory_stack[current_top-1])
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?