Add warning for those custom functions that are similar but different from built-in magic functions

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.

def __func__:# '_'*2+'func'+'_'*2
    pass
def _func___:# '_'*1+'func'+'_'*3
    pass
def __func__:
    pass
def _func___:
    ^^^^^^^^
Unanticipated consequences

End

Most sentences are translated by Google, please forgive me if there are any inconsistencies.

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?

The upcoming PEP 698 (PEP 698: Override Decorator for Static Typing (`@typing.override`) by stroxler ¡ Pull Request #2783 ¡ python/peps ¡ GitHub) will provide one way to detect issues like this.

2 Likes

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.

1 Like

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.

1 Like