0

I want to force a child class to implement or override all of the inherited methods from a parent class, but I want to allow the parent class to be instantiated. Therefore, I need the parent class to have a proper implementation rather than simply raising NotImplementedError exceptions.

If a child class does not override all of its parent's methods, I want the Python interpreter to scream at me.

For example:

    class Parent:
      # This __init__() doesn't matter, I can change it to whatever
      def __init__(self):
          pass
    
      def foo(self):
        print("Parent::foo()")
    
      def bar(self):
        print("Parent::bar()")
    
    class Child(Parent):
      # This __init__() doesn't matter, I can change it to whatever
      def __init__(self):
        pass
      
      # The interpreter should complain about a missing override for foo()
    
      def bar(self):
        print("Child::bar()")
    
    # Parent cannot be abstract because I want to instantiate
    parent = Parent()
    
    # As soon as I create the Child object, or even before, I want the
    # interpreter to stop me due to the missing override for Parent::foo()
    child = Child()

I would prefer an approach geared towards Python 2 since that's what I use at work, but I would be glad and happy to read any approach for Python 3 because that's what I use at home.

FriskySaga
  • 409
  • 1
  • 8
  • 19
  • The use case would be that someone adds a new function to a parent class, but they forget to add a function for a child class. In hindsight, I think the overall design pattern I was aiming for could be reworked such that I wouldn't have this issue. – FriskySaga Aug 23 '20 at 19:23
  • The Python compiler? Python is an interpreted, dynamic language. Static type checking, especially with version 2, will have to rely on external tools and be of questionable value. – Jan Wilamowski May 19 '21 at 06:47
  • @JanWilamowski Python can be compiled. See https://stackoverflow.com/questions/471191/why-compile-python-code and https://stackoverflow.com/questions/6889747/is-python-interpreted-or-compiled-or-both That said, whether you want to label it as an interpreter compiling code doesn't really matter to me because that's not the point of the post. I was moreso asking a theoretical question. I wanted to know if something like that existed. – FriskySaga May 21 '21 at 01:05
  • "The use case would be that someone adds a new function to a parent class, but they forget to add a function for a child class." But why is that a problem? It's perfectly normal for a child class to only implement a small subset of the methods available on a parent. – larsks Sep 07 '21 at 00:56
  • @larsks It's been so long that I honestly don't remember why exactly I needed this and what I chose for a workaround. I edited the my post yesterday to get rid of some irrelevant filler in case someone ever looks up this question in the future. – FriskySaga Sep 08 '21 at 02:28

0 Answers0