Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #8133

Re: Handling import errors

From Mel <mwilson@the-wire.com>
Newsgroups comp.lang.python
Subject Re: Handling import errors
Followup-To comp.lang.python
Date 2011-06-21 17:12 -0400
Organization Aioe.org NNTP Server
Message-ID <itr1gu$dhf$1@speranza.aioe.org> (permalink)
References <ac1909f8-4e16-4094-92a4-5239122e1511@j31g2000yqe.googlegroups.com>

Followups directed to: comp.lang.python

Show all headers | View raw


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.

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Handling import errors Guillaume Martel-Genest <guillaumemg@gmail.com> - 2011-06-21 13:51 -0700
  Re: Handling import errors Mel <mwilson@the-wire.com> - 2011-06-21 17:12 -0400
  Re: Handling import errors Chris Rebert <clp2@rebertia.com> - 2011-06-21 22:12 -0700
    Re: Handling import errors Guillaume Martel-Genest <guillaumemg@gmail.com> - 2011-06-22 18:52 -0700

csiph-web