Raise an exception at import if conditions not met
Question: I have a module that depends on some system settings. For example, to work
properly it needs to have an environment variable FOO set. I would like the
module to raise an Exception if this condition is not met at import time.

    
    
    # mymodule.py
    if 'FOO' not in sys.environ:
        raise SomeException('ensure that FOO is provided')
    

I would like to know:

  1. Is it the best practice to check those conditions at import time, or maybe it would be better to do it later (when)
  2. What type of exception should I raise? Should it be my own `class MyModuleImportError(Exception)` or maybe some built-in exceptions are more suitable and commonly used? One candidate would be [ImportError](http://docs.python.org/2/library/exceptions.html#exceptions.ImportError), but it seems to be reserved for situation when python _"fails to find the module definition"_


Answer: Is this what you are looking for?

    
    
    >>> import os
    >>> if not os.getenv('FOO', False):
        raise OSError('FOO not in envs')
    

* * *

  1. Yes, you should check these kind of things at the start of your code. Else there is no reason for it to continue running.
  2. an [OSError](http://docs.python.org/2/library/exceptions.html#exceptions.OSError) (as above)

