Archive for April, 2019

Python 3 Iterable Unpacking Catch-all

I’m one of those terrible people that still haven’t switched over to using Python3 …just yet. But one thing that pleasantly surprised me recently was learning of the “new” starred expression catch-all that can be used when unpacking iterables. This lets you use up to one starred expression to receive the rest of the items of an iterable during an unpacking assignment.

full_name = "Steven W J Brown"

#python2
names             = full_name.split()                # ['Steven', 'W', 'J', 'Brown']
first, last       = names[0], names[-1]              # 2.A: ignore middle names
first, mids, last = names[0], names[1:-1], names[-1] # 2.B: store middle names

#python3, 
first, *_, last    = full_name.split() # 3.A: ignore middle names
first, *mids, last = full_name.split() # 3.B: store middle names

It’s easy to read, eliminates the need for an intermediary variable and makes the code cleaner. And it can be used in loops. More details here: PEP 3132. Love it.

I really have to start re-configuring my environments for python3….

Org-mode: Indirect Buffer, Narrowing to tree

Here’s a really quick Emacs Org-mode tip that I find extremely useful.

In your config add the following two lines:

(setq org-indirect-buffer-display 'new-frame)
(setq org-src-window-setup 'other-frame)

(Or just run it in your scratch buffer to try it out for your current session.)

The first line sets the org-indirect-buffer-display variable to new-frame. Now when you call org-tree-to-indirect-buffer or org-agenda-tree-to-indirect-buffer (C-c C-x b) from an Org buffer or an Org agenda item, Emacs will create a new frame narrowed to that Org sub-tree. I find this much more useful than the default other-window as I usually operate with one frame vertically split with two windows, and like to maintain manual control over the contents of the windows.

Similarly, I like a frame-focused behaviour when editing literal source blocks, which is what the second line sets. While in an Org source block, calling org-edit-special (C-c ' ) will open a new frame narrowed to the current source block and in the appropriate major mode (python-mode, for example). The variable for this setting is org-src-window-setup.

To see the documentation for either variables, use the Emacs help system! (C-h v variable-name)

See also: Emacs Indirect-Buffers, Emacs Buffer Narrowing, org-narrow-to-subtree