DUDANF
DUDANF

Reputation: 2990

Organising utility functions

This is more of a best practice question than a coding question. I have written a project, within the project I have some "helper functions". I have put them into a separate class and each function is a @staticmethod

My colleague believes I shouldn't have it as a class and @staticmethod and should simply have them as a module. Import the model into my code, and work directly with the functions instead of instantiating the class.

I'm uncertain and so decided to ask a question on SO.

myproject/
├── actual_code/
│   └── main.py
└── utils/
    └── helper_funcs.py

Q. Should helper_funcs.py be a class or just a file with funcs?

Currently:

class HelperFuncs():

    @staticmethod
    def first_util():
        print("first")

Colleague proposed, simply:

def first_util():
    print("First")

Upvotes: 2

Views: 2747

Answers (1)

John Kugelman
John Kugelman

Reputation: 361605

Your co-worker is right. There's no point in having a class with a bunch of static methods. Thinking you always need a class is a bad habit carried over from Java or C# where everything needs a class. It's not idiomatic in Python.

Python is like C++. Freestanding methods are not only permissible, they are often preferred. Use a module to group related methods together, not a nominal class.

Also, you don't need separate directories.

myproject/
└── src/
    ├── main.py
    └── utils.py

Upvotes: 4

Related Questions