Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to visually group class methods into sections?

Tags:

python

I am a little on the pedantic side when it comes to organizing my code, so I've tried coming up with ways to visually group my class methods into logical parts/sections. My question is whether there are any preferable ways to visually separate class method groups in Python editors?. PEP8 doesn't mention this non-issue so I'm not sure how to do this "correctly".

I guess this desire comes from my Xcode usage where I would add #pragma mark - XY to separate the method sections. I'm using Sublime Text for Python, are there editors or IDEs that support a certain style of grouping?

So an example grouping that I'm currently using is to have logically similar methods one below each other but add more whitespace and a horizontal line (until it hits the 80 char border) between the "groups", like so:

class Foo (object):
    def __init__(self)
    
    # ------------------------- Properties
    @property
    def foo(self)
    @property
    def bar(self)
    
    # ------------------------- Querying
    def find(self, id)
    def find_siblings(self)
    def find_related(self, attr)
    
    # ------------------------- Class Methods
    @classmethod
    def setup(cls)
    @classmethod
    def purge_cache(cls)
    
    # ------------------------- Utilities
    def __str__(self)
    def __unicode__(self)
    def __repr__(self)
like image 953
Pascal Avatar asked May 21 '26 08:05

Pascal


1 Answers

One useful method is to use a long docstring on the class itself that logically groups the methods, see PEP 258

In this case you would do something like:

class MyClass():
   """
   This class provides a number of methods grouped accordingly:
      Methods to do with a:
       - a_do_something - Quick Summary
       - a_do_something_else - Quick Summary
      Methods to do with b:
       - b_do_something - Quick Summary
       - b_do_something_else - Quick Summary
   """
   def __init__(self):
       """ Initialise MyClass """
       pass  # More likely some code

   if True:  # Allow group folding for Functional Group A
   ## 
   ## The following functions and class methods are to do with a:
   ## 
       def a_do_something(params):
          """ Quick Summary

          Parameters:
              Describe Each
          Returns:
              What

          Long description text.
          """
          pass # really the code for this function

etc.

However you may wish to consider breaking any code that is long enough to need this into more classes and grouping things that way.

like image 64
Steve Barnes Avatar answered May 22 '26 21:05

Steve Barnes