How to handle conditional-imports-dependent exceptions?
<p>I'm wondering what is the most elegant way to handle exceptions that depend on a conditional import.
For example:</p>

<pre><code>import ldap
try:
    ...
    l = ldap.open(...)
    l.simple_bind_s(...)
    ...
except ldap.INVALID_CREDENTIALS, e:
    pass
except ldap.SERVER_DOWN, e:
    pass
</code></pre>

<p>In the real-world scenario (the one that made me think of this), we have a cherrypy server with a 'login' page. And the login method does a lot of stuff - one of them is authentication.</p>

<p>However, I can use something else than LDAP to do authentication, in which case I do not want to import ldap at all.</p>

<p>But if I make the 'import ldap' statement conditional (e.g. it only gets imported when USE_LDAP value is True in a config file), I have to do something with the 'except's too. The question is: what? </p>

<p>Catch a generic Exception, use an if statement to check whether we use LDAP (i.e., ldap is imported) and then use isinstance to check, whether the Exception is the correct type (ldap.INVALID_CREDENTIALS)?</p>

<p>Try to concentrate the code that depends on ldap at one place and re-raise a user defined exception that finally gets caught in the login method?</p>

<p>What would you suggest as the most pythonic?</p>
