473,397 Members | 1,969 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

Testing the availability of a module

Dear list,

Is there a better way than doing

try:
import aModule
except:
has_aModule = False
else:
has_aModule = True

The main concern here is that loading aModule is unnecessary (and may
take time).

Many thanks in advance.
Bo
Dec 19 '05 #1
12 1195
Bo Peng wrote:
Dear list,

Is there a better way than doing

try:
import aModule
except:
has_aModule = False
else:
has_aModule = True

The main concern here is that loading aModule is unnecessary (and may
take time).


No, there is not really a better way.

You *could* check for the existance of files, but a file existing and it
really being successfully loadable as a module are not the same.

Besides, it is a lot of work to reimplement half the Python import
machinery just for checking for all kinds of files. If you're serious
about it, you also need to cope with modules loadable from ZIP files,
and with .pth files, etc.

This is not fun to program, and you're really better off just checking
for a successful import like you're doing now.

-- Gerhard
Dec 19 '05 #2
Gerhard Häring <gh@ghaering.de> writes:
Bo Peng wrote:
Dear list,
Is there a better way than doing
try:
import aModule
except:
has_aModule = False
else:
has_aModule = True
The main concern here is that loading aModule is unnecessary (and
may take time).


No, there is not really a better way.

You *could* check for the existance of files, but a file existing and
it really being successfully loadable as a module are not the same.

Besides, it is a lot of work to reimplement half the Python import
machinery just for checking for all kinds of files. If you're serious
about it, you also need to cope with modules loadable from ZIP files,
and with .pth files, etc.

This is not fun to program, and you're really better off just checking
for a successful import like you're doing now.


I don't think the above is entirely correct. imp.find_module() probably
does what the OP needs.

Thomas
Dec 19 '05 #3
Gerhard Häring wrote:
Bo Peng wrote:
Dear list,

Is there a better way than doing

try:
import aModule
except:
has_aModule = False
else:
has_aModule = True

The main concern here is that loading aModule is unnecessary (and may
take time).


No, there is not really a better way.

You *could* check for the existance of files, but a file existing and it
really being successfully loadable as a module are not the same.

Besides, it is a lot of work to reimplement half the Python import
machinery just for checking for all kinds of files. If you're serious
about it, you also need to cope with modules loadable from ZIP files,
and with .pth files, etc.


*Unless*, someone else has already done all of it for you:

http://peak.telecommunity.com/DevCenter/PythonEggs
http://peak.telecommunity.com/DevCenter/PkgResources

--
Robert Kern
ro*********@gmail.com

"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter

Dec 19 '05 #4
On Mon, 19 Dec 2005 02:52:08 -0600, Bo Peng wrote:
Dear list,

Is there a better way than doing

try:
import aModule
except:
has_aModule = False
else:
has_aModule = True
Do you mean to catch every possible exception when importing aModule?

