+(defun python-nav--syntactically (fn poscompfn &optional contextfn)
+ "Move point using FN avoiding places with specific context.
+FN must take no arguments. POSCOMPFN is a two arguments function
+used to compare current and previous point after it is moved
+using FN, this is normally a less-than or greater-than
+comparison. Optional argument CONTEXTFN defaults to
+`python-syntax-context-type' and is used for checking current
+point context, it must return a non-nil value if this point must
+be skipped."
+ (let ((contextfn (or contextfn 'python-syntax-context-type))
+ (start-pos (point-marker))
+ (prev-pos))
+ (catch 'found
+ (while t
+ (let* ((newpos
+ (and (funcall fn) (point-marker)))
+ (context (funcall contextfn)))
+ (cond ((and (not context) newpos
+ (or (and (not prev-pos) newpos)
+ (and prev-pos newpos
+ (funcall poscompfn newpos prev-pos))))
+ (throw 'found (point-marker)))
+ ((and newpos context)
+ (setq prev-pos (point)))
+ (t (when (not newpos) (goto-char start-pos))
+ (throw 'found nil))))))))
+
+(defun python-nav--forward-defun (arg)
+ "Internal implementation of python-nav-{backward,forward}-defun.
+Uses ARG to define which function to call, and how many times
+repeat it."
+ (let ((found))
+ (while (and (> arg 0)
+ (setq found
+ (python-nav--syntactically
+ (lambda ()
+ (re-search-forward
+ python-nav-beginning-of-defun-regexp nil t))
+ '>)))
+ (setq arg (1- arg)))
+ (while (and (< arg 0)
+ (setq found
+ (python-nav--syntactically
+ (lambda ()
+ (re-search-backward
+ python-nav-beginning-of-defun-regexp nil t))
+ '<)))
+ (setq arg (1+ arg)))
+ found))
+
+(defun python-nav-backward-defun (&optional arg)
+ "Navigate to closer defun backward ARG times.
+Unlikely `python-nav-beginning-of-defun' this doesn't care about
+nested definitions."
+ (interactive "^p")
+ (python-nav--forward-defun (- (or arg 1))))
+
+(defun python-nav-forward-defun (&optional arg)
+ "Navigate to closer defun forward ARG times.
+Unlikely `python-nav-beginning-of-defun' this doesn't care about
+nested definitions."
+ (interactive "^p")
+ (python-nav--forward-defun (or arg 1)))
+