6

I am starting to write a big python library for some area of mathematics.

So I have this data structure (defined in class A) which represents a mathematical model.

I have a bunch of smaller functions, which I have put in A:

A.f(), A.g(),...

Which are more or less "helper functions" that are needed to calculate more important functions A.X(), A.Y(),... which the end user is interested in.

All of these functions of course depend on the data in A.

But the number of methods in A is growing and growing and getting confusing. How does one split such a class into smaller pieces. Lets say, the data structure with basic operations in it and the "methods" that do calculations on the structure?

What is the usual approach and the most pythonic approach?

Jake B.
  • 435
  • 3
  • 13

2 Answers2

4

You can use pure functional approach and move methods that class users are not supposed to call on object instance to separate files.

In pure functional approach the functions don't depend on any internal state, have no side effects and calculate the return value based only on the arguments provided.

An example for illustration would be replacing the following:

# shape.py
class Shape:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def area(self):
        return self.x * self.y

with:

# shape.py
class Shape:

    def __init__(self, x, y):
        self.x = x
        self.y = y

# func.py
def area(shape):
    return shape.x * shape.y

Of course, it might be not a good idea to extract area method of the Shape class into a separate function in another file, but you can definitely move all "helper functions" to separate files and call them properly from the class methods.

This will also greatly simplify helper function testing.

krl
  • 5,087
  • 4
  • 36
  • 53
0

It is a convention to prefix "private" or helper methods that are not part of the public interface of a class with single or double underscores.

One effect is for example that methods like _my_helper are not shown when help is invoked on the class.

More details are given in this post.

Community
  • 1
  • 1
mkrieger1
  • 19,194
  • 5
  • 54
  • 65