Checking module name inside 'except ImportError'
<pre><code>try:
   import MySQLdb
   # some action
except ImportError as err:
   # fallback code
</code></pre>
<p>PyCharm gives a code inspection warning on that:</p>
<blockquote>
<p>'MySQLdb' in try block with 'except ImportError' should also be defined in except block</p>
<p>This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.</p>
</blockquote>
<p>Ok, I thought the warning is reasonable, because the <code>fallback code</code> assumes that 'MySQLdb' is not installed, while it could be some different error that just raised ImportError. So I used something like:</p>
<pre><code>try:
   import MySQLdb
   # some action
except ImportError as err:
   if &quot;MySQLdb&quot; in repr(err):
       # fallback code
   else:
       raise
</code></pre>
<p>The PyCharm alert is still exists, but It could be just a PyCharm issue (google shows issues with such inspections)</p>
<p><em><strong>Questions:</strong></em></p>
<ol>
<li><p>Is it really worth checking for name when you &quot;except ImportError&quot;? Even in simple cases (no <code>some action</code> after <code>import MySQLdb</code>)?</p>
</li>
<li><p>If it worth checking, Is the above example the right way to do it? If no - what is the right way?</p>
</li>
</ol>
<p><strong>P.S.</strong> MySQLdb is just an example of a module that could be absent in the system.</p>