Sep 22, 2021 12:21:41 PM |
Python Exception Handling – NotImplementedError
Struggling with a NotImplementedError in your code? In this blog, we’ll go over what it is, how to raise it, and how to handle it.
Today, we’re making our way through our in-depth Python Exception Handling series, and we’ll dive into the NotImplementedError in Python. The NotImplementedError is commonly raised when an abstract method is not implemented in a derived class.
Throughout this post, we’ll examine the NotImplementedError in more detail, starting with where it sits in the larger Python Exception Class Hierarchy. We’ll also look at raising this error, how to handle it, and how Airbrake can help you find this error quickly.
Hierarchy
Like most Python errors, the NotImplementedError derives from the BaseException, more specifically from the RuntimeError class.
- BaseException
- RuntimeError
- NotImplementedError
- RuntimeError
The NotImplementedError is, fortunately, a non-fatal error. It won’t stop your application from running, but it’s always best to clear errors before they cause issues.
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.
Let’s break this down a bit.
While it doesn’t provide abstract classes, Python allows you to use its module, Abstract Base Classes (ABC). Abstract classes are helpful because they create blueprints for other classes and establish a set of methods.
An Abstract Base Class includes one or more abstract methods (methods that have been declared but lack implementation). Subclasses, or child classes, are necessary to implement these abstract methods.
To summarize, you’ll see the NotImplementedError two reasons:
- When you need a derived class to override the abstract method
- When the implementation is still missing
Now that you know what a NotImplementedError is and why it happens, here’s what you need to do to raise this exception.
How to Raise a NotImplementedError Exception
The NotImplementedError is part of Python’s BaseException, meaning it is a built-in exception. Like with all BaseExceptions, you can raise a NotImplementedError exception.
Raise the NotImplementedError like so:
It’s that simple. But imagine having to raise every exception in a similar fashion manually? It’s a time-consuming process. Save time and find Python errors more quickly with Airbrake Error Monitoring.
How to Handle a NotImplementedError
If you run into the NotImplementedError, the recommended way to handle it is to implement the abstract method for which the error is being raised. Because the NotImplementedError is user-defined, Python can’t raise this error on its own. So, you’ll need to raise it by a package you’re using or code your team wrote. Once you’ve raised it, you can then implement whatever’s missing.
Let’s refer back to this screenshot:
In its current form, you’ll raise a NotImplementedError. All you need to do to handle this error is implement the howl function by a subclass before it’s used.
That’s it!
Why Use Airbrake Error Monitoring
Want to be alerted about errors within your application? Airbrake Error Monitoring and Performance Monitoring provides real-time alerts about any Python errors in your code. Airbrake alerts will tell you:
- When an unhandled Python error occurs
- Where an error exists, right down to the line of code
- The number of occurrences of an error
- New deploys that introduce errors
- Data about an error via the aggregations’ tab
See for yourself how powerful Airbrake is with a free dev account. For the first 30 days, you’ll have access to all of Airbrake’s paid features and unlimited error and performance monitoring.
Introduction to Python NotImplementedError
Python NotImplementedError Exception occurs at runtime when client characterized base classes; conceptual techniques should raise this exception when they require inferred classes to abrogate the strategy or while the class is being created to demonstrate that the genuine usage despite everything should be included. This does not have a valid syntax as it is an exception runtime error. This ought not to be utilized to show that an administrator or technique isn’t intended to be bolstered by any means; all things considered, either leave the administrator or strategy unclear or, if a subclass, set it to None.
An exception is an occasion that happens during the execution of a program that disturbs the program’s directions’ ordinary progression. By and large, when a Python content experiences a circumstance that it cannot adapt to, it raises an exception. An exception is a Python object that speaks to a mistake. When a Python content raises an exception, it should either deal with the exemption promptly else it ends and stops.
How NotImplementedError Works in Python?
Now we look at how these NotImplementedErrors or exceptions work in Python.
Example
Code:
class BaseClass(object):
def __init__(self):
super(BaseClass, self).__init__()
def do_something(self):
raise NotImplementedError(self.__class__.__name__ + '.try_something')
class SubClass(BaseClass):
def do_something(self):
print (self.__class__.__name__ + ' trying something!')
SubClass().do_something()
BaseClass().do_something()
Output:
Code Explanation: In the above program, we first define an abstract class as our base class. In the main class, we define the interface using the init function and declare an index called self. Once this interface is defined in the base class, it gets prepared to be implemented as soon as we provide the command to define the interface. Soon after this is done, we immediately raise a NotImplementedError, preventing this interface from implementing the command. Hence, when we give the command to ‘try something, it automatically terminates from the abstract class. Then we define the subclass, and we again implement the interface and this time, the implementation works, and it produces the output saying that the subclass is trying something, and it raises the NonImplementation error for the base class and asks us to traceback to this exception.
How to Avoid NotImplementedError in Python?
There are a few circumstances where runtime errors are probably going to happen. At whatever point we attempt to peruse a document or get a client’s contribution, quite possibly something startling will occur – the record may have been moved or erased, and the client may enter information that is not in the correct organization. Great developers should add shields to their projects so regular circumstances like this can be taken care of effortlessly and a program that crashes at whatever point it experiences an effectively predictable issue is not extremely lovely to utilize. Most clients anticipate that projects should be sufficiently strong to recuperate from these sorts of difficulties. Hence, we see various aspects on how to prevent these runtime errors or NotImplementedErrors in Python. There are 2 functions that help in preventing these runtime errors, and they are “try” and “except”.
Example
Code:
try:
salary = int(input("Enter salary: "))
print("So cool you earn %d amount." % salary)
except ValueError:
print("Hey, that wasn't a number!")
Output:
Code Explanation: In the above code, we realize that the blunder is probably going to happen when we attempt to change over the client’s contribution to a number. On the off chance that the info string is definitely not a number, this line will trigger a ValueError – that is the reason we indicated it as the sort of blunder that we are going to deal with. We could have determined a progressively broad sort of mistake – or even left the sort out totally, which would have caused to coordinate any sort of exemption – yet that would have been an impractical notion. Imagine a scenario where we got a totally unique mistake that we had not anticipated. It would be dealt with also, and we would not see that anything abnormal was turning out badly. We may likewise need to respond in various manners to various types of blunders. We ought to consistently attempt to pick explicit as opposed to general mistake types for our with the exception of statements. Hence there will not be a runtime error like a NotImplementedError or Value error.
Conclusion
Hence, I conclude by saying that when NotImplementedErrors or exceptions occur in Python during runtime, it will not be interchangeable, and thus the normal implementation is not accepted. This kind of exceptions and errors can be handled by try and except blocks. In NotImplementedError, base classes have unique techniques which will raise this special case when they require determined classes to supersede the strategy or while the class is being created to show that the genuine usage despite everything should be included.
Recommended Articles
This is a guide to Python NotImplementedError. Here we also discuss the introduction and how notimplementederror works in python, along with an example and its code implementation. you may also have a look at the following articles to learn more –
- Quick Sort in Python
- Python Counter
- Python Concurrency
- Python Power Function
Чем больше вы практикуетесь, тем легче программирование становится для вас, но суть не меняется:
программирование — это сложно.
Оно может стать ещё сложнее при неудачном сочетании обязательств и рабочих задач, с которыми вы справляетесь самостоятельно. Без наставника особенно сложно осознать, что применяемый вами способ неверен. Конечно, мы все возвращаемся к коду и рефакторим его спустя некоторое время, потому что постоянно учимся делать что-то лучше. К счастью, при должном уровне осведомлённости работа над этими ошибками повышает ваш уровень программирования.
Преодолевать проблемы и работать над ошибками — замечательный способ стать хорошим программистом. Всегда существует лучший способ сделать что-то, но найти этот способ бывает действительно сложно. Легко привыкнуть к тому или иному действию, и иногда нужна небольшая встряска, чтобы двигаться дальше.
NotImplemented
Хотя ошибка NotImplemented является одной из самых распространённых, я считаю важным напомнить о ней в очередной раз. Выброс NotImplemented в Python не приводит к выбросу ошибки NotImplemented, вместо этого выбрасывается TypeError. Вот пример:
def implementtest(num):
if num == 5:
raise(NotImplemented)
При любой попытке запустить функцию, где “num” равен 5, произойдёт следующее:
Для выброса корректного исключения стоить выбрасывать NotImplementedError вместо NotImplemented. Отредактируем функцию:
def implementtest(num):
if num == 5:
raise(NotImplemented)
if num == 10:
raise(NotImplementedError('This is the right way!'))
Выполнение этой функции даст нужный результат:
Изменяемые значения по умолчанию
(Каюсь, и я допускал эту ошибку).
Аргументы по умолчанию в Python задаются один раз при определении функции. Следовательно, каждый элемент используется при каждом вызове, то есть данные, содержащиеся в переменной, изменяемы при каждом обращении к ним в функции.
def add(item, items=[]):
items.append(item)
Вместо этого стоит задать нулевое значение параметрам и добавить условие для изменения списка, если его не существует.
def add(item, items=None):
if items is None:
items = []
items.append(item)
Хотя в основном это относится к пользователям Python, работающим со статистикой, данными или в машинном обучении, наличие неизменяемых данных универсально важно во многих обстоятельствах.
Глобальные переменные
Внутри объектно-ориентированного языка программирования глобальные переменные стоит сводить к минимуму. Тем не менее я считаю важным отметить, что глобальные переменные, безусловно, необходимы и вполне применимы в некоторых ситуациях. Замечательным примером служит наука о данных, где фактически происходит ограничение объектно-ориентированного программирования, и Python становится более функциональным, нежели обычно.
При использовании глобальных переменные могут возникать проблемы с именованием и приватностью, когда несколько функций обращаются или ссылаются на одно и то же значение. Прекрасным примером подходящего использования глобальной переменной может быть что-то вроде пути к файлу, особенно предназначенного для объединения в пакет с файлом Python. Даже при написании класса Gtk и перемещении компоновщика графического пользовательского интерфейса стоит делать это частно, а не глобально.
Копирование!
Использование копирования может быть объективно лучше обычного присвоения. Обычные операции присвоения просто указывают на существующий объект новой переменной, вместо создания нового объекта.
d = 5
h = d
Существуют два основных типа копирования, осуществляемых с помощью модуля копирования Python:
поверхностное копирование и глубокое копирование.
Разница между этими двумя типами заключается в типе переменной, передаваемой через функцию. При использовании глубокого копирования переменных, содержащихся в одном байте данных, таких как целые числа, числа с плавающей точкой, булёвые значения или строки, разница между двумя типами копирования не ощущается. Однако при работе со списками, кортежами и словарями я всегда рекомендую глубокое копирование.
Поверхностное копирование создаёт новый составной объект и затем (насколько это возможно) вставляет в него ссылки на объекты, найденные в исходном. Глубокое копирование создаёт новый составной объект и затем рекурсивно вставляет внутрь него копии объектов из исходного. Учитывая эти определения легко понять, почему к тому или иному типу данных больше подходит тот или иной вариант.
import copy
l = [10,15,20]
h = 5
hcopy = copy.copy(h)
z = copy.deepcopy(l)
Чтобы протестировать наши результаты, просто проверим, является ли id переменных тем же самым, что и в условном выражении:
print id(h) == id(hcopy)
False
Заключение
Быть хорошим программистом означает постоянно совершенствоваться и постепенно искоренять ошибочные концепции. Это болезненный процесс, но постоянная практика и следование простым рекомендациям и советам приносят пользу. Обсуждения в стиле “не делайте так” приводят к продуктивному разговору и повышает уровень программистов, и я полагаю, что это обсуждение будет полезным независимо от того, насколько далеко вы продвинулись в своём бесконечном путешествии в программировании.
Читайте также:
- Стоит ли заменить Python на Julia?
- 4 ситуации из жизни лямбда-функций в Python
- Топ-10 магических команд в Python, которые повысят вашу продуктивность
Перевод статьи Emmett Boudreau: Avoid These Rookie Python Mistakes