Methods as functions tend to be unproductive
This code insight counts one violation each time a method :- has no @staticmethod decorator and no "self" as first argument
- has @classmethod decorator and no "cls" as first argument
# should be preceded by @staticmethod here
def area(width, height):
return width * height
class Rectangle:
# should be preceded by @classmethod here
# missing required first argument "cls"
def print_class_name():
print("class name: Rectangle")
good
class Rectangle:
# clarifies that this is a static method and belongs here
@staticmethod
def area(width, height):
return width * height
class Rectangle:
@classmethod
def print_class_name(cls):
# "class name: Rectangle"
print("class name: {0}".format(cls))
Why you should care
When a method is not preceded by the@staticmethod or @classmethod decorators and does not contain any references to the class or instance (via keywords like cls or self), Python raises the "Method could be a function" error. This is not a critical error, but you should check the code in question in order to determine if this section of code really needs to be defined as a method of this class.
Unlike some programming languages, Python does not pass references to instance or class objects automatically behind the scenes. So the program must explicitly pass them as arguments whenever it wants to access any members of the instance or class within a method
Business Impacts
[nz_btn text="Production Risk" target="_self" animate="false" animation_type="ghost" color="pink" size="small" shape="rounded" type="normal" hover_normal="opacity" hover_ghost="fill" link="http://casthighlight.wpengine.com/category/product/indicators-methodology/innovation/" icon="icon-office"]CAST recommendations
References
http://docs.quantifiedcode.com/python-code-patterns/correctness/method_could_be_a_function.html https://www.quantifiedcode.com/knowledge-base/correctness/Provide%20argument%20or%20%60%40staticmethod%60%20to%20method/3bECxdfcAbout CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.
For reference only. For the complete details please refer the original article
https://doc.casthighlight.com/alt_unecessarymethod-avoid-methods-that-could-be-functions/
https://doc.casthighlight.com/alt_unecessarymethod-avoid-methods-that-could-be-functions/
Comments