Conditional based on whether or not a module is being used

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Mar 5 14:53:43 EST 2010


On Fri, 05 Mar 2010 11:24:44 -0800, Pete Emerson wrote:

> In a module, how do I create a conditional that will do something based
> on whether or not another module has been loaded?

try:
    import foo
except ImportError:
    foo = None

def function():
    if foo:
        return foo.func()
    else:
        do_something_else()



Or, alternatively:

try:
    import foo
except ImportError:
    import alternative_foo as foo  # This better succeed!

def function():
    return foo.func()


-- 
Steven



More information about the Python-list mailing list