This elisp code creates a key binding which inserts a new-style call to the base class method (using super) with the appropriate class and method name. For instance, if the point is inside method __init__ in class Widget, typing C-c C-f will insert the text "super(Widget,self).__init__()".
Requires Emacs and python-mode.el.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | ;; This code can go into the .emacs file
;; This works with python-mode.el version 1.0
(defun py-insert-super ()
(interactive)
(let (methodname classname)
(save-excursion
(or (py-go-up-tree-to-keyword "def")
(error "Enclosing def not found"))
(or (looking-at "[ \t]*def[ \t]+\\([a-zA-Z0-9_]+\\)")
(error "Can't determine method name"))
(setq methodname (match-string 1))
(or (py-go-up-tree-to-keyword "class")
(error "Enclosing class not found"))
(or (looking-at "[ \t]*class[ \t]+\\([a-zA-Z0-9_]+\\)")
(error "Can't determine class name"))
(setq classname (match-string 1)))
(insert (format "super(%s,self).%s()" classname methodname))
(backward-char)))
;; Add a hook to bind a key to this function for Python buffers
(defun bind-super-key ()
(local-set-key "\C-c\C-f" 'py-insert-super))
(add-hook 'python-mode-hook 'bind-super-key)
|
One of the more annoying things about the new-style classes is the new-style way to call base class methods. The new-style base method invocation looks like this:
super(ClassName,self).method_name(*args)
This unwieldiness is perhaps partly responsible for many people retaining the old-style method, even though the old-style method invocation can cause problems in MI situations.
Emacs to the rescue.
Now, users of python-mode.el (but not python.el, which ships with Emacs 22) can insert the base method call by typing C-c C-f, which calls th elisp function py-super-insert, which inserts a call to super with the appropriate class and method names in place. The args are not inserted by this function (they aren't necessarily the same as the derived method's arguments); however, the cursor is helpfully left in position to type arguments in.
I chose the key binding "\C-c\C-f" because it resembled a major-mode binding and it wasn't already in use. Feel free to use whatever key you like; you wouldn't be an Emacs user if you've never thought of changing a key binding.