Magic Methods in Python can be Risky
bad
first_names = ["eve", "lisa", "robert", "paul", "alice"]
if first_names.__contains__("robert"):
print("list of first names contains robert")
good
example 1
first_names = ["eve", "lisa", "robert", "paul", "alice"]
if "robert" in first_names:
print("list of first names contains robert")
this example illustrate the work around for the bad example above: the __contains__ method is still called, but in background through the use of python high level mechanism, for which magic methods are intended to be used.
example 2
class child_class(parent_class):
def __init__():
super().__init__()
def __contains__(arg1, arg2):
parent_class.__contains__(arg1)
print(arg2)
in this example, the call to super().__init__() and parent_class.__init__() are not violation because its a call of parent’s method in a context of respectively overriding and overloading
Â
Â
Why you should care
Magic methods (starting and ending with two underscores) should not have to be called directly unless you’re overriding a method of the same name. Magic methods are used to implement specific protocols and are called for you, either due to operator access or due to some special operation.
Business Impacts
CAST recommendations
References
https://www.quantifiedcode.com/knowledge-base/correctness/Avoid%20calling%20magic%20methods/7dz67uIe
About 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.