Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 11661

How to avoid calling expensive methods in parent if child doesn't override parent's method

$
0
0

I have a base class which has several derived classes. Some of the derived classes override a parent method which does nothing. If the derived class has overridden the base method then the parent class needs to do some expensive preparation. I want to avoid doing the expensive preparation if the derived class hasn't actually overridden the base method to do anything. There's also some tidy up I'd like to avoid.

He's a simplified example:

class MyBase:    def some_work(self):        file = self._do_expensive_preparation()        self._do_work(file)        self._do_tidy_up()    def _do_expensive_preparation(self) -> Path:""" Do some time consuming preparation. Return a file. """    def _do_work(self, file: Path):""" Parent class does nothing """        def _do_tidy_up(self):""" Tidy up if _do_expensive_prepation was called """class DerivedA(MyBase):""" This class doesn't implement _do_work (though it does others things which are omitted) """class DerivedB(MyBase):    def _do_work(self, file: Path):""" Do some work """        # Do something with file

I could make the derived class call the preparation and tidy up classes but then I'd need to make all derived classes get this right (and I'm not maintaining them all).

Or I could do something like:

    def some_work(self):        if self._do_work != MyBase._do_work:            self._do_expensive_preparation()            self._do_work()            self._do_tidy_up()

neither of these seem great.

Additionally it would be nice if there was a context manager to ensure _do_tidy_up is called.

Is there an elegant solution to this?

I'm using Python 3.11 if that makes a difference.


Viewing all articles
Browse latest Browse all 11661

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>