How to remove "__main__." from the beginning of user-created exception classes in Python

class MyException(Exception):
    __module__ = Exception.__module__

This way looks/works better than sys.excepthook


Source Code Reference

Python2

See PyErr_Display

There're two ways to bypass the module name part:

class A(Exception):
    __module__ = None

class B(Exception):
    __module__ = 'exceptions'

But if you need to play with threading.Thread, the first one will introduce a TypeError.

Python 3

See PyErr_WriteUnraisable

class C(Exception):
    __module__ = 'builtins'

I am not sure why you want to remove __main__ because that is the module name and when your exception would be in a appropriately named module, it would look beautiful not ugly e.g. myexceptions.BadException

Alternatively you can catch exception and print as you wish.

But if you want the uncaught exceptions to be printed as per your wish, try to set sys.excepthook e.g.

class BadThings(Exception): pass 

import traceback
def myexcepthook(type, value, tb):
    l = ''.join(traceback.format_exception(type, value, tb))
    print l

import sys
sys.excepthook = myexcepthook

raise BadThings("bad bad")

Output:

Traceback (most recent call last):
  File "untitled-1.py", line 12, in <module>
    raise BadThings("bad bad")
BadThings: bad bad

So in sys.excepthook you can modify exception, format it etc