Search code examples
pythonfunctionprivate-methodspython-chess

Why only call a private function in a public function?


I was wandering in the source code of the fabulous python-chess library when I saw the following code:

def _reset_board(self):
    # code...

def reset_board(self):
    self._reset_board()

The reset_board() function only does one thing, call its private counterpart. Is there a reason behind this? Wouldn't putting the code directly in the private function be faster due to python not have to resolve the name _reset_board()?


Solution

  • _reset_board exists so it can be called from both reset_board and __init__. __init__ can't call self.reset_board, because that method is overridden in subclasses, and __init__ wants to call the specific _reset_board implementation from its own class. (Subclass reset_board implementations may depend on initialization that hasn't happened yet, among other problems.)