If you replace "except:" with "except ImportError:" then only actual
import errors will be caught. Any other errors in aModule (such as syntax
errors, etc. will still raise a exception as normal.

The main concern here is that loading aModule is unnecessary (and may
take time).


If importing aModule is unnecessary, then just don't import it.

What are you trying to protect against?
--
Steven.

Dec 19 '05 #5
Bo Peng wrote:
Is there a better way than doing

try:
import aModule
except:
has_aModule = False
else:
has_aModule = True

The main concern here is that loading aModule is unnecessary (and may
take time).


Loading a module does *not* take time after the first time. All it does
is pull a reference out of sys.modules. Are you worried about doing the
above multiple times and wasting time? Don't... you'll never notice it.

(And if you aren't doing the above multiple times, then you *really*
shouldn't be worried about the time to load "aModule", unless you have
reason to believe merely loading it takes an incredibly long time, in
which case it is probably poorly designed as most modules should not be
doing real work just by being imported.)

-Peter

Dec 19 '05 #6
Peter Hansen wrote:
Bo Peng wrote:
Is there a better way than doing

try:
import aModule
except:
has_aModule = False
else:
has_aModule = True

The main concern here is that loading aModule is unnecessary (and may
take time).
And if you aren't doing the above multiple times, then you *really*
shouldn't be worried about the time to load "aModule"


This is used in a scenario like:

if wxPython is available:
prepare wx based GUI
elif Tkinter is available:
prepare tk based GUI
else:
command line only

Since a user may prefer command line so wxPython/tkinter should not be
actually loaded before the GUI function is called.

Bo
Dec 19 '05 #7
On Mon, 19 Dec 2005 08:33:18 -0600, Bo Peng wrote:
This is used in a scenario like:

if wxPython is available:
prepare wx based GUI
elif Tkinter is available:
prepare tk based GUI
else:
command line only

Since a user may prefer command line so wxPython/tkinter should not be
actually loaded before the GUI function is called.


Since that is a choice, it shouldn't depend on the availability of a
module:
if user_preferences["commandline"]:
build CLI
run CLI
else:
try:
import wxPython
build wx GUI
except ImportError:
try:
import tkinter
build tk GUI
except ImportError:
raise NoAvailableGuiError
run GUI
--
Steven.

Dec 19 '05 #8
Bo Peng wrote:
> And if you aren't doing the above multiple times, then you *really*
> shouldn't be worried about the time to load "aModule"


This is used in a scenario like:

if wxPython is available:
prepare wx based GUI
elif Tkinter is available:
prepare tk based GUI
else:
command line only

Since a user may prefer command line so wxPython/tkinter should not be
actually loaded before the GUI function is called.


if the user happens to prefer the command line interface, why bother looking
for a GUI ? sounds like you haven't really thought this through...

here's an outline that matches your use case:

if user wants command line:
command line only
else:
if wxPython is available:
prepare wx based GUI
elif Tkinter is available:
prepare tk based GUI
else:
command line only

</F>

Dec 19 '05 #9
> if the user happens to prefer the command line interface, why bother looking
for a GUI ? sounds like you haven't really thought this through...

here's an outline that matches your use case:

if user wants command line:
command line only
else:
if wxPython is available:
prepare wx based GUI
elif Tkinter is available:
prepare tk based GUI
else:
command line only


This is exactly the logic I use,... Eliminating all unrelated stuff, I
have something like (thanks for the imp hint):

def wxGUI():
import wx
wx...

def tkGUI():
import Tkinter as tk
tk....

def cml():
command line

def GUI():
if options['cml']:
cml()
else:
if imp.find_module('wx'):
wxGUI()
elif imp.find_module('Tkinter'):
tkGUI()
else:
cml()

After a user loads this module (without wx loaded automatically as
before), he can call cml() or GUI().

Bo
Dec 19 '05 #10
Bo Peng wrote:
def GUI():
if options['cml']:
cml()
else:
if imp.find_module('wx'):
wxGUI()
elif imp.find_module('Tkinter'):
tkGUI()
else:
cml()


On the other hand, I don't see how this is superior to an exception-based
approach...

def GUI():
if options["cml"]:
cml()
else:
for ui in wxGUI, tkGUI, cml:
try:
ui()
except ImportError:
pass
else:
break

....especially as you have to deal with ImportError exceptions, too:
import imp
imp.find_module("not_there")

Traceback (most recent call last):
File "<stdin>", line 1, in ?
ImportError: No module named not_there

Peter

Dec 19 '05 #11
Bo Peng wrote:
here's an outline that matches your use case:

if user wants command line:
command line only
else:
if wxPython is available:
prepare wx based GUI
elif Tkinter is available:
prepare tk based GUI
else:
command line only


This is exactly the logic I use,... Eliminating all unrelated stuff, I
have something like (thanks for the imp hint):

def wxGUI():
import wx
wx...

def tkGUI():
import Tkinter as tk
tk....

def cml():
command line

def GUI():
if options['cml']:
cml()
else:
if imp.find_module('wx'):


that imp call is completely unnecessary, and means that you'll scan
the path *twice* for each module, instead of once.

this is more efficient:

try:
wxGUI()
except ImportError:
try:
tkGUI()
except ImportError:
cml()

</F>

Dec 19 '05 #12
Bo Peng wrote:
Is there a better way than doing

try:
import aModule
except:
has_aModule = False
else:
has_aModule = True

The main concern here is that loading aModule is unnecessary (and may
take time).


Yes. Specifically catch ImportError in your except clause.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Substance is one of the greatest of our illusions.
-- Sir Arthur Eddington
Dec 19 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Flavio codeco coelho | last post by:
I have a program that uses pythondialog for its UI. Pythondialog is a wrapper of the shell dialog and xdialog libs. But I would like for it to switch between using Dialog ( when X is not...
11
by: rhat | last post by:
Hi Everyone, I've recently been reading some articles about unit-testing in Python , but I am a bit confused: where do I go to get started with this? I tried googling for "unittest" but all I've...
4
by: Edvard Majakari | last post by:
Hi, I just found py.test and converted a large unit test module to py.test format (which is actually almost-no-format-at-all, but I won't get there now). Having 348 test cases in the module and...
2
by: Martin RAYROLE | last post by:
Hi folks, Does somebody know how to test the availability of a font on the browser platform ? Thanks for your help Martin
38
by: Christoph Zwerschke | last post by:
In August 2001, there was a thread about the "Art of Unit Testing": http://groups.google.com/group/comp.lang.python/browse_frm/thread/aa2bd17e7f995d05/71a29faf0a0485d5 Paul Moore asked the...
27
by: brad | last post by:
Does anyone else feel that unittesting is too much work? Not in general, just the official unittest module for small to medium sized projects? It seems easier to write some quick methods that are...
5
by: Ben Finney | last post by:
Howdy all, PEP 299 <URL:http://www.python.org/dev/peps/pep-0299details an enhancement for entry points to Python programs: a module attribute (named '__main__') that will be automatically called...
0
by: Matthew Fitzgibbons | last post by:
I'm by no means a testing expert, but I'll take a crack at it. Casey McGinty wrote: I've never run into this. Rule of thumb: always separate software from hardware. Write mock classes or...
7
by: alito | last post by:
Hi all, I am new to using packages to group my modules. I can't figure out how to run a module that uses relative imports without writing a wrapper that imports that module. Everything I try...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.