[Numpy-discussion] Re: Add context management for np.seterr

2024-05-09 Thread Nathan
I think you're looking for the errstate context manager:

https://numpy.org/doc/stable/reference/generated/numpy.errstate.html

On Thu, May 9, 2024 at 1:11 PM  wrote:

> The current way (according to 1.26 doc) of setting and resetting error is
> ```
> old_settings = np.seterr(all='ignore')  #seterr to known value
> np.seterr(over='raise')
> {'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid':
> 'ignore'}
> np.seterr(**old_settings)  # reset to default
> ```
> This may be tedious and not elegant when we need to suppress the error for
> some certain lines, for example, `np.nan_to_num(a/b) ` as we need to
> suppress divide here.
>
> I think it would be way more elegant to use `with` statement here, which
> should be able to be implemented with some simple changes.
>
> An ideal result would be like:
> ```
> with np.seterr(divide='ignore'):
> np.nan_to_num(a/b) # no warning
>
> a/0 # still warn
> ```
> ___
> NumPy-Discussion mailing list -- numpy-discussion@python.org
> To unsubscribe send an email to numpy-discussion-le...@python.org
> https://mail.python.org/mailman3/lists/numpy-discussion.python.org/
> Member address: nathan12...@gmail.com
>
___
NumPy-Discussion mailing list -- numpy-discussion@python.org
To unsubscribe send an email to numpy-discussion-le...@python.org
https://mail.python.org/mailman3/lists/numpy-discussion.python.org/
Member address: arch...@mail-archive.com


[Numpy-discussion] Add context management for np.seterr

2024-05-09 Thread hjenryin
The current way (according to 1.26 doc) of setting and resetting error is
```
old_settings = np.seterr(all='ignore')  #seterr to known value
np.seterr(over='raise')
{'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}
np.seterr(**old_settings)  # reset to default
```
This may be tedious and not elegant when we need to suppress the error for some 
certain lines, for example, `np.nan_to_num(a/b) ` as we need to suppress divide 
here. 

I think it would be way more elegant to use `with` statement here, which should 
be able to be implemented with some simple changes.

An ideal result would be like:
```
with np.seterr(divide='ignore'):
np.nan_to_num(a/b) # no warning

a/0 # still warn
```
___
NumPy-Discussion mailing list -- numpy-discussion@python.org
To unsubscribe send an email to numpy-discussion-le...@python.org
https://mail.python.org/mailman3/lists/numpy-discussion.python.org/
Member address: arch...@mail-archive.com