Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of NotImplementedError for fields in Python

In Python 2.x when you want to mark a method as abstract, you can define it like so:

class Base:     def foo(self):         raise NotImplementedError("Subclasses should implement this!") 

Then if you forget to override it, you get a nice reminder exception. Is there an equivalent way to mark a field as abstract? Or is stating it in the class docstring all you can do?

At first I thought I could set the field to NotImplemented, but when I looked up what it's actually for (rich comparisons) it seemed abusive.

like image 878
Kiv Avatar asked Jul 19 '09 23:07

Kiv


People also ask

What is NotImplementedError in Python?

What is the NotImplementedError? According to Python, the NotImplementedError occurs when an abstract method lacks the required derived class to override this method, thus raising this exception.

How do I fix NotImplementedError in Python?

The NotImplementedError is raised when you do not implement the abstract method in the child class. This error can be solved by using the abstract method in every child class. If we use the abstract method inside the child class, a new instance of that method is created inside the child class.

What does raise NotImplementedError () do in Python?

NotImplemented is a special value which should be returned by the binary special methods to indicate that the operation is not implemented with respect to the other type. Raise NotImplementedError to indicate that a super-class method is not implemented and that child classes should implement it.

What is Abstractmethod in Python?

An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and its abstract methods must be implemented by its subclasses.


1 Answers

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 
like image 78
Evan Fosmark Avatar answered Sep 22 '22 17:09

Evan Fosmark