Handling import errors

Mel mwilson at the-wire.com
Tue Jun 21 17:12:53 EDT 2011


Guillaume Martel-Genest wrote:

> What is the pythonic way to handle imports error? What is bugging me
> is that the imports can't be inside a function (because I use them in
> different places in the script and thus they have to be in the global
> scope).

Actually, you can if you declare them global:

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     global os
...     import os
... 
>>> dir (os)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'os' is not defined
>>> f()
>>> dir (os)
['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 
'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 
'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 
'F_OK', 'NGROUPS_MAX', 'O_APPEND', 'O_ASYNC', 'O_CREAT', 'O_DIRECT', 
'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_LARGEFILE', 'O_NDELAY', 'O_NOATIME', 
'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK

etc.

	Mel.




More information about the Python-list mailing list