开发者

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

开发者 https://www.devze.com 2023-04-10 10:42 出处:网络
I have a .py source with many class definitions, like so: class C: # code c class A: # code a class B: # code b

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 t开发者_如何学Pythonhis? What about doing it with emacs?


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 C-h f sort-paragraphs and C-h f sort-subr to pull up the documentation for them; this will include a link to the source.

Have fun :)


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)))


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消