4
\$\begingroup\$

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])
asked May 8, 2019 at 19:17
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

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:

  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:

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

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

answered May 8, 2019 at 20:17
\$\endgroup\$
2
  • \$\begingroup\$ I liked this. I ended up going with your recommendations. Thanks! gist.github.com/mxplusb/c895b90d1df65f1e741267d395b3e674 \$\endgroup\$ Commented 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\$ Commented May 9, 2019 at 18:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.