Where do I put utility functions in my Python project?

Chetan picture Chetan · Jun 16, 2010 · Viewed 10.6k times · Source

I need to create a function to rotate a given matrix (list of lists) clockwise, and I need to use it in my Table class. Where should I put this utility function (called rotateMatrixClockwise) so I can call it easily from within a function in my Table class?

Answer

Evan Plaice picture Evan Plaice · Jun 17, 2010

Make it a static function...

  • add the @staticmethod decorator
  • don't include 'self' as the first argument

Your definition would be:

@staticmethod
def rotateMatrixClockwise():
    # enter code here...

Which will make it callable everywhere you imported 'table' by calling:

table.rotateMatrixClockwise()

The decorator is only necessary to tell python that no implicit first argument is expected. If you wanted to make method definitions act like C#/Java where self is always implicit you could also use the '@classmethod' decorator.

Here's the documentation for this coming directly from the python manual.

Note: I'd recommend using Utility classes only where their code can't be coupled directly to a module because they generally violate the 'Single Responsibility Principle' of OOP. It's almost always best to tie the functionality of a class as a method/member to the class.