python - 模块中所有功能的 Numpy seterr
问题描述
我有一个包含具有 numpy 操作的函数的模块。我想为任何函数中发生的任何浮点错误(例如,除以零)引发异常。
这行代码会导致引发所有浮点错误:
np.seterr(all='raise')
我想知道如何为模块中的所有函数设置它,而不影响模块外部的代码。
据我了解,在下面编写该行将if __name__ == '__main__':
无济于事,因为在导入模块时不会调用它。
有没有比np.seterr(all='raise')
在每个函数内部编写更好的方法?
解决方案
一种可能是:
# only list functions that need to be exported
__all__ = ['main', 'foo', 'bar', 'division',]
def main():
np.seterr(all='raise')
# ....
# further function calls
if __name__ == "__main__":
main()
这是一个具体的例子:
为例如创建一个模块sample.py
import numpy as np
__all__ = ['main', 'foo', 'bar', 'division',]
def foo():
print('this is function foo')
def bar():
print('this is function bar')
def division():
print("division by zero might occur here...")
def main():
np.seterr(all='raise')
print('this is the main function')
# only executed when run from the commandline as: python sample.py
if __name__ == '__main__':
main()
然后将该模块导入例如ipython
提示符或从其他模块导入:
In [1]: import sample
# only the functions included in `__all__` will be imported
In [2]: sample.__all__
Out[2]: ['main', 'foo', 'bar', 'division']
# call whichever function is needed
In [3]: sample.main()
this is the main function
推荐阅读
- java - Java Streams 在 Codility 上的性能为 0%
- python - Flask 应用程序的启动应该如何构建?
- pandas - 在 for 循环中根据名称复制/分配 Pandas 数据框
- dependency-injection - ServiceStack:container.AutoWire(this) 给出 NullReferenceException
- amazon-web-services - 使用 IAM 角色的 cfInvalidate (jenkinsci / pipeline-aws-plugin)
- android - 从科尔多瓦的 playstore 获取应用程序版本
- mongodb - 获取“信号 15(终止),将在当前 cmd 结束后终止”和 Mongodb 关闭?配置中没有提到分叉条件
- c# - 初始化组件();在 C# 中的所有用户控制文件中返回 0 引用
- jointjs - 导出的 png/svg/jpeg 文件中不显示纸张背景图像
- python - 在 Python 程序中访问主机文件