11

I have the following code

    if self.download_format == 'mp3':
        raise NotImplementedError
    elif self.download_format == 'wav':
        with NamedTemporaryFile(suffix='.wav') as wavfile:
            self.download_wav_recording(call, wavfile.name)
            convert_wav_to_mp3(wavfile.name, filename)

And pylint reports this error

R1720: Unnecessary "elif" after "raise" (no-else-raise)

What is the motivation for this error? why this code is not ok?

Gary Kerr
  • 13,650
  • 4
  • 48
  • 51
Ryabchenko Alexander
  • 10,057
  • 7
  • 56
  • 88

1 Answers1

17
    if self.download_format == 'mp3':
        raise NotImplementedError
    elif self.download_format == 'wav':
        with NamedTemporaryFile(suffix='.wav') as wavfile:
            self.download_wav_recording(call, wavfile.name)
            convert_wav_to_mp3(wavfile.name, filename)

This is equivalent to

    if self.download_format == 'mp3':
        raise NotImplementedError
    if self.download_format == 'wav':
      with NamedTemporaryFile(suffix='.wav') as wavfile:
          self.download_wav_recording(call, wavfile.name)
          convert_wav_to_mp3(wavfile.name, filename)

Hence the warning from pylint

The raise causes control flow to be disrupted - so you don't need to use elif and can use if instead

rdas
  • 20,604
  • 6
  • 33
  • 46
  • I am not understanding it, if the first statement holds it will check the next elif – bonijad383 Sep 07 '22 at 04:50
  • @bonijad383, if the first `if` statement holds true, an exception is raised and not caught, and hence, the surrounding block of the `if-elif` control flow is exited. As such, `pylint` suggests that the `else` part of `elif` that follows the exception raising logic is redundant. The only possible branch to hit the comparison `self.download_format == 'wav'` is only via the `else`, anyway. – Arda Aytekin Oct 18 '22 at 09:22