1

Consider the following example:

>>> import numpy as np
>>> a = np.array([1.0, 2.1j])
>>> b = np.array(a, dtype=np.float64)
/Users/goerz/anaconda3/bin/ipython:1: ComplexWarning: Casting complex values to real discards the imaginary part
  #!/Users/goerz/anaconda3/bin/python

How can I catch the ComplexWarning as an Exception?

I have tried np.seterr, but this has no effect (as it only relates to floating point warnings such as underflows/overflows).

I've also tried the with warnings.catch_warnings(): context manager from the standard library, but it also has no effect.

Michael Goerz
  • 4,300
  • 3
  • 23
  • 31
  • `numpy.seterr(all='raise')` – Benoît P Feb 21 '19 at 18:56
  • 1
    I tried that, but it has no effect. According to the `seterr` documentation it only handles floating errors (which this isn't) – Michael Goerz Feb 21 '19 at 19:04
  • @Prune This is not a duplicate. I've seen the linked question, and as far as I can tell it only relates to floating errors (overflows etcs). A ComplexWarning is not such a floating error and is not caught be `seterr` – Michael Goerz Feb 21 '19 at 19:06
  • Then try the `warning` module in the standard library. You should put what you've tried in your question. Edit your question so I can remove my downvote. – Benoît P Feb 21 '19 at 19:06
  • @MichaelGoerz: Thanks; I see the difference. Reopened. My apologies. – Prune Feb 21 '19 at 19:08

1 Answers1

4

Using stdlib warnings filter causes these to raise instead of print:

>>> warnings.filterwarnings(action="error", category=np.ComplexWarning)
>>> b = np.array(a, dtype=np.float64)
ComplexWarning: Casting complex values to real discards the imaginary part

You can reset it to default filters with warnings.resetwarnings.

wim
  • 338,267
  • 99
  • 616
  • 750