Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Comments on Use cases for raising a 'NotImplementedError' in Python
Parent
Use cases for raising a 'NotImplementedError' in Python
What are some legitimate use cases for raising a NotImplementedError
exception in Python? How can it help express a code author's intentions to aid code maintenance and/or further development of code?
Post
NotImplementedError
should generally be viewed as indicating some design problem. You should not be reaching for it as a matter of course.
Here are some potential times you might feel a desire to reach for NotImplementedError
.
-
During development, you want to test some code that is partially implemented. Using
NotImplementedError
for the parts not yet implemented would be fine. Of course, these uses ofNotImplementedError
should be removed before you "release" the project. -
A third-party library requires you to implement all methods of a class to use its functionality, but some methods don't make sense for your use-case. If the documentation states that some methods don't need to be implemented, then you'd be fine (but they'd probably already have default implementations that raised
NotImplementedError
). If not, then you don't know if it is safe to not implement one of the methods. UsingNotImplementedError
in this case should be viewed as a hack that may well cause unknown issues now and/or in the future. Arguably, being in this situation either way indicates poor design in the third party library. -
You have a plugin system and a plugin may optionally provide certain functionality.
NotImplementedError
may seem like a good way to handle optional functionality that's not provided, but a better way is to query the plugin for different facets (or bundles) of coherent functionality. For example, if you had an IDE plugin that could support syntax highlighting or jump to definition among other things, you could havegetSyntaxHighlighterFacet()
andgetJumpToDefinitionFacet()
methods that the plugin must implement. These methods would return a coherent object if it supports that functionality, otherwise it would returnNone
. This would allow the plugin loader to query what functionality is available and substitute a fallback for functionality that's not available. It would also avoid finding out some functionality is unavailable at the last possible moment where it might lead to unexpected behavior or require fallback logic to be written everywhere.
0 comment threads