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])
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:
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 withos.path.abspath
.- Instead of saving the directory it's changing to,
pushd
can save the current directory (getcwd
), andpopd
can justchdir
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
?
-
\$\begingroup\$ I liked this. I ended up going with your recommendations. Thanks! gist.github.com/mxplusb/c895b90d1df65f1e741267d395b3e674 \$\endgroup\$Sienna– Sienna2019年05月09日 17:53:33 +00:00Commented 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– Anonymous2019年05月09日 18:41:02 +00:00Commented May 9, 2019 at 18:41