对 python 源文件中的类定义进行排序的最佳方法是什么?
我有一个包含许多类定义的 .py 源代码,如下所示:
class C:
# code c
class A:
# code a
class B:
# code b
我想将其转换为:
class A:
# code a
class B:
# code b
class C:
# code c
有这样做的工具吗?用 emacs 来做怎么样?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我同意 bobince 的观点,即字母顺序并不是对函数或其他代码进行排序的有用方法,但您可以尝试一下
sort-paragraphs
。它甚至可能有效。如果没有,那么我可以通过查看
sort-paragraphs
的实现来发现它是这样做的:我打赌您可以想出一些插入其中的函数来使其工作。第一个将点移动到下一条记录的开头,第二个将点移动到当前记录的末尾。函数有一些可选参数,可以告诉它排序键在记录中的位置,这也可能会派上用场。
这些函数在sort.el中;您可以使用 Ch f sort-paragraphs 和 Ch f sort-subr 来获取它们的文档;这将包括源链接。
玩得开心 :)
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: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
andC-h f sort-subr
to pull up the documentation for them; this will include a link to the source.Have fun :)
我为您编写了它,但只是因为我有兴趣了解
sort-subr
的工作原理。我不宽恕最初问题的意图。 :)另外,如果您赞成这个答案,请也赞成@db48x 的说教答案。
使用 python-sort-defs 的方式与使用
sort-paragraph
的方式相同。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
.按字母顺序排序对于测试代码是有意义的。对于包含许多特定测试的测试用例,某些测试(或者可能只是测试名称)将被重复。在重复数据删除之前,按字母顺序对测试进行排序是一个好主意。
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.