python-mode addition: an elisp function for super-call insertion

Erwin S. Andreasen erwin at andreasen.com
Thu Aug 22 11:44:13 EDT 2002


Here's an elisp function (tested in xemacs 21 and emacs 21) that will
insert the proper call to super when used inside a method. For example
in code like this:

class Derived(Base):
  defun method(self, args):
    X

whilst standing at "X", calling py-insert-super will insert:
    super(Derived, self).method(args)


(defconst py-method-start-re
    "^[ \t]*def[ \t]+\\([a-zA-Z_0-9]+\\)[ \t]*([ \t]*\\([a-zA-Z_0-9]+\\)[ \t]*,?[ \t]*\\([^:]+\\)"
  "Start of a def, matches name in #1, name of self in #2 and the rest in #3,
 up to but excluding :")

(defun py-insert-super ()
  "When used inside a def of a class, insert a call using super to the
super-method of this class, e.g. super(Classname, self).method(args)."
  (interactive "*")
  (let* ((class-name (save-excursion
		       (re-search-backward py-class-start-re) (match-string 1)))
	 (method-name (save-excursion
			;; Ensure that we won't search past the beginning of class
			(re-search-backward py-method-start-re
					    (match-end 1)) (match-string 1)))
	 (self-name (match-string 2))
	 (method-args (match-string 3)))
    ;; Clean up method-args for default values. This is not perfect;
    ;; it will not correctly catch x=[1,2,3] but will stop at the
    ;; first comma
    (while (string-match "[ \t]*=[ \t]*?[^,)]+" method-args)
      (setq method-args (replace-match "" t t method-args)))
    (indent-for-tab-command)
    (insert-string (format "super(%s, %s).%s(%s"
			   class-name self-name method-name method-args))
    (newline-and-indent)))



Note that different names for "self" will be correctly handled but class or
defuns split over several lines using \ or  more complex default
arguments won't be handled. Default arguments are handled by removing
characters that follow = until a ) or : is met, thus they will fail on
e.g. l=[1,2,3].



-- 
===============================================================
<erwin at andreasen.org>                           Herlev, Denmark     
<URL:http://www.andreasen.org/>                             <*>   
===============================================================




More information about the Python-list mailing list