Handling import errors when using doctest
Question: every now and then when I code in Python, I have to do without certain third-
party modules.

Eg. when I'm writing user authentication, it can be done in several ways and
one of them is by using LDAP. However if the user does not want to use LDAP
auth., he can choose a different option in a config file and in that case he
should not have to have ldap module installed.

Generally I solve this by:

    
    
    if config.foo: 
       import ldap_auth as auth
    elif config.foo2:
       import other_auth as auth
    ...
    auth.do_stuff(...)
    

and I import ldap module in ldap_auth module only. I personally find this
quite nice, however, of course, doctests raise an ImportError when trying to
execute ldap_auth.

Now, I know I could catch it by try-ing to import the ldap module in
ldap_auth, but that just kinda messes up the nice looking code (the whole
point of doing the whole "import ldap_auth as auth" bussiness was to avoid
ImportErrors).

Is there any more elegant way to prevent doctests from raising ImportErrors
when using this "pattern"?

Cheers,

Tom


Answer: The recommended way is

    
    
    try:
        import foo as auth
    except ImportError:
        import bar as auth
    

It avoids race conditions and I don't think it looks bad.

