简体   繁体   中英

Raise an exception at import if conditions not met

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 , but it seems to be reserved for situation when python "fails to find the module definition"

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 (as above)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM