flet, cl-flet and Dynamic/Lexical Binding

This is a post for Elisp programmers who have some Common Lisp (CL) experience. One nice feature of CL is the flet macro that lets you temporarily bind a function lexically. Emacs Lisp also has a flet in the cl library but it’s slightly different in that the binding is dynamic. If you’re not clear on what that means Chris Wellons has a nice discussion of the difference and a practical example of why the difference matters.

In Emacs 24.3 the cl-lib library was introduced to replace the cl library. Mostly that amounted to renaming the functions to have a ‘cl-’ prefix but cl-flet differs from flet in that the binding is lexical as in Common Lisp. In general, that’s a good thing because it makes Elisp consistent with CL as far as flet is concerned and is almost always the desired behavior. It turns out, though, that the old behavior was useful in certain circumstances such as stubbing out functions during testing.

Happily, there’s an easy solution. Both Wellons and Artur Malabarba explain the problem and the solution. Malabarba’s post is short and to the point while Wellons explains things in more detail. If you’re a serious Elisp programmer you should definitely read both posts. There’s a lot of confusion about flet and cl-flet and the two posts linked above do an excellent job of clearing things up.

Update [2017-12-22 Fri 13:36]: flex → flet; cl-flex → cl-flet

This entry was posted in General and tagged , . Bookmark the permalink.