I like to create helper classes that can be used by other classes and where all methods are static (staticmethod). I need to wrap each method with a decorator @staticmethod, but this solution seems to me not very aesthetic. I decided to create a metaclass for such classes - tools, here is an abstract implementation example:
import types
import math
class StaticClass(type):
def __new__(mcs, name, bases, attr):
for name, value in attr.items():
if type(value) is types.MethodType:
attr[name] = staticmethod(value)
return super().__new__(mcs, name, bases, attr)
class Tool(metaclass=StaticClass):
def get_radius_from_area(area):
return math.sqrt(area/Tool.get_pi())
def get_pi():
return math.pi
class CalcRadius:
def __init__(self, area):
self.__area = area
def __call__(self):
return Tool.get_radius_from_area(self.__area)
if __name__ == '__main__':
get_it = CalcRadius(100)
print(get_it()) # 5.641895835477563
Everything works and gives the correct result, but there are understandable and predictable problems with code inspection in the IDE (I use Pycharm 2019.2).
for def get_radius_from_area(area): Usually first parameter of a method in named 'self'. 'area' highlighted in yellow in the return of the method.
for get_pi(): Method must have a first parameter, usually called 'self' Void in brackets with out arguments is underlined in red.
If I add the line "# noinspection PyMethodParameters" above the class this partially solves the problem, but it looks even worse than dozens of @staticmethods.
I understand why this is happening and why the developers from JetBrains specially adapt parts of the code in their IDE for Django.
But can I somehow beautifully create a purely static class, in which all methods are static? Maybe metaclasses are not the best option and is there some kind of alternative solution?
@staticmethodbeing on all your class methods, or move it all into a module. For what it's worth, I think most Python devs would disagree with your aesthetic complaints about@staticmethod. Having it on all your methods more clearly communicates your intention than any roundabout method you could come up with to make this work, and clarity is good.