DEV Community

Cover image for Don't inherit from python BaseException, Here's why.
Waylon Walker
Waylon Walker

Posted on • Originally published at waylonwalker.com

7 1

Don't inherit from python BaseException, Here's why.

I ran into a PR this week where the author was inheriting what BaseException rather than exception. I made this example to illustrate the unintended side effects that it can have.

Try running these examples in a .py file for yourself and try to kill them with control-c.

You cannot Keybard interrupt

Since things such as KeyboardInterrupt are created as an exception that inherits from BaseException, if you except BaseException you can no longer
KeyboardInterrupt.

from time import sleep

while True:
    try:
        sleep(30)
    except BaseException: # ❌
        pass
Enter fullscreen mode Exit fullscreen mode

except from Exception or higher

If you except from exception or something than inherits from it you will be better off, and avoid unintended side effects.

from time import sleep

while True:
    try:
        sleep(30)
    except Exception: # ✅
        pass
Enter fullscreen mode Exit fullscreen mode

This goes with Custom Exceptions as well

When you make custom exceptions expect that users, or your team members will want to catch them and try to handle them if they can. If you inherit from
BaseException you will put them in a similar situation when they use your
custom Exception.

class MyFancyException(BaseException): # ❌
    ...

class MyFancyException(Exception): # ✅
    ...
Enter fullscreen mode Exit fullscreen mode

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay