Python – Defining Exit Method Before Importing

importpython

This breaks nothing (in my experience), but lots of things "don't break anything" and are still wrong.

#! /usr/bin/env python
"""Short description of this module."""

def preferred_exit_method(*args):
    #code for exiting as desired

try:
    import foo
    import bar
    import eggs
except ImportError as e:
    #code code code
    preferred_exit_method(e)

So, clearly defining the program's behavior on exit, then using it during the import process can't be too terrible, right? But it goes against the oft-cited PEP 8, which states that modules should be absolutely be imported before anything global.

It seems like an unrisky proposition, but then there's always something like this:

#! /usr/bin/env python
"""Description of module"""

def exit_of_choice(*args):
    #code code code
    sys.exit(0)

try:
    import sys
    import other_things
except ImportError as e:
    exit_of_choice(e)

Apart from writing code that never needs to do this because it is perfect and never fails at anything, is there a reason besides PEP 8 and "other Python people will be cross with you" not to do this? (well, I'm less concerned with the latter – even though sys wouldn't typically fail to import, I still sort of hate that on principle)

Best Answer

is there a reason besides PEP 8

Multiple module interaction

Your code becomes much more troublesome when there are multiple modules there isn't a good way to parameterize the modules with the code you have. So you're left with 2 choices:

  • Duplicated the custom import-exit in every module that needs to import modules (or at least the imports you want to customize)
  • Centralize all your imports in one module and have subsequent modules import from the central module for use in their local namespace.
  • Only use it in one place, but an import of a particular module may or may not come from your custom import-exit code. Any number of other imports may cause a different import to initialize the module in sys.modules.

It should be written as a custom importer

There is a better way. If you want to customize imports Python has facilities for this. They are called import hooks and you can write a hook that does a lookup against a white (or black) list of modules whose import you want to customize. You can then have the hook exit explicitly when the import fails.

Related Topic