Q: How to handle conditional-imports-dependent exceptions? I'm wondering what is the most elegant way to handle exceptions that depend on a conditional import.
For example:
import ldap
try:
    ...
    l = ldap.open(...)
    l.simple_bind_s(...)
    ...
except ldap.INVALID_CREDENTIALS, e:
    pass
except ldap.SERVER_DOWN, e:
    pass

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.
However, I can use something else than LDAP to do authentication, in which case I do not want to import ldap at all.
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? 
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)?
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?
What would you suggest as the most pythonic?

A: Probably somewhere there should be a configuration option in your program that is used to decide which kind of authentication should be used. The imports should be done depending on this option.
If you put all the ldap related authentication functions into their own module, like auth_ldap and do the same for your other methods of authentication, you could do the login check like this:
if config.auth_method == 'ldap':
  import ldap_auth as auth
elif config.auth_method == 'db':
  import db_auth as auth
else:
  raise Exception("No valid authentication module configured")

auth.check_login(user, password)

The check_login method in each module would here provide a uniform interface that internally does whatever is necessary to perform the specific login. This function could also translate specific Ldap exceptions into a generic LoginFailure or just return True or False depending on the success of the user check.

A: This will be easier to handle if you write a set of abstraction modules for authn (Strategy Pattern). Each module will catch its specific authn exceptions, and in place raise generic exceptions defined by the application.
