I have been a Python Scientific Programmer for a few years now, and I find myself coming to a sort specific problem as my programs get larger and larger. I am self taught so I have never had any formal training and spent any time really on 'conventions' of coding in Python "properly".
Anyways, to the point, I find myself always creating a utils.py file that I store all my defined functions in that my programs use. I then find myself grouping these functions into their respective purposes. One way of I know of grouping things is of course using Classes, but I am unsure as to whether my strategy goes against what classes should actually be used for.
Say I have a bunch of functions that do roughly the same thing like this:
def add(a,b):
return a + b
def sub(a,b):
return a -b
def cap(string):
return string.title()
def lower(string):
return string.lower()
Now obviously these 4 functions can be seen as doing two seperate purposes one is calculation and the other is formatting. This is what logic tells me to do, but I have to work around it since I don't want to initialise a variable that corresponds to the class evertime.
class calc_funcs(object):
def __init__(self):
pass
@staticmethod
def add(a,b):
return a + b
@staticmethod
def sub(a, b):
return a - b
class format_funcs(object):
def __init__(self):
pass
@staticmethod
def cap(string):
return string.title()
@staticmethod
def lower(string):
return string.lower()
This way I have now 'grouped' these methods together into a nice package that makes finding desired methods much faster based on their role in the program.
print calc_funcs.add(1,2)
print format_funcs.lower("Hello Bob")
However that being said, I feel this is a very 'unpython-y' way to do things, and it just feels messy. Am I going about thinking this the right way or is there an alternate method?
__init__.py
– Magicaltypes.ModuleType
(or retrieve this very type from some module object, e.g.ModuleType = type(sys)
but you shouldn't it doesn't make sense to do that, you can just use something like atypes.SimpleNamespace
or any other data structure. using a class with@staticmethod
isn't a workaround, that's just silly, the point of classees isn't to group methods. it's to define types – Magical