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.

        target {str} -- Where you want to go
    highest_seen = max(_directory_stack.keys())
    _directory_stack[highest_seen+1] = 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)


1 Answer 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:


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

There are two ways to fix this:

  1. pushd can convert the path to an absolute path with os.path.abspath.
  2. 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:


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

  • \$\begingroup\$ I liked this. I ended up going with your recommendations. Thanks! gist.github.com/mxplusb/c895b90d1df65f1e741267d395b3e674 \$\endgroup\$
    – Sienna
    May 9, 2019 at 17:53
  • 1
    \$\begingroup\$ If you post that version as a new question, you can get someone else to review it. (There's some unnecessary complexity.) \$\endgroup\$
    – Anonymous
    May 9, 2019 at 18:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.