Conditional based on whether or not a module is being used

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Mar 8 08:02:46 EST 2010


Pete Emerson wrote:
> On Mar 5, 1:14 pm, Chris Rebert <c... at rebertia.com> wrote:
>   
>> On Fri, Mar 5, 2010 at 12:25 PM, Pete Emerson <pemer... at gmail.com> wrote:
>>     
>>> On Fri, Mar 5, 2010 at 12:17 PM, Chris Rebert <c... at rebertia.com> wrote:
>>>       
>>>> On 3/5/10, 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?
>>>>>           
>> <snip>
>>     
>>>>> 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.
>>>>>           
>>>> Just try importing foo, and then catch the exception if it's not installed.
>>>>         
>> <snip>
>>     
>>> Except I want to use the module only if the main program is using it
>>> too, not just if it's available for use. I think that I found a way in
>>> my follow-up post to my own message, but not sure it's the best way or
>>> conventional.
>>>       
>> What is your use case for this behavior exactly? You've piqued my curiosity.
>>
>> Cheers,
>> Chris
>> --http://blog.rebertia.com
>>     
>
> I have written my first module called "logger" that logs to syslog via
> the syslog module but also allows for logging to STDOUT in debug mode
> at multiple levels (to increase verbosity depending on one's need), or
> both. I've looked at the logging module and while it might suit my
> needs, it's overkill for me right now (I'm still *very* much a python
> newbie).
>
> I want to write other modules, and my thinking is that it makes sense
> for those modules to use the "logger" module to do the logging, if and
> only if the parent using the other modules is also using the logger
> module.
>
> In other words, I don't want to force someone to use the "logger"
> module just so they can use my other modules, even if the "logger"
> module is installed ... but I also want to take advantage of it if I'm
> using it.
>
> Now that I've written that, I'm not sure that makes a whole lot of
> sense. It seems like I could say, "hey, this person has the 'logger'
> module available, let's use it!".
>
> Thoughts?
>   
The logging module is not overkill, use it.
It can be simple if you want it to be, and can be more complex if you 
need advanced logging features.

All the "what if the application is not using my logger module" is dealt 
with by the logging module.
And I'm not its designer in any way, so my advice is completely 
objective :-)

It's definitely worth spending some time ramping up with it.

JM




More information about the Python-list mailing list