I heard from one guy that you should not use magic methods directly. and I think in some use cases I would have to use magic methods directly. So experienced devs, should I use python magic methods directly?
Should Python Magic Methods Be Used Directly?
magic-methodspython
Best Answer
I intended to show some benefits of not using magic methods directly:
1- Readability:
Using built-in functions like
len()
is much more readable than its relevant magic/special method__len__()
. Imagine a source code full of only magic methods instead of built-in function... thousands of underscores...2- Comparison operators:
I haven't implemented
__gt__
for neither of those classes, but ind > c
when Python sees that classD
doesn't have__gt__
, it checks to see if classC
implements__lt__
. It does, so we get'__lt__ called'
in output which isn't the case withd.__gt__(c)
.3- Extra checks:
or:
As you see, when Python calls that magic methods implicitly, it does some extra checks as well.
4- This is the least important but using let's say
len()
on built-in data types such asstr
gives a little bit of speed as compared to__len__()
:output:
It's because of the lookup process(
__len__
in the namespace), If you create a bound method before timing, it's gonna be faster.