-The dunder methods (special methods, magic methods, etc... methods of the form _ _ method _ _ ) are basically responsible for the huge amount of syntactic sugar that Python presents, which is largely what makes the language is so simple, because with the title I do not mean to use them and therefore overwrite them, but to create them from 0 no matter how difficult it may be, if this is not possible, I would like you to clarify why...
The dunder methods are "special" because the Python interpreter itself uses them under certain conditions. They are part of your " data model " and therefore of the language specification.
When for example the interpreter finds
a+b
, what it will do is invokea.__add__(b)
. That translation of+
en__add__()
is "embedded" in the Python interpreter implementation itself.If what you are proposing is something like, for example, defining a new operator, let
??
's call it so that before an expression likea ?? b
a dunder method will automatically be executed, let 's call__doublequestion__()
it , the short answer would be that it is not easy to do that. And I explain.In order to do that you would need:
??
??
before anything else, like the**
exponentiation operator, or is it always executed last, with the bitwise logic operators&
,|
,~
?NotImplemented
??
is necessary. Write a PEP detailing why, code examples showing how things were done before you invented that operator and how things will be done after, showing that the language is improved in simplicity or expressiveness by your addition.If you don't do 4, even though all of the above is technically possible, you'll end up with something that isn't Python, because it doesn't follow the language specification. It would be your own private use python.
Therefore, as you can see, the question is not if it is possible but if it is worth it . why would you want to do something like that? Keep in mind that the Python data model is very rich and already allows you to redefine lots of operators, do you really need a new one? The Python developer community is pretty reluctant to include them, and it has to be for very good reasons. For example, it has already happened in the past with the operator
@
, because it was thought that it could be useful for packages likenumpy
and others for matrix algebra, as a way of representing the product between matrices (proposed in PEP 465, finally implemented in Python 3.5). That operator is not implemented in any of the standard Python types, but is available to be implemented in the special method__matmul__()
.