Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alphabetizing functions in a Python class

Tags:

People also ask

How do you sort a class method in Python?

A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.

Does the order of classes matter in Python?

It doesn't matter in which order variables and functions are defined in Class in Python.


Warning, this is a sheer-laziness query! As my project develops, so also do the number of functions within a class. I also have a number of classes per .py file. So what I would like to do is re-sort them to that the function names are organised [sorry, UK here, I've already compromised hugely with the 'z' in Alphabetizing ;-)] alphabetically.

Eg currently:

class myClass():
    stuff
    def __init__():
        do stuff
    def b():
        also do stuff
    def c():
        do other stuff
    def a():
        do even more stuff

..and for ease of lookup, I'd like to rearrange to:

class myClass():
    stuff
    def __init__():
        do stuff
    def a():
        do even more stuff         
    def b():
        also do stuff
    def c():
        do other stuff

purely for cosmetic reasons, as it makes searching for the relevant functions more intuitive. I'd obviously want to keep the init() etc at the top of the class.

Now, I can (but haven't yet) do this with a python script that reads in the .py the class(es) reside in as a text file, and do a tonne of string manipulation. But I wonder is there a better way to do this? Perhaps there's a tool I can use somewhere? I've had a good hunt, but I can't really find anything I could use.

I'm using emacs, so perhaps there's a big 5-minute key combination sequence that will do the magic (eg), but I can't see anything in python-mode!

Finally, I would like some way to be able to visualise and publicise the class structure/docstrings.

When I say visualise structure, I mean, for example, where myClass.a() calls myOtherClass.g(), that would be a link, so I'd be able to see what calls what, either on a class-by-class basis (ie, what functions/classes does myClass use?) or overall (here are a bunch of files, how do they 'connect'?)

When I say publicise the class, I guess I mean something like the API documentation you see in eg1,eg2.