I am working on a project in Python using the Object Oriented paradigm.
I have two utility functions that do not semantically fit in my class since they are generic and can be re-used across different classes and indeed, different projects. I'd like them separate to ensure maximum reusability (following the Don't Repeat Yourself (DRY) Principle).
One function takes a sequence of dictionaries and merges them using a dict comprehension:
def mergedict(dictionaries):
return {
k:v
for d in (dictionaries)
for k, v in d.iteritems()
}
Another takes a string and returns its integer value or 0
if it isn't numeric.
def getint(s):
try:
i = int(float(s))
except ValueError:
i = 0
return i
For these types of functions, should I:
- Define a utility class with static methods (which seems like a misuse of the OOP paradigm)
- Define them as functions in a module (maybe have a module for each type e.g. string_utils, dict_utils etc)
- A better way?
I'm struggling to determine the best semantic placement for such functions. getint()
could be a method of a class that is a wrapper of Python strings but mergedict()
seems more vague.
How have others handled this type of issue, possibly in a manner that retains OOP purity?
Aucun commentaire:
Enregistrer un commentaire