I have a file that meant to be an utility file. The file should contain alot of static methods.
Should i define the methods inside a class this way:
#utility.py
class utility(object):
@staticmethods
def method1(a,b,c):
pass
@staticmethods
def method2(a,b,c):
pass
or use it like this (without a class):
#utility.py
def method1(a,b,c):
pass
def method2(a,b,c):
pass
The second option is the modus operandi in Python. I mean, if all you're doing is importing functions, then you can do something like this:
which will import your function.
Best practice is if you're using only static functions, then just put them in the global namespace of a separate module, it will make your life a lot easier. What you're trying to do is make objects and just fill them in with static methods. Why do this, when you can just define the functions in a
.py
file?In fact, what you're trying to do has been done. You're trying to store away some good utility functions. Well,
python-requests
, is a third party library that is just adored by the majority of Pythonistas just does this. It stores away its good utility functions in a separate module. Here is the example.Classes encapsulate both data, and behavior, so as general rules:
namedtuple
, not aclass
, unless you need to modify that data after creating it.@classmethod
.@staticmethod
.class
only has one method, or one method in addition to__init__()
, then you almost certainly can and should rewrite it as a function.Classes are really easy to abuse, but the temptation to shove everything into a class should really be avoided. You should use them when they make sense, and avoid using them when they don't.
While this question is a little opinion based, I'd say the second one is better. It reduces redundancy. Using the first method, you will have to do:
or:
Using the second one however allows you to simply do:
or:
If you are making a class that only contains static methods, my question is "why do you need the class?" It contributes nothing positive here.