首页 > 解决方案 > 模块中所有功能的 Numpy seterr

问题描述

我有一个包含具有 numpy 操作的函数的模块。我想为任何函数中发生的任何浮点错误(例如,除以零)引发异常。

这行代码会导致引发所有浮点错误:

np.seterr(all='raise')

我想知道如何为模块中的所有函数设置它,而不影响模块外部的代码。

据我了解,在下面编写该行将if __name__ == '__main__':无济于事,因为在导入模块时不会调用它。

有没有比np.seterr(all='raise')在每个函数内部编写更好的方法?

标签: pythonnumpyerror-handling

解决方案


一种可能是:

# 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

推荐阅读