简体   繁体   English

如果不满足条件,则在导入时引发异常

[英]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. 例如,要正常工作,需要设置环境变量FOO。 I would like the module to raise an Exception if this condition is not met at import time. 如果导入时未满足此条件,我希望模块引发Exception。

# 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? 应该是我自己的class MyModuleImportError(Exception)还是某些内置的异常更合适且更常用? One candidate would be ImportError , but it seems to be reserved for situation when python "fails to find the module definition" 一个候选对象将是ImportError ,但是它似乎是为python “无法找到模块定义”而保留的。

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) OSError (如上所述)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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