Conditional based on whether or not a module is being used

Pete Emerson pemerson at gmail.com
Fri Mar 5 14:39:41 EST 2010


On Mar 5, 11:24 am, Pete Emerson <pemer... at gmail.com> wrote:
> In a module, how do I create a conditional that will do something
> based on whether or not another module has been loaded?
>
> Suppose I have the following:
>
> import foo
> import foobar
>
> print foo()
> print foobar()
>
> ########### foo.py
> def foo:
>     return 'foo'
>
> ########### foobar.py
> def foobar:
>     if foo.has_been_loaded(): # This is not right!
>         return foo() + 'bar'      # This might need to be foo.foo() ?
>     else:
>         return 'bar'
>
> If someone is using foo module, I want to take advantage of its
> features and use it in foobar, otherwise, I want to do something else.
> In other words, I don't want to create a dependency of foobar on foo.
>
> My failed search for solving this makes me wonder if I'm approaching
> this all wrong.
>
> Thanks in advance,
> Pete

Aha, progress. Comments appreciated. Perhaps there's a different and
more conventional way of doing it than this?

def foobar():
        import sys
        if 'foomodule' in sys.modules.keys():
                import foomodule
                return foomodule.foo() + 'bar'
        else:
                return 'bar'



More information about the Python-list mailing list