I'm trying to setup activating virtual environments conditional on hostname.

Until recently I've been using...

(pyvenv activate "~/.virtualenv/default")

...across all hosts, but because work laptop is locked down and stuck on an old (3.6.9) version that isn't going to get updated any time soon and I've have started using features of Python 3.8.3 I've switched to using the Conda Virtual Environment which is installed in ~/.miniconda3.

I've read a few threads and based on this and this I could write an if statement. However, I prefer the solution here, so I've started with...

(setq virtualenv-byhost
      '(("kimura" . "~/.virtualenvs/python3_9")
       ("work" . "~/.miniconda3/")))

Next step though has me a little stumped since I'm still getting started with Lisp and haven't sat down and started learning it formally.

  (assoc system-name virtualenv-byhost)))

If I understand it (assoc system-name virtualenv-byhost) associates whatever system-name returns with the virtualenv-byhost, but how does it know which to pick and pass onto the parent pyvenv-activate? Is that what cdr is doing and if so what is it doing and how?


You can figure this one out on your own by using C-x C-e to evaluate the individual forms. For example if you place point after system-name and hit C-x C-e, it will display your hostname (say, "kimura") in the echo area. If you reposition point after (assoc system-name virtualenv-byhost), it will display ("kimura" . "~/.virtualenvs/python3_9"). Repeating this with point after (cdr (assoc system-name virtualenv-byhost)) will display "~/.virtualenvs/python3_9". From this you can deduce that pyenv-activate receives a string denoting the path associated with the host name.

One more thing to use here is F1 v to inspect variables and F1 f to inspect functions. It will tell you that system-name holds the hostname, assoc looks up a pair in an association list (which virtualenv-byhost happens to be) and cdr returns the tail of a pair. Once you learn the Lisp basics, you'll be able to figure out everything that way, by using the Emacs introspection, evaluation and documentation facilities on everything you don't know yet.

  • Now that is some really useful information that I'm going to be able to use time and time again, thank you for the clear explanation @wasamasa – slackline Oct 12 '20 at 13:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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