Equivalent of NotImplementedError for fields in Python Equivalent of NotImplementedError for fields in Python python python

Equivalent of NotImplementedError for fields in Python


Yes, you can. Use the @property decorator. For instance, if you have a field called "example" then can't you do something like this:

class Base(object):    @property    def example(self):        raise NotImplementedError("Subclasses should implement this!")

Running the following produces a NotImplementedError just like you want.

b = Base()print b.example


Alternate answer:

@propertydef NotImplementedField(self):    raise NotImplementedErrorclass a(object):    x = NotImplementedFieldclass b(a):    # x = 5    passb().xa().x

This is like Evan's, but concise and cheap--you'll only get a single instance of NotImplementedField.


A better way to do this is using Abstract Base Classes:

import abcclass Foo(abc.ABC):    @property    @abc.abstractmethod    def demo_attribute(self):        raise NotImplementedError    @abc.abstractmethod    def demo_method(self):        raise NotImplementedErrorclass BadBar(Foo):    passclass GoodBar(Foo):    demo_attribute = 'yes'    def demo_method(self):        return self.demo_attributebad_bar = BadBar()# TypeError: Can't instantiate abstract class BadBar \# with abstract methods demo_attribute, demo_methodgood_bar = GoodBar()# OK

Note that you should still have raise NotImplementedError instead of something like pass, because there is nothing preventing the inheriting class from calling super().demo_method(), and if the abstract demo_method is just pass, this will fail silently.