【问题标题】:Numpy seterr for all functions in module模块中所有功能的 Numpy seterr
【发布时间】:2018-06-13 19:50:25
【问题描述】:

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

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

np.seterr(all='raise')

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

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

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

【问题讨论】:

    标签: python numpy error-handling


    【解决方案1】:

    一种可能是:

    # 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
    

    【讨论】:

    • 在导入模块时不会运行main()函数吗,因为它是在if __name__ == "__main__"下调用的?
    • @Vermillion 添加了一个例子!
    【解决方案2】:

    似乎这个话题已经存在了很长时间,我猜你/其他人已经管理好了,但是对于未来的观众(比如我)来说,这里有一些东西可以挽救你几分钟的生命:

    import numpy as np
    
    
    def unmasked_call(func):
        def func2(*args, **kwargs):
            with np.errstate(all='raise'):
                return func(*args, **kwargs)
        return func2
    
    
    @unmasked_call
    def one():
        print ("One:")
        return np.max([1, 2, np.nan])
    
    
    print ("Starting")
    one()
    

    【讨论】:

      猜你喜欢
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 2015-06-01
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多