简体   繁体   中英

What's the best way to sort class definitions in a python source file?

I have a .py source with many class definitions, like so:

class C:
    # code c

class A:
    # code a

class B:
    # code b

I want to turn it into:

class A:
    # code a

class B:
    # code b

class C:
    # code c

Is there a tool for this? What about doing it with emacs?

I coded it for you, but only because I was interested in seeing how sort-subr works. I do not condone the intent of the original question. :)

Also, if you upvote this answer, plase also upvote @db48x's didactic answer.

Use python-sort-defs the same way you would use sort-paragraph .

(defun python-sort-defs (reverse beg end)
  (interactive "P\nr")
  (save-excursion
    (save-restriction
      (narrow-to-region beg end)
      (goto-char (point-min))
      (sort-subr reverse
                 (function
                  (lambda ()
                    (while (and (not (eobp)) (looking-at paragraph-separate))
                      (forward-line 1))))
                 'python-end-of-block-must-move))))

(defun python-end-of-block-must-move ()
  (when (eq (point) (progn
                      (python-end-of-block)
                      (point)))
    (forward-line 1)))

I agree with bobince that alphabetical order isn't a useful way to sort functions or other bits of code, but you might give sort-paragraphs a go. It might even work.

If it doesn't, then I can see by looking at the implementation of sort-paragraphs that it does this:

  (sort-subr reverse
     (function
      (lambda ()
        (while (and (not (eobp)) (looking-at paragraph-separate))
          (forward-line 1))))
     'forward-paragraph))))

I bet you could come up with some functions to plug in there that would make it work. The first one moves point to the start of the next record and the second one moves the point to the end of the current record. There are some optional arguments for functions that tell it where the sort key is within the record which might also come in handy.

These functions are in sort.el; you can use Ch f sort-paragraphs and Ch f sort-subr to pull up the documentation for them; this will include a link to the source.

Have fun :)

Sorting alphabetically would make sense in testing code. For test cases that contain many specific tests, some tests (or maybe just test names) will be duplicated. Sorting the tests alphabetically is a good idea prior to deduping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM