Add warnings for those custom functions that are similar but different from built-in magic functions
Description
While programming recently, I ran into a bug or feature that took me a long time.
It looks like this
class base:
'''
a lot of functions here
'''
def __str__(self):
if type(self)==base:
return 'Base'
else:
return 'Error'
'''
a lot of functions here
'''
'''
a lot of codes here
'''
class myclass(base):
'''
a lot of functions here
'''
def __str___(self):
return 'Expected'
'''
a lot of functions here
'''
print(myclass())
Output:
"Error"
Finally, I found that the function myclass.__str__ had one more _, and the compiler does not report an error or warning.
For example, character â\tâ and character â â look the same, and it is difficult to find the difference.
But if we do not distinguish between these two characters, it may cause fatal errors.
Suggestion
In my opinion, when inheriting or overloading, if two functions have similar names, the compiler should give a warning or an error.
Having the language give warnings to things that might be a problem seems like a recipe for users turning off those warnings and be generally annoyed that they have to do that.
Wouldnât this type of warning make a lot more sense in a linter?
As @notatallshaw indicated, youâre likely to get bad behavior from people. I think a better place for such warnings would likely be in static analyzers like pylint.
Surely PEP 698 will have no effect unless you actually run a type checker?
Weâve all done this, but it isnât a big deal. There is an infinite number of ways to misspell methods. The case of âtoo many or too few underscores on a dunderâ is not special enough to build it into the language itself. Developers can protect against this in at least five ways:
pay more attention to the code they are writing;
use TDD and unit tests to verify their code is working;
use a linter;
use code review to get more eyeballs looking for errors in the code;
use an IDE or programmerâs editor with syntax highlighting that highlights misspelled dunders (e.g. __len___).
There is no need to burden the interpreter with trying to guess whether you have added an extra underscore or not.
If existing linters donât already check for this case, they should.