Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I put utility functions in my Python project?

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?

like image 489
Chetan Avatar asked Jun 15 '10 22:06

Chetan


2 Answers

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.

like image 53
Evan Plaice Avatar answered Oct 02 '22 13:10

Evan Plaice


If you don't want to make it a member of the Table class you could put it into a utilities module.

like image 37
Andrew Hare Avatar answered Oct 02 '22 12:10

Andrew Hare