2

What I am trying to do is to extend the base ImportError Exception, so whenever it is called, it does somethings else as well

import logging

logging.basicConfig(filename="logs", level=logging.DEBUG)

class ImportError(Exception):

    def __init__(self, message):
        Exception.__init__(self)
        self.message = message

        logging.warning(self.message)



import module

But this doesn't work, can some one please tell me how can we achieve something like this..

thanks.

1 Answer 1

3

ImportError is a built-in exception; an import failure will not look for the exception in the current module globals.

In fact, in Python 2, the import machinery doesn't even look in builtins for this; it uses the C equivalent of the exception, PyExc_ImportError. You cannot replace the exception with your own.

Just catch the exception at the top level of your python main script:

try:
    main()  # or whatever function is your main entrypoint
except ImportError:
    logging.exception('Import oopsie')

or raise a custom exception in a exception handler instead. This is far clearer to future maintainers of your code than hacking additional features into standard exceptions.

In Python 3.1 and up, the import machinery has been largely reimplemented using a lot more Python code, and there you can do this by using the builtins module and assigning to builtins.ImportError, but I'd strongly advice against such hackery. If you do go this route, note that ImportError is passed name and path keyword arguments in addition to message.

Sign up to request clarification or add additional context in comments.

7 Comments

ohk, so it means that i can not do what i am trying to do, instead i can create my custom Exception class and raise that when i get a ImportError ??
@abhishekgarg: Exactly.
Thanks Martijn, also i have many try except in my script, can i also do a try except for the whole main function like you've shown in your example instead of several different ones??
@abhishekgarg: That depends on what should happen when you have an import error; do you want to continue right after the failed import statement or do you want to end your program?
i want to end the program whenever i get any exception either ImportError, IOError, or any other exception. i would like to do something like try: main() except Exception, e: logging.error(e)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.