我有一个包含numpy操作函数的模块。我想对任何函数中出现的任何浮点错误(例如,除以零)提出异常。
这行代码会引发所有浮点错误:
np.seterr(all='raise')
我想知道如何为模块中的所有功能设置它,而不会影响模块外部的代码。
据我了解,在if __name__ == '__main__':
下写下这行不会有帮助,因为在导入模块时不会调用它。
有没有比在每个函数中编写np.seterr(all='raise')
更好的方法?
答案 0 :(得分: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
答案 1 :(得分:0)
似乎该线程存活了很长时间,我想您/其他人已经管理好了,但是对于像我这样的未来观众来说,这可以节省几分钟的时间:
return (
<View style={styless.rideChatView}>
<Card style={styles.card}>
<Avatar
activeOpacity={0.7}
icon={{name: 'user', type: 'font-awesome'}}
size="small"
rounded
source={require('../../static_images/classtrav0.jpeg')}
/>
<Text>Name</Text>
<Avatar
activeOpacity={0.7}
icon={{name: 'user', type: 'font-awesome'}}
size="small"
rounded
source={require('../../static_images/classtrav0.jpeg')}
/>
<Text>Name</Text>
<Avatar
activeOpacity={0.7}
icon={{name: 'user', type: 'font-awesome'}}
size="small"
rounded
source={require('../../static_images/classtrav0.jpeg')}
/>
<Text>Name</Text>
<Avatar
activeOpacity={0.7}
icon={{name: 'user', type: 'font-awesome'}}
size="small"
rounded
source={require('../../static_images/classtrav0.jpeg')}
/>
<Text>Name</Text>
</Card>
</View>
);
}
}
export default RideChat;
const styless = StyleSheet.create({
rideChatView: {
height: '70%',
backgroundColor: 'white',
position: 'absolute',
bottom: 0,
right: 0,
left: 0,
},
card: {
alignItems: 'center',
justifyContent: 'center',
},
});